# Tree-sitter Grammar

---

# Tree-sitter Grammar

_GCSL / Tree-sitter Grammar_

> How the GCSL editor grammar provides syntax trees and editor queries.

The GCSL Tree-sitter grammar lets an editor recognize the structure of a
GCSL file as you type. It supplies syntax highlighting and the structural
information an editor can use for folding, indentation, and selections.
The grammar does not run the program or check its types.

## Parser and queries

The parser turns source into a concrete syntax tree. Named nodes identify
constructs such as a function, an import, or a string interpolation. The
tree also records punctuation and source positions so an editor can work
with incomplete text and update a changed region.

Queries attach names to selected nodes. The editor interprets those names:
for example, a function capture can select a highlight group or define a
text object. [Editor Queries](/gcsl/tree-sitter/tree-sitter-queries.md) describes the four
query files shipped with the grammar.

## Native and WebAssembly parsers

The repository builds two forms of the same parser. A native shared object
is loaded by an editor that accepts C Tree-sitter grammars. A WebAssembly
module is loaded by an editor with Tree-sitter's Wasm runtime. Both export
the language entry point `tree_sitter_gcsl` and use language ABI 15.

These artifacts are grammar plugins. They do not embed the GCSL evaluator
or a separate copy of the Tree-sitter runtime. The native parser and Wasm
parser are tested against Tree-sitter 0.27.1.

## Relationship to the language server

The GCSL compiler owns the language rules. Its language server provides
type errors, name resolution, navigation, and formatting. The Tree-sitter
grammar is a separate editor component and can work without the language
server.

The syntax tree is not the compiler's abstract syntax tree. Some node names
are similar, but their structure and meaning are not interchangeable.
The grammar deliberately accepts some text the compiler rejects and has
its own scanner limits. See
[Parser Differences](/gcsl/tree-sitter/tree-sitter-differences.md) before using it to
judge whether a program is valid.

---

# Installing GCSL Parsers

_GCSL / Tree-sitter Grammar_

> Load the native GCSL parser and queries in Neovim.

You can load the native parser directly in Neovim without a parser-manager
plugin. This procedure configures syntax highlighting and folds. It does
not configure the language server or install an indentation plugin.

## Before you start

You need the following:

- Neovim 0.11 with support for Tree-sitter language ABI 15.
- The grammar's `gcsl.so` native build for your host.
- The four files in the grammar repository's `queries/` directory.

The example uses a Linux development build. From the grammar repository,
build the native parser with pekit:

```sh
parser=$(pekit build parser | sed -n 's/^  //p')
```

The command keeps the built parser's path, which pekit prints indented
under the target name, in `parser`.

## Install the parser and queries

1. Create the runtime directories under your Neovim configuration:

   ```sh
   config="${XDG_CONFIG_HOME:-$HOME/.config}/nvim"
   mkdir -p "$config/parser" "$config/queries/gcsl"
   ```

2. Copy the parser and queries into those directories:

   ```sh
   cp "$parser" "$config/parser/gcsl.so"
   cp queries/*.scm "$config/queries/gcsl/"
   ```

3. Add the file type and highlighting setup to `init.lua`:

   ```lua
   vim.filetype.add({ extension = { gcsl = "gcsl" } })
   vim.api.nvim_create_autocmd("FileType", {
       pattern = "gcsl",
       callback = function()
           vim.treesitter.start(0, "gcsl")
           vim.wo.foldmethod = "expr"
           vim.wo.foldexpr = "v:lua.vim.treesitter.foldexpr()"
       end,
   })
   ```

## Check the result

Open a `.gcsl` file containing a function and a string interpolation. Run
`:InspectTree` to view the syntax tree. It should contain `named_function`
and `interpolation` nodes for those constructs.

Run `:Inspect` over a function name to see its highlight capture. Use `za`
on a multiline block to toggle its fold. A parser-load error usually means
the shared object was built for a different host or the editor does not
support its language ABI.

## Indentation and text objects

The indentation and text-object queries require an editor integration that
understands their capture names and predicates. Merely copying the files
does not enable those features. Configure your chosen integration using
its version's instructions; plugin APIs can differ between branches.

---

# Installing the Wasm Grammar

_GCSL / Tree-sitter Grammar_

> Assemble a GCSL language pack for clackatoo from the Wasm parser and queries.

The Wasm parser lets clackatoo recognize GCSL without loading a native
shared object into the editor. A language pack combines the parser, query
files, and a small language declaration.

## Before you start

You need a clackatoo version that supports Wasm language packs and the
grammar repository. To use the language server too, install `gcsl` on the
editor's command search path.

Build the portable parser from the grammar repository with pekit:

```sh
wasm=$(pekit build wasm | sed -n 's/^  //p')
```

The command keeps the built parser's path, which pekit prints indented
under the target name, in `wasm`.

## Create the language pack

1. Create the user language-pack directory:

   ```sh
   pack="${XDG_DATA_HOME:-$HOME/.local/share}/clackatoo/languages/gcsl"
   mkdir -p "$pack"
   ```

2. Copy the parser and supported queries:

   ```sh
   cp "$wasm" "$pack/grammar.wasm"
   cp queries/highlights.scm queries/indents.scm queries/textobjects.scm "$pack/"
   ```

