Skip to content

API Reference parrot.knowledge.wiki.languages.astgrep

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.knowledge.wiki.languages.astgrep

View source

Optional ast-grep structural extraction seam for the wiki scanners.

Mirrors :mod:parrot.knowledge.wiki.languages.treesitter: a cached, never-raising seam that hides an optional dependency (ast-grep-py, extra wiki-structural). :func:is_available / :func:supported_language / :func:parse return None/False whenever the package, a language grammar, or a rule file is missing — callers fall back to the existing tree-sitter walker or heuristic tier unconditionally.

Extraction rules are pure data: one YAML file per language under languages/rules/<lang>.yaml, validated into a :class:RuleSet at load time. Anything a rule needs that is not expressible as kind/field/ inside/has data lives in the small, fixed :data:EXTRACTORS table (doc-comment/parent lookups) — implemented once here, never per rule file.

This module never touches the working tree beyond the src string it is given, and it never raises: a pyo3 PanicException (a BaseException, not an Exception) is caught around the one call that can produce it (SgRoot(...)), and every other failure mode degrades to None with at most one log record per (language, rule id) key.

Attribute EXTRACTORS

Type: dict[str, Callable[[SgNode], str]]

Class ImportSpec

One imports[] entry of a language rule file.

Fields:

Field Type Default Description
rule dict[str, Any]

Class RefSpec

One refs[] entry of a language rule file.

Fields:

