From dc771fc7adda661fc0aa7f8896dc59fcfdc39051 Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Tue, 23 Apr 2024 02:37:01 -0700 Subject: [PATCH] Working simple tree-sitter grammar --- experiments/tree-sitter-test/grammar.js | 13 +++++++-- experiments/tree-sitter-test/justfile | 4 +++ .../tree-sitter-test/test/corpus/test.txt | 28 +++++++++++-------- 3 files changed, 31 insertions(+), 14 deletions(-) diff --git a/experiments/tree-sitter-test/grammar.js b/experiments/tree-sitter-test/grammar.js index 2de25d1..5fcb29b 100644 --- a/experiments/tree-sitter-test/grammar.js +++ b/experiments/tree-sitter-test/grammar.js @@ -9,17 +9,20 @@ module.exports = grammar({ ), function_definition: $ => seq( - "fn", + 'fn', $.identifier, $.parameter_list, - optional($._type), + field("return_type", optional($._type)), $.block, ), parameter_list: $ => seq("(", /* TODO */ ")"), block: $ => seq( "{", - repeat(optional($._statement)), + choice( + repeat($._statement), + "", + ), "}" ), @@ -35,6 +38,10 @@ module.exports = grammar({ binary: $ => choice(prec.left(2, seq($._expression, "*", $._expression)), prec.left(1, seq($._expression, "+", $._expression))), _type: $ => "bool", + _type: $ => choice( + $.primitive_type, + ), + primitive_type: $ => choice("bool", "int"), identifier: $ => /[a-z]+/, } diff --git a/experiments/tree-sitter-test/justfile b/experiments/tree-sitter-test/justfile index 2ca36b2..7904349 100644 --- a/experiments/tree-sitter-test/justfile +++ b/experiments/tree-sitter-test/justfile @@ -1,4 +1,8 @@ +_default: + just --list # Test out the grammar test-grammar: + #!/usr/bin/env bash + tree-sitter generate tree-sitter test diff --git a/experiments/tree-sitter-test/test/corpus/test.txt b/experiments/tree-sitter-test/test/corpus/test.txt index ab26e36..0ef6cff 100644 --- a/experiments/tree-sitter-test/test/corpus/test.txt +++ b/experiments/tree-sitter-test/test/corpus/test.txt @@ -4,17 +4,23 @@ Initial test fn main() { } +---- +(source_file + (function_definition + (identifier) + (parameter_list) + (block) + ) +) + +==== +Another test +==== + +fn yolo() bool { } ---- -(source_file) - - -===== -Another -==== - -fn main() bool { } - ------- -() +(source_file + (function_definition + (identifier) (parameter_list) (primitive_type) (block)))