Skip to content

fix(resolve): find an enclosing namespace's import before an outer member - #2672

Open
HuiJun wants to merge 3 commits into
developfrom
fix/enclosing-import-precedence
Open

HuiJun wants to merge 3 commits into
developfrom
fix/enclosing-import-precedence

Conversation

@HuiJun

@HuiJun HuiJun commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

What and why

A name imported by an enclosing namespace now resolves before a same-named member owned further out. Closes #2666.

Behaviour change to review first: a package that imports its own name no longer names itself from inside. The leading segment of a qualified name follows the same lookup order, so in

package V {
    private import SI::*;
    enum def Grade { enum high; }
    attribute g : Grade = V::Grade::high;   // now unresolved: V is SI::V, the volt
}

the reference is unresolved where it used to resolve. The pinned pilot validator reports the same reference unresolved. $::V::Grade::high, Grade::high, or importing the units by name all still resolve.

Two consequences of that in this PR:

  • REPL test model narrowed. internal/frontend/repl/import_test.go had exactly this shape, so its model now imports SI::kg and SI::m instead of SI::*. The assertions are unchanged.
  • Known limitation, not fixed here. %import writes enumeration values as unrooted qualified names, so it cannot set one in a package that imports its own name by wildcard.

The bug

package Q { part def T; }
package P {
    part def T;
    package K {
        private import Q::*;
        package N { part v : T; }   // was P::T, is now Q::T
    }
}

walkUnqualifiedHiding searched the members every enclosing scope declares before the imports of the scope it was standing in, so P::T won over the nearer K's import and no diagnostic was reported. It now takes a scope's imports first, then walks outward only as far as the nearest scope that imports the name. A member the nearer namespace owns or inherits still comes first, and an outer member is still found when no namespace between imports the name.

The second commit makes that outward walk happen once per lookup instead of once per scope level.

Specification basis

KerML 8.2.3.5.4 (local resolution): a name that is not a membership of the local namespace resolves in the enclosing namespace, whose memberships include its imported ones. Adds a row to docs/project/spec-compliance/02-detailed-semantic-compliance-map/28-name-resolution.md.

How it was verified

Failing first: with develop's unqualified.go, the new test reports the wrong owner.

--- FAIL: TestEnclosingImportPrecedesOuterMember (0.00s)
    enclosing_import_test.go:57: K1: T resolves to P::T, want Q::T
    enclosing_import_test.go:57: K3: T resolves to P::T, want Q::T
    enclosing_import_test.go:57: cInner: T resolves to P::T, want Q::T
    enclosing_import_test.go:57: uInner: T resolves to P::T, want Q::T
    ...

With the fix all three new tests pass. They assert the resolved owner, across wildcard and membership imports in a package, a definition, a usage, a state and action bodies, with the nearer-member and no-import controls. Try it:

go test -count=1 ./internal/semantic/resolve -run 'TestEnclosingImportPrecedesOuterMember|TestInheritedMemberPrecedesOuterImport|TestImportedNameHidesTheImportingPackageFromItself' -v

Run locally on this head, after merging develop:

  • go build ./..., go vet ./..., gofmt -l . (empty), make lint
  • go test -count=1 ./...
  • go test ./tests/corpus with OPENSYSML_REQUIRE_TRAINING_CORPUS, OPENSYSML_REQUIRE_PILOT_CORPORA and OPENSYSML_REQUIRE_SPEC_EXAMPLES set: no baseline moved

Run before the develop merge and the second commit, not repeated since: go test -C tools ./... and derived-census -check -recorded-pilot.

Not run: the race detector.

Benchmarks

go test ./tests/perf -run '^$' -bench '^Benchmark(Analyze|AnalyzeManyDiagnostics|LookupQualified|REPLLoadFile|WorkspaceEdit|FeaturesOf)$' -benchmem -count=8, develop's unqualified.go against this branch's, same machine, compared with benchstat.

