Agent Native

psl-ast-layers

This skill teaches agents how to correctly use the three-layer syntax tree produced by the PSL parser: the green tree for internal storage, the red tree for…

by PrismaOfficial publisherNot reviewed

Identity proven by GitHub's verified organisation badge (prisma)

Agents
Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode, claude.ai and API
License
Apache-2.0 (permissive)
Pin
55458c4pinned Oct 9, 2026
Context cost
about 2,200 tokenswhen the skill loads
GitHub stars
415on prisma/prisma-next
Scripts
None found

What it does

“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 @prisma-next/psl-parser.”
The author's description, from SKILL.md

Generated summary from the skill's own text

This skill teaches agents how to correctly use the three-layer syntax tree produced by the PSL parser: the green tree for internal storage, the red tree for navigation with positions and parents, and the typed AST for accessing structural information about known nodes. It provides guidance on choosing the right layer, navigation patterns, and common anti-patterns to avoid when working with PSL syntax trees in interpreters, language servers, formatters, or other tools that consume parser output.

When to use it

  • Building PSL language server features like hover, completions, or go-to-definition
  • Writing PSL formatters, linters, or diagnostic tools
  • Navigating or transforming PSL syntax trees in contract-psl or psl-parser helpers
  • Extracting structural information from parsed PSL documents

When not to

  • Working inside the psl-parser package's internal parser or green tree builder
  • Building text-based string manipulation tools unrelated to PSL structure
  • Parsing non-PSL languages or grammars

Install

These commands install from the publisher's repository and need no account.

skills CLI

npx skills add prisma/prisma-next --skill psl-ast-layers

Installs from the repository's default branch, which may have changed since the commit we checked.

GitHub CLI 2.90 or later

gh skill install prisma/prisma-next psl-ast-layers@55458c441d2cf452028c22eed21370447720840a

Installs the commit we checked (55458c4).

Copy by hand

Download the folder at 55458c4 and put it in .claude/skills/psl-ast-layers for Claude Code and in .agents/skills/psl-ast-layers for Codex, Cursor, Gemini CLI, GitHub Copilot and OpenCode.

Skill folder on GitHub at 55458c4

Copy for your agent

A prompt for any coding agent. It installs this skill from GitHub at the pinned commit, copies the files as they are, and runs nothing unless you ask.

Prompt

Install the agent skill "psl-ast-layers" by Prisma.

Source, pinned to commit 55458c441d2cf452028c22eed21370447720840a:
https://github.com/prisma/prisma-next/tree/55458c441d2cf452028c22eed21370447720840a/skills-contrib/psl-ast-layers

1. Download that folder at exactly this commit. Do not use the default branch.
2. Copy every file unchanged, keeping the folder structure, into .claude/skills/psl-ast-layers/ for Claude Code and .agents/skills/psl-ast-layers/ for Codex, Cursor, Gemini CLI, GitHub Copilot and OpenCode. Create the folders if they do not exist.
3. Do not edit the files, and do not run any script in the folder unless I ask you to.
4. When you are done, list the files you copied and where you put them.

Listing and checks: https://www.agentnative.dev/skills/prisma/psl-ast-layers

SKILL.md at the pin

---
name: psl-ast-layers
description: >-
  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 @prisma-next/psl-parser.
---

# 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.

| Layer | Types | Job | Use in consumer code? |
|-------|-------|-----|-----------------------|
| Green tree | `GreenNode`, `GreenToken` (`syntax/green.ts`) | Immutable, position-independent storage. Foundation only. | **Never** |
| Red tree | `SyntaxNode`, `SyntaxToken` (`syntax/red.ts`, `syntax/navigation.ts`) | Navigation with offsets and parents: `findAncestor()`, `tokenAtOffset()`, `nextToken`/`prevToken`, `nonTriviaSibling()` | Navigation *outside* the current node |
| Typed AST | `ModelDeclarationAst`, `FieldDeclarationAst`, … (`syntax/ast/`) | Structural information about a *known* node via getters (`name()`, `fields()`, `lbrace()`, `value()`) | **Default choice** |

