Delphi-RAG-Lint
Delphi tooling · parsing

What Tree-sitter Is, and Why Delphi Needs a Preprocessor in Front of It

Tree-sitter turns a grammar file into a fast, error-tolerant parser that any language can call, and for Delphi it reaches every file only when a preprocessor resolves the conditional compilation first. This article explains what tree-sitter is, how drag-lint uses it, how you can use it from your own tools, and why no grammar on its own can read all Delphi source.

Micronite, the quality and production-control software we build for manufacturers, is the Delphi code base drag-lint first had to read in full, and “can the parser read all of it?” was the first question we had to answer with a number. (Micronite is still the code base every grammar change is measured against.) Our earlier article, Three Ways to Read Delphi, compared tree-sitter with a raw lexer and with DelphiAST. This one looks at tree-sitter itself.

01 — The idea

A parser generator, a runtime, and a tree

Tree-sitter started at GitHub as the parsing engine for the Atom editor. Today Neovim, Helix, Zed and Emacs use it, and GitHub uses it for syntax highlighting and code navigation. It has three parts:

  • A generator. You describe the language in grammar.js, a JavaScript file of rules such as seq, choice, repeat and prec. The tree-sitter generate command turns it into parser.c: plain C tables for an LR parser, with GLR fallback where the grammar is ambiguous. GLR means that when the parser cannot decide between two readings, it keeps both alive until one of them fails.
  • An external scanner. Some tokens cannot be described with rules alone, because recognising them depends on context. For those you write a small C file, scanner.c, and the generated parser calls it whenever it expects one of these tokens.
  • A runtime. A small C library (tree-sitter.dll on Windows) runs the tables. It has a plain C API, so anything that can call a C function can use it: Rust, Node, Python, a browser through WebAssembly, and Delphi.

The output is a concrete syntax tree. Every token is a node, and every node knows its exact byte range and its row and column in the source. Here is a record whose first field is named Platform, a directive word, which is legal Delphi:

type
  TProjectContext = record Platform, Config: string; end;

