Psl Ast Layers logo

Psl Ast Layers

OrganizationPopular
prisma
psl-ast-layers

How to use the PSL syntax tree layers (green tree, red tree, strongly-typed AST classes) correctly. Use for any PSL-related work: PSL interpreters (contract-psl), helpers inside the psl-parser package, the language server, formatters, or anything else that consumes `parse()` output from @internal/psl-parser.

Overview

Publisherprisma
Repositoryorm
Skill namepsl-ast-layers
Stars
47.6K
Forks
2.5K
Bundled files
Instructions only
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by prisma on GitHub. Read the source before you install it.

Installation

Install the Psl Ast Layers AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/prisma/orm.git /tmp/orm
mkdir -p .claude/skills
cp -r /tmp/orm/skills-contrib/psl-ast-layers .claude/skills/psl-ast-layers
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Psl Ast Layers in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Psl Ast Layers on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Psl Ast Layers is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

PSL AST Layers

The PSL parser (packages/1-framework/2-authoring/psl-parser) produces a three-layer syntax tree. Each layer has exactly one job — pick the right one and the code stays lossless, typed, and cheap.

LayerTypesJobUse in consumer code?
Green treeGreenNode, GreenToken (syntax/green.ts)Immutable, position-independent storage. Foundation only.Never
Red treeSyntaxNode, SyntaxToken (syntax/red.ts, syntax/navigation.ts)Navigation with offsets and parents: findAncestor(), tokenAtOffset(), nextToken/prevToken, nonTriviaSibling()Navigation outside the current node
Typed ASTModelDeclarationAst, FieldDeclarationAst, … (syntax/ast/)Structural information about a known node via getters (name(), fields(), lbrace(), value())Default choice

Everything is exported from @internal/psl-parser/syntax. parse(source) returns { document: DocumentAst, diagnostics, sourceFile } — you start in the typed layer.

Choosing a layer

  1. You know what the node is (you hold a ModelDeclarationAst, a FieldAttributeAst, …) and want its parts → call the typed getters. Never dig through children yourself.

  2. You need to move outward or sideways (find the enclosing model, the previous declaration, the token after the cursor) → use the red tree's navigation helpers, then immediately re-enter the typed layer with a static cast:

    ts
    // enclosing model (tests the node itself first, then walks ancestors)
    const model = node.syntax.findAncestor(ModelDeclarationAst.cast);
    
    // enclosing model OR composite type — combine casts with any(…)
    const owner = node.syntax.findAncestor(
      any(ModelDeclarationAst.cast, CompositeTypeDeclarationAst.cast),
    );

    Sideways and token-level movement all have dedicated helpers — do not hand-roll the walks:

    • nextSiblingOrToken / prevSiblingOrToken — adjacent element within the same parent (works from both nodes and tokens)
    • token.nextToken / token.prevToken — document order, crossing node boundaries
    • nonTriviaSibling(element, 'next' | 'prev'), skipTriviaToken(token, direction), isTrivia(token) (from syntax/navigation.ts) — trivia-aware movement; never write your own whitespace/comment-skipping loop
  3. You genuinely don't know the node's type yet (e.g. resolving a cursor position in the language server) → anchor on the red tree, then cast back into the typed layer immediately:

    ts
    // cursor → token: seam-aware, no descendant scanning
    const token = document.syntax.tokenAtOffset(offset).leftBiased();
    const attr = token?.parent.findAncestor(FieldAttributeAst.cast);
    
    // selection range → smallest enclosing element
    const covering = document.syntax.coveringElement(start, end);

    tokenAtOffset returns a TokenAtOffset that models the offset-on-a-seam case explicitly — pick leftBiased() or rightBiased() deliberately (completions usually want left, hover often wants right). Reach for a manual descendants() walk only when no offset anchors the search, and even then the loop body's first move is a cast (castExpression(child), ModelDeclarationAst.cast(child), …).

  4. Green tree → only inside psl-parser itself (parser, GreenNodeBuilder, red-tree internals). If consumer code touches node.green, that's a bug.

Every typed AST class exposes readonly syntax: SyntaxNode (the AstNode interface), so switching layers is always one property access away — there is no excuse to stay in the wrong layer.

Adding missing getters instead of working around them

If a typed AST class lacks a getter for the structure you need, add the getter to the class in syntax/ast/ (test-first, exported via exports/syntax.ts) rather than hand-rolling child iteration at the call site. The helpers findChildToken, findFirstChild, and filterChildren from ast-helpers.ts are the building blocks for those getters — they belong inside AST classes, not scattered through consumer code.

Anti-patterns

1. Re-stringifying the AST to extract information

Never round-trip through text: neither printSyntax(node) nor slicing the SourceFile by offsets, followed by string matching / regex / re-parsing. The tree already holds the structure; text extraction throws away parsing work and breaks on comments, whitespace, and escapes.

