Skip to content

JetBrains/intellij-community / .agents/skills/poly-symbols

poly-symbols

Verified

Implement PolySymbols completion, references, and rename.

FileKindSize
OWNERSHIPother25 B
SKILL.mdskill md16.7 KB
references/case-studies.mdmarkdown23.6 KB
references/migration.mdmarkdown11.7 KB
references/patterns.mdmarkdown8.7 KB
references/query-model.mdmarkdown43.7 KB
references/testing.mdmarkdown15.3 KB
references/web-types.mdmarkdown6.0 KB

references/query-model.md

View on GitHub
# PolySymbols query model

Part of [poly-symbols](../SKILL.md). This is the "how it actually resolves" reference: the query
executor, scopes, contributors/configurators, declarations, references, completion, and how a
resolved `PolySymbol` lights up search/rename/navigation/documentation.

## PolySymbolQueryExecutor

Central entry point (`community/platform/polySymbols/shared/src/com/intellij/polySymbols/query/PolySymbolQueryExecutor.kt`).
Built via `PolySymbolQueryExecutorFactory.create(location: PsiElement)`, which configures the
executor from every registered `PolySymbolQueryScopeContributor` and `PolySymbolQueryConfigurator`
based on the PSI location — contributors supply initial scopes, configurators supply `PolyContext`
and name-conversion rules. Three query kinds:

```kotlin
executor.nameMatchQuery(kind, name).run(): List<PolySymbol>          // resolve a specific name
executor.listSymbolsQuery(kind, expandPatterns).run(): List<PolySymbol>  // enumerate everything of a kind
executor.codeCompletionQuery(kind, name, position).run(): List<PolySymbolCodeCompletionItem>
```

All three accept `additionalScope(...)` to push extra scopes onto the query on top of whatever the
contributors registered — this is how a reference provider narrows/extends resolution for one
specific query (e.g. GDScript's qualified-reference scopes, described in
[case-studies.md](case-studies.md)).

## PolySymbolScope

```kotlin
interface PolySymbolScope {
  fun createPointer(): Pointer<out PolySymbolScope>
  fun getMatchingSymbols(qualifiedName, params, stack): List<PolySymbol>   // default: getSymbols().flatMap { it.match(...) }
  fun getSymbols(kind, params, stack): List<PolySymbol> = emptyList()
  fun getCodeCompletions(qualifiedName, params, stack): List<PolySymbolCodeCompletionItem>
  fun isExclusiveFor(kind): Boolean = false
}
```

A scope is itself often a `PolySymbol` that contains other symbols (an HTML element scoping its
attributes, a JS class scoping its members) — `PolySymbol.queryScope` defaults to `listOf(this)` if
the symbol implements `PolySymbolScope`.

**For any scope backed by more than a handful of symbols, or whose computation should be cached**,
use the `polySymbolScopeCached(...)` DSL
(`community/platform/polySymbols/shared/src/com/intellij/polySymbols/query/PolySymbolScopeDsl.kt`) rather
than hand-extending `PolySymbolScopeWithCache` — it's the same `PolySymbolScopeWithCache`/
`CachedValuesManager` engine underneath, just without the manual `createPointer()`/`equals`/
`hashCode` boilerplate:

```kotlin
fun <T : PsiElement, K> polySymbolScopeCached(element: T, key: K, configure: PsiPolySymbolScopeCachedBuilder<T, K>.() -> Unit): PolySymbolScope
fun <T : PsiElement> polySymbolScopeCached(element: T, configure: PsiPolySymbolScopeCachedBuilder<T, Unit>.() -> Unit): PolySymbolScope
fun polySymbolScopeCached(project: Project, configure: ProjectPolySymbolScopeCachedBuilder<Unit>.() -> Unit): PolySymbolScope
fun <T : UserDataHolder, K> polySymbolScopeCached(project: Project, dataHolder: T, key: K, configure: PolySymbolScopeCachedBuilder<T, K>.() -> Unit): PolySymbolScope
```

Four overloads keyed by holder shape — a `PsiElement` (cache keyed on that element, invalidated via
whatever you pass to `cacheDependencies(...)`), a `Project` (`Unit` key, hard-pointer), or an
arbitrary `UserDataHolder` + explicit key (requires an explicit `pointer { }` in the config lambda —
omitting it throws). The builder exposes `provides(...)`/`exclusiveFor(...)`/`requiresResolve(...)`
as one-liners, plus `filterCodeCompletions { }`/`filterNameMatches { }` to post-process the cached
base result without subclassing. The `initialize { }` block must call `cacheDependencies(...)` with
a non-empty set (throws otherwise) and add symbols via `add`/`addAll`/`+`/`addSymbol`. Real examples:
`contrib/Astro/src/org/jetbrains/astro/polySymbols/scope/AstroAvailableComponentsScope.kt` (Project,
Unit key), `AstroNamespacedComponentsScope.kt` (PsiElement, Unit key, with `filterCodeCompletions`).

