Skip to content

Language server / linter #23

Closed
Closed

Description

@JuroOravec

Language-server and batch-checker support for Citry templates.

Current foundations

  • The parser exposes UTF-8 source spans, scope-level used and introduced variables, slots, and caller-supplied TagRules. It is still fail-fast and the PyO3 boundary still flattens diagnostics to exception strings.
  • Citry 0.3.0 shipped the versioned component catalog, Citry.inspect_component(), Citry.inspect_components(), and citry inspect --json.
  • Project selection currently uses the CLI contract --app module:attribute. A [tool.citry] table is not a current configuration surface.
  • Runtime registry completeness is the authority for component-aware checks. A static scan is partial and must never produce an unknown-component diagnostic from absence alone.

Accepted implementation path

  1. Add a conservative citry check that validates base Citry syntax wherever a template region is definite.
  2. Enable registered-component, input, and slot checks only when the configured app imports and discovery completes. Import failure degrades to syntax-only and is reported once as project status.
  3. Add stable structured diagnostic codes/ranges, expose HtmlAttr.kind, and add a tested UTF-8-byte to host-source to LSP UTF-16 mapper.
  4. Build a thin diagnostics-first pygls server reusing the checker engine.
  5. Add narrow component/attribute/slot completion, catalog hover, lexical loop/fill navigation, component navigation at catalog precision, and document symbols.

Extension-transformed templates and alternate *_lang dialects are reported as unsupported until they provide an authored-source analysis mapping. Exact schema-field navigation waits for additive definition locations or a proven static/runtime join.

The detailed accepted design is tracked in docs/design/ide_integration.md.