Everything is exported from `@prisma-next/psl-parser/syntax` (and re-exported from the package root). `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`

From prisma/prisma-next at 55458c4, shown as plain text under its license: Apache-2.0 (permissive). The license text is in LICENSE.

View SKILL.md on GitHub at 55458c4

Files

1 file, 9.1 KB in total. Each file has a sha256 in the pin's manifest; the first 12 characters are shown.

Skill folder on GitHub at 55458c4
All 44 skills from Prisma

More from Prisma

  • prisma-8

    This skill helps agents work with Prisma 8, a contract-first data layer for TypeScript projects.

    Contains scripts

    Claude Code, Codex, Cursor +3 · about 3.5K tokens · pinned 6 days ago

  • adr-review

    This skill reviews Architecture Decision Records (ADRs) from a fresh perspective, identifying clarity and structural issues, then rewrites them for future…

    Claude Code, Codex, Cursor +4 · about 590 tokens · pinned 6 days ago

  • ast-visitor-pattern

    This skill teaches agents to use the visitor pattern with frozen subclasses for discriminated unions that need multiple dispatch sites.

    Claude Code, Codex, Cursor +4 · about 710 tokens · pinned 6 days ago

  • bumping-biome

    Updates the biome code formatter package to a specified version using pnpm, renames configuration files to biome.jsonc format, updates schema references, and…

    Claude Code, Codex, Cursor +4 · about 290 tokens · pinned 6 days ago

  • contrib-pr

    This skill guides external contributors through opening a pull request against prisma-next by following the project's contribution guidelines.

    Claude Code, Codex, Cursor +4 · about 2.2K tokens · pinned 6 days ago

  • create-pr

    This skill creates a GitHub pull request with a Linear-ticket-prefixed title and a decision-led narrative description for the prisma-next repository.

    Claude Code, Codex, Cursor +4 · about 4.3K tokens · pinned 6 days ago

All Coding workflow skills
  • prisma-next-build

    This skill integrates Prisma Next's contract-emit into the Vite build system via the @prisma-next/vite-plugin-contract-emit plugin, automatically re-emitting…

    by PrismaOfficial publisher

    Claude Code, Codex, Cursor +4 · about 2.3K tokens · pinned 6 days ago

  • prisma-next-extension-upgrade

    Upgrades Prisma Next dependencies in an extension package across one or more minor versions.

    by PrismaOfficial publisher

    Contains scripts

    Claude Code, Codex, Cursor +3 · about 2K tokens · pinned 6 days ago

  • prisma-next-feedback

    Routes bug reports, feature requests, and team Q&A to the appropriate Prisma Next channel.

    by PrismaOfficial publisher

    Claude Code, Codex, Cursor +4 · about 4.2K tokens · pinned 6 days ago

  • prisma-next-upgrade

    Upgrades Prisma Next dependencies in a user app from one version to the next, applying code translations from per-transition instructions, validating with the…

    by PrismaOfficial publisher

    Contains scripts

    Claude Code, Codex, Cursor +3 · about 1.9K tokens · pinned 6 days ago

  • record-upgrade-instructions

    Records upgrade instructions in published skill packages whenever a PR makes breaking changes to Prisma Next that require downstream users or extension…

    by PrismaOfficial publisher

    Claude Code, Codex, Cursor +4 · about 4.2K tokens · pinned 6 days ago

  • planning

    This skill orchestrates multi-workflow projects with dependencies and shared data tables by creating a task graph in the orchestrator via the create-tasks tool.

    by n8nOfficial publisher

    Claude Code, Codex, Cursor +3 · about 2.4K tokens · pinned 6 days ago

The skills listed here are third-party software, collected from public GitHub repositories as a catalog of recent skills and provided as is. Agent Native does not write or control them and is not responsible for any harm, loss or damage caused by installing or using them. Labels and checks describe what we saw at one commit and are not a guarantee. Read a skill's files before you run it. Terms of use