# Refactoring Annotation into a Sealed Hierarchy

This document outlines the structural refactoring of `Annotation` into a sealed hierarchy separating parsed (syntactic) representations from resolved (semantic) representations.

In the current AST, `Annotation` is a single concrete node type that attempts to model multiple distinct semantic constructs (constructor invocations, constant variable references, static field getters). Furthermore, its parsed version contains `Identifier` nodes, which are `Expression`s. This forces purely syntactic name parts to participate in expression-oriented processing even when they are not expressions themselves.

By moving to a sealed hierarchy, we completely separate the un-resolved syntactic shapes (using raw tokens to avoid dangling expressions) from the fully resolved semantic shapes.

## 1. Current State (Legacy Design)

Currently, an `Annotation` (e.g., `@override` or `@Foo(1)`) is parsed as an `AnnotationImpl`. It holds its name as an `Identifier` (either `SimpleIdentifier` or `PrefixedIdentifier`) and relies on nullable fields to accommodate its various shapes.

### Legacy Hierarchy

*   **`Annotation` (Legacy):**
    ```dart
    abstract final class Annotation implements AstNode {
      Token get atSign;
      Identifier get name; // Expression!
      TypeArgumentList? get typeArguments;
      Token? get period;
      SimpleIdentifier? get constructorName; // Expression!
      ArgumentList? get arguments;
      
      Element? get element;
      ElementAnnotation? get elementAnnotation;
    }
    ```

## 2. New Design (Target State)

The new design makes **`Annotation`** a sealed interface and introduces two distinct phases: **Parsed** and **Resolved**.

1.  **Parsed Phase**: Generated by `AstBuilder`, these nodes hold raw tokens and structural pairs instead of `Identifier` expressions. The parser enforces that any annotation with type arguments receives synthetic `()` if missing, cleanly dividing the parsed space into two non-overlapping groups:
    *   `ParsedAnnotationConstant`: No arguments, no type arguments. Modeled as a token chain.
    *   `ParsedAnnotationInvocation`: With arguments. Modeled as a constructor invocation.
2.  **Resolved Phase**: Generated during `AnnotationResolver` execution by rewriting the parsed node in the parent's `metadata` list into a dedicated resolved AST shape. The rewritten node still carries the resolution-specific syntax needed by downstream consumers, but no longer exposes the vague parsed representation. This phase must represent both successful semantic resolution and invalid/unresolved outcomes, because annotations remain in the AST even when resolution reports errors.

### Detailed Structure

*   **`Annotation` (Sealed Base):**
    ```dart
    sealed class Annotation implements AstNode {
      Token get atSign;
    }
    ```

#### The Parsed Phase

*   **`ParsedAnnotation` (Parsed Base):**
    ```dart
    abstract interface class ParsedAnnotation implements Annotation {
      // Common syntactic access if necessary, but strictly no elements
    }
    ```

*   **`ParsedAnnotationConstant` (No Arguments):**
    This category is further sealed by arity to guarantee that periods and identifiers are always paired correctly without nullable fields.

    ```dart
    sealed class ParsedAnnotationConstant implements ParsedAnnotation {}

    abstract interface class ParsedAnnotationConstant1 implements ParsedAnnotationConstant {
      Token get name; // e.g., @override
    }

    abstract interface class ParsedAnnotationConstant2 implements ParsedAnnotationConstant {
      Token get name1;   // e.g., @prefix OR @Class
      Token get period;
      Token get name2;   // e.g., constant OR staticField
    }

    abstract interface class ParsedAnnotationConstant3 implements ParsedAnnotationConstant {
      Token get name1;   // e.g., @prefix
      Token get period1;
      Token get name2;   // e.g., Class
      Token get period2;
      Token get name3;   // e.g., staticField
    }
    ```

*   **`ParsedAnnotationInvocation` (With Arguments):**
    ```dart
    abstract interface class ParsedAnnotationInvocation implements ParsedAnnotation {
      ParsedAnnotationInvocationTarget get target;
      TypeArgumentList? get typeArguments;
      ParsedAnnotationConstructorSelector? get constructorSelector;
      ArgumentList get arguments;
    }

    sealed class ParsedAnnotationInvocationTarget implements AstNode {}

    abstract interface class ParsedAnnotationInvocationTarget1
        implements ParsedAnnotationInvocationTarget {
      Token get name;
    }

    abstract interface class ParsedAnnotationInvocationTarget2
        implements ParsedAnnotationInvocationTarget {
      Token get name1;
      Token get period;
      Token get name2;
    }

    abstract interface class ParsedAnnotationConstructorSelector
        implements AstNode {
      Token get period;
      Token get name;
    }
    ```

#### The Resolved Phase

The resolved hierarchy should distinguish four concerns that the legacy node conflates:

1.  The annotation has been through binding/resolution.
2.  The annotation resolved successfully or failed.
3.  If successful, what semantic kind it resolved to.
4.  What syntax must still be preserved after AST rewriting.

It should also follow the same principle as `ImportPrefixReference`: child syntax nodes can carry best-effort binding information, but they must not promise exact semantic element kinds in invalid code.

That suggests the following shape:

*   **`ResolvedAnnotation` (Post-Rewrite Base):**
    ```dart
    sealed class ResolvedAnnotation implements Annotation {
      ElementAnnotation get elementAnnotation;
    }
    ```

