Skip to content
Open
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
91 changes: 38 additions & 53 deletions lib/lrama/state/inadequacy_annotation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,60 +41,45 @@ def dominant_contribution(lookaheads, kernels)

# @rbs (Array[action] actions) -> Array[action]
def resolve_conflict(actions)
# @type var shifts: Array[Action::Shift]
return actions if actions.length < 2

shift = actions.find { |action| action.is_a?(Action::Shift) } #: Action::Shift?
return actions unless shift
shift_prec = shift.next_sym.precedence
return actions unless shift_prec

# @type var reduces: Array[Action::Reduce]
shifts = actions.select {|action| action.is_a?(Action::Shift)}
reduces = actions.select {|action| action.is_a?(Action::Reduce) }

shifts.each do |shift|
reduces.each do |reduce|
sym = shift.next_sym

shift_prec = sym.precedence
reduce_prec = reduce.item.rule.precedence

# Can resolve only when both have prec
unless shift_prec && reduce_prec
next
end

case
when shift_prec < reduce_prec
# Reduce is selected
actions.delete(shift)
next
when shift_prec > reduce_prec
# Shift is selected
actions.delete(reduce)
next
end

# shift_prec == reduce_prec, then check associativity
case sym.precedence&.type
when :precedence
# %precedence only specifies precedence and not specify associativity
# then a conflict is unresolved if precedence is same.
next
when :right
# Shift is selected
actions.delete(reduce)
next
when :left
# Reduce is selected
actions.delete(shift)
next
when :nonassoc
# Can not resolve
#
# nonassoc creates "run-time" error, precedence creates "compile-time" error.
# Then omit both the shift and reduce.
#
# https://www.gnu.org/software/bison/manual/html_node/Using-Precedence.html
actions.delete(shift)
actions.delete(reduce)
else
raise "Unknown precedence type. #{sym}"
end
reduces = actions.select { |action| action.is_a?(Action::Reduce) }
# Match the order in which the parser tables resolve reductions against this shift.
reduces.sort_by! { |reduce| reduce.rule.id } if reduces.length > 1

reduces.each do |reduce|
reduce_prec = reduce.rule.precedence
next unless reduce_prec

if shift_prec < reduce_prec
actions.delete(shift)
break
elsif shift_prec > reduce_prec
actions.delete(reduce)
next
end

case shift_prec.type
when :precedence
# Equal precedence alone leaves the conflict unresolved.
next
when :right
actions.delete(reduce)
when :left
actions.delete(shift)
break
when :nonassoc
# An explicit syntax error overrides every remaining action for this token.
# https://www.gnu.org/software/bison/manual/html_node/Using-Precedence.html
return []
else
raise "Unknown precedence type. #{shift_prec.type}"
end
end

Expand Down
32 changes: 32 additions & 0 deletions spec/fixtures/ielr/annotation_conflict_order.y
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
%define lr.type ielr
%define api.pure full
%locations
%code provides {
static int yylex(YYSTYPE *, YYLTYPE *);
static void yyerror(YYLTYPE *, const char *);
}
%nonassoc '+'
%precedence 'x'
%%
start: low '+' | high '+' | 'a' low | 'a' high '+' | '+' high;
low: 'x' %prec '+';
high: 'x' | 'x' '+';
%%
static const char *input;

static int yylex(YYSTYPE *value, YYLTYPE *location) {
(void)value;
(void)location;
return *input ? *input++ : 0;
}

static void yyerror(YYLTYPE *location, const char *message) {
(void)location;
(void)message;
}

int main(int argc, char **argv) {
if (argc != 2) return 2;
input = argv[1];
return yyparse();
}
73 changes: 73 additions & 0 deletions spec/lrama/inadequacy_annotation_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# frozen_string_literal: true