Field Type Default Description
rel str "calls", "extends", "implements" or "uses".
rule dict[str, Any] ast-grep rule object.
target dict[str, Any] How to extract the reference target text — {"field": ...} or {"each": <kind>} (one ref per descendant of that kind).
scope dict[str, Any] | str | None None Optional {"ancestor": [<kind>, ...]} (the nearest matching ancestor's bare name field becomes src_qualname) or the name of an :data:EXTRACTORS entry that computes src_qualname directly (e.g. "python_call_scope", for a dotted Class.method name the ancestor-dict form cannot produce in one hop).
languages list[str] | None None Optional allow-list of ast-grep languages this ref applies to; None means every language the RuleSet serves (FEAT-609).

Class RuleSet

Validated, cached extraction rules for one language.

Fields:

Field Type Default Description
language str ast-grep language name this file's rules target.
aliases list[str] Other ast-grep language names served by this same file (e.g. typescript.yaml also serves tsx/javascript).
summary str 'none' Name of an :data:EXTRACTORS entry used for the file's summary line.
symbols list[SymbolSpec] Symbol extraction rules.
refs list[RefSpec] Reference extraction rules.
imports list[ImportSpec] Import-statement extraction rules.

Method RuleSet.load

Load and validate languages/rules/<lang>.yaml for lang.

Resolves aliases: a rule file may declare aliases covering other ast-grep language names it also serves (e.g. typescript.yaml also serves javascript/tsx) — every rule file under the package is scanned once for a language/aliases match.

Cached (functools.lru_cache) — call RuleSet.load.cache_clear() to force a reload (tests only; rule files are package data and do not change at runtime).

load(lang: str) -> RuleSet | None

Parameter Type Default Description
lang str ast-grep language name.

Returns: RuleSet | None — The validated :class:RuleSet, or None when no rule file matches lang or the matching file fails validation (in which case exactly one WARNING is logged).

Alias StructuralOutline

Re-exported from parrot.knowledge.wiki.symbols.StructuralOutline.

Alias SymbolKind

Re-exported from parrot.knowledge.wiki.symbols.SymbolKind.

Alias SymbolRecord

Re-exported from parrot.knowledge.wiki.symbols.SymbolRecord.

Alias SymbolRef

Re-exported from parrot.knowledge.wiki.symbols.SymbolRef.

Class SymbolSpec

One symbols[] entry of a language rule file.

Fields:

Field Type Default Description
id str A :class:~parrot.knowledge.wiki.symbols.SymbolKind value ("class", "function", ...).
rule dict[str, Any] ast-grep rule object, evaluated as node.find_all({"rule": rule}).
name dict[str, Any] | None None How to extract the symbol's local name — {"field": ...}, {"path": [...]}, or {"text": true}.
signature dict[str, Any] | None None Optional, same shape as name.
doc str 'none' Name of an :data:EXTRACTORS entry ("none" for no doc).
parent dict[str, Any] | str | None None Either {"ancestor": <kind>, "name": {...}} (structural lookup) or the name of an :data:EXTRACTORS entry that returns the parent qualname directly (e.g. "preceding_package").
exported dict[str, Any] | str | None None "always", "never", {"inside": <kind>} or {"has": <kind>}.
is_async dict[str, Any] | str | None None Same shape family as exported.
depth int | None None Explicit nesting depth; when omitted, defaults to 2 when parent is set, else 1.
qualname_joiner str | None None Separator between parent and name in the computed qualname; when omitted, falls back to the language's entry in _QUALNAME_JOINER (. by default). TASK-2743: PHP needs two different separators in the same file — \ between a namespace and its class, :: between a class and its method — which a single per-language joiner cannot express.
languages list[str] | None None Optional allow-list of the ast-grep languages (the alias actually in use, e.g. "typescript", "tsx") this spec applies to. None means every language the RuleSet serves; otherwise the spec is skipped for the others (FEAT-609).

Function extract

Run the ast-grep structural extraction seam over one file.

extract(src: str, lang: str, rel_path: str, *, max_depth: int = 2) -> StructuralOutline | None

Parameter Type Default Description
src str Full file source text.
lang str ast-grep language name.
rel_path str POSIX path relative to the repository root (stamped onto every produced :class:SymbolRecord).
max_depth int 2 Symbols whose resolved depth exceeds this value are dropped.

Returns: StructuralOutline | None — class:StructuralOutline, or None when ast-grep is unavailable, the language is unsupported, parsing failed, or no rule file matches lang. Never raises.

Function first_docstring

First bare string-literal statement in node's body.

Mirrors the "docstring" convention (a lone string expression as the first statement of a block) for languages that use it.

first_docstring(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Function first_heading_comment

First comment node anywhere at the top level of the file.

first_heading_comment(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Function is_available

Return whether ast-grep-py is importable in this process.

is_available() -> bool

Returns: bool — True when import ast_grep_py succeeds, False otherwise. Never raises.

Function js_call_scope

src_qualname of a JS/TS call: the nearest named enclosing function.

Named declarations (function/method/class) yield their name exactly as the former scope: {ancestor: [...]} did. An arrow/function expression yields the identifier of the TOP-LEVEL const|let NAME = … declaring it (the same declarations the FEAT-609 function rule extracts); any other arrow — an inline callback, a nested local — is skipped and the walk continues outward. Returns "" for a module-level call (TASK-3826 re-attributes those in .svelte files to the component).

js_call_scope(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Function leading_comment

Nearest plain leading comment immediately before node.

leading_comment(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Function leading_comment_exported

Like :func:leading_comment, probing past an export_statement.

Use for TS/JS declarations the walker itself doc-probes through the export wrapper for (class/function/interface/type) — NOT for const (see :func:_first_comment_before_export_aware).

leading_comment_exported(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Function leading_doc_comment

Nearest leading doc comment (/** */, ///) before node.

leading_doc_comment(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Attribute logger

Function module_docstring

First bare string-literal statement at the top of the module.

module_docstring(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Function named_text

Join a $$$VAR metavariable capture, ignoring anonymous nodes.

Anonymous nodes (e.g. the , separators in an argument list) are included in get_multiple_matches captures; only is_named() nodes should appear in rendered output.

named_text(node: SgNode, var: str) -> str

Parameter Type Default Description
node SgNode The matched node the capture was taken from.
var str Metavariable name (without the $$$ prefix).

Returns: str — ", "-joined text of the named captured nodes, or "" when there is no such capture.

Function parse

Parse src as lang into an ast-grep SgRoot, or None.

supported_language() is checked first in every path — the BaseException fence below is defence in depth, not the primary guard, since pyo3 can panic (PanicException, a BaseException, not an Exception) for a handful of inputs the whitelist should already exclude.

parse(src: str, lang: str) -> SgRoot | None

Parameter Type Default Description
src str Full file source text.
lang str ast-grep language name.

Returns: SgRoot | None — A constructed SgRoot, or None when ast-grep is unavailable, the language is unsupported, or parsing panicked.

Function perl_pod_summary

Module summary from the first top-level POD block (TASK-2745).

Mirrors perl.py's _pod_summary: the first =head1 NAME paragraph, falling back to =head1 DESCRIPTION.

perl_pod_summary(root: SgNode) -> str

Parameter Type Default Description
root SgNode

Returns: str

Function perl_sub_parent

Enclosing package/class/role name for a Perl sub or method.

Perl's container statements have two forms: block-form (package Foo { ... }), which makes the container a real ancestor of everything inside; and block-less (package Foo;), which scopes as a preceding sibling instead (see :func:preceding_package). Tries the ancestor form first (matches perl.py's tree-sitter _walk recursing into a block with in_context set), then falls back to the preceding-sibling form.

perl_sub_parent(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Function php_qualified_container

Namespace-qualified name of node's enclosing PHP container.

PHP's block-less namespace Foo\Bar; form is a preceding sibling of the class it scopes, not an ancestor (see :func:preceding_package) — this combines that namespace lookup with the immediate class/interface/trait/enum ancestor's own name, joined by \, so a method's parent can carry the full Ns\Class qualname (spec §2 SymbolRecord.qualname example "App\Models\User::getFullName").

php_qualified_container(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Function pod_head2

First non-empty line of a Perl =head2 POD block preceding node.

TASK-2745: checks node.prev() directly for a "pod"-kind node — verified live against the dynamically-registered grammar that a POD block's own kind is exactly "pod", which does NOT contain the substring "comment", so :func:_first_comment_before (which filters on that substring) can never find one.

pod_head2(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Function pod_head2_or_leading_comment

pod_head2, falling back to a plain leading # comment.

TASK-2745: reconciles perl.py's two fallback tiers, which use two completely different doc mechanisms for the same symbols — the heuristic tier's _head2_docs (POD =head2 NAME blocks) and the tree-sitter tier's _leading_doc (a plain # comment immediately before the declaration) — so this seam matches whichever one the locally-installed fallback tier would have used.

pod_head2_or_leading_comment(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Function preceding_package

Qualname of the last package/namespace statement preceding node.

Perl's block-less package Foo; form (and PHP's equivalent block-less namespace Foo\Bar;) scopes everything until the next such statement (or EOF) — the last preceding one, not an ancestor, is the container (matches perl.py's existing walker).

preceding_package(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Function python_call_scope

Dotted Class.method qualname of node's enclosing scope.

TASK-2746: a ref's generic scope: {"ancestor": [...]} form stops at the nearest matching ancestor's own bare name field — for a Python ref that is just the method name ("get_user"), not the class-qualified name ("UserService.get_user") TASK-2741's ast-derived symbols use. This walks outward once, joining the nearest enclosing function_definition's name with its enclosing class_definition's name (if any). Module-level code (no enclosing function) returns "".

python_call_scope(node: SgNode) -> str

Parameter Type Default Description
node SgNode

Returns: str

Alias sha1_of_text

Re-exported from parrot.knowledge.wiki.symbols.sha1_of_text.

Function supported_language

Return whether lang can be parsed by ast-grep-py right now.

supported_language(lang: str) -> bool

Parameter Type Default Description
lang str ast-grep language name (e.g. "python", "rust", "perl").

Returns: bool — True for the built-in whitelist, or for "perl" once dynamic registration against the installed tree-sitter-perl wheel has succeeded. False for anything else, including when ast-grep-py itself is not installed. Never raises.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally