From 0aef27e506f6b0b2bb046ca2aabb3f07aec74ebc Mon Sep 17 00:00:00 2001 From: yui-knk Date: Tue, 12 Sep 2023 19:44:46 +0900 Subject: [PATCH] Improve error message for invalid named references --- lib/lrama/lexer/token.rb | 9 +++++++-- spec/lrama/parser_spec.rb | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/lib/lrama/lexer/token.rb b/lib/lrama/lexer/token.rb index 6221abe0..a6180746 100644 --- a/lib/lrama/lexer/token.rb +++ b/lib/lrama/lexer/token.rb @@ -28,8 +28,13 @@ def numberize_references(lhs, rhs) if lhs.referred_by?(ref_name) '$' else - # TODO: Better error message for wrong reference - rhs.find_index {|token| token.referred_by?(ref_name) } + 1 + index = rhs.find_index {|token| token.referred_by?(ref_name) } + + if index + index + 1 + else + raise "'#{ref_name}' is invalid name." + end end [ref[0], value, ref[2], ref[3], ref[4]] else diff --git a/spec/lrama/parser_spec.rb b/spec/lrama/parser_spec.rb index 0c1dd71c..32fe0fe8 100644 --- a/spec/lrama/parser_spec.rb +++ b/spec/lrama/parser_spec.rb @@ -1277,6 +1277,43 @@ class : keyword_class tSTRING keyword_end { code 1 } ]) end end + + context "includes invalid named references" do + it "raise an error" do + y = <<~INPUT +%{ +// Prologue +%} + +%union { + int i; +} + +%token NUM +%type expr + +%% + +input : /* empty */ + | input line +; + +line : '\\n' + | expr '\\n' + { printf("\\t%.10g\\n", $expr); } +; + +expr[result]: NUM + | expr[left] expr[right] '+' + { $results = $left + $right; } + | expr expr '-' + { $$ = $1 - $2; } +; + INPUT + + expect { Lrama::Parser.new(y).parse }.to raise_error("'results' is invalid name.") + end + end end end end