RSpec.describe Lrama::State::InadequacyAnnotation do
describe '#dominant_contribution' do
[
['higher precedence before nonassociativity', "%nonassoc 'b'\n%precedence HIGH",
["empty: %empty %prec HIGH;", "direct: 'a' %prec 'b';"], ['direct', 'empty']],
['nonassociativity before higher precedence', "%nonassoc 'b'\n%precedence HIGH",
["direct: 'a' %prec 'b';", "empty: %empty %prec HIGH;"], []],
['left associativity before lower precedence', "%precedence LOW\n%left 'b'",
["empty: %empty %prec 'b';", "direct: 'a' %prec LOW;"], ['direct', 'empty']],
['lower precedence before left associativity', "%precedence LOW\n%left 'b'",
["direct: 'a' %prec LOW;", "empty: %empty %prec 'b';"], ['empty']],
['nonassociativity with another reduction', "%precedence LOW\n%nonassoc 'b'",
["empty: %empty %prec 'b';", "direct: 'a' %prec LOW;"], []],
['right associativity', "%right 'b'",
["empty: %empty %prec 'b';", "direct: 'a' %prec 'b';"], ['shift']],
['unresolved equal precedence', "%precedence 'b'",
["empty: %empty %prec 'b';", "direct: 'a' %prec 'b';"], ['shift', 'direct', 'empty']],
].each do |description, precedences, rules, expected|
it "matches state conflict resolution for #{description}" do
grammar = Lrama::Parser.new(<<~GRAMMAR, 'annotation_conflicts.y').parse
#{precedences}
%%
start: 'a' empty 'b' 'x' | direct 'b' 'y' | 'a' 'b' 'z';
#{rules.join("\n")}
GRAMMAR
grammar.prepare
states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new))
states.compute
state = states.states.find { |s| s.reduces.length == 2 }
token = grammar.find_symbol_by_s_value!("'b'")
actions = state.inadequacy_list.fetch(token)
annotation = described_class.new(state, token, actions, actions.map { |action| [action, nil] }.to_h)

original_actions = actions.dup
result = annotation.dominant_contribution({}, [])

expect(result.map { |action| action.is_a?(Lrama::State::Action::Shift) ? 'shift' : action.rule.lhs.name }).to eq(expected)
expect(annotation.actions).to eq(original_actions)
end
end

it 'distinguishes a nonassociative error from a reduction when comparing states' do
grammar = Lrama::Parser.new(<<~GRAMMAR, 'annotation_conflicts.y').parse
%nonassoc 'b'
%precedence HIGH
%%
start: first 'b' | second 'b' | 'a' 'b';
first: 'a' %prec 'b';
second: 'a' %prec HIGH;
GRAMMAR
grammar.prepare
states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new))
states.compute
state = states.states.find { |s| s.reduces.length == 2 }
token = grammar.find_symbol_by_s_value!("'b'")
actions = state.inadequacy_list.fetch(token)
first = actions.find { |action| action.is_a?(Lrama::State::Action::Reduce) && action.rule.lhs.name == 'first' }
matrix = actions.map { |action| [action, action == first ? 1 : nil] }.to_h
annotation = described_class.new(state, token, actions, matrix)
state.annotation_list << annotation
present = state.kernels.map { |item| [item, 1 << token.number] }.to_h
absent = state.kernels.map { |item| [item, 0] }.to_h
state.item_lookahead_set = present
state.lookaheads_recomputed = true

expect(state.is_compatible?(absent)).to be(false)
expect(annotation.dominant_contribution(present, state.kernels)).to eq([])
expect(annotation.dominant_contribution(absent, state.kernels).map { |action| action.rule.lhs.name }).to eq(['second'])
end
end
end
13 changes: 13 additions & 0 deletions spec/lrama/integration_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,19 @@ def generate_object(grammar_file_path, c_path, obj_path, command_args: [])
end
end

it "keeps a nonassociative error separate from a reduction in IELR states" do
Dir.mktmpdir do |directory|
c_path = File.join(directory, "annotation_order#{file_extension}")
obj_path = File.join(directory, "annotation_order")
generate_object(fixture_path("ielr/annotation_conflict_order.y"), c_path, obj_path)

{"ax+" => 0, "x+" => 1, "ax" => 0, "+x+" => 0}.each do |input, expected_status|
_, error, status = Open3.capture3(obj_path, input)
expect(status.exitstatus).to eq(expected_status), "#{input}: #{error}"
end
end
end

it "propagates initial item lookaheads through recursive IELR rules" do
Dir.mktmpdir do |directory|
c_path = File.join(directory, "initial_lookaheads#{file_extension}")
Expand Down