3. Save this declaration as `language.toml` in that directory:

   ```toml
   grammar = "gcsl"
   extensions = ["gcsl"]
   filenames = []
   server = ["gcsl", "lsp"]
   roots = ["workspace.gcsl"]
   word = "-"
   ```

The `word` entry keeps names such as `build-root` together during word
navigation. The `server` entry starts the separate GCSL language server;
omit it if you only want grammar features. The root marker selects the
workspace for language-server requests.

## Check the result

Open a `.gcsl` file in clackatoo and check that strings and function names
are highlighted. Use a function text object to select a function. If the
language server is enabled, hover over a declaration to check that the
server starts separately from the grammar.

The pack does not include `folds.scm`: this clackatoo integration does not
consume the folding query. The same query remains available for editors
that support it.

---

# Editor Queries

_GCSL / Tree-sitter Grammar_

> The GCSL highlight, indentation, folding, and text-object query contracts.

The query files use Tree-sitter node patterns and capture names understood
by editor integrations. Keep the parser and queries from the same grammar
revision: a query referring to a missing node cannot be loaded.

The files have distinct roles:

| File | Purpose | Required editor behavior |
| --- | --- | --- |
| `highlights.scm` | Syntax colors | Map captures to highlight groups and evaluate predicates |
| `indents.scm` | Structural indentation | Interpret `indent.*` captures and `#not-has-parent?` |
| `folds.scm` | Fold ranges | Interpret `@fold` on multiline constructs |
| `textobjects.scm` | Structural selections | Combine captures in one match into an inner or outer range |

## Highlights

Top-level field names use `@variable`; fields inside bodies use
`@variable.member`. A called field uses `@function.call`, because GCSL has
function values rather than a separate method-call syntax. The final name
in a definition path uses `@function`, while preceding segments use
`@module`. Function effect markers use `@keyword.modifier`.

Editors differ in which overlapping highlight pattern wins. The queries
avoid most competing names and repeat specialized field-call patterns on
both sides of the general field pattern. This supports integrations that
choose either the first or last applicable capture.

## Indentation

Blocks, lists, argument lists, and parenthesized constructs open indentation
levels. An `if` opens a level for its branches; the branch blocks do not
open an extra level. A continued binary expression opens a hanging level
only at the outermost binary node.

The editor chooses the width of a level. GCSL's house style is four spaces.
String content and comments use `@indent.auto` so structural indentation
does not rewrite literal text. The predicate `#not-has-parent?` is an editor
extension; a generic query engine alone does not implement its behavior.

## Folds and selections

Folds cover blocks, record types, lists, functions, definitions, metas, and
runs of imports. A one-line node does not need a multiline fold.

Text objects cover functions, classes, parameters, blocks, conditionals,
loops, calls, comments, returns, assignments, and attributes. The `.inner`
capture selects the contents and `.outer` includes the surrounding
construct. Parameter outer ranges include an adjacent separator where one
is present.

The text-object query uses captures for the first and last selected nodes
rather than `#make-range!`. The editor combines those captures. It treats
a block as a record-like class only in the contexts described by the query;
it does not perform the compiler's type analysis.

---

# Parser Differences

_GCSL / Tree-sitter Grammar_

> Deliberate differences between the editor grammar and the GCSL compiler.

Use the compiler or GCSL language server to validate a program. The editor
grammar favors useful syntax trees while a file is incomplete. A successful
Tree-sitter parse does not establish that the compiler accepts the file.

## Accepted forms with additional compiler rules

The grammar accepts these broader forms:

| Area | Editor grammar behavior |
| --- | --- |
| Comparisons and ranges | Chained forms such as `a < b < c` and `a..b..c` associate left |
| Negation | A space can separate `-` from its operand |
| Paths | Shared path rules accept index segments in declarations and fields, quoted first names, and dotted mutable declarations |
| Quoted field names | Interpolation can appear where the compiler expects a plain string |
| Attributes | Attribute names and placement are not checked as strictly as by the compiler |
| Definition references | A def-type can be a field access on a computed expression |
| Definition paths | Some glued numeric and hyphenated segments are accepted more broadly |
| Loop headers | The grammar does not enforce every condition and declaration ordering rule |
| Newlines | A newline can be skipped before a token the compiler expects on the same line |
| Labels | A record-like block can carry a label |
| Escapes | Unknown escapes and a lone closing brace in string content can parse |
| Imports | Dotted members and repeated wildcard imports can parse |

These are editor parsing choices, not alternative GCSL language rules.
The compiler remains responsible for rejecting invalid source.

## Scanner boundaries

The external scanner stores at most 64 simultaneously open string literals.
Nested interpolation can reach this limit. The scanner stops opening more
literals and lets Tree-sitter recover; it does not allocate an unbounded
stack. This editor limit is separate from the compiler's depth limits.

String delimiter lengths are stored as 32-bit counts, including across
incremental edits. Delimiters longer than 255 quotes are supported.
The byte counts in Tree-sitter's input interface bound the document size.
The compatibility tests and known limitations should be reviewed whenever
the language's lexer or parser changes.

The grammar produces a concrete syntax tree with punctuation and recovery
nodes. Its tree shape is not the compiler's AST, even where node names are
shared. `@` is not source syntax; namespace keys created internally by the
compiler do not become valid source identifiers here.