And the tree tree-sitter-delphi13 1.4.0 builds for the type declaration (taken from the grammar's test corpus):

(declType
  (identifier)
  (kEq)
  (type
    (declClass
      (kRecord)
      (declField
        (identifier)
        (identifier)
        (type
          (declString
            (kString))))
      (kEnd))))

The tree prints only node kinds. Behind each (identifier) is the byte range of Platform or Config, so a tool can always go back to the exact source text.

02 — Three properties

What makes it different from a hand-written parser

It does not give up

When the input does not match the grammar, tree-sitter wraps the smallest region it can in an ERROR node, or inserts a zero-width MISSING node where it expected a token, and carries on. A unit with one construct the grammar does not know still yields every declaration outside that construct. For an indexer this decides everything. A parser that raises on the first surprise loses the whole unit, and usually nobody notices.

It re-parses only what changed

After an edit, you tell the runtime which bytes changed (ts_tree_edit) and parse again with the old tree. The parser reuses every subtree the edit did not touch. This is why editors can re-parse on every keystroke, even in large units.

It has a query language

Instead of walking the tree by hand, you can write patterns in an S-expression syntax and capture the nodes that match. This pattern captures every field name in every record or class, including the second name in Platform, Config:

(declField (identifier) @field.name)

Editors get their syntax colouring, code folding, outline and indentation from files of such patterns: highlights.scm, folds.scm, outline.scm, indents.scm. tree-sitter-delphi13 ships these files for both of its grammars, plus tags.scm for symbol indexers.

03 — The Delphi grammar

Where Delphi needed the external scanner

Most of Delphi fits ordinary grammar rules. The places where it does not are where the scanner comes in. Three examples from tree-sitter-delphi13:

  • Directive words as names. platform, message, index, name, default, read, absolute and 62 other directive words are not reserved, so Message: string is a valid field. Since 1.4.0 the scanner offers such a word as a name only in a position where a name is expected, and only when the next character makes it one (: or , in a declaration, = in a constant or type). Everywhere else it is still a directive.
  • Multi-line strings (Delphi 12 and later). An odd number of quotes, three or more, at the end of a line opens the string. The first line that starts with the same run of quotes closes it. Counting quotes across lines is beyond grammar rules, but it is a few dozen lines of C.
  • Conditional compilation. The scanner reads through {$IFDEF} blocks. The THEN branch flows to the parser as ordinary tokens. The {$ELSE} branch is swallowed as one opaque token, and the directives themselves are treated like comments. We call this THEN-wins. It is the best a grammar can do on its own, and section 05 shows where it runs out.

The project publishes two grammars from the same source. tree-sitter-delphi13 is the full grammar with THEN-wins, for hosts that cannot run anything before the parser. tree-sitter-delphi13-pure has no directive handling at all. It expects text that a preprocessor has already resolved.

04 — Inside drag-lint

From file on disk to index rows

drag-lint is written in Delphi, and it loads tree-sitter as DLLs. Its third_party\dll-win64 folder holds tree-sitter.dll (the runtime), tree-sitter-delphi13.dll (the Delphi grammar) and tree-sitter-dfm.dll (a separate grammar for form files). A thin Object Pascal wrapper, TTSParser, calls the C API. Parsing a unit is three steps:

drag-lint
.pas bytes → Delphi preprocessor → tree-sitter-delphi13.dll → tree → SQLite index

The indexer and the linter run the same preprocessing step, and it never changes the length of the text, so a finding's line and column always point where the editor does.

Preprocess. drag-lint's preprocessor, the DRagLint.Preprocess units, evaluates {$DEFINE}, {$IFDEF}, {$IF} expressions and {$ELSEIF} against a define profile chosen for each file. It follows {$I} includes for the defines they set. Then it does one unusual thing: it blanks every inactive branch to spaces instead of deleting it. The output is exactly as long as the input, and every byte that survives sits at its original offset. This is how drag-lint avoids the source-map problem that Three Ways to Read Delphi warned about: there is nothing to map back.

Parse. TTSParser parses the blanked text, with Language set to tree_sitter_delphi13. The parser never sees an inactive branch, so THEN-wins has nothing left to guess.

Extract. The indexer walks the tree and writes units, types, routines, fields, calls and uses edges into the project's SQLite database. Every question you ask drag-lint is answered from that database.

If preprocessing throws, drag-lint does not drop the file. It parses the raw bytes instead and keeps the findings. In our code, a file that silently disappears from the index counts as a worse failure than a noisy one.

05 — The hard limit

Why no grammar can read all Delphi

A grammar describes one language. A Delphi file with conditional compilation is not one program. It is a family of programs, one for each set of defines, and the compiler builds only one of them. Which one depends on facts that are not in the file:

  • the defines from the project options and the target platform (WIN64, CPUX64, DEBUG, ...);
  • the defines that an {$I} include file sets, which can steer every branch after it;
  • the values that {$IF CompilerVersion >= 36} or {$IF Declared(TFoo)} evaluate to.

And the directives can cut the source anywhere, not only between declarations:

{$IFDEF CPUX64}
procedure Fill(var Dest; Count: NativeInt; Value: Byte);
asm
  { x64 assembler }
end;
{$ELSE}
{$IFDEF CPUX86}
procedure Fill(var Dest; Count: NativeInt; Value: Byte);
asm
  { x86 assembler, different registers }
end;
{$ELSE}
procedure Fill(var Dest; Count: NativeInt; Value: Byte);
begin
  FillChar(Dest, Count, Value);
end;
{$ENDIF}
{$ENDIF}

An illustration of a common RTL pattern, a three-way choice: two assembler bodies and one Pascal body. Each branch is valid only for its own target.

This example parses under THEN-wins, because the first branch happens to be complete on its own. The real failures come when it is not: a THEN branch that opens a begin which only the ELSE branch closes, or a branch written for an older compiler that is no longer valid Delphi 13, or an {$IF} whose winning branch is the second one. A grammar that cannot evaluate the condition can only guess. THEN-wins is a good guess, but it is still a guess.

We also tried the other route: teaching the grammar to accept directives as tokens in expression and statement positions. The project's design notes record seven separate attempts. Each one cost between 100 and 3,000 files on the full corpus, because the GLR parser explores too many alternatives once a directive can appear anywhere.

The way out is to change the input, not the grammar. Give the preprocessor the define profile, let it evaluate the conditions the way the compiler does, and hand the grammar the one program the compiler would actually build. Then the grammar parses ordinary Delphi, which is something a grammar can do completely. That evaluation step is what a preprocessor is, so the conclusion is not a matter of taste. Reading every file correctly means knowing which branch is live, and only a preprocessor knows that.

RAD Studio 37.0 source tree, 2,217 readable files Files parsed without error Rate
Full grammar alone (THEN-wins, raw source) 2,183 98.47%
Preprocessor → pure grammar 2,217 100.000%

The two rows use the same grammar rules. The only difference is the preprocessor, and it parses all 34 files that the grammar alone fails on. Grammar fixes do not move that gap. Version 1.4.0 fixed every directive-word-name failure in a 1,506-case test set (122 failing files down to 0) and added multi-line strings. On the RAD Studio tree, the grammar-only figure stayed exactly where it was, and the preprocessor path stayed at 100%. On Micronite's own 786 source files, the grammar alone fails on one. Version 1.4.1 then fixed one more construct, an array-typed last field with no ; before end, which let two more RTL units parse with the full grammar (Winapi.ShlObj and FireDAC.Phys.MongoDBCli), with no regressions. Version 1.4.2 only rebuilt the prebuilt binaries from 1.4.1.

What 100% means

All files the compiler would accept under the chosen define profile, after the preprocessor has picked the live branches. A file is not counted as a parser failure if it is not valid Delphi 13, if it targets another compiler, or if it is a deliberately broken test fixture. The other branches of each {$IFDEF} are not parsed in that run. To cover them, run again with a different profile.

06 — Using it yourself

The grammar is not tied to drag-lint

The grammars are MIT-licensed on GitHub and published to npm as tree-sitter-delphi13 and tree-sitter-delphi13-pure. Each package carries prebuilt native bindings for Windows, Linux and both macOS architectures, a WebAssembly build, and the query files.

  • From Node: npm install tree-sitter tree-sitter-delphi13, then parser.setLanguage(require('tree-sitter-delphi13')).
  • In a browser or a VS Code extension: load tree-sitter-delphi13.wasm with web-tree-sitter. Hosts like these can run a JavaScript preprocessor in front of the pure grammar (delphi13-preprocessor in the same repository), so they can reach the full 100%.
  • In an editor that loads one grammar: Neovim, Helix and Zed can load the full grammar and its queries directly. They cannot run a preprocessor, so expect the 98.47% figure there: highlighting and outline still work in every file, but a few files show an ERROR region.
  • From Delphi: do what drag-lint does. Load tree-sitter.dll and the grammar DLL, call tree_sitter_delphi13 to get the language, and drive the C API through a small wrapper.

Whichever host you choose, make the same decision drag-lint made. If you need every file read correctly, put a preprocessor in front of the parser and give it the define profile your project actually builds with. If you can live with a few ERROR regions, the full grammar alone is simpler and needs nothing else.

As of 2026-11-03, tree-sitter-delphi13 1.4.2: the table figures are for 1.4.0 (full and pure grammars), measured file by file on the RAD Studio 37.0 source tree (2,218 files, one unreadable), on a 1,506-case directive-word test set, and on the Micronite source tree (786 files). The drag-lint pipeline is described from its source on 2026-11-01 (DRagLint.Diagnostics.ParseCache, DRagLint.Preprocess). The 1.4.1 file counts come from that release's notes. drag-lint 1.40.0-alpha ships the 1.4.0 grammar; the 1.4.1 fix reaches it in a later release.