ts
// BAD: stringify then string-hack
const text = printSyntax(attr.syntax);
const isUnique = text.includes('@unique');

// BAD: slicing the source file by offsets
const raw = source.slice(node.syntax.offset, node.syntax.offset + node.syntax.textLength);
const name = raw.split(' ')[1];

// GOOD: ask the tree
const isUnique = attr.name()?.identifier()?.token()?.text === 'unique';
const name = model.name()?.token()?.text;

Same rule for values: StringLiteralExprAst.value() returns the decoded string (escapes resolved, quotes stripped); slicing quotes off raw text yields wrong results for \n, \u…., etc.

printSyntax and SourceFile offsets have legitimate uses — producing output for humans: error-message snippets, formatter output, positionAt for LSP ranges. Extracting structural facts from that text is the anti-pattern.

2. Reading through the green tree

node.green exists so the red tree can do its job. Consumer code must not inspect green children, kinds, or text — green elements have no offsets and no parents, so any information you pull from them is positionally blind and will not survive refactors of the storage layer.

ts
// BAD: peeking into green storage
const first = model.syntax.green.children[0];
if (first?.type === 'token' && first.text === 'model') {}

// GOOD: red/typed access
const keyword = model.keyword(); // SyntaxToken with a real offset

3. Collecting child iterators into arrays

children(), childNodes(), descendants(), fields(), attributes(), declarations() are lazy generators on purpose. Materializing them just to index or filter allocates for nothing and hides intent.

ts
// BAD: collect then poke
const fields = Array.from(model.fields());
const idField = fields.filter((f) => f.name()?.token()?.text === 'id')[0];

// GOOD: iterate lazily, stop early
let idField: FieldDeclarationAst | undefined;
for (const field of model.fields()) {
  if (field.name()?.token()?.text === 'id') {
    idField = field;
    break;
  }
}

4. Red-tree spelunking on a node of known type

If you already know the node is a ModelDeclarationAst, iterating its red children to find tokens or sub-nodes manually re-implements the typed getters — badly.

ts
// BAD: manual token hunt on a known node
let lbrace: SyntaxToken | undefined;
for (const child of model.syntax.children()) {
  if (child instanceof SyntaxToken && child.kind === 'LBrace') {
    lbrace = child;
    break;
  }
}

// GOOD: the getter already exists
const lbrace = model.lbrace();

Likewise use field.typeAnnotation(), attr.argList()?.args(), kv.value() — and if the getter you want is missing, add it to the AST class (see above) instead of spelunking.

The same rule applies to navigation: a hand-written ancestor loop, whitespace-skipping loop, or offset-scanning descendants() walk re-implements findAncestor, skipTriviaToken / nonTriviaSibling, or tokenAtOffset / coveringElement. Use the helper.

Quick reference

  • Parse: parse(source)ParseResult { document, diagnostics, sourceFile }
  • Enter typed layer from red: SomeAst.cast(syntaxNode) (returns undefined on kind mismatch), castExpression(node) for expression unions, any(CastA, CastB, …) to combine casts into one predicate
  • Drop to red from typed: astNode.syntax
  • Upward: findAncestor(cast) (checks self first), ancestors(), parent
  • Sideways: nextSiblingOrToken / prevSiblingOrToken; trivia-aware: nonTriviaSibling, skipTriviaToken, isTrivia
  • Token order: token.nextToken / token.prevToken (crosses node boundaries); subtree edges: node.firstToken / node.lastToken
  • Offsets: tokenAtOffset(offset) (seam-aware TokenAtOffset), coveringElement(start, end), endOffset, isInside(offset) / isOutside(offset)
  • Positions for humans/LSP: sourceFile.positionAt(token.offset) / sourceFile.offsetAt(position) — offsets live only on red SyntaxToken / SyntaxNode, never green
  • Getter helpers for building AST classes: findChildToken, findFirstChild, filterChildren, any, and the BracedBlock interface (for lbrace()/rbrace() blocks) in syntax/ast-helpers.ts

Frequently asked questions

What does the Psl Ast Layers AI skill do?

How to use the PSL syntax tree layers (green tree, red tree, strongly-typed AST classes) correctly. Use for any PSL-related work: PSL interpreters (contract-psl), helpers inside the psl-parser package, the language server, formatters, or anything else that consumes `parse()` output from @internal/psl-parser.

Why use Psl Ast Layers on TypingMind?

Because you install it once and use it with any model. Psl Ast Layers is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Psl Ast Layers in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/prisma/orm/tree/main/skills-contrib/psl-ast-layers. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Psl Ast Layers?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Psl Ast Layers?

As many as you like. As long as a model supports skills, you can use Psl Ast Layers with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Psl Ast Layers AI skill free?

Yes. It is published on GitHub by prisma under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