A Tree-sitter grammar for Parsing Expression Grammar (PEG) files.
This grammar supports the PEG format used by pigeon and similar PEG parsers, including an optional Go preamble section.
- Full PEG expression parsing: sequences, ordered choices (
/), quantifiers (*,+,?), predicates (&,!), grouping ((...)) - String literals with escape sequences (single-quoted
'...'and double-quoted"...") - Character classes (
[a-z]) - Any-character (
.) - Line comments (
# ...) - Optional Go preamble (
package,type ... Peg { ... })
| Node | Description |
|---|---|
source_file |
Root node |
go_section |
Optional Go preamble |
peg_section |
Contains all PEG rules |
peg_rule |
A single rule definition |
rule_name |
The name being defined (field: rule) |
operator_assign |
The <- operator |
rule_body |
The rule's expression |
choice_expr |
Alternatives separated by / |
sequence_expr |
Sequence of expressions |
prefix_expr |
Predicate + expression |
suffix_expr |
Expression + quantifier |
primary_expr |
Atom or group |
group |
Parenthesized expression |
identifier |
Rule reference |
literal |
String literal |
single_quoted |
'...' literal |
double_quoted |
"..." literal |
char_class |
[...] character class |
any_char |
. wildcard |
and_predicate |
& lookahead |
not_predicate |
! negative lookahead |
quantifier |
*, +, or ? |
comment |
# ... line comment |
- Node.js (for grammar development)
- A C compiler (for building the shared library)
- tree-sitter CLI
git clone https://github.com/shen390s/tree-sitter-peg.git
cd tree-sitter-peg/tree-sitter-peg
npm install
npx tree-sitter generateAdd to your nvim-treesitter configuration:
local parser_config = require("nvim-treesitter.parsers").get_parser_configs()
parser_config.peg = {
install_info = {
url = "https://github.com/shen390s/tree-sitter-peg",
files = { "tree-sitter-peg/src/parser.c" },
branch = "master",
},
filetype = "peg",
}Using the companion peg-ts-mode package:
;; Install the grammar
(add-to-list 'treesit-language-source-alist
'(peg "https://github.com/shen390s/tree-sitter-peg"
nil nil nil "tree-sitter-peg"))
(treesit-install-language-grammar 'peg)Or interactively after loading peg-ts-mode:
M-x peg-ts-mode-install-grammar
Add to languages.toml:
[[language]]
name = "peg"
scope = "source.peg"
file-types = ["peg"]
roots = []
[language.auto-pairs]
'(' = ')'
'[' = ']'
'{' = '}'
'"' = '"'
"'" = "'"
[[grammar]]
name = "peg"
source = { git = "https://github.com/shen390s/tree-sitter-peg", rev = "master", subpath = "tree-sitter-peg" }npx tree-sitter generatenpx tree-sitter testnpx tree-sitter parse examples/gnparser.pegpackage parser
type Engine Peg {
baseEngine
}
# Match a greeting
Greeting <- Hello _ Name '!'
Hello <- 'hello' / 'hi' / 'hey'
Name <- [A-Z] [a-z]+
_ <- ' '+
MIT