package bigguy.texteditor.semantics; import bigguy.texteditor.treesitter.java.TextSpan; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * Unified import resolution index for a single script document. * *
Replaces the four separate import-tracking fields that previously lived in * {@code ScriptDocument} ({@code imports}, {@code wildcardPackages}, * {@code importsBySimpleName}, {@code implicitImports}) with a single source of * truth backed by a list of {@link ImportEntry} objects.
* *Two derived lookup maps ({@code bySimpleName} and {@code byFullPath}) are * computed lazily on first access after any mutation, and cached until the next * mutation invalidates them. This gives O(1) lookups without paying rebuild * cost on every add.
* *A monotonically increasing version counter is bumped on every mutation. * External code can call {@link #version()} to detect whether the index has * changed since its last snapshot.
* *All mutation methods are {@code synchronized}. All query methods return * defensive copies or unmodifiable snapshots, so callers never observe * partially-mutated state.
* * @since Phase 2 — CST editor architecture */ public final class ImportIndex { // ── Primary store ────────────────────────────────────────────────── /** The authoritative list of all import entries (explicit + implicit). */ private final ListInstances are immutable. Two entries are equal if and only if they * share the same {@code fullPath} and {@code isImplicit} flag — the * source range is deliberately excluded from equality so that * re-parsing the same import at a different offset does not produce * a spurious "changed" signal.
*/ public static final class ImportEntry { private final String fullPath; private final String simpleName; private final boolean isWildcard; private final boolean isStatic; private final boolean isImplicit; private final TextSpan range; private final String packagePath; /** * Creates a new {@code ImportEntry}. * * @param fullPath the fully qualified import path, e.g. {@code "java.util.List"} * or {@code "java.util.*"} * @param simpleName the unqualified name, e.g. {@code "List"} or {@code "*"} * @param isWildcard {@code true} for wildcard imports ({@code import pkg.*}) * @param isStatic {@code true} for static imports ({@code import static ...}) * @param isImplicit {@code true} for auto-injected imports (e.g. {@code java.lang.*}) * @param range source location of the import statement; may be {@code null} * for implicit imports * @param packagePath the package portion, e.g. {@code "java.util"} */ public ImportEntry(String fullPath, String simpleName, boolean isWildcard, boolean isStatic, boolean isImplicit, TextSpan range, String packagePath) { if (fullPath == null) { throw new IllegalArgumentException("fullPath must not be null"); } if (simpleName == null) { throw new IllegalArgumentException("simpleName must not be null"); } if (packagePath == null) { throw new IllegalArgumentException("packagePath must not be null"); } this.fullPath = fullPath; this.simpleName = simpleName; this.isWildcard = isWildcard; this.isStatic = isStatic; this.isImplicit = isImplicit; this.range = range; this.packagePath = packagePath; } /** * Factory for creating an {@code ImportEntry} from a fully qualified path string. * *Automatically derives {@code simpleName}, {@code isWildcard}, and * {@code packagePath} from the path.
* * @param fullPath the fully qualified import path * @param isStatic whether this is a static import * @param isImplicit whether this is an implicit (auto-injected) import * @param range source location, or {@code null} for implicit imports * @return a new {@code ImportEntry} */ public static ImportEntry fromFullPath(String fullPath, boolean isStatic, boolean isImplicit, TextSpan range) { boolean isWildcard = fullPath.endsWith(".*"); String simpleName; String packagePath; int lastDot = fullPath.lastIndexOf('.'); if (lastDot >= 0) { simpleName = fullPath.substring(lastDot + 1); packagePath = fullPath.substring(0, lastDot); } else { simpleName = fullPath; packagePath = ""; } return new ImportEntry(fullPath, simpleName, isWildcard, isStatic, isImplicit, range, packagePath); } /** @return the fully qualified import path (e.g. {@code "java.util.List"}) */ public String getFullPath() { return fullPath; } /** @return the unqualified name (e.g. {@code "List"} or {@code "*"}) */ public String getSimpleName() { return simpleName; } /** @return {@code true} for wildcard imports ({@code import pkg.*}) */ public boolean isWildcard() { return isWildcard; } /** @return {@code true} for static imports */ public boolean isStatic() { return isStatic; } /** @return {@code true} for auto-injected imports */ public boolean isImplicit() { return isImplicit; } /** * @return the source location of the import statement, or {@code null} * for implicit imports */ public TextSpan getRange() { return range; } /** @return the package portion (e.g. {@code "java.util"}) */ public String getPackagePath() { return packagePath; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof ImportEntry)) return false; ImportEntry that = (ImportEntry) obj; return this.isImplicit == that.isImplicit && this.fullPath.equals(that.fullPath); } @Override public int hashCode() { int result = fullPath.hashCode(); result = 31 * result + (isImplicit ? 1 : 0); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (isImplicit) sb.append("[implicit] "); if (isStatic) sb.append("static "); sb.append("import ").append(fullPath); if (range != null) { sb.append(" at ").append(range); } return sb.toString(); } } // ── Building (mutators) ──────────────────────────────────────────── /** * Removes all import entries and resets the version counter. */ public synchronized void clear() { entries.clear(); markDirty(); } /** * Adds a single import entry. * * @param entry the entry to add; must not be {@code null} * @throws IllegalArgumentException if {@code entry} is {@code null} */ public synchronized void addImport(ImportEntry entry) { if (entry == null) { throw new IllegalArgumentException("entry must not be null"); } entries.add(entry); markDirty(); } /** * Adds an implicit (auto-injected) import from a fully qualified path. * *The entry is created with {@code isImplicit=true}, {@code isStatic=false}, * and {@code range=null}.
* * @param fullPath the fully qualified path (e.g. {@code "java.lang.*"}) */ public synchronized void addImplicitImport(String fullPath) { ImportEntry entry = ImportEntry.fromFullPath(fullPath, false, true, null); entries.add(entry); markDirty(); } /** * Atomically replaces all entries with the given list. * *The previous contents are discarded. This is the preferred method * when rebuilding imports from a fresh parse — it avoids intermediate * states visible to concurrent readers.
* * @param newEntries the replacement entries; the list is defensively copied */ public synchronized void replaceAll(ListResolution order:
*This checks both exact matches (e.g. an implicit import of * {@code "java.lang.String"}) and wildcard matches (e.g. an implicit * import of {@code "java.lang.*"} covers {@code "java.lang.String"}).
* * @param fqn the fully qualified name to check * @return {@code true} if an implicit import covers this FQN */ public synchronized boolean isImplicitlyImported(String fqn) { if (fqn == null || fqn.isEmpty()) { return false; } for (int i = 0, size = entries.size(); i < size; i++) { ImportEntry entry = entries.get(i); if (!entry.isImplicit) { continue; } if (entry.fullPath.equals(fqn)) { return true; } // Check wildcard coverage: "java.lang.*" covers "java.lang.String" if (entry.isWildcard) { String pkg = entry.packagePath; if (fqn.startsWith(pkg + ".") && fqn.indexOf('.', pkg.length() + 1) < 0) { return true; } } } return false; } // ── Wildcard package queries ─────────────────────────────────────── /** * Returns all wildcard package paths (e.g. {@code "java.util"} from * {@code import java.util.*}). * * @return an unmodifiable set of package paths; never {@code null} */ public synchronized SetWildcard implicit imports are never removed by this method, since * they cannot be matched by simple name alone.
* *This is typically called after the token-build pass to discard * implicit imports that turned out to be unused.
* * @param usedSimpleNames the set of simple names actually referenced * in the source; must not be {@code null} */ public synchronized void removeUnusedImplicitImports(SetThe version is bumped on every mutation. External code can snapshot * this value and later compare to detect whether the index has changed.
* * @return the current version (starts at 0, increments monotonically) */ public synchronized int version() { return version; } // ── Internals ────────────────────────────────────────────────────── /** * Marks the derived indexes as stale and increments the version counter. * Must be called under the instance lock. */ private void markDirty() { dirty = true; version++; } /** * Rebuilds the derived indexes if they are stale. Must be called under * the instance lock. */ private void ensureIndexes() { if (!dirty) { return; } Map