*   **`ResolvedValidAnnotation` (Successful Resolution):**
    ```dart
    sealed class ResolvedValidAnnotation implements ResolvedAnnotation {
      Element get element; // Non-nullable, successfully resolved
    }
    ```

*   **Resolved child syntax nodes (best-effort binding):**
    ```dart
    abstract interface class AnnotationImportPrefixReference implements AstNode {
      Token get name;
      Token get period;

      /// Usually a PrefixElement, but can be anything in invalid code.
      Element? get element;
    }

    abstract interface class AnnotationTypeReference implements AstNode {
      Token get name;

      /// Usually an InterfaceElement or TypeAliasElement, but can be anything
      /// in invalid code.
      Element? get element;
    }

    abstract interface class AnnotationNameReference implements AstNode {
      Token get name;

      /// Best-effort binding for this referenced name.
      Element? get element;
    }

    abstract interface class AnnotationSelector implements AstNode {
      Token get period;
      Token get name;

      /// Best-effort binding for the selected member/constructor name.
      Element? get element;
    }
    ```

*   **`ConstructorInvocationAnnotation`:**
    ```dart
    abstract interface class ConstructorInvocationAnnotation
        implements ResolvedValidAnnotation {
      @override
      ConstructorElement get element;

      AnnotationImportPrefixReference? get importPrefix;
      AnnotationTypeReference get type;
      TypeArgumentList? get typeArguments;
      AnnotationSelector? get constructorSelector;

      InterfaceType get invokedType;
      ArgumentList get arguments;
    }
    ```

*   **`ConstantReferenceAnnotation`:**
    ```dart
    abstract interface class ConstantReferenceAnnotation
        implements ResolvedValidAnnotation {
      @override
      PropertyAccessorElement get element;

      AnnotationImportPrefixReference? get importPrefix;
      AnnotationTypeReference? get enclosingType;
      AnnotationNameReference get name;
    }
    ```

*   **`InvalidAnnotation`:**
    ```dart
    abstract interface class InvalidAnnotation implements ResolvedAnnotation {
      /// Preserved rewritten syntax, with only best-effort binding.
      AnnotationImportPrefixReference? get importPrefix;
      AnnotationTypeReference? get type;
      AnnotationNameReference? get name;
      TypeArgumentList? get typeArguments;
      AnnotationSelector? get selector;
      ArgumentList? get arguments;

      /// Best-effort binding of the whole annotation, if any.
      Element? get element;
    }
    ```

The key point is that resolution rewrites the AST into a more precise node, but does not discard syntax. Each resolved node carries the syntax relevant to its semantic shape, and the child syntax nodes carry only best-effort binding information. For example, constructor-invocation annotations retain the import prefix (if any), invoked type, optional type arguments, optional constructor selector, and argument list; constant-reference annotations retain whether the resolved reference was top-level, prefixed top-level, static, or prefixed static.

This is intentionally stronger than the parsed phase but still does not force invalid code into a misleading semantic taxonomy. Successful resolution gets strong root-node guarantees; invalid resolution preserves a syntax-first rewritten shape with partial bindings.

---

## 3. Advantages

1.  **Semantic Accuracy & Type Safety:** A successfully resolved annotation guarantees at compile time what semantic kind it targets, while invalid annotations remain explicit instead of being encoded through nullable fields.
2.  **Clean AST (No Dangling Expressions):** `ParsedAnnotation` nodes do not hold `Identifier` nodes. This stops syntactic name parts from polluting expression-visiting logic or inference logs.
3.  **Strict Phase Enforcement:** External clients cannot mistakenly assume an un-resolved annotation has semantic meaning, and they also cannot accidentally treat invalid annotations as successful resolutions.
4.  **Immediate Structural Segregation:** The parser's `()` recovery immediately clarifies whether an annotation *aims* to be a constructor invocation or a constant field reference.
5.  **Structured Parsed Invocations:** `ParsedAnnotationInvocation` separates the syntactic target (`A` or `p.A`) from the optional constructor selector (`.named`), instead of flattening both into nullable token fields with mixed semantics.
6.  **Syntax-Preserving Rewriting:** Resolution can rewrite the AST into stronger node shapes without forcing later passes to reach back into parsed nodes to recover source syntax.
7.  **Best-Effort Child Binding:** Resolved child syntax nodes can expose partial binding information like `ImportPrefixReference`, without over-promising exact element kinds in invalid code.

---

## 4. Implementation

This change will be implemented as an **in-place breaking change**.

### Steps

1.  **Define new interfaces** in `lib/dart/ast/ast.dart` and implementations in `lib/src/dart/ast/ast.dart`.
2.  **Update `AstBuilder.endMetadata`** to unpack the temporary `IdentifierImpl` into tokens and push either `ParsedAnnotationConstantImpl` or `ParsedAnnotationInvocationImpl`.
3.  **Update `AnnotationResolver`** to perform the resolution and replace the `ParsedAnnotation` node with the appropriate `ResolvedAnnotationImpl` inside the parent's `metadata` list, preserving the syntax relevant to the resolved shape.
4.  **Migrate internal visitors** and tools (Summary2, search engine, refactoring tools) to the new sealed hierarchy.