Activity

  1. added
    enhancement
    on Jul 1, 2026
  2. JuroOravec commented on Jul 1, 2026

    @JuroOravec
    MemberAuthor

    (Chatgpt export from chatgpt.com/share/68f9fcd9-0bc0-8004-aece-8381111d56f1)

    Python type inference options

    User: Anonymous
    Created:
    Updated:
    Exported: 7/1/2026 12:57:36
    Link: https://chatgpt.com/share/68f9fcd9-0bc0-8004-aece-8381111d56f1

    Prompt:

    I want to build a linter for vscode similar to Vue's vetur. What are the options for inferring types of variables defined in user's python files?

    Response:

    Thought for 11s

    Great project! In Python you’ve basically got three families of ways to figure out types in users’ files. You can mix these depending on how “Vetur-like” you want your linter to feel (fast, incremental, framework-aware).

    1. Where types can come from (sources of truth)
      ===============================================
    • Explicit annotations: def f(x: int) -> str: ..., var: Path, typing.cast, assert isinstance(x, T), reveal_type (dev only).
    • Stub files: .pyi in the project, installed packages with PEP 561 typing, and the global typeshed. Overloads, protocols, generics resolution live here.
    • Docstrings: Google/Numpy/ReST styles → parse into types when no hints exist.
    • Runtime hints mirrored statically: dataclasses, attrs, pydantic fields, TypedDict, NewType, Enum, Literal, Final, Annotated, etc.
    • Type narrowing constructs: isinstance, issubclass, typing.assert_type, if x is None, pattern matching (match/case), guard functions (def is_user(o) -> TypeGuard[User]: ...).
    • Library/provider stubs: Per-library plugins (e.g., pandas, Django) that synthesize better types than raw stubs.
    1. Static inference strategies (without running code)
      =====================================================
    • Name/attribute resolution with a symbol table
      Build scopes (module, class, function, comprehension), bind targets (a=b=c), track imports/aliases, and resolve attributes through MRO/descriptors/dataclass/attrs transformations.
    • Flow-sensitive type inference
      Track variable reassignments across branches/loops; narrow on guards (e.g., if x: → x != None|False|0|"" depending on context).
    • Control-flow graph (CFG) + dataflow
      Construct CFG per function; propagate type constraints forward/backward; compute join/meet of unions at merge points.
    • Constraint solving for generics/overloads
      When calling fn[T](arg), solve for T from argument types and overload signatures (incl. ParamSpec, TypeVarTuple).
    • Literal/value-based refinement
      Track Literal["GET"], integer ranges for slicing/len() == k in narrow cases; refine containers (list[int] flows from append(int)).
    • Protocol/structural typing
      Accept “duck types” by required methods/attrs; combine with @runtime_checkable when available.
    • Partial evaluation of decorators
      Recognize known decorators that transform signatures (@dataclass, @overload, @functools.wraps) and synthesize the resulting type.
    1. Hybrid & dynamic strategies (if you’re willing to run code)
      ==============================================================
    • Import-time introspection (unsafe for general use)
      Import in a sandbox/venv and read __annotations__, dataclass fields, Pydantic models. Fast but risky (side effects).
    • Tracing/probing
      Run tests/scripts under a tracer to collect observed types per location; merge with static types as hints (never as the only truth).
    • Runtime stub generation
      Emit .pyi from observed types and feed back into the static pass. Good for big dynamic frameworks behind stable test suites.
    1. Engines you can leverage (and how)
      =====================================
    • Pyright (TypeScript, very fast, incremental)
      Reuse its analyzer via the Language Server Protocol (LSP) and add custom rules on top; or learn from its approach (file-based incremental graph, fine-grained caching).
    • Mypy (Python, sound-ish on annotated code)
      Use its semantic analyzer/typeshed loader; or call mypy.api programmatically to get types/diags, then add your lint layer.
    • Pyre / pytype (OCaml/C++; aggressive, good for large codebases)
      Heavier setup, great for batch analysis and CFG/dataflow ideas.
    • Jedi / parso (completion-oriented inference)
      Easier to embed for quick symbol/attr inference; weaker on full typing semantics but great for editor UX.
    • Astroid (Pylint’s AST) / LibCST (concrete syntax)
      Excellent for building your own passes; LibCST preserves formatting, which is perfect for code actions/fixes.

    Pragmatic route: run an LSP that wraps Pyright (for speed + correctness on modern typing) and layer:

    • Your lint rules (style, framework conventions, anti-patterns),
    • Docstring type extraction (where annotations are missing),
    • Framework providers (e.g., infer Django Model.objects.filter(...) return types, or pandas DataFrame.groupby chains).
    1. Handling Python’s “fun” bits
      ===============================
    • Dynamic imports / __getattr__ at module level → fall back to Any with opt-in strictness. Provide diagnostics but don’t spam.
    • Metaclasses/descriptors → implement a small MRO/descriptor evaluator so Model.field types are properties, not Any.
    • Star imports and re-exports (__all__) → build export maps; avoid loading the world.
    • Partial stubs → allow per-package pyrightconfig.json/mypy.ini-like config to trust incomplete stubs.
    • Versioned typing → gate features by Python version (e.g., Self, TypeAliasType, PEP 695 generics).
    1. Incremental, Vetur-like UX plan for VS Code
      ==============================================
    1. File watcher + project graph
      • Parse with LibCST (for edits & fix-its).
      • Maintain a dependency graph (imports, from-imports).
    2. Fast precheck
      • Cheap syntax/semantic pass: missing imports, unused vars, unreachable code, shadowed names.
    3. Type pass (incremental)
      • Defer to Pyright (or your engine) for rich types; cache per file + per symbol; re-run only affected nodes.
    4. Lint rules with types
      • e.g., suspicious await on non-coroutines, unsafe except Exception: pass, incorrect TypedDict keys, misuse of Optional, cast that can be avoided, Union not narrowed before attribute access.
    5. Framework providers
      • Register analyzers per library: Django ORM, FastAPI (dependency injection producing types), pandas/NumPy, asyncio.
    6. Fix-its/code actions
      • Insert annotations, add from __future__ import annotations, generate .pyi, add typing.cast, replace list() with list[str] when inferable, add @overload skeletons.
    7. Perf knobs
      • “Open files first” mode, background project indexing, user-tuned strictness, cache to disk.
    1. Accuracy vs. speed trade-offs
      ================================
    • Prefer flow-sensitive inference + stubs over whole-program global inference.
    • Treat unknowns as Any but track provenance (why it became Any) and surface a single actionable note.
    • Cache aggressively; hash per cell of the CFG rather than per file when possible.
    1. Minimal viable path (concrete)
      =================================
    • Start with LibCST for parsing + edits.
    • Embed Pyright (run its server or library) to query types at specific locations (you only need spans → types).
    • Add a docstring-to-type extractor for unannotated functions.
    • Implement 5–10 high-value type-aware lint checks and a couple fix-its.
    • Add one framework provider you care about (Django or pandas) to showcase “smarts”.

    If you tell me your target stack (e.g., Django + pandas) I can sketch the provider interface and a couple of sample rules that query Pyright’s type at a node and emit precise diagnostics/fixes.

    Prompt:

    How would I use pyright? Say I have a function that returns a literal dict with some keys. How could I use pyright to extract the info on the dict that's being returned from that function?

    Response:

    Thought for 29s

    Awesome—there are two practical ways to “ask Pyright what type this dict literal is” from your VS Code linter:


    1. Treat Pyright as a black-box via LSP (easy + stable)
      =======================================================

    Run pyright-langserver and query the type at a file/position. The simplest probe is the Hover request; Pyright returns the inferred type as markdown (exactly what Pylance shows on hover).

    Flow

    1. Start a language client that talks to pyright-langserver --stdio.
    2. Send textDocument/didOpen (and didChange as you edit).
    3. Send textDocument/hover at the span of your dict literal (or the return expression).
    4. Parse the returned markdown to get the type string (e.g., dict[str, int] or a TypedDict name).

    Notes

    • You can also use textDocument/inlayHint to get inferred types for variables/returns.
    • textDocument/typeDefinition is for jumping to definitions, not a good fit here.
    • This approach is robust and version-resilient because it uses the public LSP surface.

    1. Embed Pyright’s analyzer (powerful, but “internal”)
      ======================================================

    Use the pyright-internal npm package and directly ask the type evaluator for the node’s type. This gives you structured access (e.g., recognize if the inferred type is a TypedDict, Dict[Key, Val], union, etc.).

    Sketch (TypeScript, conceptually):

    import { AnalyzerService, createFromRealFileSystem, ParseNodeType } from 'pyright-internal';
    
    const fs = createFromRealFileSystem(false);
    const service = new AnalyzerService('my-probe', fs, /* console? */ undefined);
    
    // Configure search paths, python version, typeCheckingMode, etc.
    service.setOptions({
      venvPath: '...', pythonVersion: '3.12', typeCheckingMode: 'strict',
    });
    
    service.setTrackedFiles(['/<proj>/pkg/mod.py']);  // your file(s)
    service.invalidateAndForceReanalysis(['/<proj>/pkg/mod.py']);
    service.analyze(); // or service.backgroundAnalyze()
    
    const program = service.getProgram()!;
    const source = program.getBoundSourceFile('/<proj>/pkg/mod.py')!;
    const evaluator = program.evaluator!;
    
    // Walk the parse tree to find the return statement’s expression node
    let targetNode: any = undefined;
    source.parseTree.statements.forEach(stmt => {
      // ... descend to function 'def f(...)' and its return statement ...
      // when you hit the dict literal parse node:
      // if (node.nodeType === ParseNodeType.Dictionary) targetNode = node;
    });
    
    // Ask Pyright for the type:
    if (targetNode) {
      const type = evaluator.getType(targetNode); // returns a rich Type object
      // You can now inspect:
      // - if it's a TypedDictType (has key->field map)
      // - if it's a ClassType of dict, with key/value type args
      // - if it’s a union, literal-typed values, etc.
    }
    

    Caveats

    • pyright-internal is not a public API—upgrades can break you. Pin versions, wrap calls, and be ready to update.
    • You must mirror Pyright’s config (search paths, typeshed, pythonVersion) or you’ll see different results than users.

    What Pyright will actually infer for a bare dict literal

    • Bare dict literal in a return position without annotations is usually inferred as dict[key_type, value_type] (e.g., dict[str, int]), not a shape. Pyright does not synthesize a new TypedDict from a literal on its own.
    • You get key-set/shape only when:
      • the expression is assigned to or returned as a variable/return annotated with a TypedDict, or
      • it’s passed to a parameter expecting a specific TypedDict.

    So if you need the exact keys from that function, the most pragmatic pattern is:

    from typing import TypedDict
    
    class UserInfo(TypedDict):
        id: int
        name: str
    
    def get_user() -> UserInfo:
        return {"id": 1, "name": "Ada"}  # Pyright now checks keys & types precisely
    

    Then your probe (LSP hover or internal evaluator) will report UserInfo and you can resolve it to the per-key field map.


    Putting it together in a VS Code linter

    • Fast path (recommended):
      • Parse your file (LibCST/AST) → find the dict literal (or the return expression).
      • Ask Hover at that position via LSP → read the inferred type string.
      • If it’s just dict[str, Any], consider a code action: “Generate TypedDict from literal and annotate return”.
    • Deep path (if you need structure programmatically):
      • Use pyright-internal to get the actual Type object for the node.
      • If it’s a TypedDictType, read its fields.
      • If it’s dict[K,V], you only know K/V, not concrete keys.

    Handy diagnostics / code actions you can build

    1. Suggest TypedDict when returning a dict literal from a public function:
      • Offer: create a TypedDict next to the function and set -> NewTypeName.
    2. Missing keys vs. extra keys (once annotated):
      • Use Pyright’s result to flag extras/missing, with precise spans.
    3. Narrow Any: if values are all literals (int/str/bool) or uniform, offer to add -> dict[str, int] or generate TypedDict.

    If you want, I can sketch a minimal VS Code extension snippet that starts pyright-langserver, sends Hover to a position, and parses the returned type text—so you can wire it into your lint rule.

    Prompt:

    Ok, suppose I use pyright via LSP and it returns a markdown with 'UserInfo'.

    Now let's do something more close to vetur. I guess that it works something like this:

    • it detects the dictionary that's returned from Vue's setup.
      """
      return {
      myVar: abc,
      }
      """
    • it finds js and Vue expressions in template
      """
      {{ myVar.item.name }}
      """
    • to provide type hints inside the template, it may construct a dummy code like so
      """
      // Generated from the returned dict
      var1 = abc;
      // Paste the js expression
      myVar.item.name
      """
    • sends this dummy code to lsp to get errors. Then identifies where the expression starts in the dummy code and original in-template js expression. And adjusted the line number and col. And finally returns the adjusted annotations/errors to the editor.

    Is this how vetur does it? Does it sound correct? Or if vetur does it differently, how do they do it? Lastly, it seems like a workaround, having to construct the dummy code like that. Could we instead simply pass the js expression and context what variables and their types are available?

    Show moreShow less

    Response:

    Thought for 34s

    Short answer: yes—your mental model matches how Vue tools do it. Vetur (and today’s Volar) compile template expressions into a virtual TypeScript file, run the TypeScript language service on that file, then map diagnostics/quick-info back to the original template via a source map. Vetur’s docs say this explicitly: compile → sourcemap → run language features on the virtual TS → map results back. vuejs.github.io Volar generalizes this with first-class “virtual code objects” and a source-map utility. Yarn+1

    So for a Python/Vetur-like linter powered by Pyright over LSP, do the same pattern:

    What Vetur/Volar do (confirmed)

    • Build a virtual TS file that declares the bindings from setup()/data/props, then inlines each template expression as TS code.
    • Run TS Language Service on the virtual file.
    • Source-map every virtual range back to the <template> node ranges so hover/errors/completions line up in the editor. vuejs.github.io+2blog.matsu.io+2

    The Python analogue with Pyright (LSP)

    LSP has no “evaluate this expression under this symbol table” RPC. So you must provide a file (real or virtual) that contains both the context and the expression—exactly like Vetur.

    Pipeline

    1. Extract context from the Python function that returns your dict (e.g., a “setup” function).
      • If the return is annotated as a TypedDict, great—use that. Otherwise, synthesize one from the literal keys you see (optionally offer a code action to generate it in real code later).
    2. Create a virtual Python module in memory (an LSP “opened” document, e.g., py://virtual/<component>/<hash>.py) that declares the bindings visible to the template:
      # --- synthesized context ---
      from typing import TypedDict, Any, Literal, Optional
      class __Ctx(TypedDict):
          myVar: "AbcType"        # or Dict[str, Any] fallback
      __ctx: __Ctx
      # Option A: bind names directly for template sugar
      myVar = __ctx["myVar"]
      # --- paste one expression per line for checking ---
      # @expr_0 start
      __probe_0 = myVar.item.name
      # @expr_0 end
      
      • When you know the precise type of abc (from a prior hover/definition in user code), emit it as AbcType with an import or a forward reference. If not, fall back to Any (and later offer to tighten types).
    3. Send LSP requests against this virtual file:
      • textDocument/publishDiagnostics (by triggering a Pyright re-analysis)
      • textDocument/hover, completion, etc., at offsets of __probe_k.
    4. Map ranges back to the template:
      • Keep a simple source map: for each @expr_k, store the template start/end and the virtual file start offset. Subtract/add to translate positions for all results.
      • This is exactly how Vetur/Volar do it. vuejs.github.io+1

    Why you can’t “just pass an expression + context” to Pyright

    Pyright’s LSP surface doesn’t accept arbitrary environments. It analyzes files in a project graph. That’s why the virtual-file + sourcemap pattern is the standard solution across SFC ecosystems (Vue Vetur/Volar, Svelte, etc.). GitHub

    Practical tips that make this work well

    • Use TypedDicts for shape: Pyright will not invent a shape from a bare dict literal; it infers dict[K, V]. If you want per-key errors and hovers, annotate (or synthesize) a TypedDict for the function’s return.
    • Prefer type names over values in the virtual file: reference real project symbols (imports/forward refs) so Pyright can follow definitions.
    • Keep one virtual file per template and update incrementally when the user edits (only rewrite the changed probes).
    • Cache and debounce: feed edits through a small scheduler so you don’t thrash Pyright while typing.
    • Surface provenance: if a binding was Any in your context, note it in the diagnostic so users understand why a template expr has weak types (and offer a fix: generate TypedDict, add annotation, etc.).

    Minimal end-to-end sketch (VS Code side)

    • Run pyright-langserver via your extension’s language client.
    • On template parse:
      • Build context from the Python “setup” function’s return type (read annotations or synthesize).
      • Generate/didOpen a virtual module containing context + one line per template expression.
      • For each expression, send hover at the virtual offset; translate back using your source map; render the hint in the template.
      • Let diagnostics flow via publishDiagnostics on the virtual file; remap and re-publish them for the template document.

    If you want, I can draft a tiny sample virtual-file generator and the source-range mapper you can drop into a VS Code extension (TypeScript) to prove this out with Pyright LSP.


    Powered by ChatGPT Exporter

  3. JuroOravec commented on Aug 30, 2026

    @JuroOravec
    MemberAuthor

    Implemented. See citry-lsp and VSCode ext

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions