Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions docs/grammars/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# NCC Output Grammars

TextMate grammars for syntax-highlighting NCC's debug/intermediate output. They
mirror what the compiler actually prints, so pasted compiler dumps can be
colourised instead of guessed.

**Primary consumer: [johnhringiv.com](https://johnhringiv.com).** The website
highlights ncc output in blog write-ups with [Shiki](https://shiki.style/) using
the **vitesse-dark** theme. The website copy of these grammars is kept identical
to this folder; treat this repo as the source of truth and copy downstream.

| File | Highlights | Produced by |
| --- | --- | --- |
| [`tokens.json`](tokens.json) | `Processed tokens: [...]` token dump | `ncc file.c --lex` |
| [`ast-tree.json`](ast-tree.json) | The tree-view IRs at every stage | `ncc file.c --parse` / `--validate` / `--tacky` / `--codegen` |
| [`package.json`](package.json) | VS Code / JetBrains bundle manifest so the folder imports as a TextMate bundle | — |

## Source of truth

These grammars are derived from the code, not vice-versa. When the relevant
enums or pretty-printer change, update the grammar:

- **`tokens.json`** ← the `Token` enum in [`src/lexer.rs`](../../src/lexer.rs).
Tokens are printed with Rust's `{:?}`, so the matched words are the exact
variant names (`IntKeyword`, `Negation`, `BitwiseLeftShiftAssign`, …) and the
payload forms `Identifier("…")` / `ConstantInt("…")` etc.

- **`ast-tree.json`** ← the `ItfDisplay` implementations in
[`src/pretty.rs`](../../src/pretty.rs), plus the enums they format
(`parser`, `validate`, `tacky`, `codegen`).

## Colour scheme ⇄ `pretty.rs`

`src/pretty.rs` colours the tree view for the **terminal** (ANSI truecolor);
these grammars re-colour the *same* text for the **web** (Shiki, vitesse-dark).
They are meant to agree, so the grammar's scope names track the vitesse-dark
roles. The authoritative palette (RGB constants + which node gets which colour)
lives in the doc comment at the top of `pretty.rs`. In summary:

| Role | Colour | Examples |
| --- | --- | --- |
| Declarations | teal | `Program`, `FunctionDefinition`, `VarDeclaration` |
| Instructions / opcodes & expression nodes | gold | `Mov`, `Binary`, `Copy`, `Cast`, `Assignment` |
| Control flow | green | `Return`, `If`, `While`, `Conditional`, `None` |
| Operators & condition codes | muted red | `Add`, `Sub`, `NotEqual`, `E`, `NE`, `LE` |
| Names & jump labels (incl. `Data` global name) | olive | function names, `-> break_loop.0` |
| Locals / temporaries & `Pseudo` payload | cream | `temp.1`, `i.1` |
| Numbers / offsets & `Imm` immediates | cyan | `-4`, `Imm(3)` |
| Registers & `Pseudo` keyword | indigo | `AX`, `R10`, `SP`, `XMM0` |
| Memory-operand keywords | tan | `Stack(…)`, `Data(…)` |

The key idea is that **operands are coloured by storage class** — immediate
(cyan), register (indigo), memory (tan) — so a spill to memory (the expensive,
interesting event when reading codegen) stands out at a glance.

Two intentional parity gaps between the grammar and `pretty.rs`:

- Parser `Constant(Int(0))` literals are gold in `pretty.rs` but teal
(`constant.numeric`, the number/immediate family) in the grammar — the gold
isn't reachable from a flat vitesse scope, and teal is the more internally
consistent choice.
- Flat text can't distinguish some nodes the AST can: e.g. a temporary on the
right of `->` (`Copy 5 -> i.1`) is coloured like a jump label, because targets
share the `name.N` shape (`break_loop.0`) and the two are indistinguishable
without the tree.

### Potential: align `-S` with this palette

The `-S` flag (emit x86-64 assembly) is a **separate** colour path — it renders
real assembly via iced-x86's formatter, mapped to named 16-colour ANSI in
`get_color` (`src/main.rs`), not the vitesse truecolor constants above. It isn't
consumed by these grammars (assembly is highlighted with a stock `asm` grammar
downstream), so nothing needs to change. But the two terminal views disagree on
the same concepts — registers are indigo here vs `blue` in `-S`, instructions
gold vs `magenta` mnemonics, labels olive vs `green` (numbers already agree at
cyan). A future consistency pass could point `get_color` at these constants
(Register→indigo, Mnemonic→gold, Number→cyan, Label→olive), which would require
exposing the palette from `pretty.rs` (make the `const`s `pub` or lift them into
a shared module). Fine as-is for now.

## Multiple compiler versions, on purpose

Blog snippets are **pinned to the compiler version each post is written about** —
they are *not* refreshed to track `ncc`. So the grammar must highlight several
historical output formats at once, permanently. This is a standing design
constraint, not tech debt:

- `AllocateStack` / `DeallocateStack` — older stack-allocation form (current
`ncc` emits `Binary<Q> Sub Imm(n) -> SP`). Kept as an always-on rule.
- `Constant(0)` — older bare parser-literal form (current `ncc` emits
`Constant(Int(0))`). The parser-constant rule matches both.

When the compiler changes an output format, **add** the new form to the grammar;
don't replace the old one, or posts about earlier versions lose their
highlighting.

## Notes / known limitations

- TextMate matching is first-match-wins per position, so order matters:
payload operands (`Imm(…)`, `Stack(…)`, …), size markers (`<L>`/`<Q>`/`<D>`),
registers, and the `Label(…)` / `FunctionDefinition:` headers are matched
before the bare keyword lists. In particular a register destination
(`Mov R10 -> AX`) is matched *before* the arrow-target rule so it is coloured
as a register, not a jump label.
- Trailing `# …` annotations are matched as comments, so hand-annotated pastes
(`Copy a -> b # note`) don't mis-highlight words inside the note.
- `Return` prints as a statement (parser/validate) and as a TACKY instruction;
both are highlighted with one scope. The single-letter condition codes
(`E`, `A`, `B`, `G`, `L`) are matched as whole words after the
`<L>`/`<Q>`/`<D>` size markers have been consumed.
- The grammars only cover language features NCC currently implements
(`int`/`long`/`unsigned int`/`unsigned long`/`double`, the operators and
statements in the source, the SSE conversion/`XMM` machinery for `double`).
No pointers, structs, chars, etc. — add them here when the compiler grows
them.

## Regenerating / sanity-checking

```bash
cargo build --release
./target/release/ncc file.c --tacky | sed 's/\x1b\[[0-9;]*m//g' # strip ANSI to see raw labels
```

Compare the bare node/keyword words against the alternations in
`ast-tree.json`; every emitted label should fall into exactly one scope.
198 changes: 198 additions & 0 deletions docs/grammars/ast-tree.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
{
"name": "ast-tree",
"scopeName": "source.ast-tree",
"_comment": "TextMate grammar for NCC's tree-view pretty printer (src/pretty.rs) covering --parse, --validate, --tacky and --codegen output. Scope names are chosen to track the vitesse-dark colour roles documented at the top of src/pretty.rs. Earlier patterns win, so payload-carrying and size markers are matched before bare keywords.",
"patterns": [
{
"comment": "Comment lines",
"name": "comment.line.ast-tree",
"match": "^\\s*#.*$"
},
{
"comment": "Trailing annotations (e.g. `Copy a -> b # Store result`). Matched before the keyword rules so words inside a comment (like the legacy `Store`) are not mis-highlighted as instructions.",
"name": "comment.line.ast-tree",
"match": "#.*$"
},
{
"comment": "Box-drawing characters used for the tree",
"name": "punctuation.tree.ast-tree",
"match": "[\\u251c\\u2514\\u2502\\u2500\\u250c\\u2510\\u2518\\u252c\\u2534\\u253c]+"
},
{
"comment": "TACKY/codegen dataflow arrow (src -> dst)",
"name": "punctuation.arrow.ast-tree",
"match": "->"
},
{
"comment": "Assembly operand size marker <L> (longword) / <Q> (quadword) / <D> (double)",
"name": "storage.modifier.size.ast-tree",
"match": "<[LQD]>"
},
{
"comment": "Imm(<int>) immediate operand. Keyword coloured teal (constant.numeric) so the immediate reads as one constant together with its number.",
"match": "\\b(Imm)\\((-?[0-9]+)\\)",
"captures": {
"1": { "name": "constant.numeric.operand.ast-tree" },
"2": { "name": "constant.numeric.immediate.ast-tree" }
}
},
{
"comment": "Stack(<offset>) operand",
"match": "\\b(Stack)\\((-?[0-9]+)\\)",
"captures": {
"1": { "name": "constant.other.operand.ast-tree" },
"2": { "name": "constant.numeric.ast-tree" }
}
},
{
"comment": "Pseudo(<name>) operand — pseudo-register (pre-allocation virtual register). Keyword shares the indigo register colour since it is register-class, not memory.",
"match": "\\b(Pseudo)\\(([^)]*)\\)",
"captures": {
"1": { "name": "type.identifier.register.ast-tree" },
"2": { "name": "string.other.temporary.ast-tree" }
}
},
{
"comment": "Data(<name>) operand — static/global symbol. Keyword tan (memory); the global name uses the olive names colour (a global name is a name), avoiding a clash with the control-flow green.",
"match": "\\b(Data)\\(([^)]*)\\)",
"captures": {
"1": { "name": "constant.other.operand.ast-tree" },
"2": { "name": "entity.name.function.data.ast-tree" }
}
},
{
"comment": "Parser/validated Constant literal. Matches both the current typed form Constant(Int(0)) / Long / UInt / ULong / Double and the older bare form Constant(0) (blog snippets are pinned to the compiler version each post covers, so both formats persist). Teal (constant.numeric) so parser constants join the immediate/number 'constant' family across all stages, instead of the green that clashed with control-flow.",
"name": "constant.numeric.constant.ast-tree",
"match": "\\bConstant\\((?:(?:Int|Long|UInt|ULong|Double)\\([^)]*\\)|-?[0-9]+)\\)"
},
{
"comment": "TACKY Const debug value: ConstInt/ConstLong/ConstUInt/ConstULong/ConstDouble(...)",
"name": "constant.numeric.ast-tree",
"match": "\\bConst(?:Int|Long|UInt|ULong|Double)\\([^)]*\\)"
},
{
"comment": "Static initializer value: IntInit/LongInit/UIntInit/ULongInit/DoubleInit(...)",
"name": "constant.numeric.ast-tree",
"match": "\\b(?:Int|Long|UInt|ULong|Double)Init\\([^)]*\\)"
},
{
"comment": "Identifier(\"name\") leaf",
"name": "entity.name.function.ast-tree",
"match": "\\bIdentifier\\(\"[^\"]*\"\\)"
},
{
"comment": "Label(<target>) TACKY/codegen instruction with its label payload",
"match": "\\b(Label)\\(([^)]*)\\)",
"captures": {
"1": { "name": "support.function.ast-tree" },
"2": { "name": "entity.name.label.ast-tree" }
}
},
{
"comment": "FunctionDefinition: <name> header (TACKY/codegen)",
"match": "\\b(FunctionDefinition)(:)\\s*([A-Za-z_][A-Za-z0-9_]*)",
"captures": {
"1": { "name": "entity.name.class.ast-tree" },
"2": { "name": "punctuation.separator.ast-tree" },
"3": { "name": "entity.name.function.ast-tree" }
}
},
{
"comment": "StaticVariable: <name> header",
"match": "\\b(StaticVariable)(:)\\s*([A-Za-z_][A-Za-z0-9_]*)",
"captures": {
"1": { "name": "entity.name.class.ast-tree" },
"2": { "name": "punctuation.separator.ast-tree" },
"3": { "name": "entity.name.function.ast-tree" }
}
},
{
"comment": "CPU registers (System V scratch/arg set + SSE XMM). Matched BEFORE the arrow-target rule so a register on the right of `->` (e.g. `Mov R10 -> AX`) is coloured as a register, not mis-scoped as a jump label. Indigo gives registers their own hue, clearly separated from teal immediates/numbers and warm tan memory operands (Stack/Data).",
"name": "type.identifier.register.ast-tree",
"match": "\\b(AX|CX|DX|DI|SI|R8|R9|R10|R11|SP|XMM[0-9]+)\\b"
},
{
"comment": "Renamed locals / temporaries: name.<n>. Dusty-rose (the best clean/unstyled hue this warm theme offers that is distinct from instruction gold / memory tan; the cooler options in vitesse-dark all carry bold/italic diff-markup styling). Matched BEFORE the arrow-target rule so a temporary destination (`Copy x -> temp.1`) gets the same colour as when it appears as a source — otherwise the same variable renders two different colours. Real jump targets (else_label, end_label) have no .N suffix, so they still fall through to the arrow-target rule and stay label-coloured.",
"name": "string.other.temporary.ast-tree",
"match": "\\b[A-Za-z_][A-Za-z0-9_]*\\.[0-9]+\\b"
},
{
"comment": "Jump / branch target following an arrow",
"name": "entity.name.label.ast-tree",
"match": "(?<=->\\s)[A-Za-z_][A-Za-z0-9_.]*"
},
{
"comment": "FunCall / Call instruction followed by its callee name",
"match": "\\b(FunCall|Call)\\s+([A-Za-z_][A-Za-z0-9_]*)",
"captures": {
"1": { "name": "support.function.ast-tree" },
"2": { "name": "entity.name.function.ast-tree" }
}
},
{
"comment": "Top-level / declaration nodes (teal)",
"name": "entity.name.class.ast-tree",
"match": "\\b(Program|FunctionDefinition|FunDeclaration|VarDeclaration|StaticVariable|FunType)\\b"
},
{
"comment": "TACKY & codegen instructions and parser/validated expression nodes (teal)",
"name": "support.function.ast-tree",
"match": "\\b(Mov|Movsx|MovZeroExtend|Cvttsd2si|Cvtsi2sd|Binary|Unary|Cmp|Idiv|Div|Cdq|Jmp|JmpCC|SetCC|Push|Call|Ret|Copy|Jump|JumpIfZero|JumpIfNotZero|FunCall|SignExtend|Truncate|ZeroExtend|DoubleToInt|DoubleToUInt|IntToDouble|UIntToDouble|Cast|CompoundAssignment|Assignment|PostFix|PreFix|FunctionCall)\\b"
},
{
"comment": "Older-form instructions NOT emitted by the current NCC. Blog snippets are pinned to the compiler version each post covers, so this output is permanent (not a snippet to regenerate). Today's compiler lowers stack allocation to `Binary<Q> Sub Imm(n) -> SP` instead of AllocateStack/DeallocateStack; the grammar must highlight both across the post history.",
"name": "support.function.ast-tree",
"match": "\\b(AllocateStack|DeallocateStack)\\b"
},
{
"comment": "Statement / control-flow nodes (teal-green)",
"name": "keyword.control.ast-tree",
"match": "\\b(Return|Expression|If|Null|Goto|Labeled|Compound|Break|Continue|While|DoWhile|For|Switch|Case|Default|Conditional|None)\\b"
},
{
"comment": "Storage class / linkage markers",
"name": "storage.modifier.ast-tree",
"match": "\\b(storage_class:\\s*(?:static|extern)|static|extern|global|local)\\b"
},
{
"comment": "Types",
"name": "storage.type.ast-tree",
"match": "\\b(Int|Long|UInt|ULong|Double|FunType)\\b"
},
{
"comment": "Operators across parser, TACKY and codegen op enums",
"name": "keyword.operator.ast-tree",
"match": "\\b(BitwiseComplement|Negate|Not|Neg|Subtract|Sub|Add|Multiply|Mult|DivDouble|Divide|Remainder|BitwiseAnd|BitwiseOr|BitwiseXOr|BitwiseLeftShift|BitwiseRightShift|BitAnd|BitOr|BitXOr|BitShl|BitSar|BitShr|Shr|And|Or|Equal|NotEqual|LessThan|LessOrEqual|GreaterThan|GreaterOrEqual|Increment|Decrement)\\b"
},
{
"comment": "Condition codes (longer names first; sizes <L>/<Q> already consumed above)",
"name": "keyword.operator.condition.ast-tree",
"match": "\\b(NE|AE|BE|GE|LE|E|A|B|G|L)\\b"
},
{
"comment": "Branch labels carried inline, e.g. [label: 0] or [break_loop.0]",
"name": "entity.name.label.ast-tree",
"match": "\\[(?:label:\\s*)?[A-Za-z0-9_.]*\\]"
},
{
"comment": "Child field labels (uncoloured in the printer; highlighted here for readability)",
"name": "variable.parameter.label.ast-tree",
"match": "\\b(name|type|return|params|init|args|condition|then|else|body|post|expr|stmt|target_type|cases|align):"
},
{
"comment": "Vector length header, e.g. [3]",
"name": "constant.numeric.ast-tree",
"match": "\\[[0-9]+\\]"
},
{
"comment": "Bare integers (offsets, alignments, loop labels)",
"name": "constant.numeric.ast-tree",
"match": "\\b-?[0-9]+\\b"
},
{
"comment": "Any remaining quoted string",
"name": "string.quoted.double.ast-tree",
"match": "\"[^\"]*\""
}
]
}
33 changes: 33 additions & 0 deletions docs/grammars/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "ncc-output-grammars",
"displayName": "NCC Output Grammars",
"version": "0.1.0",
"description": "TextMate grammars for NCC's --lex token dump and --parse/--validate/--tacky/--codegen tree view. Importable as a TextMate bundle in JetBrains IDEs and VS Code.",
"engines": { "vscode": "*" },
"contributes": {
"languages": [
{
"id": "ncc-tokens",
"aliases": ["NCC Tokens"],
"extensions": [".ncctok"]
},
{
"id": "ncc-ast-tree",
"aliases": ["NCC AST Tree"],
"extensions": [".nccir"]
}
],
"grammars": [
{
"language": "ncc-tokens",
"scopeName": "source.tokens",
"path": "./tokens.json"
},
{
"language": "ncc-ast-tree",
"scopeName": "source.ast-tree",
"path": "./ast-tree.json"
}
]
}
}
Loading
Loading