**The DSL exposes `PolySymbolScopeWithCache.partialMatchingSupport` too**, via two builder overloads:
```kotlin
fun partialMatchingSupport(cacheDependencies: Collection<Any>, getMatchingSymbols: (kind: PolySymbolKind, nameVariant: String) -> List<PolySymbol>)
fun partialMatchingSupport(provider: () -> PolySymbolScopePartialMatchingSupport?)
```
The first is the common case: a fixed, *unconditionally* active fast path - a single name-match query
goes straight to `getMatchingSymbols` (typically a direct index/point lookup) instead of forcing (or
waiting on) the full symbol-set build first. GDScript's `gdPsiClassesPolySymbolScope`/
`gdPsiResourceClassesPolySymbolScope`
(`dotnet/Plugins/godot-support/gdscript/.../polySymbols/scope/GdPsiClassesPolySymbolScope.kt`/
`GdPsiResourceClassesPolySymbolScope.kt`) both use this form - each backed by a project-wide
index/lookup where a full walk is proportional to everything in the project, but a single point
lookup is always cheap regardless of project size, so the fast path is worth providing
unconditionally. The second is the general form, for a *conditional* activation strategy: `provider`
is invoked fresh on every `getMatchingSymbols` call (matching the underlying property's own contract)
and may return `null` to skip the partial path for that call and fall through to the DSL's normal,
full-cache-backed matching. If the *decision itself* is non-trivial to compute (e.g. checking a stub
count), cache that decision inside `provider` the same way a hand-written scope would (e.g. via
`CachedValuesManager.getCachedValue(dataHolder) { ... }`) - the DSL does not do this for you, it just
forwards the call through.

A scope whose candidate set is bounded to one PSI element/file (the common case) should still default
to the plain form of `polySymbolScopeCached(...)`, with **no** `partialMatchingSupport` at all: a full
PSI/stub walk over an already-open file is normally *cheaper* than a project-wide index lookup for
the same answer, and the DSL's caching means repeat queries (including code completion) reuse the
walk for free - see GDScript's `gdPsiInnerClassesPolySymbolScope`
(`dotnet/Plugins/godot-support/gdscript/.../polySymbols/scope/GdPsiInnerClassesPolySymbolScope.kt`)
for the idiomatic shape (an iterative, stub-only walk of one file, cached by the DSL). Reach for
`partialMatchingSupport` only when full enumeration is genuinely expensive - i.e. the scope's
candidate set spans many files/the whole project (GDScript's `gdPsiClassesPolySymbolScope`/
`GdClassNamingIndex`, deliberately project-wide, see [case-studies.md](case-studies.md#gdscript)) or a
single file is large enough that walking it every time is wasteful, gated behind a real size check -
the way CSS's `CssStylesheetClassesScope` does in
`plugins/css/backend/src/com/intellij/polySymbols/css/classes/CssTagClassesScope.kt` (only turns on
its index-backed partial matching, over `CssClassIndex`, when the containing file's stub tree exceeds
500 stubbed symbols - "using indexes on small files can cause performance issues," per its own
comment) and `CssCustomPropertiesScope`
(`plugins/css/backend/src/com/intellij/polySymbols/css/CssSymbolQueryScopeContributor.kt`, gated on
whether the file is indexed at all, no size threshold) do. Both predate this DSL addition and haven't
been migrated onto it - the size/indexed-file gate maps onto the general `provider` overload above,
but migrating a different plugin's hand-written scope onto a platform DSL feature is a separate,
deliberate follow-up, not something to do silently as part of adding the feature.

Reach for a hand-written `PolySymbolScopeWithCache` subclass (bypassing the DSL entirely) only when
you need custom `createPointer()` chaining through an owning symbol (rare) - not for
`partialMatchingSupport` itself anymore, now that the DSL covers both the unconditional and the
conditional/gated case.

`isExclusiveFor(kind)`: when a scope is exclusive for a kind, pattern-matching stops walking further
down the scope stack for that kind once this scope has been consulted — use it when a scope is
known to be a complete, self-contained answer (no outer scope could contribute more).

**A symbol's own `kind` must always agree with the query kind that found it - never return a symbol
whose `.kind` disagrees with the kind a scope is answering for.** `PolySymbolScopeWithCache` enforces
this literally: both `initialize`'s `consumer` and `PartialMatchingSupport.getMatchingSymbols` throw
`IllegalArgumentException` when a produced symbol's `.kind` isn't among what `provides(kind)` accepts.
A hand-written raw `PolySymbolScope` has no such check, but the rule is still correct there too - skip
it and any consumer reading `.kind` off the raw (non-unwrapped) resolved symbol silently sees the wrong
kind. This bites whenever a scope's *query-routing* kind is answered by a real symbol whose *own* kind
is genuinely different - e.g. GDScript's `gdPsiResourceClassesPolySymbolScope` answers
`GdPolySymbolKind.RESOURCE_CLASS` queries (`extends "res://base.gd"`) with whatever the resource file
actually declares, which always reports kind `CLASS` (`GdPsiClassSymbol` for a named file,
`GdPsiResourceClassSymbol` for an anonymous one) - `RESOURCE_CLASS` is a routing-only kind that no
symbol class ever reports as its own.

Do **not** reach for a kind-overriding `PolySymbolDelegate` to fix this (there is no platform utility
for that, and inventing a bespoke one is the wrong tool) - wrap the real symbol in a one-segment
`PolySymbolMatch` reporting the routing kind instead:
```kotlin
PolySymbolMatch.create(
  matchedName, routingKind,
  PolySymbolNameSegment.create(0, matchedName.length, realSymbol.withName(matchedName)),
)
```
`PolySymbolMatch` is already the platform's supported "reports kind X, composed of a real symbol
underneath" mechanism, and - unlike a hypothetical kind-overriding delegate - it's exactly what
`unwrapMatchedSymbols()` (used pervasively, including by own references' final name check - see the
Hard Constraint note in [References — own references](#references--own-references-polysymbolownreferences))
already knows how to peel back to the real symbol. The platform's own
`ReferencingPolySymbol.create(kind, name, vararg kinds)`
(`community/platform/polySymbols/shared/src/com/intellij/polySymbols/utils/ReferencingPolySymbol.kt`) builds
exactly this shape declaratively, but only for the case where the referencing and the real target
share the *same name*: it works by *re-querying* other scopes for `kinds` via a `symbolReference(name)`
pattern, using that one shared name (its own worked example: Angular Forms' `formControlName="x"`
resolving as a `FormGroup`'s `"x"` key - see [case-studies.md](case-studies.md#angular)). When the
queried name and the real target's own name differ too (GDScript's case: `"res://base.gd"` vs. the
real class's `"Base"`) and the target is already known - found by a direct lookup, not a fresh
by-name search - `ReferencingPolySymbol.create` doesn't apply; build the `PolySymbolMatch` by hand as
above instead, `withName`-aliasing the real symbol *inside* the one nameSegment (not just on the outer
match) so `unwrapMatchedSymbols()`'s eventual leaf still reports the queried name - the outer
`PolySymbolMatch`'s own name is computed from the segment's range regardless, but the *leaf* the own-
reference check inspects after unwrapping is the aliased real symbol, and that leaf's name is what
must match. GDScript's `referencingResourceClassSymbol`
(`dotnet/Plugins/godot-support/gdscript/.../polySymbols/scope/GdPsiResourceClassesPolySymbolScope.kt`)
is the worked example of this hand-built variant.

## PolySymbolQueryScopeContributor — the registrar DSL

```kotlin
interface PolySymbolQueryScopeContributor {
  fun registerProviders(registrar: PolySymbolQueryScopeProviderRegistrar)
}
```

Register at EP `com.intellij.polySymbols.queryScopeContributor`. The registrar is a **builder**:
each call returns a new stage, so you can freely reuse partial chains. Order of calls does not
affect performance — the framework reorders conditions to match contributors against locations
efficiently, conceptually like how completion contributors are matched.

```kotlin
registrar
  .inFile(AstroFileImpl::class.java)
  .inContext { it.framework == AstroFramework.ID }        // gate by PolyContext — see poly-context skill
  .apply {
    forAnyPsiLocationInFile()
      .contributeScopeProvider { location -> listOf(AstroFrontmatterScope(location.containingFile as AstroFileImpl)) }

    forPsiLocation(CssElement::class.java)
      .contributeScopeProvider { location ->
        location.parentOfType<XmlTag>()
          ?.takeIf { StringUtil.equalsIgnoreCase(it.name, HtmlUtil.STYLE_TAG_NAME) }
          ?.let { listOf(AstroStyleDefineVarsScope(it)) }
        ?: emptyList()
      }
  }
```

Chain shape: `inFile(s)`/no-file-filter → `inContext { }` (optional) → `withResolveRequired()`
(optional — restricts to locations where resolve, not just listing, is actually needed) →
`forPsiLocation(s)`/`forAnyPsiLocationInFile()`/`forAnywhere()` → `contributeScopeProvider { }`.
`forAnywhere()` (no file filter at all) is used for scopes that should apply project-wide
regardless of file type — e.g. the Node/package.json Web Types scope in the JS platform.

### PolySymbolQueryStack and `queryScope` chaining

Scopes contributed for a location seed the initial `PolySymbolQueryStack`. During pattern matching,
**every matched symbol's `queryScope` is pushed onto the stack**, extending what the *next* segment
of a microsyntax pattern (or the next qualifier in a dotted reference) can resolve against. This is
how e.g. `a.b.c` chains: resolving `a` pushes `a`'s member scope, so `b` resolves against it, and so
on — see the `PolySymbolCompoundScope` delegation pattern in
[case-studies.md](case-studies.md#gdscript) for a concrete qualifier-resolution implementation.

## PolySymbolQueryConfigurator

```kotlin
interface PolySymbolQueryConfigurator {
  fun getContextRulesProviders(project, dir): List<PolyContextRulesProvider> = emptyList()
  fun getNameConversionRulesProviders(project, element, context): List<PolySymbolNameConversionRulesProvider> = emptyList()
  fun beforeQueryExecutorCreation(project) {}
}
```

Register at EP `com.intellij.polySymbols.queryConfigurator`. Two jobs: dynamic `PolyContext` rules
(see [poly-context](../../poly-context/SKILL.md)), and **name-conversion rules** — mapping between
a symbol's canonical name and the various surface spellings it can appear as (kebab-case HTML
attribute ↔ camelCase JS property, or Vue's `v-` directive internal-name stripping). Conversion
rules apply uniformly to `canonicalNames`, `renames`, and `completionVariants` so that resolve,
rename, and completion never disagree about which spellings are valid.

## Declarations

Three paths — pick based on whether the symbol has a backing `PsiElement` at all, and if so,
whether that `PsiElement` also needs to keep working as a target for **legacy, non-PolySymbols**
find-usages/rename:

- **`PolySymbolDeclaredInPsi`** (`community/platform/polySymbols/shared/src/com/intellij/polySymbols/utils/PolySymbolDeclaredInPsi.kt`)
  — **the default for a PSI-backed symbol that lives purely in the PolySymbols model.** Override
  `sourceElement`/`textRangeInSourceElement`, and register a `PolySymbolDeclarationProvider`
  (EP `com.intellij.polySymbols.declarationProvider`) that instantiates/finds the symbol for a given
  `PsiElement` and returns its `declaration`. You get navigation, find-usages, and rename for the
  *symbol* for free. It does **not** link the symbol to the `PsiElement` for reverse lookups — a
  usage/rename search started directly on `sourceElement` (bypassing the symbol) will not find or
  rename it, and this includes any *other*, unrelated classic `PsiReferenceBase` elsewhere in the
  project (even in another language/file type) that resolves straight to `sourceElement` — that
  classic reference will not be recognized as a usage of the symbol. There is no supported way to
  get that back other than `PsiLinkedPolySymbol` below (which requires the *declaring* symbol to
  implement it, not something the referencing side can opt into) — if you hit this, it's a real
  platform limitation, not a bug in your provider; stop and ask before reaching for a platform patch
  (see [SKILL.md](../SKILL.md#do-not-modify-polysymbols-platform-source)).
  **The provider must be pure dispatch — decide *which* symbol(s) a `PsiElement` backs, then return
  `symbol.declaration` (the interface's own default, built from `sourceElement`/
  `textRangeInSourceElement`).** Do not hand-roll a `PolySymbolDeclaration` implementation inside the
  provider, and do not thread a range through provider-side helper functions. If a symbol's
  declaration range differs from the default (`TextRange(0, sourceElement.textLength)`) — e.g. a
  symbol anchored to a whole file with no real name-identifier token to point at — override
  `textRangeInSourceElement` **on that symbol class**, not in the provider: the symbol represents
  itself, the provider only knows which symbol to build. See GDScript's
  `GdPsiPolySymbolDeclarationProvider`/`GdPsiResourceClassSymbol` for the worked example (the latter
  overrides `textRangeInSourceElement` to `TextRange.EMPTY_RANGE` since a whole-file declaration has
  no caret-anchorable position). Reach for `PolySymbolDeclaredInPsi` first; it doesn't require a
  legacy PSI-reference mechanism to exist.
- **`PsiLinkedPolySymbol`** (`community/platform/polySymbols/shared/src/com/intellij/polySymbols/search/PsiLinkedPolySymbol.kt`)
  + registering `polySymbols.psiLinkedSymbol host="..."` — **a bridge, not a general shortcut.**
  Its own doc comment says exactly this: *"serves as a bridge between Symbol-based functionality
  and the old PSI-based functionality."* Implementing it makes usage-search/rename **bidirectional**
  with the raw `linkedElement`: a reference resolving to the `PsiLinkedPolySymbol` is treated as a
  usage of `linkedElement` and vice versa. Reach for this specifically when a language still runs a
  legacy `PsiReferenceContributor`/PSI-based resolve mechanism side by side with a PolySymbols
  integration and hasn't (or can't yet) migrate it away — i.e. exactly the "additive, not
  authoritative" situation described in the [main skill](../SKILL.md), and exactly why GDScript's
  `GdPsiPolySymbol` implements it (see [case-studies.md](case-studies.md#gdscript)). If you're
  building a symbol kind with no legacy PSI-resolve counterpart to bridge to, use
  `PolySymbolDeclaredInPsi` instead. **Do not** override `renameTarget`/`searchTarget` on a
  `PsiLinkedPolySymbol` — the framework handles those from the linked element. Pair it with a
  `PsiLinkedPolySymbolProvider` for the reverse element→symbol lookup (see below).
- **Hand-written `PolySymbolDeclarationProvider`**, with no `PolySymbolDeclaredInPsi`/
  `PsiLinkedPolySymbol` involved — for symbols with no real backing `PsiElement` at all, e.g. a
  synthetic SDK/engine symbol whose only PSI representation is a lazily-generated file created on
  demand for navigation (GDScript's `GdSdkPolySymbolDeclarationProvider` is the concrete example —
  it only fires inside that synthetic file, closing the "element → symbol" loop the platform can't
  discover on its own because the file didn't exist until `getNavigationTargets` created it).

Whichever path a symbol uses to declare itself, consumers reading its data afterward should still
never cast down to the concrete class to get at it — see
[SKILL.md#consumer-code-must-not-cast-to-a-concrete-symbol-class](../SKILL.md#consumer-code-must-not-cast-to-a-concrete-symbol-class).
A `@PolySymbol.Property`-annotated member is the equivalent, cast-free way to expose exactly the
kind/backing-specific data a declaration-construction detail like `textRangeInSourceElement` doesn't
already cover generically.

## References — `PsiPolySymbolReferenceProvider`

```kotlin
interface PsiPolySymbolReferenceProvider<T : PsiExternalReferenceHost> {
  fun getReferencedSymbol(psiElement: T): PolySymbol? = null
  fun getReferencedSymbolNameOffset(psiElement: T): Int = 0
  fun getOffsetsToReferencedSymbols(psiElement: T): Map<Int, PolySymbol> = ...   // multiple refs in one element
  fun canReference(target: Symbol): Boolean = true   // optimize usage search: bail out before an expensive resolve
  fun shouldShowProblems(element: T): Boolean = true
}
```

Register per host-element type at EP `com.intellij.polySymbols.psiReferenceProvider`
(`hostElementClass`/`hostLanguage`/`implementationClass`). Implement `getReferencedSymbol` for the
single-reference case; `getReferencedSymbolNameOffset` when the reference sits at an offset inside
the element (e.g. inside a string literal); `getOffsetsToReferencedSymbols` for multiple
non-pattern-expressible references in one element. Internally these almost always call
`PolySymbolQueryExecutorFactory.create(psiElement).nameMatchQuery(kind, text).run().firstOrNull()`
— qualifier/dotted-path resolution is typically delegated to the *scope* layer (via `queryScope`
chaining above), not handled inside the reference provider itself.

`canReference(target)` is a usage-search optimization: return `false` early if this provider could
never possibly reference the given symbol, before the platform builds expensive cache keys or
attempts a resolve. Use with care — it's often hard to prove a symbol with a pattern *can't* match.

## References — own references (`PolySymbolOwnReferences`)

The alternative to `PsiPolySymbolReferenceProvider`, not a feature of it. Own references are "known
by the element, part of the language" (per `PsiExternalReferenceHost`'s own javadoc) — a language's
own canonical resolve, meant to fully replace a legacy `PsiReferenceContributor`-style mechanism.
External references (`PsiPolySymbolReferenceProvider`, above) are for a *different* plugin/language
layering a reference onto a host that doesn't know about it — e.g. a filename string literal
referenced by unrelated framework support.

`PsiElement.getOwnReferences(): Collection<PsiSymbolReference>` is a default method on `PsiElement`
itself (`community/platform/core-api/src/com/intellij/psi/PsiElement.java`, defaults to empty) — every
PSI element already has it and can override it directly. **Building the result via the
`polySymbolOwnReferences` DSL, however, requires the host element's own type to implement
`PolySymbolOwnReferenceHost`** (`community/platform/polySymbols/shared/src/com/intellij/polySymbols/references/PolySymbolOwnReferenceHost.kt`),
a marker interface extending `PsiElement`:

```kotlin
interface PolySymbolOwnReferenceHost : PsiElement

fun polySymbolOwnReferences(element: PolySymbolOwnReferenceHost, configure: PolySymbolOwnReferencesBuilder.() -> Unit): List<PolySymbolReference>

interface PolySymbolOwnReferencesBuilder {
  fun resolveFromNameMatchQuery(kind: PolySymbolKind, name: String)
  fun resolveFromNameMatchQuery(kind: PolySymbolKind, name: String, filter: (PolySymbol) -> Boolean)
  fun resolveFromNameMatchQuery(kind: PolySymbolKind, name: String, textRangeInElement: TextRange)
  fun resolveFromNameMatchQuery(kind: PolySymbolKind, name: String, textRangeInElement: TextRange, filter: (PolySymbol) -> Boolean)
  fun reference(textRangeInElement: TextRange, kind: PolySymbolKind, resolver: () -> List<PolySymbol>)
}
```
(`community/platform/polySymbols/backend/src/com/intellij/polySymbols/references/PolySymbolOwnReferences.kt`)
`polySymbolOwnReferences(element, ...)` won't compile against a plain `PsiElement`-typed host — make
the PSI element's own interface extend `PolySymbolOwnReferenceHost`, then override `getOwnReferences()`
on the impl class and return the DSL result straight from it:
```kotlin
interface MyRefElement : PolySymbolOwnReferenceHost   // was `: PsiElement`

abstract class MyRefElementImpl(node: ASTNode) : ASTWrapperPsiElement(node), MyRefElement {
  override fun getOwnReferences(): Collection<PsiSymbolReference> =
    polySymbolOwnReferences(this) {
      resolveFromNameMatchQuery(MY_KIND, text)   // or the raw reference(range, kind) { ... } form
    }
}
```
This isn't just a compile-time formality — see
[the annotator-gating note below](#polysymbolhighlightingannotator-only-processes-marked-hosts) for why
skipping the marker interface means the override is never actually reached by highlighting/diagnostics.
GDScript's `GdRefElement` and Tscn's `TscnNamedElement` are the worked examples of adding this marker to
an existing element interface.

`resolveFromNameMatchQuery` is a convenience wrapper around
`PolySymbolQueryExecutorFactory.create(element, true).nameMatchQuery(kind, name).run()`, optionally
`.filter`ed; reach for the lower-level `reference(range, kind, resolver)` when the resolve logic is
more than a single name-match query (multiple candidate kinds, special-cased tokens, etc. — see
GDScript's `GdRefIdRefImpl`, which branches on the token text before falling back to a name-match
query+filter, all inside one `reference(...)` call).

**Do not implement both mechanisms for the same element.** Per
`PsiSymbolReferenceServiceImpl.getReferences()`, own references — once non-empty — are used *instead
of* external ones for resolve/search/rename, so a `PsiPolySymbolReferenceProvider` registered for a
host that also overrides `getOwnReferences()` is dead code, not a supplement. (An older `iteration`
of this API had you implement a now-deleted `PolySymbolOwnReferencesHost` interface — plural
"References" — instead of overriding `getOwnReferences()` directly; if you see that name in old
code/docs, it's stale, the direct-override form above is current. Don't confuse it with the
similarly-named but current `PolySymbolOwnReferenceHost` — singular "Reference" — described above,
which is the marker interface the `polySymbolOwnReferences` DSL's `element` parameter requires.)

### PolySymbolHighlightingAnnotator only processes marked hosts

`PolySymbolHighlightingAnnotator.annotate()` gates its *entire* body — reference-problem annotation,
own/external reference resolution for symbol-kind highlighting, **and** declaration highlighting via
`PolySymbolDeclarationProvider.getAllDeclarations(element, -1)` — behind a single check:
`element is PsiExternalReferenceHost || element is PolySymbolOwnReferenceHost`. Before this check was
added (WEB-78948), the annotator ran that whole body — including a declaration-provider lookup and a
reference-service call — unconditionally for *every* `PsiElement` in a file, which was a real
performance regression on large files.

Practical consequence: a PSI element that declares a `PolySymbol` (via `PolySymbolDeclaredInPsi`/a
`PolySymbolDeclarationProvider`) or resolves one (via own or external references) must implement
`PsiExternalReferenceHost` or `PolySymbolOwnReferenceHost` for this annotator to look at it at all.
Implementing neither means silently getting no highlighting and no reference-problem diagnostics from
`PolySymbolHighlightingAnnotator`, even if the declaration/reference wiring itself is otherwise
correct — there's no separate opt-in, this `is` check is the only gate. See also
[the `PolySymbolHighlightingCustomizer` section](#polysymbolhighlightingcustomizer) below for what the
annotator does once it decides to process an element.

**Hard constraint: the resolved symbol's `name` must equal the referencing element's text at the
given range, exactly.** `PolySymbolOwnReference.resolveReference()`/`getProblems()` asserts
`symbol.name == text` and separately `.filter { it.name == text }` after
`unwrapMatchedSymbols()` — own references only support "this exact text resolves to a symbol with
this exact name," not an aliased/renamed match. This bites whenever a query is resolved *by* one
piece of text to a symbol whose *own* declared name is different — e.g. resolving `ClassName.new(...)`'s
`new` token to the class's `_init` constructor symbol, or resolving a resource-path string
(`extends "res://base.gd"`) to the target file's differently-named `class_name`-declared class. Two
ways this can go wrong, and the one that actually works:
- **Wrong: `PolySymbol.withMatchedName(text)`.** This wraps the symbol in a `PolySymbolMatch`, and
  `unwrapMatchedSymbols()` recurses *through* `PolySymbolMatch` wrapping down to the real, wrongly-named
  leaf symbol — the alias name never survives to the final filter.
- **Right: a `PolySymbolDelegate<T>` that overrides `name`.** A delegate is not a `PolySymbolMatch`, so
  `unwrapMatchedSymbols()` treats it as a leaf and its overridden name survives. The platform now has a
  shared, reusable implementation of this: `PolySymbol.withName(name: String): PolySymbolDelegate<PolySymbol>`
  (`community/platform/polySymbols/shared/src/com/intellij/polySymbols/utils/PolySymbolUtils.kt`, backed by a
  private `AliasedPolySymbol` delegate, `renameTarget = null`) — apply the wrapping *in the query scope*
  that resolves the mismatched name (e.g. Angular's `Angular2BlockReferenceProvider.getReferencedSymbol`
  aliasing a canonicalized, whitespace-collapsed block name like `else if` back onto whatever spacing
  variant was actually typed; GDScript's `gdPsiResourceClassesPolySymbolScope`'s
  `referencingResourceClassSymbol` helper does the same aliasing one layer deeper, *inside* a
  `PolySymbolMatch` nameSegment, because that scope also has a **kind** mismatch to fix at the same
  time - see the `PolySymbolScope` section's note on kind-consistency above), not in the
  reference/own-reference call site, so every consumer of that
  scope (own references, completion, etc.) sees a consistently-named symbol. (GDScript previously had
  its own bespoke `GdAliasedNameSymbol` for this; it has been migrated onto the shared
  `withName`/`AliasedPolySymbol` utility, so if you see `GdAliasedNameSymbol` referenced elsewhere,
  that's stale.) `PolySymbolDelegate.unwrapAllDelegates()`
  recovers the real symbol for production code that
  needs it (`GdSymbolResolverUtil.resolveSymbolReferences()` calls this centrally); test helpers that
  call the platform's raw `resolveSymbolReference()`/`multiResolveSymbolReference()` do **not** unwrap
  delegates automatically, so an assertion like `assertInstanceOf(resolved, RealSymbolClass::class.java)`
  needs its own `.unwrapAllDelegates()` call first if the resolve target may be delegate-wrapped.

**Unresolved matches are handled for you, correctly, by the builder** — if `resolver()`/the name-match
query returns nothing, `getProblems()` synthesizes a `PolySymbolMatch` with `MatchProblem.UNKNOWN_SYMBOL`
and, critically, `symbolKinds = setOf(kind)` set correctly. (The older, still-existing
`PsiPolySymbolReferenceProvider.unresolvedSymbol(kind, name)` static helper — meant for hand-rolled
*external*-reference unresolved matches — does **not** set `symbolKinds`, which silently defeats
`polySymbols.inspectionToolMapping`-based suppression for anyone who copies its shape into an
own-reference `resolver()`; don't hand-roll this for own references, let the builder's own fallback
handle it.) This means: an own-reference-only host with no matches for some text is *not* silent —
the platform's generic annotator reports a hardcoded `WARNING`-severity "Unrecognized {kind}" for it,
independent of and *in addition to* any hand-written annotator your language already has for
"reference not found." If your language has its own tolerant/hand-written diagnostic for this kind
(GDScript's `GdRefIdAnnotator`, see below), register a `polySymbols.inspectionToolMapping` pointing at
a disabled-by-default `LocalInspectionTool` to suppress the generic one — see GDScript's
`GdUnrecognizedIdentifierInspection` for the worked example (one inert inspection + one
`inspectionToolMapping` entry per symbol kind that needs it). Do this **per kind** — GDScript
initially only mapped `qualifiable-symbol` (its `GdRefIdRef` kind) and missed `type-hint`
(`GdTypeHintRef`'s kind), which surfaced as spurious "Unrecognized name" warnings on type hints in
SDK-less test fixtures once the builder started stamping `symbolKinds` correctly. Conversely, if a
kind has **no** existing tolerant diagnostic at all, the generic warning may be the *only* signal
your language gives users for that mistake — consider whether suppressing it is actually wanted
before mapping it away, versus updating test fixtures/gold files to expect the (now correctly
surfaced) diagnostic.

**Generic find-usages/rename (`PolySymbolUsageSearcher`) sees own references without any extra
marker.** Own references are checked via plain `getReferences()`, which merges own+external
regardless of host type — the searcher's word-search walk-up calls this whenever
`element is PsiExternalReferenceHost || element.ownReferences.isNotEmpty()`, so an own-references-only
host (no external provider at all) participates in generic find-usages/rename automatically. (Older
guidance said to add the zero-method `PsiExternalReferenceHost` marker purely to satisfy this
searcher; that workaround is no longer necessary — the searcher now checks own references directly.)

**This does not mean "full automatic highlighting with no extra work," though — two corrections to a
common misreading:** (1) `PolySymbolHighlightingAnnotator` picks up highlighting from **either**
own-references **or** EP-provided (`PsiExternalReferenceHost`) references — own-references is not
the exclusive source, it's one of two equally-supported paths, and it's also the *only* condition the
annotator checks before running at all (see
[the annotator-gating note above](#polysymbolhighlightingannotator-only-processes-marked-hosts): no
`PolySymbolOwnReferenceHost`/`PsiExternalReferenceHost` means the annotator skips the element
entirely, not just the highlighting). (2) Neither path produces *any* actual
color by itself. Confirmed by reading the annotator's attribute-lookup chain directly
(`PolySymbolHighlightingAnnotator.highlightSymbols()`): for every resolved symbol it tries, in order,
`PolySymbolHighlightingCustomizer.getSymbolTextAttributes(host, symbol, level)`, then
`symbol[TextAttributesKeyProperty]`, then `PolySymbolHighlightingCustomizer.getTextAttributesFor(kind)`
— all three return `null` unless something registers a customizer or sets a per-symbol property. With
nothing registered, a fully-working own/external reference resolves and is find-usages/rename-able,
but renders with zero color. Overriding `getOwnReferences()` gets you the *mechanism* (a hook the
annotator will call into); a [`PolySymbolHighlightingCustomizer`](#polysymbolhighlightingcustomizer)
is what actually supplies the colors.

## PolySymbolHighlightingCustomizer

```kotlin
interface PolySymbolHighlightingCustomizer {
  fun getSymbolKindTextAttributes(kind: PolySymbolKind): TextAttributesKey? = null
  fun getDefaultHostClassTextAttributes(): Map<Class<out PsiElement>, TextAttributesKey> = emptyMap()
  fun getSymbolTextAttributes(host: PsiElement, symbol: PolySymbol, level: Int): TextAttributesKey? = null
}
```

Register at EP `com.intellij.polySymbols.highlightingCustomizer`
(`community/platform/polySymbols/backend/src/com/intellij/polySymbols/highlighting/PolySymbolHighlightingCustomizer.kt`).
All three methods default to "no opinion" (`null`/empty map) — a customizer only needs to implement
the one(s) it actually has an answer for. Multiple registered customizers compose **first-non-null-wins**,
in EP registration order, so `order="before ..."` matters when more than one customizer could answer
for the same kind/symbol — Angular registers `order="before js, before html"` so its own coloring for
Angular-specific symbol kinds takes precedence over the generic JS/HTML customizers that would
otherwise also match.

Two real shapes:
- **Kind-only**: CSS's customizer just maps `PolySymbolKind` → `TextAttributesKey` via
  `getSymbolKindTextAttributes` — no need to inspect the concrete symbol.
- **Symbol-aware**: override `getSymbolTextAttributes(host, symbol, level)` when the color depends on
  something the kind alone can't express — a modifier (static vs. instance), which class declared it
  (user code vs. SDK/builtin), or the host's own syntax (is this identifier followed by a call).
  JS's and GDScript's customizers (`GdPolySymbolHighlightingCustomizer`) are both this shape.

**The `symbol` passed to `getSymbolTextAttributes` is whatever the query/reference machinery
produced — usually the raw, unwrapped `nameMatchQuery` result, not necessarily the real underlying
symbol.** Confirmed by reading `PolySymbolHighlightingAnnotator.highlightSymbols()`: it passes
`nameSegment.symbols` entries straight through. For a language whose own-references go through
`fromNameMatchQuery`-style filtering, that's the same `PolySymbolMatchBase` wrapper whose own `.kind`
reports the *query's* composite kind, not the real symbol's — unwrap first
(`symbol.unwrapMatchedSymbols().firstOrNull()`) before reading `.kind`/`.modifiers`/anything else
kind-specific, or the customizer will silently return `null`/a wrong answer for almost every symbol
once it's wired in as the real coloring path (not a niche fallback). GDScript's
`GdPolySymbolHighlightingCustomizer` hit exactly this while migrating off a legacy annotator: a
mechanical transplant of the old (correct, because it ran *after* a classic-PSI-resolve success)
`when (symbol.kind)` coloring logic silently rendered almost everything as a generic fallback color
once it became the primary path, because the raw query result it now received had a useless `.kind`.

**No platform hook exists for unresolved-reference diagnostics or resolution-dependent checks** —
worth knowing explicitly rather than assuming a customizer/EP covers it. The only built-in mechanism
is mechanical: a `PsiPolySymbolReferenceProvider`/own-reference can return
`PsiPolySymbolReferenceProvider.unresolvedSymbol(kind, name)` instead of `null`, which the annotator
turns into a hardcoded `WARNING`-severity "unrecognized identifier" annotation — optionally remapped
to a real, user-configurable inspection via EP `com.intellij.polySymbols.inspectionToolMapping`
(`PolySymbolInspectionToolMappingEP`; Vue's `VueUnrecognizedSlotInspection` is the worked example).
There is **no** hook for: domain-specific tolerance logic that should suppress "unresolved" for
certain shapes (e.g. GDScript tolerates unresolved members on a `Variant`/`Node`-typed qualifier), or
a diagnostic that depends on resolution *succeeding* to a particular kind (GDScript's "SDK builtin
type with a constructor can't be assigned to a variable" check — that only makes sense once you know
what the reference resolved *to*). Both stay hand-written `Annotator`s that resolve via the
PolySymbols APIs (`element.getOwnReferences()`/a `resolveSymbolReference()`-style helper) and run
their own checks on the result — see GDScript's `GdRefIdAnnotator` for the worked example of an
annotator that does exactly this and nothing else (coloring is fully delegated to the customizer
above).

**Testing:** see the "Highlighting" recipe in [testing.md](testing.md) - use
`doHighlightingTest(checkSymbolNames = true)`, not a direct `getSymbolTextAttributes()` call from test
code.

## Completion — `PolySymbolsCompletionProviderBase`

```kotlin
abstract class PolySymbolsCompletionProviderBase<T : PsiElement> : CompletionProvider<CompletionParameters>() {
  abstract fun getContext(position: PsiElement): T?
  abstract fun addCompletions(parameters, result, position, name, queryExecutor, context: T)
}
```

Register an ordinary `completion.contributor` whose provider extends this base class. It handles
offset/prefix bookkeeping (including injected-document offset translation) and calls your
`addCompletions`, which typically calls the companion helper
`processCompletionQueryResults(queryExecutor, result, kind, name, position, location, ...)` — which
itself runs `queryExecutor.codeCompletionQuery(kind, name, position).run()` and converts results
into `LookupElement`s, deduplicating and restarting completion on prefix changes for
`completeAfterInsert` items (multistaged completion, see [patterns.md](patterns.md)).

## Lighting up search / rename / navigation / documentation

`PolySymbol` already wires these through overridable properties/methods with sensible defaults —
you do **not** need to hand-roll `SearchTarget`/`RenameTarget` unless you need behavior the default
doesn't provide:

```kotlin
val searchTarget: PolySymbolSearchTarget? get() = null       // usually PolySymbolSearchTarget.create(...)
val renameTarget: PolySymbolRenameTarget? get() = null       // usually PolySymbolRenameTarget.create(...)
fun getDocumentationTarget(location: PsiElement?): DocumentationTarget? = null   // usually PolySymbolDocumentationTarget.create(...)
override fun getNavigationTargets(project: Project): Collection<NavigationTarget> = emptyList()
```

**`PsiLinkedPolySymbolProvider`** (EP `com.intellij.polySymbols.psiLinkedSymbolProvider`,
`getSymbols(element: PsiElement): List<PsiLinkedPolySymbol>`) is the reverse lookup: element → the
symbol(s) it backs. You need this specifically when Find Usages/Rename is invoked **from the raw
PSI declaration** rather than from an already-resolved symbol reference — e.g. right-clicking an
`@Input() foo` field in a `.ts` file. Generic `ReferencesSearch` only has a bare `PsiElement`; without
a `PsiLinkedPolySymbolProvider` to recover the `PolySymbol`, the search falls back to a literal-name
text search and misses every usage written under an aliased/converted name (Angular's
`Angular2PsiLinkedPolySymbolProvider` is the worked example — see [case-studies.md](case-studies.md#angular)).

## PolySymbolQueryResultsCustomizer

```kotlin
interface PolySymbolQueryResultsCustomizer {
  fun apply(matches: List<PolySymbol>, strict: Boolean, qualifiedName: PolySymbolQualifiedName): List<PolySymbol>
  fun apply(item: PolySymbolCodeCompletionItem, kind: PolySymbolKind): PolySymbolCodeCompletionItem?
}
```

Register a `PolySymbolQueryResultsCustomizerFactory` at EP
`com.intellij.polySymbols.queryResultsCustomizerFactory`. This is the general "post-filter or remap
whatever the query returned" hook — e.g. Angular Forms uses it to wrap resolved
`formControlName`/`formGroupName`/`formArrayName` attribute symbols so their *value* is forced to
resolve as a `FormGroup`-key symbol reference instead of a free string (see
[case-studies.md](case-studies.md#angular)). One instance is created per query-executor build, via
`PolySymbolQueryResultsCustomizerFactory.create(location, context)` — it's context/location-scoped
and can change *which* symbols resolve or complete, not just how they render.

## PolySymbolCodeCompletionItemCustomizer

```kotlin
interface PolySymbolCodeCompletionItemCustomizer {
  fun customize(item: PolySymbolCodeCompletionItem, context: PolyContext, kind: PolySymbolKind, location: PsiElement): PolySymbolCodeCompletionItem?
}
```

Register at EP `com.intellij.polySymbols.codeCompletionItemCustomizer`
(`community/platform/polySymbols/backend/src/com/intellij/polySymbols/completion/PolySymbolCodeCompletionItemCustomizer.kt`).
**Global, unscoped hook** — every registered customizer runs, in registration order, for every
completion item from every language/framework
(`PolySymbolsCompletionProviderBase.processPolySymbolCodeCompletionItems`, right after a scope's
`getCodeCompletions()` — custom or the `getSymbols()`-derived platform default — has already
produced the item). Each implementation must self-gate, typically on
`item.symbol?.namespace`/`item.symbol is SomeBaseSymbolClass` (CSS's
`CssImplCodeCompletionItemCustomizer`, GDScript's `GdPolySymbolCodeCompletionItemCustomizer`) or on
`context.framework` (Angular's `Angular2CodeCompletionItemCustomizer`) — returning the item
unchanged, or `null` to drop it, when it doesn't apply.

**Not the same thing as [`PolySymbolQueryResultsCustomizer`](#polysymbolqueryresultscustomizer)
above**: that's the heavier, per-query-executor-build mechanism used for *semantic remapping* of
both resolve matches and completion items. `PolySymbolCodeCompletionItemCustomizer` is purely
presentational — it only ever adjusts a completion item's rendering
(`icon`/`priority`/`tailText`/`typeText`/etc.) after the symbol set is already final; it cannot
change *which* symbols are offered. Prefer this one whenever the goal is "make completion items for
symbols of kind X look right," not "change what X resolves to."
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall