diff --git a/lib/lrama/state.rb b/lib/lrama/state.rb index 1786d18a..ba006225 100644 --- a/lib/lrama/state.rb +++ b/lib/lrama/state.rb @@ -1,6 +1,7 @@ # rbs_inline: enabled # frozen_string_literal: true +require "set" require_relative "state/action" require_relative "state/inadequacy_annotation" require_relative "state/item" @@ -21,6 +22,8 @@ class State # type dominant_contributions = Hash[InadequacyAnnotation, Array[InadequacyAnnotation::action]?] # type item_pair = [State, Item] # type item_origins_cache = Hash[item_pair, Array[item_pair]] + # type annotation_key = [Integer, Grammar::Symbol, Array[InadequacyAnnotation::action], Hash[InadequacyAnnotation::action, Bitmap::bitmap?]] + # type annotation_indexes = Hash[Integer, Set[annotation_key]] # # @id: Integer # @accessing_symbol: Grammar::Symbol @@ -432,8 +435,8 @@ def annotate_manifestation # Definition 3.32 (annotate_predecessor) # - # @rbs (State predecessor, ?Array[InadequacyAnnotation] annotations) -> bool - def annotate_predecessor(predecessor, annotations = annotation_list) + # @rbs (State predecessor, ?Array[InadequacyAnnotation] annotations, ?annotation_indexes indexes) -> bool + def annotate_predecessor(predecessor, annotations = annotation_list, indexes = {}) always_contributions = {} #: Hash[Grammar::Symbol, Hash[Item, bool]] propagating_list = [] annotations.each {|annotation| @@ -480,27 +483,22 @@ def annotate_predecessor(predecessor, annotations = annotation_list) propagating_list << InadequacyAnnotation.new(annotation.state, annotation.token, annotation.actions, contribution_matrix) } - predecessor.append_annotation_list(propagating_list) + predecessor.append_annotation_list(propagating_list, indexes) end - # @rbs (Array[InadequacyAnnotation] propagating_list) -> bool - def append_annotation_list(propagating_list) - changed = false - propagating_by_key = propagating_list.group_by {|annotation| - [annotation.state.id, annotation.token, annotation.actions] - } + # @rbs (Array[InadequacyAnnotation] propagating_list, ?annotation_indexes indexes) -> bool + def append_annotation_list(propagating_list, indexes = {}) + return false if propagating_list.empty? - annotation_list.each do |annotation| - merging_list = propagating_by_key.delete([annotation.state.id, annotation.token, annotation.actions]) - changed = annotation.merge_matrix(merging_list.map(&:contribution_matrix)) || changed if merging_list + # Unioning distinct paths can hide differences in their dominant actions. + keys = indexes[id] ||= Set.new(annotation_list.map do |annotation| + [annotation.state.id, annotation.token, annotation.actions, annotation.contribution_matrix] #: annotation_key + end) + appending = propagating_list.select do |annotation| + keys.add?([annotation.state.id, annotation.token, annotation.actions, annotation.contribution_matrix]) end - - # Preserve propagation order even when unmatched keys are interleaved. - appending = propagating_list.select {|annotation| - propagating_by_key.key?([annotation.state.id, annotation.token, annotation.actions]) - } - @annotation_list += appending - changed || !appending.empty? + @annotation_list.concat(appending) + !appending.empty? end # Definition 3.31 (compute_lhs_contributions) diff --git a/lib/lrama/state/inadequacy_annotation.rb b/lib/lrama/state/inadequacy_annotation.rb index 8f24ff3d..384d399c 100644 --- a/lib/lrama/state/inadequacy_annotation.rb +++ b/lib/lrama/state/inadequacy_annotation.rb @@ -26,32 +26,6 @@ def contributed?(kernel_index) @contribution_matrix.any? {|action, contributions| !contributions.nil? && contributions[kernel_index] == 1 } end - # @rbs (Array[Hash[action, Bitmap::bitmap?]] another_matrixes) -> bool - def merge_matrix(another_matrixes) - changed = false - another_matrixes.each do |another_matrix| - another_matrix.each do |action, another_contributions| - unless @contribution_matrix.key?(action) - @contribution_matrix[action] = another_contributions - changed = true - next - end - contributions = @contribution_matrix[action] - next if contributions.nil? - - if another_contributions.nil? - @contribution_matrix[action] = nil - changed = true - else - merged = contributions | another_contributions - changed = true if merged != contributions - @contribution_matrix[action] = merged - end - end - end - changed - end - # Definition 3.42 (dominant_contribution) # # @rbs (State::lookahead_set lookaheads, Array[Item] kernels) -> Array[action]? diff --git a/lib/lrama/states.rb b/lib/lrama/states.rb index 238abc08..0c5158e8 100644 --- a/lib/lrama/states.rb +++ b/lib/lrama/states.rb @@ -759,6 +759,8 @@ def compute_inadequacy_annotations queue = @states.reject {|state| state.annotation_list.empty? } queued = Set.new(queue.map(&:id)) propagated = {} #: Hash[State::InadequacyAnnotation, Hash[State::InadequacyAnnotation::action, Bitmap::bitmap?]] + # Scope insertion indexes to this pass, while contribution matrices are fixed. + indexes = {} #: State::annotation_indexes while (curr = queue.shift) do queued.delete(curr.id) @@ -771,7 +773,7 @@ def compute_inadequacy_annotations true end curr.predecessors.each do |pred| - changed = curr.annotate_predecessor(pred, annotations) + changed = curr.annotate_predecessor(pred, annotations, indexes) queue << pred if changed && queued.add?(pred.id) end end diff --git a/sig/generated/lrama/state.rbs b/sig/generated/lrama/state.rbs index aa968ecf..fd40d619 100644 --- a/sig/generated/lrama/state.rbs +++ b/sig/generated/lrama/state.rbs @@ -14,6 +14,10 @@ module Lrama type item_origins_cache = Hash[item_pair, Array[item_pair]] + type annotation_key = [ Integer, Grammar::Symbol, Array[InadequacyAnnotation::action], Hash[InadequacyAnnotation::action, Bitmap::bitmap?] ] + + type annotation_indexes = Hash[Integer, Set[annotation_key]] + @id: Integer @accessing_symbol: Grammar::Symbol @@ -204,11 +208,11 @@ module Lrama # Definition 3.32 (annotate_predecessor) # - # @rbs (State predecessor, ?Array[InadequacyAnnotation] annotations) -> bool - def annotate_predecessor: (State predecessor, ?Array[InadequacyAnnotation] annotations) -> bool + # @rbs (State predecessor, ?Array[InadequacyAnnotation] annotations, ?annotation_indexes indexes) -> bool + def annotate_predecessor: (State predecessor, ?Array[InadequacyAnnotation] annotations, ?annotation_indexes indexes) -> bool - # @rbs (Array[InadequacyAnnotation] propagating_list) -> bool - def append_annotation_list: (Array[InadequacyAnnotation] propagating_list) -> bool + # @rbs (Array[InadequacyAnnotation] propagating_list, ?annotation_indexes indexes) -> bool + def append_annotation_list: (Array[InadequacyAnnotation] propagating_list, ?annotation_indexes indexes) -> bool # Definition 3.31 (compute_lhs_contributions) # diff --git a/sig/generated/lrama/state/inadequacy_annotation.rbs b/sig/generated/lrama/state/inadequacy_annotation.rbs index 7ea0fd3a..61f4fa63 100644 --- a/sig/generated/lrama/state/inadequacy_annotation.rbs +++ b/sig/generated/lrama/state/inadequacy_annotation.rbs @@ -20,9 +20,6 @@ module Lrama # @rbs (Integer kernel_index) -> bool def contributed?: (Integer kernel_index) -> bool - # @rbs (Array[Hash[action, Bitmap::bitmap?]] another_matrixes) -> bool - def merge_matrix: (Array[Hash[action, Bitmap::bitmap?]] another_matrixes) -> bool - # Definition 3.42 (dominant_contribution) # # @rbs (State::lookahead_set lookaheads, Array[Item] kernels) -> Array[action]? diff --git a/spec/fixtures/ielr/distinct_annotation_contributions.y b/spec/fixtures/ielr/distinct_annotation_contributions.y new file mode 100644 index 00000000..2d4840c4 --- /dev/null +++ b/spec/fixtures/ielr/distinct_annotation_contributions.y @@ -0,0 +1,36 @@ +%define lr.type ielr +%right 'b' +%right HIGH +%define api.pure full +%locations +%code provides { + static int yylex(YYSTYPE *, YYLTYPE *); + static void yyerror(YYLTYPE *, const char *); +} +%% +start: expr; +empty: %empty; +expr: expr tail 'a' tail | %empty | nested 'c'; +tail: 'b' | %empty %prec HIGH | 'b' nested empty; +prefix: %empty; +suffix: %empty; +nested: suffix prefix | expr tail 'b' tail; +%% +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(); +} diff --git a/spec/lrama/integration_spec.rb b/spec/lrama/integration_spec.rb index f74c5da3..0332f514 100644 --- a/spec/lrama/integration_spec.rb +++ b/spec/lrama/integration_spec.rb @@ -133,6 +133,19 @@ def generate_object(grammar_file_path, c_path, obj_path, command_args: []) end end + it "preserves distinct IELR annotation contributions through nullable recursive rules" do + Dir.mktmpdir do |directory| + c_path = File.join(directory, "distinct_annotations#{file_extension}") + obj_path = File.join(directory, "distinct_annotations") + generate_object(fixture_path("ielr/distinct_annotation_contributions.y"), c_path, obj_path) + + {"bbc" => true, "" => true, "c" => true, "bc" => true, "b" => false, "bb" => false}.each do |input, accepted| + _, error, status = Open3.capture3(obj_path, input) + expect(status.success?).to be(accepted), "#{input}: #{error}" + end + end + end + it "accepts all paths through nested IELR rules" do Dir.mktmpdir do |directory| c_path = File.join(directory, "nested#{file_extension}") diff --git a/spec/lrama/state_spec.rb b/spec/lrama/state_spec.rb index 47d66a4a..a8120c46 100644 --- a/spec/lrama/state_spec.rb +++ b/spec/lrama/state_spec.rb @@ -299,6 +299,16 @@ def annotation(contributions, from: origin, on: token, with: actions) expect(state.is_compatible?(current.dup)).to be(true) end + it "keeps distinct path contributions separate when checking compatibility" do + swapped = Lrama::State::InadequacyAnnotation.new(origin, token, entry.actions, { + actions.first => 0b10, other_action => 0b01, + }) + state.append_annotation_list([swapped]) + + expect(state.is_compatible?(incoming)).to be(false) + expect(entry.contribution_matrix).to eq({ actions.first => 0b01, other_action => 0b10 }) + end + it "reuses stored contributions and invalidates them when lookaheads are assigned" do expect(entry).to receive(:dominant_contribution).with(current, state.kernels).once.and_call_original expect(entry).to receive(:dominant_contribution).with(incoming, state.kernels).exactly(3).times.and_call_original @@ -455,7 +465,7 @@ def annotation(contributions, from: origin, on: token, with: actions) }) end - it "does not mutate cached lhs contributions when merging annotations for empty reductions" do + it "does not mutate cached lhs contributions when appending annotations for empty reductions" do state = described_class.new(0, token, [item]) empty_rule = rule.dup empty_rule.rhs = [] @@ -466,9 +476,10 @@ def annotation(contributions, from: origin, on: token, with: actions) state.annotate_manifestation entry = state.annotation_list.first - entry.merge_matrix([{ reduce => 0b01 }]) + state.append_annotation_list([Lrama::State::InadequacyAnnotation.new(state, token, [reduce], { reduce => 0b01 })]) - expect(entry.contribution_matrix[reduce]).to eq(0b01) + expect(entry.contribution_matrix[reduce]).to eq(0) + expect(state.annotation_list.last.contribution_matrix[reduce]).to eq(0b01) expect(contributions).to eq({ item => false }) end end @@ -591,29 +602,62 @@ def annotation(contributions, from: origin, on: token, with: actions) state.annotate_predecessor(predecessor) - expect(predecessor.annotation_list).to eq([existing]) - expect(existing.contribution_matrix[reduce]).to eq(0) - expect(existing.contribution_matrix[other_action]).to eq(0b10) + expect(predecessor.annotation_list.length).to eq(2) + expect(predecessor.annotation_list.map { |entry| entry.contribution_matrix[reduce] }).to eq([0, 0]) + expect(predecessor.annotation_list.map { |entry| entry.contribution_matrix[other_action] }).to eq([0, 0b10]) end end describe "#append_annotation_list" do - it "matches state IDs and equal action arrays while retaining the existing annotation" do + it "indexes existing annotations only once when an index is shared" do + existing = annotation(0b01) + state.annotation_list << existing + indexes = {} + expect(existing).to receive(:contribution_matrix).once.and_call_original + + 3.times do + expect(state.append_annotation_list([annotation(0b01)], indexes)).to be(false) + end + + expect(state.append_annotation_list([annotation(0b10)], indexes)).to be(true) + expect(state.append_annotation_list([annotation(0b10)], indexes)).to be(false) + expect(state.annotation_list.length).to eq(2) + end + + it "keeps the indexes for different receiving states separate" do + other = described_class.new(2, token, []) + indexes = {} + + [state, other].each do |receiver| + expect(receiver.append_annotation_list([annotation(0b01)], indexes)).to be(true) + expect(receiver.append_annotation_list([annotation(0b01)], indexes)).to be(false) + expect(receiver.annotation_list.length).to eq(1) + end + end + + it "rebuilds the index for independent calls after existing contributions change" do + existing = annotation(0b01) + state.append_annotation_list([existing]) + existing.contribution_matrix[actions.first] = 0b10 + + expect(state.append_annotation_list([annotation(0b10)])).to be(false) + expect(state.annotation_list).to eq([existing]) + end + + it "deduplicates equal matrices with matching state IDs and action arrays" do existing = annotation(0b10) state.annotation_list << existing - incoming = annotation(0b01, - from: described_class.new(origin.id, token, []), with: actions.dup) + incoming = annotation(0b10, from: described_class.new(origin.id, token, []), with: actions.dup) propagating = [incoming] - expect(state.append_annotation_list(propagating)).to be(true) + expect(state.append_annotation_list(propagating)).to be(false) expect(state.annotation_list).to eq([existing]) - expect(existing.contribution_matrix).to eq({ actions.first => 0b11 }) expect(propagating).to eq([incoming]) end it "keeps annotations for different states, token objects, or actions separate" do - existing = annotation(0) + existing = annotation(0b01) state.annotation_list << existing incoming = [ annotation(0b01, from: described_class.new(2, token, [])), @@ -624,96 +668,40 @@ def annotation(contributions, from: origin, on: token, with: actions) expect(state.append_annotation_list(incoming)).to be(true) expect(state.annotation_list).to eq([existing] + incoming) - expect(existing.contribution_matrix[actions.first]).to eq(0) - end - - it "merges all matching incoming annotations into only the first existing match" do - first = annotation(0) - duplicate = annotation(0) - state.annotation_list.concat([first, duplicate]) - - state.append_annotation_list([annotation(0b01), annotation(0b10)]) - - expect(state.annotation_list).to eq([first, duplicate]) - expect(first.contribution_matrix[actions.first]).to eq(0b11) - expect(duplicate.contribution_matrix[actions.first]).to eq(0) end - it "appends unmatched annotations in their original order, including duplicate keys" do - existing = annotation(0) + it "retains distinct matrices in arrival order and removes incoming duplicates" do + existing = annotation(0b01) + first = annotation(0b10) + second = annotation(0b01, from: described_class.new(2, token, [])) + third = annotation(0b11) state.annotation_list << existing - first = annotation(0, from: described_class.new(2, token, [])) - second = annotation(0b10, on: rule.rhs.last) - third = annotation(0b01, from: first.state) - state.append_annotation_list([first, annotation(0b01), second, third]) + expect(state.append_annotation_list([first, annotation(0b01), second, annotation(0b10), third])).to be(true) expect(state.annotation_list).to eq([existing, first, second, third]) - expect(first.contribution_matrix[actions.first]).to eq(0) - expect(existing.contribution_matrix[actions.first]).to eq(0b01) + expect(state.annotation_list.map { |entry| entry.contribution_matrix[actions.first] }).to eq([0b01, 0b10, 0b01, 0b11]) end - it "retains always contributions when conditional contributions arrive" do - existing = annotation(nil) - state.annotation_list << existing + [false, true].each do |reverse| + it "keeps unconditional, empty and conditional contributions distinct with reverse order #{reverse}" do + incoming = [annotation(nil), annotation(0), annotation(0b01)] + incoming.reverse! if reverse - expect(state.append_annotation_list([annotation(0b01), annotation(nil)])).to be(false) + expect(state.append_annotation_list(incoming)).to be(true) + expect(state.append_annotation_list([annotation(nil), annotation(0), annotation(0b01)])).to be(false) - expect(existing.contribution_matrix[actions.first]).to be_nil - expect(existing.dominant_contribution({ item => 0 }, [item])).to eq(actions) + expect(state.annotation_list).to eq(incoming) + expect(state.annotation_list.map { |entry| entry.contribution_matrix[actions.first] }).to eq(reverse ? [0b01, 0, nil] : [nil, 0, 0b01]) + end end - it "replaces conditional contributions with always contributions and reports the change once" do + it "reports no change for empty input" do existing = annotation(0b01) state.annotation_list << existing - expect(state.append_annotation_list([annotation(nil), annotation(0b01)])).to be(true) - expect(state.append_annotation_list([annotation(nil)])).to be(false) - - expect(existing.contribution_matrix[actions.first]).to be_nil - expect(existing.dominant_contribution({ item => 0 }, [item])).to eq(actions) - end - - it "does not mutate contributions shared with another annotation" do - contributions = 0 - first = annotation(contributions) - second = annotation(contributions, on: rule.rhs.last) - state.annotation_list.concat([first, second]) - - expect(state.append_annotation_list([annotation(0b01)])).to be(true) - - expect(first.contribution_matrix[actions.first]).to eq(0b01) - expect(second.contribution_matrix[actions.first]).to eq(0) - expect(contributions).to eq(0) - end - - it "reports no change when no contributions are added" do - state.annotation_list << annotation(0b01) - - expect(state.append_annotation_list([annotation(0b01)])).to be(false) expect(state.append_annotation_list([])).to be(false) - end - - it "does not treat empty conditional contributions as changes" do - existing = annotation(0) - state.annotation_list << existing - - expect(state.append_annotation_list([annotation(0)])).to be(false) - expect(existing.contribution_matrix[actions.first]).to eq(0) - end - - it "does not rescan incoming annotation keys for every existing annotation" do - incoming = 8.times.map do |index| - from = described_class.new(index + 1, token, []) - state.annotation_list << annotation(0, from: from) - annotation(0b01, from: from) - end - incoming.each { |entry| expect(entry).to receive(:state).at_most(2).times.and_call_original } - - state.append_annotation_list(incoming) - - expect(state.annotation_list.length).to eq(8) - expect(state.annotation_list).to all(have_attributes(contribution_matrix: { actions.first => 0b01 })) + expect(state.annotation_list).to eq([existing]) end end end diff --git a/spec/lrama/states_spec.rb b/spec/lrama/states_spec.rb index cddf92f6..97014388 100644 --- a/spec/lrama/states_spec.rb +++ b/spec/lrama/states_spec.rb @@ -2279,14 +2279,31 @@ class go to state 5 source.annotation_list.concat([unchanged, changed]) end + it "shares insertion indexes within a propagation pass and discards them between passes" do + allow(source).to receive(:predecessors).and_return([first_predecessor, second_predecessor]) + indexes = [] + allow(source).to receive(:annotate_predecessor) do |_, _, shared_indexes| + indexes << shared_indexes + false + end + + 2.times { states.send(:compute_inadequacy_annotations) } + + expect(indexes.length).to eq(4) + expect(indexes.first).to be_a(Hash) + expect(indexes[1]).to equal(indexes[0]) + expect(indexes[3]).to equal(indexes[2]) + expect(indexes[2]).not_to equal(indexes[0]) + end + [0b11, nil].each do |contributions| - it "repropagates merged and new annotations to every predecessor when contributions become #{contributions.inspect}" do + it "repropagates changed and new annotations to every predecessor when contributions become #{contributions.inspect}" do added = Lrama::State::InadequacyAnnotation.new(first_predecessor, token, [action], { action => 0b10 }) updater.annotation_list << Lrama::State::InadequacyAnnotation.new(updater, token, [action], { action => 0b10 }) allow(source).to receive(:predecessors).and_return([first_predecessor, second_predecessor]) allow(updater).to receive(:predecessors).and_return([source]) allow(updater).to receive(:annotate_predecessor) do - changed.merge_matrix([{ action => contributions }]) + changed.contribution_matrix[action] = contributions source.annotation_list << added true end @@ -2313,7 +2330,10 @@ class go to state 5 allow(source).to receive(:annotate_predecessor) do |_, annotations = source.annotation_list| propagated << annotations.map {|annotation| annotation.state.id } raise "Annotation propagation did not converge" if propagated.length > 2 - changed.merge_matrix([{ action => 0b11 }]) + next false if changed.contribution_matrix[action] == 0b11 + + changed.contribution_matrix[action] = 0b11 + true end states.send(:compute_inadequacy_annotations)