Benchmark sec/op before sec/op after Δ time B/op before B/op after Δ B/op
AnalyzeManyDiagnostics/100 43.61m ± 3% 43.76m ± 3% ~ 5.925Mi 5.925Mi ~
AnalyzeManyDiagnostics/400 154.9m ± 1% 158.8m ± 2% +2.54% 7.995Mi 7.995Mi ~
AnalyzeManyDiagnostics/1600 672.3m ± 3% 668.7m ± 5% ~ 17.34Mi 17.32Mi ~
Analyze/synthetic 1.661 ± 10% 1.591 ± 41% ~ 537.7Mi 537.7Mi ~
WorkspaceEdit/synthetic 275.4m ± 34% 251.1m ± 13% ~ 88.77Mi 88.72Mi ~
WorkspaceEdit/synthetic/reindex+diagnostics 2.026 ± 4% 2.246 ± 15% +10.85% 571.2Mi 571.3Mi ~
WorkspaceEdit/vehicle 80.45m ± 40% 62.19m ± 3% -22.69% 16.42Mi 16.42Mi ~
WorkspaceEdit/vehicle/reindex+diagnostics 276.5m ± 76% 258.7m ± 7% ~ 126.3Mi 134.4Mi +6.39%
LookupQualified 1.144m ± 9% 1.337m ± 15% ~ 0 0 ~
FeaturesOf 601.0m ± 3% 617.2m ± 6% +2.69% 237.5Mi 237.4Mi ~
REPLLoadFile 1.741 ± 7% 1.695 ± 7% ~ 626.6Mi 626.6Mi ~
geomean 233.4m 229.7m -1.61% +0.55%

~ is no significant difference (p > 0.05, n = 8).

  • The one real cost is WorkspaceEdit/vehicle/reindex+diagnostics: +6.4% bytes and +5.8% allocations, time unchanged. A scope's imports are now consulted before its enclosing scopes' members, which is the corrected order.
  • The three time increases come with flat allocations on a machine whose run-to-run spread is up to ±76% on these benchmarks; I read them as noise but did not isolate them further.
  • The table was measured before the develop merge.

Checklist

  • make test and make lint pass locally (go test ./... without -race; make lint passes)
  • Tests added or updated for the change
  • Documentation extended where it already covers the surface (see CONTRIBUTING.md)
  • Changelog entry added as changes/unreleased/<slug>.<section>.md, not as an edit to CHANGELOG.md
  • baselines regenerated and make docs-counts run if a gate count moved (none moved)
  • No internal work-item labels (waves, slices, F4, K5) in the body, docs, or changelog

Software Factory opened this PR for Jason
Implemented in session Fix enclosing import losing to outer member
Review with Devin · Open in Devin Desktop


devin-ai-integration Bot and others added 3 commits November 26, 2026 06:50
…mber

An unqualified name was looked up among the members every enclosing
namespace owns before the imports of the namespace the walk had reached,
so a name imported by an enclosing namespace lost to a same-named member
owned further out. The walk now consults a namespace's imports before
the namespaces around it, and the look-ahead over enclosing owned
members stops at the nearest namespace importing the name
(KerML 8.2.3.5.4).

Fixes #2666

Co-Authored-By: jason.han <hanhuijun@gmail.com>
Co-Authored-By: jason.han <hanhuijun@gmail.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 2 findings. Devin fixed 1 finding; 1 finding is left for you to triage below.

