(ref: UnresolvedRef, imports: ImportMapping[], context: ResolutionContext)
| 4069 | * mapping. |
| 4070 | */ |
| 4071 | export function pythonImportsInScope(ref: UnresolvedRef, imports: ImportMapping[], context: ResolutionContext): ImportMapping[] { |
| 4072 | if (ref.language !== 'python' || ref.referenceKind === 'imports') return imports; |
| 4073 | const dot = ref.referenceName.indexOf('.'); |
| 4074 | if (dot < 0 && /^[A-Za-z_]\w*$/.test(ref.referenceName)) return pythonBareImportsInScope(ref, imports, context); |
| 4075 | if (dot <= 0) return imports; |
| 4076 | const receiver = ref.referenceName.slice(0, dot); |
| 4077 | // `import pkg.mod` binds `pkg`, under a mapping named after `mod`. |
| 4078 | const binds = (m: ImportMapping): boolean => m.localName === receiver || |
| 4079 | (m.isNamespace && m.source.split('.')[0] === receiver && m.localName === m.source.split('.').pop()); |
| 4080 | if (!imports.some(binds)) return imports; |
| 4081 | const binding = pythonReceiverBinding(receiver, ref, context); |
| 4082 | if (binding === 'module') { |
| 4083 | // Where nothing nearer binds the name, the module's own import of it |
| 4084 | // does — not a from-import written inside some other function, which the |
| 4085 | // mappings list too (first, ahead of the module's `import pkg.other as |
| 4086 | // other`). Asked only when the receiver's mappings disagree; with no |
| 4087 | // module-level one found, every mapping stays as it was. |
| 4088 | const keyOf = (m: ImportMapping): string => (m.isNamespace ? `${m.source}:*` : `${m.source}:${m.exportedName}`); |
| 4089 | if (new Set(imports.filter(binds).map(keyOf)).size < 2) return imports; |
| 4090 | const moduleLevel = pythonModuleImportKeys(receiver, ref.filePath, context); |
| 4091 | const kept = imports.filter((m) => !binds(m) || m.isNamespace || moduleLevel.has(keyOf(m))); |
| 4092 | return kept.some(binds) ? kept : imports; |
| 4093 | } |
| 4094 | return imports.filter((m) => { |
| 4095 | if (!binds(m)) return true; |
| 4096 | if (binding === 'local') return false; |
| 4097 | // The module a namespace mapping binds the receiver to: `import x as |
| 4098 | // receiver` / `import receiver` bind its source, `import receiver.sub` |
| 4099 | // the top-level `receiver`. |
| 4100 | if ('module' in binding) return m.isNamespace && (m.localName === receiver ? m.source : receiver) === binding.module; |
| 4101 | return !m.isNamespace && m.source === binding.source && m.exportedName === binding.exportedName; |
| 4102 | }); |
| 4103 | } |
| 4104 | |
| 4105 | /** |
| 4106 | * The file's import mappings as a bare Python name reads them (#3229). The |
no test coverage detected