Fixed by Devin (1)
  • Unqualified calls run the shadowed calculation — Confirmed: a call to f() two packages inside private import Q::* evaluated the outer P::f (1) instead of Q::f (2). unqualifiedCandidates now follows the same order as walkUnqualifiedHiding; failing-first test added. Committed locally, not pushed yet (push waits for the CI coordinator's GO).

View findings in Devin Review · Follow Devin's work

Devin Review

Comment on lines +95 to +96
if sym, ok := r.importedName(scope, name, hide); ok {
return nil, scope, sym

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Wildcard imports expose shadowed members

When an enclosing import shadows a wildcard target’s qualifier, enclosingLocal selects the nearer qualifier. resolveWildcardTarget still indexes the outer target when the nearer qualifier’s subtree has no index entry under its imported name. Qualified references then resolve members the wildcard import did not bring in.

Devin left this for you to triage: Confirmed: with package K { private import Q::X; package N { public import X::*; } } inside a P that owns its own X, N re-exports the members of both P::X (through the symbol index) and Q::X (through the resolver). The index records only wildcard imports, so it cannot see K's membership import; develop has the mirror-image mismatch when K's import is a wildcard, which this PR fixes. A proper fix needs the index and its cache snapshot to record membership imports; I recommend a separate issue and PR rather than widening this one.

Learn more

walkQualified resolves the leading qualifier lexically before walking the remaining segments. resolveWildcardTarget instead tries the complete target under each enclosing package prefix. A wildcard re-export of a package indexes that package's name but not its subtree, so the closer prefix can lack the full target key. expandImporter then records public re-exports from the farther target. When the direct import lookup misses one of those members, membersNamed accepts the indexed re-export.

Example: Declare L::Q::D::New and P::Q::D::Old in separate package trees. Inside P::K, write public import L::*; and declare package N { public import Q::D::*; }. The import in N now points to L::Q::D, but the index still expands P::Q::D because it cannot find P::K::Q::D as a full key. A usage typed by P::K::N::Old therefore still finds Old through the index, although the import only brings in New.

Recommended fix: Make wildcard expansion resolve the leading segment before following the target's remaining segments, using the same precedence as semantic lookup. Do not admit a fallback re-export that disagrees with the resolved import target. Add a workspace regression with the expanded index that accepts P::K::N::New and rejects P::K::N::Old.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

QA: pass, with two behavior changes to confirm and hosted CI not run

Tested head 207959a2d3 against base 81a86b24e8 (the merge base; develop is now 6f13c63949, and the commits in between touch only client/opensysml and a changelog entry, not the resolver).

Recording of the run

The fix

Surface Base Head
sysml -validate on a model where Line imports Catalog::* and Plant owns a same-named Motor unresolved reference: torque no errors
sysml -e 'Plant::Line::Cell::drive.torque' does not analyse = 2.5
Expression limit + 1 with an imported limit = 10 and an outer limit = 99 100 11
Two-file workspace (import in one file, target in the other, either load order) P::T Q::T
VS Code Problems view 3 errors 0 errors from the fix (see below)
VS Code go-to-definition on Motor inside Cell Plant::Motor Catalog::Motor
Standard library: Real / mass under import ScalarValues::* / ISQ::* with outer members of the same name 2 type errors clean

Go-to-definition was also probed over the LSP across a matrix of reference sites: package, part definition, part usage, state and action bodies, wildcard and membership imports, public and private, recursive imports, an import declared after the nested namespace, and two import levels (the nearer one wins). Every site that the PR describes moved from the outer member to the import, and nothing else moved.

The three new tests fail on base (two of the three) and pass on head.

Base Problems Head Problems
Base Head

Orders that stayed the same

  • A member owned by a nearer namespace still wins over an import farther out.
  • An inherited member of a nearer type still wins over an outer import.
  • With no import in between, the outer member is still found.
  • A filtered import that excludes the name does not hide the outer member.
  • An import in the referencing namespace itself, aliases, and $:: rooted names resolve as before.

Behavior changes a user will notice (not failures, please confirm they are intended)

  1. A package that imports its own name. package V { private import SI::*; enum def Grade {…} part def Engine { attribute grade : Grade = V::Grade::high; } } validated on base and now reports unresolved reference: V::Grade::high, because V is the volt in SI. Base already rejected the same reference written directly in V's body, so head is consistent, and $::V::Grade::high works. This is the consequence the PR description names; a model whose package is named like an SI unit (V, m, N, W) and qualifies its own members from a nested body will stop validating.
  2. A qualified name whose first segment is now imported. With Q::T imported by an enclosing package and an outer P::T, T::OnlyP (a member only P::T has) resolved on base and is unresolved on head. The first segment binds to the import and there is no fallback to the outer member.

Past fixes in the touched areas

211 inventory rows selected (name resolution, imports, cyclic public imports, query identity, and all 15 Tim Weilkiens rows). Their test packages were run on head: 49 packages, all ok, including internal/semantic/resolve, tests/resolve, tests/identity, internal/semantic/query, internal/doc/queryexec, internal/frontend/lsp, internal/frontend/repl, internal/workspace/project, internal/exec/runtime, tests/model, tests/export and tests/corpus.

Hosted CI

Not green and not informative: the run for this head was cancelled, so 26 jobs are cancelled or skipped and the required Build and test gate failed only because of that. It needs a re-run before merge.

Not run

  • The race detector, and go test ./... over packages outside the 49 above.
  • A base build at the exact develop tip (see the first line).
  • Editors other than VS Code.

Also seen on both base and head, so not from this PR: the language server reports Duplicate of inherited member name 'T' from Q on a usage typed by a definition that publicly imports Q::* while an outer T exists; sysml -validate does not.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

An import in an enclosing namespace loses to a same-named member owned further out

1 participant