From 48bad14a5ca3478f2a2417d944573adff9f0e1e6 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 21:06:53 +0900 Subject: [PATCH 01/24] pslr: add grammar directives for PSLR(1) lexical specification Introduce the specification language for PSLR(1) pseudo-scanners: * %token-pattern declares a regex pattern for a terminal (with optional tag and alias), registering the terminal on the fly * %lex-prec declares lexical precedence with the seven PSLR operators (<~ <- -~ << -< Array[Grammar::Symbol] # def find_symbol_by_s_value!: (::String s_value) -> Grammar::Symbol # def ielr_defined?: () -> bool + # def pslr_defined?: () -> bool + # def token_patterns: () -> Array[Grammar::TokenPattern] + # def lex_prec: () -> Grammar::LexPrec + # def pslr_max_states: () -> Integer? + # def pslr_max_state_ratio: () -> Float? # end # # include Symbols::Resolver::_DelegatedMethods @@ -69,6 +80,10 @@ class Grammar # @union: Union # @precedences: Array[Precedence] # @start_nterm: Lrama::Lexer::Token::Base? + # @token_patterns: Array[Grammar::TokenPattern] + # @lex_prec: Grammar::LexPrec + # @symbol_sets: Hash[String, Array[Lexer::Token::Base]] + # @lex_tie: Grammar::LexTie # @nodes: Array[Node::Base] extend Forwardable @@ -103,6 +118,18 @@ class Grammar attr_accessor :define #: Hash[String, String?] attr_accessor :required #: bool attr_accessor :nodes #: Array[Node::Base] + attr_reader :token_patterns #: Array[Grammar::TokenPattern] + attr_reader :lex_prec #: Grammar::LexPrec + attr_reader :symbol_sets #: Hash[String, Array[Lexer::Token::Base]] + attr_reader :lex_tie #: Grammar::LexTie + attr_reader :lexer_contexts #: Hash[String, Grammar::LexerContext] + attr_reader :token_actions #: Array[Grammar::TokenAction] + + # Argument symbol names for each parameterized rule expansion. + # @rbs () -> Hash[String, Array[String]] + def parameterized_expansion_args + @parameterized_resolver.expansion_args + end def_delegators "@symbols_resolver", :symbols, :nterms, :terms, :add_nterm, :add_term, :find_term_by_s_value, :find_symbol_by_number!, :find_symbol_by_id!, @@ -139,6 +166,14 @@ def initialize(rule_counter, midrule_action_counter, locations, define = {}) @required = false @precedences = [] @start_nterm = nil + @token_patterns = [] + @lex_prec = Grammar::LexPrec.new + @symbol_sets = {} + @lex_tie = Grammar::LexTie.new + @lexer_contexts = {} + @lexer_context_counter = 0 + @token_pattern_counter = 0 + @token_actions = [] @nodes = nil append_special_symbols @@ -270,6 +305,7 @@ def prepare normalize_rules collect_symbols set_lhs_and_rhs + resolve_lexical_aliases fill_default_precedence fill_symbols fill_sym_to_rules @@ -289,6 +325,7 @@ def validate! validate_no_precedence_for_nterm! validate_rule_lhs_is_nterm! validate_duplicated_precedence! + validate_pslr_configuration! end # @rbs (Grammar::Symbol sym) -> Array[Rule] @@ -316,8 +353,364 @@ def ielr_defined? @define.key?('lr.type') && @define['lr.type'] == 'ielr' end + # @rbs () -> bool + def pslr_defined? + @define.key?('lr.type') && @define['lr.type'] == 'pslr' + end + + # @rbs () -> String? + def pslr_state_member + @define['api.pslr.state-member'] + end + + # @rbs () -> Integer? + def pslr_max_states + parse_pslr_positive_integer('pslr.max-states') + end + + # @rbs () -> Float? + def pslr_max_state_ratio + parse_pslr_positive_float('pslr.max-state-ratio') + end + + # True when the generated parser owns lexical analysis completely + # (%define api.pslr.lexer generated, the paper's own model). + # @rbs () -> bool + def pslr_lexer_generated? + @define['api.pslr.lexer'] == 'generated' + end + + # Base table construction for PSLR: extended IELR (default) or + # canonical LR(1) for debugging unresolved-conflict reports whose + # contexts would otherwise be merged (section 3.4.3). + # @rbs () -> String + def pslr_tables + value = @define['pslr.tables'] + return 'ielr' if value.nil? || value.empty? + + value + end + + # @rbs () -> bool + def pslr_canonical_tables? + pslr_defined? && pslr_tables == 'canonical-lr' + end + + # Terminals that the pseudo-scanner cannot produce: real terminals + # used by the grammar that have no %token-pattern (explicit or + # synthesized). Pure mode requires this list to be empty; bridge + # mode reports it so users know which tokens their yylex must keep + # producing. + # @rbs () -> Array[String] + def uncovered_pslr_terminals + covered = @token_patterns.map(&:name).to_set + + terms.reject do |term| + term == eof_symbol || term == error_symbol || term == undef_symbol || + covered.include?(term.name) + end.map(&:name) + end + + # LAC (lookahead correction) setting from %define parse.lac. + # PSLR parsers default to full because exploratory parses are what + # keep merged-state pseudo-scanning canonical-equivalent; other + # parser types default to none for Bison compatibility. + # @rbs () -> String + def parse_lac + value = @define['parse.lac'] + return (pslr_defined? ? 'full' : 'none') if value.nil? || value.empty? + + value + end + + # @rbs () -> bool + def parse_lac_full? + parse_lac == 'full' + end + + # @rbs () -> bool + def parse_lac_explicit_none? + @define['parse.lac'] == 'none' + end + + # @rbs () -> Array[Grammar::TokenPattern] + def layout_token_patterns + @token_patterns.select(&:layout?) + end + + # @rbs () -> Set[String] + def layout_token_names + layout_token_patterns.map(&:name).to_set + end + + # Add a token pattern from %token-pattern directive + # @rbs (id: Lexer::Token::Ident, pattern: Lexer::Token::Regex, ?alias_name: String?, ?tag: Lexer::Token::Tag?, lineno: Integer) -> Grammar::TokenPattern + def add_token_pattern(id:, pattern:, alias_name: nil, tag: nil, lineno:) + token_pattern = Grammar::TokenPattern.new( + id: id, + pattern: pattern, + alias_name: alias_name, + tag: tag, + lineno: lineno, + definition_order: @token_pattern_counter + ) + @token_pattern_counter += 1 + @token_patterns << token_pattern + + symbol_id = Grammar::Symbol::Id.from_token(id) + existing = @symbols_resolver.find_symbol_by_id(symbol_id) + term = add_term(id: symbol_id, alias_name: existing&.alias_name || alias_name, location: id.location) + term.alias_name = alias_name if alias_name + term.tag = tag if tag + + token_pattern + end + + # Add a symbol set from %symbol-set directive. + # @rbs (name: String, symbols: Array[Lexer::Token::Base]) -> Array[Lexer::Token::Base] + def add_symbol_set(name:, symbols:) + @symbol_sets[name] = symbols.map {|id| canonical_lexical_operand(id) } + end + + # Add lex-prec rules from %lex-prec directive. + # Stores as raw declaration for delayed expansion after implicit literal synthesis. + # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Grammar::LexPrec::Declaration + def add_lex_prec_rule(left_token:, operator:, right_token:, lineno:) + # Register terminals so they are known to the symbol resolver + canonical_lexical_operand(left_token) unless left_token.s_value == "yyall" || @symbol_sets.key?(left_token.s_value) + canonical_lexical_operand(right_token) unless right_token.s_value == "yyall" || @symbol_sets.key?(right_token.s_value) + + @lex_prec.add_declaration( + left_operand: left_token, + operator: operator, + right_operand: right_token, + lineno: lineno + ) + end + + # Finalize lexical declarations after implicit literal synthesis. + # Expands yyall and symbol-set operands using the post-synthesis token universe. + # Validates that identity-component operators are not used as self-pairs. + # @rbs () -> void + def finalize_lexical_declarations! + @lex_prec.declarations.each do |decl| + expand_pslr_operand(decl.left_operand).product(expand_pslr_operand(decl.right_operand)).each do |left, right| + validate_lex_prec_self_pair!(left, right, decl.operator, decl.lineno) + next if left.s_value == right.s_value && Grammar::LexPrec::IDENTITY_OPERATORS.include?(decl.operator) + + @lex_prec.add_rule( + left_token: left, + operator: decl.operator, + right_token: right, + lineno: decl.lineno + ) + end + end + end + + # Add lexical tie relationships from %lex-tie directive. + # @rbs (operands: Array[Lexer::Token::Base]) -> void + def add_lex_tie(operands:) + groups = operands.map {|operand| pslr_operand_group(operand) } + @lex_tie.add_tie_declaration(groups: groups) + end + + # Add no-tie declarations from %lex-no-tie directive. + # @rbs (operands: Array[Lexer::Token::Base]) -> void + def add_lex_no_tie(operands:) + groups = operands.map {|operand| pslr_operand_group(operand) } + @lex_tie.add_no_tie_declaration(groups: groups) + expanded = groups.map {|group| group.names.map {|name| Lrama::Lexer::Token::Ident.new(s_value: name) } } + i = 0 + while i < expanded.size + j = i + 1 + while j < expanded.size + left_group = expanded.fetch(i) + right_group = expanded.fetch(j) + left_group.product(right_group).each do |left, right| + next if left.s_value == right.s_value + + @lex_tie.add_no_tie(left.s_value, right.s_value) + end + j += 1 + end + i += 1 + end + end + + # Add a lexer context from %lexer-context directive + # @rbs (name: String, symbols: Array[Lexer::Token::Base]) -> Grammar::LexerContext + def add_lexer_context(name:, symbols:) + unless /\A[a-zA-Z_][a-zA-Z_0-9]*\z/.match?(name) + raise "%lexer-context name must be a valid C identifier, got #{name.inspect}." + end + + unless ctx = @lexer_contexts[name] + ctx = Grammar::LexerContext.new(name: name, index: @lexer_context_counter) + @lexer_context_counter += 1 + @lexer_contexts[name] = ctx + end + ctx.add_symbols(symbols) + ctx + end + + # Add a token action from %token-action directive + # @rbs (id: Lexer::Token::Ident, code: Lexer::Token::UserCode, lineno: Integer) -> Grammar::TokenAction + def add_token_action(id:, code:, lineno:) + token_action = Grammar::TokenAction.new( + token_id: id, + code: code, + lineno: lineno + ) + @token_actions << token_action + token_action + end + + # Find a token pattern by its name + # @rbs (String name) -> Grammar::TokenPattern? + def find_token_pattern(name) + @token_patterns.find { |tp| tp.name == name } + end + + # @rbs (Set[String] tokens) -> Set[String] + def expand_lexical_ties(tokens) + tokens.each_with_object(Set.new) do |token, expanded| + @lex_tie.tied_names(token).each {|name| expanded << name } + end + end + + # @rbs (ScannerFSA scanner_fsa) -> void + def finalize_lexical_ties!(scanner_fsa) + @lex_tie.finalize!( + @token_patterns.map(&:name), + scanner_fsa.pairwise_conflict_pairs + ) + end + + REGEX_LITERAL_ESCAPES = ["/", "\\", "*", "+", "?", "(", ")", "[", "]", "{", "}", ".", "|", "^", "$", "-"].freeze #: Array[String] + REGEX_CONTROL_ESCAPES = { + "\n" => "\\n", + "\t" => "\\t", + "\r" => "\\r", + "\f" => "\\f", + "\v" => "\\v" + }.freeze #: Hash[String, String] + + # @rbs () -> void + def synthesize_implicit_literal_token_patterns! + existing_names = @token_patterns.map(&:name).to_set + + locations = {} #: Hash[String, Lexer::Location] + @rules.each do |rule| + rule._rhs.each_with_index do |id, index| + location = rule._rhs_locations&.[](index) + locations[id.name] ||= location if location && !id.ident? + end + end + + terms.each do |term| + pattern = implicit_literal_regex_pattern(term) + next unless pattern + next if existing_names.include?(term.name) + + @token_patterns << Grammar::TokenPattern.new( + id: Lexer::Token::Ident.new(s_value: term.name, location: locations[term.name]), + pattern: Lexer::Token::Regex.new(s_value: "/#{pattern}/", location: locations[term.name]), + lineno: locations[term.name]&.first_line || 0, + definition_order: @token_pattern_counter + ) + @token_pattern_counter += 1 + existing_names << term.name + end + end + private + # Validate that identity-component operators are not applied to self-pairs. + # Self-pair is allowed only for length-only operators (-~ and -s). + # @rbs (Lexer::Token::Base left, Lexer::Token::Base right, Symbol operator, Integer lineno) -> void + def validate_lex_prec_self_pair!(left, right, operator, lineno) + return unless left.s_value == right.s_value + + # Length-only operators are fine for self-pairs (e.g., %lex-prec COM -s COM) + return if operator == Grammar::LexPrec::LONGEST + return if operator == Grammar::LexPrec::SHORTEST + + # Identity-component operators on self-pairs are errors + if Grammar::LexPrec::IDENTITY_OPERATORS.include?(operator) + raise "%lex-prec self-pair identity rule is invalid: #{left.s_value} cannot have an identity conflict with itself (line #{lineno})." + end + + # TOKEN_RIGHT_LENGTH (-<) on self-pair is contradictory + if operator == Grammar::LexPrec::TOKEN_RIGHT_LENGTH + raise "%lex-prec self-pair with -< is contradictory: #{left.s_value} (line #{lineno})." + end + end + + # @rbs (Grammar::Symbol term) -> String? + def implicit_literal_regex_pattern(term) + literal = + case term.id.kind + when :char + term.character_code.chr + when :string + term.name[1..-2] + end + return if !literal || literal.empty? || !literal.ascii_only? + + escape_regex_literal(literal) + end + + # @rbs (String literal) -> String + def escape_regex_literal(literal) + escaped = REGEX_CONTROL_ESCAPES[literal] + return escaped if escaped + + literal.each_char.map do |char| + if REGEX_LITERAL_ESCAPES.include?(char) + "\\#{char}" + else + char + end + end.join + end + + # @rbs () -> void + def validate_pslr_configuration! + return unless pslr_defined? + + member = pslr_state_member + if member && member !~ /\A[a-zA-Z_][a-zA-Z0-9_]*\z/ + raise %(%define api.pslr.state-member must be a valid C identifier, got "#{member}".) + end + + pslr_max_states + pslr_max_state_ratio + end + + # @rbs () -> void + def validate_parse_lac! + value = @define['parse.lac'] + return if value.nil? || value.empty? + return if %w[full none].include?(value) + + raise %(%define parse.lac must be "full" or "none", got "#{value}".) + end + + # Layout tokens are consumed by the pseudo-scanner and never reach + # the parser, so they must not appear in grammar rules (section 3.6). + # @rbs () -> void + def validate_no_layout_tokens_in_rules! + @rules.each do |rule| + rule.rhs.each do |sym| + next unless sym.term? + next unless sym.name.start_with?("YYLAYOUT") + + raise "layout token #{sym.name} must not appear in a grammar rule (line #{rule.lineno})." + end + end + end + # @rbs (Node::Base node) -> void def validate_character_literals_in(node) case node @@ -325,6 +718,13 @@ def validate_character_literals_in(node) node.tokens.each { |token| validate_character_literals_in(token) } when Node::TypeDecl, Node::NtermDecl node.symbols.each { |symbol| validate_character_literals_in(symbol) } + when Node::SymbolSetDecl, Node::LexerContextDecl + node.symbols.each { |symbol| validate_character_token!(symbol) } + when Node::LexTieDecl + node.operands.each { |operand| validate_character_token!(operand) } + when Node::LexPrecDecl + validate_character_token!(node.left) + validate_character_token!(node.right) when Node::Rule node.rhs.each { |rhs_node| validate_character_literals_in(rhs_node) } when Node::ParameterizedRule @@ -425,6 +825,22 @@ def _evaluate_nodes self.after_shift_error_token = node.id when Node::AfterPopStackDecl self.after_pop_stack = node.id + when Node::TokenPatternDecl + add_token_pattern(id: node.id, pattern: node.pattern, alias_name: node.alias_name, tag: node.tag, lineno: node.id.first_line) + when Node::TokenActionDecl + add_token_action(id: node.id, code: node.code, lineno: node.id.first_line) + when Node::LexerContextDecl + add_lexer_context(name: node.name, symbols: node.symbols) + when Node::SymbolSetDecl + add_symbol_set(name: node.name, symbols: node.symbols) + when Node::LexPrecDecl + add_lex_prec_rule(left_token: node.left, operator: node.operator, right_token: node.right, lineno: node.left.first_line) + when Node::LexTieDecl + if node.kind == :tie + add_lex_tie(operands: node.operands) + else + add_lex_no_tie(operands: node.operands) + end when Node::TokenDecl node.tokens.each do |token| add_term(id: Grammar::Symbol::Id.from_token(token.id), alias_name: token.alias_name, token_id: token.token_id, tag: token.tag, replace: true, location: token.id.location) @@ -520,6 +936,82 @@ def _evaluate_nodes end end + # @rbs () -> void + def validate_pslr_lexer! + value = @define['api.pslr.lexer'] + return if value.nil? || value.empty? + + unless value == 'generated' + raise %(%define api.pslr.lexer must be "generated", got "#{value}".) + end + + unless pslr_defined? + raise "%define api.pslr.lexer generated requires %define lr.type pslr." + end + end + + # @rbs () -> void + def validate_pslr_tables! + value = @define['pslr.tables'] + return if value.nil? || value.empty? + return if %w[ielr canonical-lr].include?(value) + + raise %(%define pslr.tables must be "ielr" or "canonical-lr", got "#{value}".) + end + + # @rbs (Lexer::Token::Base operand) -> Lexer::Token::Base + def canonical_lexical_operand(operand) + term = add_term(id: Grammar::Symbol::Id.from_token(operand), location: operand.location) + return operand if term.name == operand.s_value + + Lexer::Token::Ident.new(s_value: term.name, location: operand.location) + end + + # @rbs (Lexer::Token::Base operand) -> Array[Lexer::Token::Base] + def expand_pslr_operand(operand) + return @token_patterns.map(&:id) if operand.s_value == "yyall" + return @symbol_sets.fetch(operand.s_value) if @symbol_sets.key?(operand.s_value) + + [canonical_lexical_operand(operand)] + end + + # @rbs (Lexer::Token::Base operand) -> Grammar::LexTie::OperandGroup + def pslr_operand_group(operand) + if operand.s_value == "yyall" + Grammar::LexTie::OperandGroup.new(names: @token_patterns.map(&:name), kind: :all) + elsif @symbol_sets.key?(operand.s_value) + Grammar::LexTie::OperandGroup.new(names: @symbol_sets.fetch(operand.s_value).map(&:s_value), kind: :set) + else + Grammar::LexTie::OperandGroup.new(names: [canonical_lexical_operand(operand).s_value], kind: :token) + end + end + + # @rbs (String key) -> Integer? + def parse_pslr_positive_integer(key) + value = @define[key] + return nil if value.nil? || value.empty? + + parsed = Integer(value, 10) + raise %(%define #{key} must be greater than 0, got "#{value}".) unless 0 < parsed + + parsed + rescue ArgumentError + raise %(%define #{key} must be an integer, got "#{value}".) + end + + # @rbs (String key) -> Float? + def parse_pslr_positive_float(key) + value = @define[key] + return nil if value.nil? || value.empty? + + parsed = Float(value) + raise %(%define #{key} must be greater than or equal to 1.0, got "#{value}".) unless 1.0 <= parsed + + parsed + rescue ArgumentError + raise %(%define #{key} must be a number, got "#{value}".) + end + # @rbs () -> void def sort_precedence @precedences.sort_by! do |prec| @@ -766,6 +1258,26 @@ def set_lhs_and_rhs end end + # @rbs () -> void + def resolve_lexical_aliases + return if @lexer_contexts.empty? && @symbol_sets.empty? && @lex_tie.declarations.empty? + + aliases = {} #: Hash[String, String] + terms.each { |term| aliases[term.alias_name] = term.name if term.alias_name } + return if aliases.empty? + + (@symbol_sets.values + @lexer_contexts.values.map(&:symbols)).each do |tokens| + tokens.map! do |token| + name = aliases[token.s_value] + name ? Lexer::Token::Ident.new(s_value: name, location: token.location) : token + end + end + + @lex_tie.declarations.each do |decl| + decl.groups.each { |group| group.names.map! { |name| aliases.fetch(name, name) } } + end + end + # Rule inherits precedence from the last term in RHS. # # https://www.gnu.org/software/bison/manual/html_node/How-Precedence.html diff --git a/lib/lrama/grammar/lex_prec.rb b/lib/lrama/grammar/lex_prec.rb new file mode 100644 index 000000000..22c787356 --- /dev/null +++ b/lib/lrama/grammar/lex_prec.rb @@ -0,0 +1,200 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Grammar + # Represents lexical precedence rules defined by %lex-prec. + # + # Lrama accepts ASCII spellings for the PSLR paper operators: + # <~ identity conflict: right token wins; length conflict: longest wins + # <- identity conflict: right token wins + # -~ length conflict: longest wins + # << identity and length conflicts: right token wins + # -< length conflict: right token wins + # void + def initialize(left_operand:, operator:, right_operand:, lineno:) + @left_operand = left_operand + @operator = operator + @right_operand = right_operand + @lineno = lineno + end + end + + class Rule + attr_reader :left_token #: Lexer::Token::Base + attr_reader :operator #: Symbol + attr_reader :right_token #: Lexer::Token::Base + attr_reader :lineno #: Integer + + # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> void + def initialize(left_token:, operator:, right_token:, lineno:) + @left_token = left_token + @operator = operator + @right_token = right_token + @lineno = lineno + end + + # @rbs () -> String + def left_name + @left_token.s_value + end + + # @rbs () -> String + def right_name + @right_token.s_value + end + end + + attr_reader :rules #: Array[Rule] + attr_reader :declarations #: Array[Declaration] + attr_reader :used_rules #: Set[Integer] + + # @rbs () -> void + def initialize + @rules = [] + @declarations = [] + @used_rules = Set.new + end + + # Mark a rule as used by conflict resolution. + # @rbs (Integer rule_index) -> void + def mark_used(rule_index) + @used_rules << rule_index + end + + # Returns rules that were never used in conflict resolution. + # @rbs () -> Array[Rule] + def useless_rules + @rules.each_with_index.select { |_, i| !@used_rules.include?(i) }.map(&:first) + end + + # Store a raw declaration for delayed expansion. + # @rbs (left_operand: Lexer::Token::Base, operator: Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> Declaration + def add_declaration(left_operand:, operator:, right_operand:, lineno:) + decl = Declaration.new( + left_operand: left_operand, + operator: operator, + right_operand: right_operand, + lineno: lineno + ) + @declarations << decl + decl + end + + # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Rule + def add_rule(left_token:, operator:, right_token:, lineno:) + rule = Rule.new( + left_token: left_token, + operator: operator, + right_token: right_token, + lineno: lineno + ) + @rules << rule + rule + end + + # True when winner explicitly wins an identity conflict against loser. + # The relation is intentionally not transitive. + # @rbs (String winner, String loser, ?track: bool) -> bool + def identity_precedes?(winner, loser, track: false) + return true if winner == loser + + @rules.each_with_index.any? do |rule, i| + if IDENTITY_OPERATORS.include?(rule.operator) && + rule.left_name == loser && + rule.right_name == winner + mark_used(i) if track + true + else + false + end + end + end + + # True when rule declares a longest-match length relation for the pair. + # @rbs (String token1, String token2) -> bool + def longest_pair?(token1, token2) + pair_rule?(token1, token2, LONGEST_OPERATORS) + end + + # True when rule declares a shortest-match length relation for the pair. + # @rbs (String token1, String token2) -> bool + def shortest_pair?(token1, token2) + pair_rule?(token1, token2, SHORTEST_OPERATORS) + end + + # Returns the explicit right-token length winner for a pair, if any. + # @rbs (String token1, String token2) -> String? + def right_token_length_winner(token1, token2) + rule = @rules.find do |r| + RIGHT_TOKEN_LENGTH_OPERATORS.include?(r.operator) && + ((r.left_name == token1 && r.right_name == token2) || + (r.left_name == token2 && r.right_name == token1)) + end + + rule&.right_name + end + + private + + # @rbs (String token1, String token2, Array[Symbol] operators) -> bool + def pair_rule?(token1, token2, operators) + @rules.any? do |rule| + operators.include?(rule.operator) && + ((rule.left_name == token1 && rule.right_name == token2) || + (rule.left_name == token2 && rule.right_name == token1)) + end + end + end + end +end diff --git a/lib/lrama/grammar/lex_tie.rb b/lib/lrama/grammar/lex_tie.rb new file mode 100644 index 000000000..b4d89557c --- /dev/null +++ b/lib/lrama/grammar/lex_tie.rb @@ -0,0 +1,290 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +require "set" + +module Lrama + class Grammar + # Stores PSLR lexical ties and explicit no-tie declarations. + # + # Lexical ties expand acc(sp); they never resolve a scanner conflict by + # themselves. Conflict selection is still handled by %lex-prec. + class LexTie + class OperandGroup + attr_reader :names #: Array[String] + attr_reader :kind #: ::Symbol + + # @rbs (names: Array[String], kind: ::Symbol) -> void + def initialize(names:, kind:) + @names = names + @kind = kind + end + end + + class Declaration + attr_reader :kind #: ::Symbol + attr_reader :groups #: Array[OperandGroup] + attr_reader :lineno #: Integer + + # @rbs (kind: ::Symbol, groups: Array[OperandGroup], lineno: Integer) -> void + def initialize(kind:, groups:, lineno:) + @kind = kind + @groups = groups + @lineno = lineno + end + end + + class Decision + attr_reader :kind #: ::Symbol + attr_reader :specificity #: Integer + attr_reader :lineno #: Integer + + # @rbs (kind: ::Symbol, specificity: Integer, lineno: Integer) -> void + def initialize(kind:, specificity:, lineno:) + @kind = kind + @specificity = specificity + @lineno = lineno + end + end + + attr_reader :ties #: Hash[String, Set[String]] + attr_reader :no_ties #: Set[[String, String]] + attr_reader :declarations #: Array[Declaration] + + # @rbs () -> void + def initialize + @ties = Hash.new { |h, k| h[k] = Set.new([k]) } + @no_ties = Set.new + @declarations = [] + end + + # @rbs (String left, String right) -> void + def add_tie(left, right) + left_set = tied_names(left) + right_set = tied_names(right) + merged = left_set | right_set + + merged.each do |name| + @ties[name] = merged.dup + end + end + + # @rbs (String left, String right) -> void + def add_no_tie(left, right) + @no_ties << pair_key(left, right) + end + + # @rbs (groups: Array[OperandGroup], ?lineno: Integer) -> void + def add_tie_declaration(groups:, lineno: 0) + @declarations << Declaration.new(kind: :tie, groups: groups, lineno: lineno) + end + + # @rbs (groups: Array[OperandGroup], ?lineno: Integer) -> void + def add_no_tie_declaration(groups:, lineno: 0) + @declarations << Declaration.new(kind: :no_tie, groups: groups, lineno: lineno) + end + + # @rbs (Array[String] token_names, Set[[String, String]] conflict_pairs) -> void + def finalize!(token_names, conflict_pairs) + decisions = {} #: Hash[[String, String], Decision] + + @declarations.each do |declaration| + declaration_pairs(declaration, token_names, conflict_pairs).each do |pair, specificity| + apply_decision(decisions, pair, Decision.new(kind: declaration.kind, specificity: specificity, lineno: declaration.lineno)) + end + end + + rebuild_relations(token_names, decisions) + end + + # @rbs (String name) -> Set[String] + def tied_names(name) + @ties[name].dup + end + + # @rbs (String left, String right) -> bool + def tied?(left, right) + tied_names(left).include?(right) + end + + # @rbs (String left, String right) -> bool + def no_tie?(left, right) + @no_ties.include?(pair_key(left, right)) + end + + # @rbs () -> Array[[String, String]] + def no_ties_conflicting_with_ties + @no_ties.select do |left, right| + tied?(left, right) + end + end + + private + + # @rbs (Hash[[String, String], Decision] decisions, [String, String] pair, Decision decision) -> void + def apply_decision(decisions, pair, decision) + current = decisions[pair] + if current.nil? || current.specificity < decision.specificity + decisions[pair] = decision + return + end + + if current.specificity == decision.specificity && current.kind != decision.kind + raise "%lex-tie and %lex-no-tie conflict for #{pair.join(' ')}." + end + end + + # @rbs (Declaration declaration, Array[String] token_names, Set[[String, String]] conflict_pairs) -> Array[[[String, String], Integer]] + def declaration_pairs(declaration, token_names, conflict_pairs) + pairs = [] #: Array[[[String, String], Integer]] + + declaration.groups.combination(2) do |left_group, right_group| + next unless left_group && right_group + + specificity = group_specificity(left_group, right_group) + left_names = names_for_group(left_group, token_names) + right_names = names_for_group(right_group, token_names) + + left_names.product(right_names).each do |left, right| + next if left == right + + pair = pair_key(left, right) + if declaration.kind == :tie && specificity < 3 + next unless conflict_pairs.include?(pair) + end + + if declaration.kind == :no_tie && specificity < 3 + next unless conflict_pairs.include?(pair) + end + + pairs << [pair, specificity] + end + end + + pairs + end + + # @rbs (OperandGroup group, Array[String] token_names) -> Array[String] + def names_for_group(group, token_names) + return token_names if group.kind == :all + + group.names + end + + # @rbs (OperandGroup left, OperandGroup right) -> Integer + def group_specificity(left, right) + return 3 if left.kind == :token && right.kind == :token + return 0 if left.kind == :all && right.kind == :all + return 2 if left.kind == :token || right.kind == :token + + 1 + end + + # @rbs (Array[String] token_names, Hash[[String, String], Decision] decisions) -> void + def rebuild_relations(token_names, decisions) + parents = {} #: Hash[String, String] + tie_specificities = {} #: Hash[[String, String], Integer] + token_names.each {|name| parents[name] = name } + + decisions.each do |pair, decision| + next unless decision.kind == :tie + + union(parents, pair[0], pair[1]) + tie_specificities[pair] = decision.specificity + end + + @ties = Hash.new { |h, k| h[k] = Set.new([k]) } + groups = token_names.group_by {|name| root(parents, name) } + groups.each_value do |names| + tied = names.to_set + names.each {|name| @ties[name] = tied.dup } + end + + closure_specificities = {} #: Hash[[String, String], Integer] + groups.each_value do |names| + names.combination(2) do |left, right| + next unless left && right + + pair = pair_key(left, right) + closure_specificities[pair] = tie_specificity_between(left, right, tie_specificities) + end + end + + @no_ties = Set.new + decisions.each do |pair, decision| + next unless decision.kind == :no_tie + + tie_specificity = closure_specificities[pair] + if tie_specificity && decision.specificity >= tie_specificity + raise "%lex-no-tie #{pair[0]} #{pair[1]} conflicts with an existing %lex-tie closure." + end + + @no_ties << pair unless tie_specificity + end + end + + # @rbs (Hash[String, String] parents, String name) -> String + def root(parents, name) + parents[name] ||= name + while parents[name] != name + parents[name] = parents[parents[name]] + name = parents[name] + end + name + end + + # @rbs (Hash[String, String] parents, String left, String right) -> void + def union(parents, left, right) + left_root = root(parents, left) + right_root = root(parents, right) + return if left_root == right_root + + parents[right_root] = left_root + end + + # Compute closure specificity between two tokens via tie graph BFS. + # Path specificity = min(edge specificities on the path). + # Result = max over all paths connecting left and right. + # @rbs (String left, String right, Hash[[String, String], Integer] tie_specificities) -> Integer + def tie_specificity_between(left, right, tie_specificities) + direct = tie_specificities[pair_key(left, right)] + return direct if direct + + # Build adjacency list from tie edges + graph = Hash.new { |h, k| h[k] = [] } #: Hash[String, Array[[String, Integer]]] + tie_specificities.each do |(a, b), specificity| + graph[a] << [b, specificity] + graph[b] << [a, specificity] + end + + return 0 unless graph.key?(left) + + # BFS/Dijkstra-like: find path from left to right maximizing min-edge specificity + # best[node] = best (max) path-min-specificity to reach node from left + best = { left => Float::INFINITY } #: Hash[String, Integer | Float] + queue = [[left, Float::INFINITY]] #: Array[[String, Integer | Float]] + + until queue.empty? + node, path_min = queue.shift + next unless node && path_min + + graph[node].each do |neighbor, edge_spec| + new_min = [path_min, edge_spec].min + if !best.key?(neighbor) || new_min > best[neighbor] + best[neighbor] = new_min + queue << [neighbor, new_min] + end + end + end + + result = best[right] + result && result != Float::INFINITY ? result.to_i : 0 + end + + # @rbs (String left, String right) -> [String, String] + def pair_key(left, right) + left <= right ? [left, right] : [right, left] + end + end + end +end diff --git a/lib/lrama/grammar/lexer_context.rb b/lib/lrama/grammar/lexer_context.rb new file mode 100644 index 000000000..e779899f4 --- /dev/null +++ b/lib/lrama/grammar/lexer_context.rb @@ -0,0 +1,39 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Grammar + # Represents a lexer context defined by %lexer-context directive. + # + # Example: + # %lexer-context BEG keyword_if keyword_unless '(' '[' '{' + # + # The bitmask value is automatically assigned by definition order (1 << index). + class LexerContext + attr_reader :name #: String + attr_reader :index #: Integer + attr_reader :symbols #: Array[Lexer::Token::Ident] + + # @rbs (name: String, index: Integer) -> void + def initialize(name:, index:) + @name = name + @index = index + @symbols = [] + end + + # Bitmask value for this context (1 << index). + # @rbs () -> Integer + def bitmask + 1 << @index + end + + # Add symbols that belong to this context. + # @rbs (Array[Lexer::Token::Ident] syms) -> void + def add_symbols(syms) + syms.each do |sym| + @symbols << sym + end + end + end + end +end diff --git a/lib/lrama/grammar/node.rb b/lib/lrama/grammar/node.rb index 2739950c8..3e863eec3 100644 --- a/lib/lrama/grammar/node.rb +++ b/lib/lrama/grammar/node.rb @@ -15,6 +15,9 @@ require_relative "node/expect_decl" require_relative "node/initial_action_decl" require_relative "node/lex_param_decl" +require_relative "node/lex_prec_decl" +require_relative "node/lex_tie_decl" +require_relative "node/lexer_context_decl" require_relative "node/locations_decl" require_relative "node/no_stdlib_decl" require_relative "node/nterm_decl" @@ -29,7 +32,10 @@ require_relative "node/rule_rhs" require_relative "node/start_decl" require_relative "node/symbol" +require_relative "node/symbol_set_decl" require_relative "node/token" +require_relative "node/token_action_decl" require_relative "node/token_decl" +require_relative "node/token_pattern_decl" require_relative "node/type_decl" require_relative "node/union_decl" diff --git a/lib/lrama/grammar/node/lex_prec_decl.rb b/lib/lrama/grammar/node/lex_prec_decl.rb new file mode 100644 index 000000000..89cbf44e9 --- /dev/null +++ b/lib/lrama/grammar/node/lex_prec_decl.rb @@ -0,0 +1,22 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Grammar + module Node + class LexPrecDecl < Base + attr_reader :left #: Lexer::Token::Base + attr_reader :operator #: ::Symbol + attr_reader :right #: Lexer::Token::Base + + # @rbs (left: Lexer::Token::Base, operator: ::Symbol, right: Lexer::Token::Base, location: Lexer::Location) -> void + def initialize(left:, operator:, right:, location:) + @left = left + @operator = operator + @right = right + super(location: location) + end + end + end + end +end diff --git a/lib/lrama/grammar/node/lex_tie_decl.rb b/lib/lrama/grammar/node/lex_tie_decl.rb new file mode 100644 index 000000000..3561b7be6 --- /dev/null +++ b/lib/lrama/grammar/node/lex_tie_decl.rb @@ -0,0 +1,20 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Grammar + module Node + class LexTieDecl < Base + attr_reader :operands #: Array[Lexer::Token::Base] + attr_reader :kind #: :tie | :no_tie + + # @rbs (operands: Array[Lexer::Token::Base], kind: :tie | :no_tie, location: Lexer::Location) -> void + def initialize(operands:, kind:, location:) + @operands = operands + @kind = kind + super(location: location) + end + end + end + end +end diff --git a/lib/lrama/grammar/node/lexer_context_decl.rb b/lib/lrama/grammar/node/lexer_context_decl.rb new file mode 100644 index 000000000..03a9d9a51 --- /dev/null +++ b/lib/lrama/grammar/node/lexer_context_decl.rb @@ -0,0 +1,20 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Grammar + module Node + class LexerContextDecl < Base + attr_reader :name #: String + attr_reader :symbols #: Array[Lexer::Token::Base] + + # @rbs (name: String, symbols: Array[Lexer::Token::Base], location: Lexer::Location) -> void + def initialize(name:, symbols:, location:) + @name = name + @symbols = symbols + super(location: location) + end + end + end + end +end diff --git a/lib/lrama/grammar/node/symbol_set_decl.rb b/lib/lrama/grammar/node/symbol_set_decl.rb new file mode 100644 index 000000000..a80925bb6 --- /dev/null +++ b/lib/lrama/grammar/node/symbol_set_decl.rb @@ -0,0 +1,20 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Grammar + module Node + class SymbolSetDecl < Base + attr_reader :name #: String + attr_reader :symbols #: Array[Lexer::Token::Base] + + # @rbs (name: String, symbols: Array[Lexer::Token::Base], location: Lexer::Location) -> void + def initialize(name:, symbols:, location:) + @name = name + @symbols = symbols + super(location: location) + end + end + end + end +end diff --git a/lib/lrama/grammar/node/token_action_decl.rb b/lib/lrama/grammar/node/token_action_decl.rb new file mode 100644 index 000000000..412360351 --- /dev/null +++ b/lib/lrama/grammar/node/token_action_decl.rb @@ -0,0 +1,20 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Grammar + module Node + class TokenActionDecl < Base + attr_reader :id #: Lexer::Token::Ident + attr_reader :code #: Lexer::Token::UserCode + + # @rbs (id: Lexer::Token::Ident, code: Lexer::Token::UserCode, location: Lexer::Location) -> void + def initialize(id:, code:, location:) + @id = id + @code = code + super(location: location) + end + end + end + end +end diff --git a/lib/lrama/grammar/node/token_pattern_decl.rb b/lib/lrama/grammar/node/token_pattern_decl.rb new file mode 100644 index 000000000..c157f7357 --- /dev/null +++ b/lib/lrama/grammar/node/token_pattern_decl.rb @@ -0,0 +1,24 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Grammar + module Node + class TokenPatternDecl < Base + attr_reader :id #: Lexer::Token::Ident + attr_reader :pattern #: Lexer::Token::Regex + attr_reader :alias_name #: String? + attr_accessor :tag #: Lexer::Token::Tag? + + # @rbs (id: Lexer::Token::Ident, pattern: Lexer::Token::Regex, alias_name: String?, location: Lexer::Location) -> void + def initialize(id:, pattern:, alias_name:, location:) + @id = id + @pattern = pattern + @alias_name = alias_name + @tag = nil + super(location: location) + end + end + end + end +end diff --git a/lib/lrama/grammar/parameterized/resolver.rb b/lib/lrama/grammar/parameterized/resolver.rb index 008ef04c4..d9a4303d2 100644 --- a/lib/lrama/grammar/parameterized/resolver.rb +++ b/lib/lrama/grammar/parameterized/resolver.rb @@ -7,11 +7,13 @@ class Parameterized class Resolver attr_accessor :rules #: Array[Rule] attr_accessor :created_lhs_list #: Array[Grammar::Symbol::Id] + attr_reader :expansion_args #: Hash[String, Array[String]] # @rbs () -> void def initialize @rules = [] @created_lhs_list = [] + @expansion_args = {} end # @rbs (Rule rule) -> Array[Rule] @@ -34,6 +36,14 @@ def created_lhs(lhs_s_value) @created_lhs_list.reverse.find { |created_lhs| created_lhs.name == lhs_s_value } end + # Register the argument symbol names for a parameterized rule expansion. + # Used by LexerContextClassifier to inherit context from arguments. + # + # @rbs (String lhs_s_value, Array[String] args) -> void + def register_expansion_args(lhs_s_value, args) + @expansion_args[lhs_s_value] = args + end + # @rbs () -> Array[Rule] def redefined_rules @rules.select { |rule| @rules.count { |r| r.name == rule.name && r.required_parameters_count == rule.required_parameters_count } > 1 } diff --git a/lib/lrama/grammar/rule_builder.rb b/lib/lrama/grammar/rule_builder.rb index 4c3b2226f..417a17acc 100644 --- a/lib/lrama/grammar/rule_builder.rb +++ b/lib/lrama/grammar/rule_builder.rb @@ -174,6 +174,9 @@ def process_rhs lhs_id = Grammar::Symbol::Id.new(name: lhs_s_value, kind: :ident) replaced_rhs << lhs_id @parameterized_resolver.created_lhs_list << lhs_id + @parameterized_resolver.register_expansion_args(lhs_s_value, node.args.map { |arg| + arg.is_a?(Node::RuleRhs::InstantiateRule) ? bindings.concatenated_args_str(arg) : arg.name + }) parameterized_rule.rhs.each do |r| rule_builder = RuleBuilder.new(@rule_counter, @midrule_action_counter, @parameterized_resolver, lhs_tag: node.lhs_tag || parameterized_rule.tag) rule_builder.lhs = lhs_id diff --git a/lib/lrama/grammar/symbol.rb b/lib/lrama/grammar/symbol.rb index de8a58ef1..fda4325c5 100644 --- a/lib/lrama/grammar/symbol.rb +++ b/lib/lrama/grammar/symbol.rb @@ -108,6 +108,50 @@ def character? term? && id.char? end + # @rbs () -> Integer + def character_code + # Ignore ' on both sides. + code = + case name[1..-2] + when "\\a" + 7 + when "\\b" + 8 + when "\\f" + 12 + when "\\n" + 10 + when "\\r" + 13 + when "\\t" + 9 + when "\\v" + 11 + when "\\\"" + 34 + when "\\'" + 39 + when "\\?" + 63 + when "\\\\" + 92 + when /\A\\([0-7]{1,3})\z/ + Integer($1, 8) + when /\A\\[xuU]([0-9a-fA-F]+)\z/ + Integer($1, 16) + when /\A(.)\z/ + $1&.bytes&.first + end + + raise "Unknown Char s_value #{name}" unless code + + unless (1..255).cover?(code) + raise "Invalid character: `#{name}`. Character code must be between 1 and 255." + end + + code + end + # @rbs () -> bool def eof_symbol? !!@eof_symbol diff --git a/lib/lrama/grammar/symbols/resolver.rb b/lib/lrama/grammar/symbols/resolver.rb index a63b940c5..82fb33ca0 100644 --- a/lib/lrama/grammar/symbols/resolver.rb +++ b/lib/lrama/grammar/symbols/resolver.rb @@ -294,44 +294,7 @@ def fill_terms_number end if sym.character? - # Ignore ' on both sides. - code = - case sym.name[1..-2] - when "\\a" - 7 - when "\\b" - 8 - when "\\f" - 12 - when "\\n" - 10 - when "\\r" - 13 - when "\\t" - 9 - when "\\v" - 11 - when "\\\"" - 34 - when "\\'" - 39 - when "\\?" - 63 - when "\\\\" - 92 - when /\A\\([0-7]{1,3})\z/ - Integer($1, 8) - when /\A\\[xuU]([0-9a-fA-F]+)\z/ - Integer($1, 16) - when /\A(.)\z/ - $1&.bytes&.first - end - - raise "Unknown Char s_value #{sym}" unless code - - unless (1..255).cover?(code) - raise "Invalid character: `#{sym.name}`. Character code must be between 1 and 255." - end + code = sym.character_code if sym.token_id.nil? && named_token_ids[code] raise "code #{code} reassigned to token #{sym.name}" diff --git a/lib/lrama/grammar/token_action.rb b/lib/lrama/grammar/token_action.rb new file mode 100644 index 000000000..cb3a154f6 --- /dev/null +++ b/lib/lrama/grammar/token_action.rb @@ -0,0 +1,33 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Grammar + # Represents a token action defined by %token-action directive. + # + # Token actions are user code blocks associated with token patterns. + # When a token is matched by the pseudo-scanner, the associated code runs. + # Layout tokens are accumulated, and the accumulated text is available + # to the next non-layout token's action. + # + # Example: + # %token-action ID { printf("matched ID: %.*s\n", yyleng, yytext); } + class TokenAction + attr_reader :token_id #: Lexer::Token::Ident + attr_reader :code #: Lexer::Token::UserCode + attr_reader :lineno #: Integer + + # @rbs (token_id: Lexer::Token::Ident, code: Lexer::Token::UserCode, lineno: Integer) -> void + def initialize(token_id:, code:, lineno:) + @token_id = token_id + @code = code + @lineno = lineno + end + + # @rbs () -> String + def token_name + @token_id.s_value + end + end + end +end diff --git a/lib/lrama/grammar/token_pattern.rb b/lib/lrama/grammar/token_pattern.rb new file mode 100644 index 000000000..ff9a834c3 --- /dev/null +++ b/lib/lrama/grammar/token_pattern.rb @@ -0,0 +1,43 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Grammar + # Represents a token pattern defined by %token-pattern directive + # Example: %token-pattern RSHIFT />>/ "right shift" + class TokenPattern + attr_reader :id #: Lexer::Token::Base + attr_reader :pattern #: Lexer::Token::Regex + attr_reader :alias_name #: String? + attr_reader :tag #: Lexer::Token::Tag? + attr_reader :lineno #: Integer + attr_reader :definition_order #: Integer + + # @rbs (id: Lexer::Token::Base, pattern: Lexer::Token::Regex, ?alias_name: String?, ?tag: Lexer::Token::Tag?, lineno: Integer, definition_order: Integer) -> void + def initialize(id:, pattern:, alias_name: nil, tag: nil, lineno:, definition_order:) + @id = id + @pattern = pattern + @alias_name = alias_name + @tag = tag + @lineno = lineno + @definition_order = definition_order + end + + # @rbs () -> String + def name + @id.s_value + end + + # Returns the regex pattern string (without slashes) + # @rbs () -> String + def regex_pattern + @pattern.pattern + end + + # @rbs () -> bool + def layout? + name.start_with?("YYLAYOUT") + end + end + end +end diff --git a/lib/lrama/lexer.rb b/lib/lrama/lexer.rb index b6f6391d3..290374d64 100644 --- a/lib/lrama/lexer.rb +++ b/lib/lrama/lexer.rb @@ -18,7 +18,8 @@ class Lexer # [::Symbol, Token::Char] | # [::Symbol, Token::Str] | # [::Symbol, Token::Int] | - # [::Symbol, Token::Ident] + # [::Symbol, Token::Ident] | + # [::Symbol, Token::Regex] # # type c_token = [:C_DECLARATION, Token::UserCode] @@ -32,6 +33,8 @@ class Lexer PERCENT_TOKENS = %w( %union %token + %token-pattern + %symbol-set %type %nterm %left @@ -44,6 +47,11 @@ class Lexer %destructor %param %lex-param + %lexer-context + %lex-prec + %lex-tie + %lex-no-tie + %token-action %parse-param %initial-action %precedence @@ -76,6 +84,8 @@ def initialize(grammar_file) @head_line = @line = 1 @status = :initial @end_symbol = nil + @directive = nil + @expect_token_pattern_regex = false end # @rbs () -> token? @@ -111,7 +121,7 @@ def lex_token when @scanner.scan(/[^\S\n]+/) when @scanner.scan(/\/\*/) lex_comment - when @scanner.scan(/\/\/.*(?\n)?/) + when !@expect_token_pattern_regex && @scanner.scan(/\/\/.*(?\n)?/) newline if @scanner[:newline] else break @@ -124,8 +134,14 @@ def lex_token when @scanner.eos? return when @scanner.scan(SYMBOL_PATTERN) + if @scanner.matched == "%%" || @scanner.matched == ";" + @directive = nil + @expect_token_pattern_regex = false + end return [@scanner.matched, Lrama::Lexer::Token::Token.new(s_value: @scanner.matched, location: location)] when @scanner.scan(PERCENT_TOKEN_PATTERN) + @directive = @scanner.matched + @expect_token_pattern_regex = false return [@scanner.matched, Lrama::Lexer::Token::Token.new(s_value: @scanner.matched, location: location)] when @scanner.scan(/[\?\+\*]/) return [@scanner.matched, Lrama::Lexer::Token::Token.new(s_value: @scanner.matched, location: location)] @@ -135,10 +151,16 @@ def lex_token return [:CHARACTER, Lrama::Lexer::Token::Char.new(s_value: @scanner.matched, location: location)] when @scanner.scan(/"(?:\\.|[^"\\\n])*"/) return [:STRING, Lrama::Lexer::Token::Str.new(s_value: %Q(#{@scanner.matched}), location: location)] + when @expect_token_pattern_regex && (regex = scan_regex_token) + @expect_token_pattern_regex = false + return [:REGEX, regex] + when @directive == "%lex-prec" && @scanner.scan(/<~|<-|-~|<<|-<| Token::Regex? + def scan_regex_token + return nil unless @scanner.peek(1) == "/" + + start_pos = @scanner.pos + @scanner.getch + escaped = false + in_char_class = false + + until @scanner.eos? + char = @scanner.getch + + if escaped + escaped = false + elsif char == "\\" + escaped = true + elsif char == "[" + in_char_class = true + elsif char == "]" + in_char_class = false + elsif char == "/" && !in_char_class + return Lrama::Lexer::Token::Regex.new( + s_value: @scanner.string[start_pos...@scanner.pos], + location: location + ) + elsif char == "\n" + newline + end + end + + raise ParseError, location.generate_error_message("Unclosed regex pattern") + end + # @rbs () -> void def lex_comment unless @scanner.scan_until(/[\s\S]*?\*\//) diff --git a/lib/lrama/lexer/token.rb b/lib/lrama/lexer/token.rb index 7904808e7..faec581d3 100644 --- a/lib/lrama/lexer/token.rb +++ b/lib/lrama/lexer/token.rb @@ -6,6 +6,7 @@ require_relative 'token/empty' require_relative 'token/ident' require_relative 'token/int' +require_relative 'token/regex' require_relative 'token/str' require_relative 'token/tag' require_relative 'token/token' diff --git a/lib/lrama/lexer/token/regex.rb b/lib/lrama/lexer/token/regex.rb new file mode 100644 index 000000000..c4295f408 --- /dev/null +++ b/lib/lrama/lexer/token/regex.rb @@ -0,0 +1,19 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Lexer + module Token + # Token class for regex patterns used in %token-pattern directive + # Example: /[a-zA-Z_][a-zA-Z0-9_]*/ + class Regex < Base + # Returns the regex pattern without the surrounding slashes + # @rbs () -> String + def pattern + # Remove leading and trailing slashes + s_value[1..-2].to_s + end + end + end + end +end diff --git a/lib/lrama/parser.rb b/lib/lrama/parser.rb index bf482eece..10d0ebc66 100644 --- a/lib/lrama/parser.rb +++ b/lib/lrama/parser.rb @@ -655,7 +655,7 @@ def token_to_str(t) module Lrama class Parser < Racc::Parser -module_eval(<<'...end parser.y/module_eval...', 'parser.y', 631) +module_eval(<<'...end parser.y/module_eval...', 'parser.y', 735) include Lrama::Tracer::Duration @@ -773,322 +773,380 @@ def merge_locations(*locations) ##### State transition tables begin ### racc_action_table = [ - 98, 98, 99, 99, 87, 53, 53, 52, 178, 110, - 110, 97, 53, 53, 184, 178, 110, 110, 53, 181, - 184, 162, 110, 6, 163, 181, 181, 53, 53, 52, - 52, 181, 79, 79, 53, 53, 52, 52, 43, 79, - 79, 53, 4, 52, 5, 110, 88, 94, 182, 125, - 126, 163, 100, 100, 180, 193, 194, 195, 137, 185, - 188, 180, 4, 44, 5, 185, 188, 94, 24, 25, - 26, 27, 28, 29, 30, 31, 32, 46, 33, 34, - 35, 36, 37, 38, 39, 40, 41, 47, 24, 25, - 26, 27, 28, 29, 30, 31, 32, 47, 33, 34, - 35, 36, 37, 38, 39, 40, 41, 12, 13, 50, - 57, 14, 15, 16, 17, 18, 19, 20, 24, 25, - 26, 27, 28, 29, 30, 31, 32, 57, 33, 34, - 35, 36, 37, 38, 39, 40, 41, 12, 13, 57, - 60, 14, 15, 16, 17, 18, 19, 20, 24, 25, - 26, 27, 28, 29, 30, 31, 32, 57, 33, 34, - 35, 36, 37, 38, 39, 40, 41, 53, 53, 52, - 52, 110, 105, 53, 53, 52, 52, 110, 105, 53, - 53, 52, 52, 110, 105, 53, 53, 52, 52, 110, - 105, 53, 53, 52, 52, 110, 110, 53, 53, 52, - 209, 110, 110, 53, 53, 209, 209, 110, 110, 53, - 53, 209, 52, 110, 193, 194, 195, 137, 217, 222, - 230, 218, 218, 218, 53, 53, 52, 52, 193, 194, - 195, 57, 57, 57, 57, 66, 67, 68, 69, 70, - 72, 72, 72, 86, 89, 47, 57, 57, 113, 117, - 117, 79, 123, 124, 131, 47, 133, 137, 139, 143, - 149, 150, 151, 152, 133, 155, 156, 157, 110, 166, - 149, 169, 172, 173, 72, 175, 176, 183, 189, 166, - 196, 137, 200, 202, 137, 166, 212, 166, 137, 72, - 176, 219, 176, 72, 137, 227, 137, 72, 72 ] + 119, 119, 120, 120, 108, 4, 60, 5, 221, 60, + 92, 227, 118, 92, 60, 6, 221, 60, 92, 227, + 224, 92, 60, 224, 59, 50, 205, 100, 224, 206, + 51, 224, 145, 146, 147, 148, 149, 150, 151, 145, + 146, 147, 148, 149, 150, 151, 60, 60, 59, 59, + 53, 100, 100, 60, 225, 59, 54, 206, 100, 115, + 60, 109, 59, 260, 92, 126, 261, 121, 121, 223, + 265, 228, 231, 261, 60, 54, 59, 223, 92, 228, + 231, 24, 25, 26, 27, 28, 29, 30, 31, 32, + 57, 33, 34, 35, 36, 37, 38, 39, 40, 41, + 42, 43, 44, 45, 46, 47, 115, 60, 4, 59, + 5, 92, 126, 48, 60, 60, 59, 59, 92, 126, + 60, 64, 59, 273, 92, 126, 261, 64, 24, 25, + 26, 27, 28, 29, 30, 31, 32, 64, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 47, 236, 237, 238, 174, 12, 13, 67, + 48, 14, 15, 16, 17, 18, 19, 20, 24, 25, + 26, 27, 28, 29, 30, 31, 32, 64, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 47, 236, 237, 238, 174, 12, 13, 64, + 48, 14, 15, 16, 17, 18, 19, 20, 24, 25, + 26, 27, 28, 29, 30, 31, 32, 64, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 47, 60, 60, 59, 59, 92, 92, 60, + 48, 59, 60, 92, 59, 60, 92, 59, 60, 92, + 59, 60, 92, 59, 60, 92, 59, 60, 92, 59, + 60, 92, 59, 60, 92, 59, 60, 92, 59, 60, + 92, 59, 60, 92, 252, 60, 92, 252, 60, 92, + 252, 60, 92, 252, 60, 92, 59, 60, 60, 59, + 59, 60, 60, 59, 59, 60, 64, 59, 236, 237, + 238, 162, 163, 64, 73, 74, 75, 76, 77, 79, + 79, 85, 86, 87, 79, 79, 107, 110, 54, 64, + 64, 131, 135, 138, 85, 64, 155, 155, 100, 160, + 161, 168, 54, 170, 174, 176, 180, 138, 138, 184, + 191, 192, 193, 194, 170, 197, 198, 199, 92, 92, + 209, 191, 212, 215, 216, 79, 218, 219, 226, 232, + 209, 239, 174, 243, 245, 174, 209, 255, 209, 174, + 79, 219, 262, 219, 79, 174, 270, 174, 79, 79 ] racc_action_check = [ - 51, 97, 51, 97, 41, 75, 165, 75, 165, 75, - 165, 51, 171, 190, 171, 190, 171, 190, 201, 165, - 201, 148, 201, 1, 148, 171, 190, 36, 37, 36, - 37, 201, 36, 37, 38, 39, 38, 39, 5, 38, - 39, 117, 0, 117, 0, 117, 41, 46, 168, 88, - 88, 168, 51, 97, 165, 177, 177, 177, 177, 171, - 171, 190, 2, 6, 2, 201, 201, 90, 46, 46, - 46, 46, 46, 46, 46, 46, 46, 9, 46, 46, - 46, 46, 46, 46, 46, 46, 46, 10, 90, 90, - 90, 90, 90, 90, 90, 90, 90, 11, 90, 90, - 90, 90, 90, 90, 90, 90, 90, 3, 3, 12, - 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 15, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 8, 8, 16, - 17, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 18, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 63, 13, 63, - 13, 63, 63, 64, 73, 64, 73, 64, 64, 65, - 78, 65, 78, 65, 65, 106, 79, 106, 79, 106, - 106, 118, 180, 118, 180, 118, 180, 188, 196, 188, - 196, 188, 196, 202, 218, 202, 218, 202, 218, 219, - 113, 219, 113, 219, 186, 186, 186, 186, 208, 214, - 226, 208, 214, 226, 114, 123, 114, 123, 211, 211, - 211, 24, 25, 26, 27, 28, 29, 30, 31, 32, - 33, 34, 35, 40, 42, 47, 55, 60, 71, 74, - 76, 80, 81, 87, 91, 92, 93, 94, 102, 116, - 124, 125, 126, 127, 133, 136, 137, 138, 144, 150, - 151, 153, 156, 158, 162, 163, 164, 170, 174, 176, - 178, 179, 182, 184, 187, 189, 199, 200, 204, 205, - 207, 209, 213, 215, 217, 221, 222, 224, 228 ] + 58, 118, 58, 118, 48, 0, 208, 0, 208, 214, + 208, 214, 58, 214, 233, 1, 233, 244, 233, 244, + 208, 244, 43, 214, 43, 5, 190, 43, 233, 190, + 6, 244, 88, 88, 88, 88, 88, 88, 88, 89, + 89, 89, 89, 89, 89, 89, 44, 45, 44, 45, + 9, 44, 45, 46, 211, 46, 10, 211, 46, 53, + 70, 48, 70, 251, 70, 70, 251, 58, 118, 208, + 257, 214, 214, 257, 38, 11, 38, 233, 38, 244, + 244, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 12, 53, 53, 53, 53, 53, 53, 53, 53, 53, + 53, 53, 53, 53, 53, 53, 111, 71, 2, 71, + 2, 71, 71, 53, 72, 13, 72, 13, 72, 72, + 127, 14, 127, 269, 127, 127, 269, 15, 111, 111, + 111, 111, 111, 111, 111, 111, 111, 16, 111, 111, + 111, 111, 111, 111, 111, 111, 111, 111, 111, 111, + 111, 111, 111, 220, 220, 220, 220, 3, 3, 17, + 111, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 18, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 229, 229, 229, 229, 8, 8, 24, + 3, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 25, 8, 8, + 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 8, 39, 40, 39, 40, 39, 40, 86, + 8, 86, 87, 86, 87, 93, 87, 93, 94, 93, + 94, 96, 94, 96, 141, 96, 141, 144, 141, 144, + 152, 144, 152, 155, 152, 155, 223, 155, 223, 231, + 223, 231, 239, 231, 239, 245, 239, 245, 261, 245, + 261, 262, 261, 262, 80, 262, 80, 99, 100, 99, + 100, 131, 132, 131, 132, 160, 26, 160, 254, 254, + 254, 109, 109, 27, 28, 29, 30, 31, 32, 33, + 34, 35, 36, 37, 41, 42, 47, 49, 54, 62, + 67, 78, 81, 82, 83, 85, 95, 97, 101, 102, + 108, 112, 113, 114, 115, 123, 134, 135, 136, 138, + 161, 162, 163, 164, 170, 173, 174, 175, 181, 184, + 192, 193, 195, 198, 200, 205, 206, 207, 213, 217, + 219, 221, 222, 225, 227, 230, 232, 242, 243, 247, + 248, 250, 252, 256, 258, 260, 264, 265, 267, 271 ] racc_action_pointer = [ - 32, 23, 52, 93, nil, 31, 63, nil, 123, 68, - 74, 84, 103, 165, 94, 111, 123, 135, 141, nil, - nil, nil, nil, nil, 215, 216, 217, 218, 230, 231, - 232, 233, 234, 232, 233, 234, 24, 25, 31, 32, - 238, -1, 242, nil, nil, nil, 43, 232, nil, nil, - nil, -5, nil, nil, nil, 230, nil, nil, nil, nil, - 231, nil, nil, 164, 170, 176, nil, nil, nil, nil, - nil, 240, nil, 171, 241, 2, 242, nil, 177, 183, - 243, 244, nil, nil, nil, nil, nil, 209, 45, nil, - 63, 245, 242, 243, 202, nil, nil, -4, nil, nil, - nil, nil, 256, nil, nil, nil, 182, nil, nil, nil, - nil, nil, nil, 207, 221, nil, 253, 38, 188, nil, - nil, nil, nil, 222, 255, 215, 218, 252, nil, nil, - nil, nil, nil, 251, nil, nil, 219, 261, 250, nil, - nil, nil, nil, nil, 261, nil, nil, nil, -24, nil, - 219, 265, nil, 269, nil, nil, 216, nil, 256, nil, - nil, nil, 266, 270, 227, 3, nil, nil, 3, nil, - 228, 9, nil, nil, 232, nil, 229, 3, 236, 226, - 189, nil, 236, nil, 239, nil, 162, 229, 194, 235, - 10, nil, nil, nil, nil, nil, 195, nil, nil, 284, - 237, 15, 200, nil, 233, 281, nil, 241, 173, 247, - nil, 176, nil, 243, 174, 285, nil, 239, 201, 206, - nil, 278, 241, nil, 289, nil, 175, nil, 290, nil, - nil, nil ] + -6, 15, 97, 142, nil, 18, 30, nil, 182, 40, + 42, 61, 84, 112, 104, 110, 120, 154, 160, nil, + nil, nil, nil, nil, 182, 200, 279, 286, 299, 300, + 301, 302, 303, 301, 302, 306, 307, 308, 71, 230, + 231, 306, 307, 19, 43, 44, 50, 311, -1, 315, + nil, nil, nil, 55, 304, nil, nil, nil, -5, nil, + nil, nil, 302, nil, nil, nil, nil, 303, nil, nil, + 57, 104, 111, nil, nil, nil, nil, nil, 313, nil, + 281, 314, 318, 319, nil, 308, 236, 239, -19, -12, + nil, nil, nil, 242, 245, 318, 248, 319, nil, 284, + 285, 320, 321, nil, nil, nil, nil, nil, 271, 297, + nil, 102, 321, 318, 319, 264, nil, nil, -4, nil, + nil, nil, nil, 333, nil, nil, nil, 117, nil, nil, + nil, 288, 289, nil, 330, 332, 333, nil, 330, nil, + nil, 251, nil, nil, 254, nil, nil, nil, nil, nil, + nil, nil, 257, nil, nil, 260, nil, nil, nil, nil, + 292, 335, 280, 283, 331, nil, nil, nil, nil, nil, + 330, nil, nil, 284, 341, 329, nil, nil, nil, nil, + nil, 341, nil, nil, 342, nil, nil, nil, nil, nil, + -34, nil, 285, 346, nil, 350, nil, nil, 282, nil, + 336, nil, nil, nil, nil, 347, 351, 293, 3, nil, + nil, -6, nil, 294, 6, nil, nil, 298, nil, 295, + 86, 302, 292, 263, nil, 302, nil, 305, nil, 126, + 295, 266, 301, 11, nil, nil, nil, nil, nil, 269, + nil, nil, 365, 303, 14, 272, nil, 299, 362, nil, + 307, 3, 313, nil, 231, nil, 309, 10, 366, nil, + 305, 275, 278, nil, 358, 307, nil, 370, nil, 63, + nil, 371, nil, nil, nil ] racc_action_default = [ - -1, -136, -1, -3, -10, -136, -136, -2, -3, -136, - -14, -14, -136, -136, -136, -136, -136, -136, -136, -28, - -29, -34, -35, -36, -136, -136, -136, -136, -136, -136, - -136, -136, -136, -54, -54, -54, -136, -136, -136, -136, - -136, -136, -136, -13, 232, -4, -136, -14, -16, -17, - -20, -131, -100, -101, -130, -18, -23, -89, -24, -25, - -136, -27, -37, -136, -136, -136, -41, -42, -43, -44, - -45, -46, -55, -136, -47, -136, -48, -49, -92, -136, - -95, -97, -98, -50, -51, -52, -53, -136, -136, -11, - -5, -7, -14, -136, -72, -15, -21, -131, -132, -133, - -134, -19, -136, -26, -30, -31, -32, -38, -87, -88, - -135, -39, -40, -136, -56, -58, -60, -136, -83, -85, - -93, -94, -96, -136, -136, -136, -136, -136, -6, -8, - -9, -128, -104, -102, -105, -73, -136, -136, -136, -90, - -33, -59, -57, -61, -80, -86, -84, -99, -136, -66, - -70, -136, -12, -136, -103, -109, -136, -22, -136, -62, - -81, -82, -54, -136, -64, -68, -71, -74, -136, -129, - -106, -107, -127, -91, -136, -67, -70, -72, -100, -72, - -136, -124, -136, -109, -100, -110, -72, -72, -136, -70, - -69, -75, -76, -116, -117, -118, -136, -78, -79, -136, - -70, -108, -136, -111, -72, -54, -115, -63, -136, -100, - -119, -121, -125, -65, -136, -54, -114, -72, -136, -136, - -122, -136, -72, -112, -54, -120, -136, -126, -54, -77, - -123, -113 ] + -1, -160, -1, -3, -10, -160, -160, -2, -3, -160, + -14, -14, -160, -160, -160, -160, -160, -160, -160, -28, + -29, -34, -35, -36, -160, -160, -160, -160, -160, -160, + -160, -160, -160, -65, -65, -160, -160, -160, -160, -160, + -160, -65, -65, -160, -160, -160, -160, -160, -160, -160, + -13, 275, -4, -160, -14, -16, -17, -20, -155, -124, + -125, -154, -18, -23, -113, -24, -25, -160, -27, -37, + -160, -160, -160, -41, -42, -43, -44, -45, -50, -66, + -160, -51, -160, -46, -52, -160, -160, -160, -55, -160, + -111, -112, -159, -160, -160, -58, -160, -59, -60, -116, + -160, -119, -121, -122, -61, -62, -63, -64, -160, -160, + -11, -5, -7, -14, -160, -98, -15, -21, -155, -156, + -157, -158, -19, -160, -26, -30, -31, -32, -38, -39, + -40, -160, -67, -69, -71, -160, -74, -76, -160, -47, + -88, -48, -53, -54, -160, -81, -82, -83, -84, -85, + -86, -87, -160, -56, -57, -160, -109, -117, -118, -120, + -160, -160, -160, -160, -160, -6, -8, -9, -152, -128, + -126, -129, -99, -160, -160, -160, -114, -33, -70, -68, + -72, -106, -77, -75, -106, -49, -80, -79, -110, -123, + -160, -92, -96, -160, -12, -160, -127, -133, -160, -22, + -160, -73, -107, -108, -78, -65, -160, -90, -94, -97, + -100, -160, -153, -130, -131, -151, -115, -160, -93, -96, + -98, -124, -98, -160, -148, -160, -133, -124, -134, -98, + -98, -160, -96, -95, -101, -102, -140, -141, -142, -160, + -104, -105, -160, -96, -132, -160, -135, -98, -65, -139, + -89, -160, -124, -143, -145, -149, -91, -160, -65, -138, + -98, -160, -160, -146, -160, -98, -136, -65, -144, -160, + -150, -65, -103, -147, -137 ] racc_goto_table = [ - 73, 118, 136, 54, 48, 49, 164, 96, 91, 120, - 121, 93, 187, 148, 107, 111, 112, 119, 134, 171, - 56, 58, 59, 3, 61, 7, 78, 78, 78, 78, - 62, 63, 64, 65, 115, 74, 76, 192, 1, 129, - 168, 95, 187, 118, 118, 207, 204, 201, 77, 83, - 84, 85, 128, 138, 147, 93, 213, 140, 154, 145, - 146, 101, 130, 116, 42, 9, 103, 208, 78, 78, - 45, 220, 127, 214, 141, 142, 51, 71, 159, 144, - 190, 160, 161, 102, 158, 191, 132, 197, 122, 170, - 226, 177, 225, 199, 203, 205, 221, 186, 153, nil, - nil, nil, nil, 116, 116, nil, 198, nil, nil, nil, - nil, nil, 215, 78, 206, nil, 177, nil, nil, nil, - nil, nil, 211, nil, nil, 224, nil, 186, 211, 174, - 228, nil, nil, nil, nil, nil, nil, nil, nil, nil, - nil, nil, nil, nil, 211, 211, nil, nil, nil, nil, + 80, 82, 117, 89, 93, 94, 173, 68, 61, 55, + 56, 142, 143, 69, 70, 71, 72, 171, 153, 154, + 112, 156, 157, 158, 114, 133, 190, 128, 129, 130, + 207, 84, 137, 1, 230, 125, 125, 125, 99, 99, + 99, 99, 63, 65, 66, 251, 201, 9, 3, 204, + 7, 257, 52, 116, 235, 166, 124, 167, 211, 49, + 214, 164, 175, 247, 230, 58, 185, 78, 269, 202, + 250, 81, 202, 196, 140, 134, 178, 179, 165, 139, + 188, 256, 114, 189, 177, 182, 183, 88, 263, 244, + 122, 181, 125, 233, 99, 99, 98, 104, 105, 106, + 95, 97, 144, 152, 123, 200, 159, 213, 268, 186, + 242, 234, 169, 240, 264, 195, nil, 187, nil, nil, + 246, 248, nil, nil, nil, nil, 134, 134, nil, nil, + nil, nil, nil, nil, nil, nil, nil, nil, 258, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + nil, 267, nil, nil, nil, 99, 271, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, - nil, nil, 216, nil, nil, nil, nil, nil, nil, nil, - nil, nil, 223, nil, nil, nil, nil, nil, nil, nil, - nil, 229, nil, nil, nil, 231 ] + nil, nil, 217, 220, nil, nil, nil, nil, nil, 229, + nil, nil, nil, nil, nil, nil, nil, nil, 241, nil, + nil, nil, nil, nil, nil, nil, 249, nil, 220, nil, + nil, nil, nil, nil, 254, nil, nil, nil, nil, 229, + 254, nil, nil, nil, nil, 259, nil, nil, nil, nil, + nil, nil, nil, nil, nil, 266, 254, 254, nil, nil, + nil, nil, nil, nil, 272, nil, nil, nil, 274 ] racc_goto_check = [ - 29, 22, 42, 31, 14, 14, 35, 16, 8, 48, - 48, 13, 40, 34, 24, 24, 24, 45, 52, 54, - 18, 18, 18, 6, 17, 6, 31, 31, 31, 31, - 17, 17, 17, 17, 30, 26, 26, 38, 1, 5, - 34, 14, 40, 22, 22, 35, 38, 54, 27, 27, - 27, 27, 8, 16, 48, 13, 35, 24, 52, 45, - 45, 18, 9, 31, 10, 7, 17, 39, 31, 31, - 7, 38, 11, 39, 30, 30, 15, 25, 32, 33, - 36, 43, 44, 46, 47, 42, 14, 42, 50, 53, - 39, 22, 55, 56, 42, 42, 57, 22, 58, nil, - nil, nil, nil, 31, 31, nil, 22, nil, nil, nil, - nil, nil, 42, 31, 22, nil, 22, nil, nil, nil, - nil, nil, 22, nil, nil, 42, nil, 22, 22, 29, - 42, nil, nil, nil, nil, nil, nil, nil, nil, nil, - nil, nil, nil, nil, 22, 22, nil, nil, nil, nil, + 34, 34, 16, 22, 22, 22, 50, 17, 36, 14, + 14, 32, 32, 17, 17, 17, 17, 59, 32, 32, + 8, 32, 55, 55, 13, 35, 42, 24, 24, 24, + 43, 31, 40, 1, 48, 22, 22, 22, 36, 36, + 36, 36, 18, 18, 18, 47, 37, 7, 6, 37, + 6, 47, 7, 14, 46, 5, 17, 9, 42, 10, + 61, 11, 16, 46, 48, 15, 32, 25, 47, 51, + 43, 26, 51, 59, 17, 36, 35, 35, 8, 31, + 32, 43, 13, 55, 24, 40, 40, 28, 46, 61, + 18, 38, 22, 44, 36, 36, 30, 30, 30, 30, + 29, 29, 41, 41, 53, 54, 57, 60, 62, 22, + 63, 50, 14, 50, 64, 65, nil, 22, nil, nil, + 50, 50, nil, nil, nil, nil, 36, 36, nil, nil, + nil, nil, nil, nil, nil, nil, nil, nil, 50, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + nil, 50, nil, nil, nil, 36, 50, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, - nil, nil, 29, nil, nil, nil, nil, nil, nil, nil, - nil, nil, 29, nil, nil, nil, nil, nil, nil, nil, - nil, 29, nil, nil, nil, 29 ] + nil, nil, 34, 22, nil, nil, nil, nil, nil, 22, + nil, nil, nil, nil, nil, nil, nil, nil, 22, nil, + nil, nil, nil, nil, nil, nil, 22, nil, 22, nil, + nil, nil, nil, nil, 22, nil, nil, nil, nil, 22, + 22, nil, nil, nil, nil, 34, nil, nil, nil, nil, + nil, nil, nil, nil, nil, 34, 22, 22, nil, nil, + nil, nil, nil, nil, 34, nil, nil, nil, 34 ] racc_goto_pointer = [ - nil, 38, nil, nil, nil, -52, 23, 62, -38, -29, - 60, -17, nil, -35, -6, 63, -44, 6, 6, nil, - nil, nil, -74, nil, -49, 44, 1, 12, nil, -33, - -39, -10, -66, -37, -111, -144, -96, nil, -140, -129, - -159, nil, -92, -63, -62, -58, 26, -55, -69, nil, - 8, nil, -75, -66, -136, -126, -88, -116, -33 ] + nil, 33, nil, nil, nil, -57, 48, 44, -33, -55, + 55, -49, nil, -29, -1, 52, -56, -11, 28, nil, + nil, nil, -35, nil, -43, 34, 37, nil, 49, 59, + 53, -4, -75, nil, -33, -55, -5, -135, -43, nil, + -50, 14, -135, -162, -126, nil, -166, -194, -180, nil, + -109, -112, nil, 40, -71, -77, nil, 5, nil, -97, + -90, -137, -153, -114, -141, -53 ] racc_goto_default = [ - nil, nil, 2, 8, 90, nil, nil, nil, nil, nil, - nil, nil, 10, 11, nil, nil, nil, 55, nil, 21, - 22, 23, 104, 106, nil, nil, nil, nil, 114, 75, - nil, 108, nil, nil, nil, nil, 165, 135, nil, nil, - 179, 167, nil, 109, nil, nil, nil, nil, 81, 80, - 82, 92, nil, nil, nil, 210, nil, nil, nil ] + nil, nil, 2, 8, 111, nil, nil, nil, nil, nil, + nil, nil, 10, 11, nil, nil, nil, 62, nil, 21, + 22, 23, 141, 127, nil, nil, nil, 83, nil, nil, + nil, nil, nil, 132, 96, nil, 90, nil, nil, 136, + nil, nil, nil, nil, 208, 172, nil, nil, 222, 210, + nil, 91, 203, nil, nil, 102, 101, 103, 113, nil, + nil, nil, 253, nil, nil, nil ] racc_reduce_table = [ 0, 0, :racc_error, - 0, 64, :_reduce_1, - 2, 64, :_reduce_2, - 0, 65, :_reduce_3, - 2, 65, :_reduce_4, - 1, 66, :_reduce_5, - 2, 66, :_reduce_6, - 0, 67, :_reduce_none, - 1, 67, :_reduce_none, - 5, 59, :_reduce_9, - 0, 68, :_reduce_10, - 0, 69, :_reduce_11, - 5, 60, :_reduce_12, - 2, 60, :_reduce_13, - 0, 72, :_reduce_14, - 2, 72, :_reduce_15, - 2, 61, :_reduce_none, - 2, 61, :_reduce_none, - 1, 76, :_reduce_18, - 2, 76, :_reduce_19, - 2, 70, :_reduce_20, - 3, 70, :_reduce_21, - 5, 70, :_reduce_22, - 2, 70, :_reduce_23, - 2, 70, :_reduce_24, - 2, 70, :_reduce_25, - 3, 70, :_reduce_26, - 2, 70, :_reduce_27, - 1, 70, :_reduce_28, - 1, 70, :_reduce_29, - 1, 81, :_reduce_30, - 1, 81, :_reduce_31, - 1, 82, :_reduce_32, - 2, 82, :_reduce_33, - 1, 71, :_reduce_none, - 1, 71, :_reduce_none, - 1, 71, :_reduce_none, - 2, 71, :_reduce_37, - 3, 71, :_reduce_38, - 3, 71, :_reduce_39, - 3, 71, :_reduce_40, - 2, 71, :_reduce_41, - 2, 71, :_reduce_42, - 2, 71, :_reduce_43, - 2, 71, :_reduce_44, - 2, 71, :_reduce_45, - 2, 77, :_reduce_46, - 2, 77, :_reduce_47, - 2, 77, :_reduce_48, - 2, 77, :_reduce_49, - 2, 77, :_reduce_50, - 2, 77, :_reduce_51, - 2, 77, :_reduce_52, - 2, 77, :_reduce_53, - 0, 87, :_reduce_none, - 1, 87, :_reduce_none, - 1, 88, :_reduce_56, - 2, 88, :_reduce_57, - 2, 83, :_reduce_58, - 3, 83, :_reduce_59, - 0, 91, :_reduce_none, - 1, 91, :_reduce_none, - 3, 86, :_reduce_62, - 8, 78, :_reduce_63, - 5, 79, :_reduce_64, - 8, 79, :_reduce_65, - 1, 92, :_reduce_66, - 3, 92, :_reduce_67, - 1, 93, :_reduce_68, - 3, 93, :_reduce_69, - 0, 99, :_reduce_none, - 1, 99, :_reduce_none, - 0, 100, :_reduce_none, - 1, 100, :_reduce_none, - 1, 94, :_reduce_74, - 3, 94, :_reduce_75, - 3, 94, :_reduce_76, - 7, 94, :_reduce_77, - 3, 94, :_reduce_78, - 3, 94, :_reduce_79, - 0, 102, :_reduce_none, - 1, 102, :_reduce_none, - 1, 90, :_reduce_none, - 1, 103, :_reduce_83, - 2, 103, :_reduce_84, - 2, 84, :_reduce_85, - 3, 84, :_reduce_86, - 1, 80, :_reduce_none, - 1, 80, :_reduce_none, - 0, 104, :_reduce_89, - 0, 105, :_reduce_90, - 5, 75, :_reduce_91, - 1, 106, :_reduce_92, - 2, 106, :_reduce_93, - 2, 107, :_reduce_94, - 1, 108, :_reduce_95, - 2, 108, :_reduce_96, - 1, 85, :_reduce_97, - 1, 85, :_reduce_98, - 3, 85, :_reduce_99, + 0, 79, :_reduce_1, + 2, 79, :_reduce_2, + 0, 80, :_reduce_3, + 2, 80, :_reduce_4, + 1, 81, :_reduce_5, + 2, 81, :_reduce_6, + 0, 82, :_reduce_none, + 1, 82, :_reduce_none, + 5, 74, :_reduce_9, + 0, 83, :_reduce_10, + 0, 84, :_reduce_11, + 5, 75, :_reduce_12, + 2, 75, :_reduce_13, + 0, 87, :_reduce_14, + 2, 87, :_reduce_15, + 2, 76, :_reduce_none, + 2, 76, :_reduce_none, + 1, 91, :_reduce_18, + 2, 91, :_reduce_19, + 2, 85, :_reduce_20, + 3, 85, :_reduce_21, + 5, 85, :_reduce_22, + 2, 85, :_reduce_23, + 2, 85, :_reduce_24, + 2, 85, :_reduce_25, + 3, 85, :_reduce_26, + 2, 85, :_reduce_27, + 1, 85, :_reduce_28, + 1, 85, :_reduce_29, + 1, 96, :_reduce_30, + 1, 96, :_reduce_31, + 1, 97, :_reduce_32, + 2, 97, :_reduce_33, + 1, 86, :_reduce_none, + 1, 86, :_reduce_none, + 1, 86, :_reduce_none, + 2, 86, :_reduce_37, + 3, 86, :_reduce_38, + 3, 86, :_reduce_39, + 3, 86, :_reduce_40, + 2, 86, :_reduce_41, + 2, 86, :_reduce_42, + 2, 86, :_reduce_43, + 2, 86, :_reduce_44, + 2, 86, :_reduce_45, + 1, 104, :_reduce_46, + 2, 104, :_reduce_47, + 1, 105, :_reduce_48, + 2, 105, :_reduce_49, + 2, 92, :_reduce_50, + 2, 92, :_reduce_51, + 2, 92, :_reduce_52, + 3, 92, :_reduce_53, + 3, 92, :_reduce_54, + 2, 92, :_reduce_55, + 3, 92, :_reduce_56, + 3, 92, :_reduce_57, + 2, 92, :_reduce_58, + 2, 92, :_reduce_59, + 2, 92, :_reduce_60, + 2, 92, :_reduce_61, + 2, 92, :_reduce_62, + 2, 92, :_reduce_63, + 2, 92, :_reduce_64, + 0, 107, :_reduce_none, + 1, 107, :_reduce_none, + 1, 108, :_reduce_67, + 2, 108, :_reduce_68, + 2, 98, :_reduce_69, + 3, 98, :_reduce_70, + 0, 111, :_reduce_none, + 1, 111, :_reduce_none, + 3, 106, :_reduce_73, + 1, 113, :_reduce_74, + 2, 113, :_reduce_75, + 2, 99, :_reduce_76, + 3, 99, :_reduce_77, + 3, 112, :_reduce_78, + 3, 101, :_reduce_79, + 3, 101, :_reduce_80, + 1, 114, :_reduce_81, + 1, 114, :_reduce_82, + 1, 114, :_reduce_83, + 1, 114, :_reduce_84, + 1, 114, :_reduce_85, + 1, 114, :_reduce_86, + 1, 114, :_reduce_87, + 2, 100, :_reduce_88, + 8, 93, :_reduce_89, + 5, 94, :_reduce_90, + 8, 94, :_reduce_91, + 1, 115, :_reduce_92, + 3, 115, :_reduce_93, + 1, 116, :_reduce_94, + 3, 116, :_reduce_95, + 0, 122, :_reduce_none, + 1, 122, :_reduce_none, + 0, 123, :_reduce_none, + 1, 123, :_reduce_none, + 1, 117, :_reduce_100, + 3, 117, :_reduce_101, + 3, 117, :_reduce_102, + 7, 117, :_reduce_103, + 3, 117, :_reduce_104, + 3, 117, :_reduce_105, + 0, 125, :_reduce_none, + 1, 125, :_reduce_none, + 1, 110, :_reduce_none, + 2, 102, :_reduce_109, + 3, 102, :_reduce_110, + 1, 95, :_reduce_none, + 1, 95, :_reduce_none, + 0, 126, :_reduce_113, + 0, 127, :_reduce_114, + 5, 90, :_reduce_115, + 1, 128, :_reduce_116, + 2, 128, :_reduce_117, + 2, 129, :_reduce_118, + 1, 130, :_reduce_119, + 2, 130, :_reduce_120, + 1, 103, :_reduce_121, + 1, 103, :_reduce_122, + 3, 103, :_reduce_123, + 1, 109, :_reduce_none, + 1, 109, :_reduce_none, + 1, 132, :_reduce_126, + 2, 132, :_reduce_127, + 2, 77, :_reduce_none, + 2, 77, :_reduce_none, + 4, 131, :_reduce_130, + 1, 133, :_reduce_131, + 3, 133, :_reduce_132, + 0, 134, :_reduce_133, + 2, 134, :_reduce_134, + 3, 134, :_reduce_135, + 5, 134, :_reduce_136, + 7, 134, :_reduce_137, + 4, 134, :_reduce_138, + 3, 134, :_reduce_139, + 1, 119, :_reduce_none, + 1, 119, :_reduce_none, + 1, 119, :_reduce_none, + 1, 120, :_reduce_143, + 3, 120, :_reduce_144, + 1, 135, :_reduce_145, + 2, 135, :_reduce_146, + 4, 135, :_reduce_147, + 0, 136, :_reduce_148, + 0, 137, :_reduce_149, + 5, 121, :_reduce_150, + 3, 118, :_reduce_151, + 0, 138, :_reduce_152, + 3, 78, :_reduce_153, + 1, 88, :_reduce_none, + 0, 89, :_reduce_none, 1, 89, :_reduce_none, 1, 89, :_reduce_none, - 1, 110, :_reduce_102, - 2, 110, :_reduce_103, - 2, 62, :_reduce_none, - 2, 62, :_reduce_none, - 4, 109, :_reduce_106, - 1, 111, :_reduce_107, - 3, 111, :_reduce_108, - 0, 112, :_reduce_109, - 2, 112, :_reduce_110, - 3, 112, :_reduce_111, - 5, 112, :_reduce_112, - 7, 112, :_reduce_113, - 4, 112, :_reduce_114, - 3, 112, :_reduce_115, - 1, 96, :_reduce_none, - 1, 96, :_reduce_none, - 1, 96, :_reduce_none, - 1, 97, :_reduce_119, - 3, 97, :_reduce_120, - 1, 113, :_reduce_121, - 2, 113, :_reduce_122, - 4, 113, :_reduce_123, - 0, 114, :_reduce_124, - 0, 115, :_reduce_125, - 5, 98, :_reduce_126, - 3, 95, :_reduce_127, - 0, 116, :_reduce_128, - 3, 63, :_reduce_129, - 1, 73, :_reduce_none, - 0, 74, :_reduce_none, - 1, 74, :_reduce_none, - 1, 74, :_reduce_none, - 1, 74, :_reduce_none, - 1, 101, :_reduce_none ] - -racc_reduce_n = 136 - -racc_shift_n = 232 + 1, 89, :_reduce_none, + 1, 124, :_reduce_none ] + +racc_reduce_n = 160 + +racc_shift_n = 275 racc_token_table = { false => 0, @@ -1100,57 +1158,72 @@ def merge_locations(*locations) :INTEGER => 6, :STRING => 7, :TAG => 8, - "%%" => 9, - "%{" => 10, - "%}" => 11, - "%require" => 12, - ";" => 13, - "%expect" => 14, - "%define" => 15, - "{" => 16, - "}" => 17, - "%param" => 18, - "%lex-param" => 19, - "%parse-param" => 20, - "%code" => 21, - "%initial-action" => 22, - "%no-stdlib" => 23, - "%locations" => 24, - "%union" => 25, - "%destructor" => 26, - "%printer" => 27, - "%error-token" => 28, - "%after-shift" => 29, - "%before-reduce" => 30, - "%after-reduce" => 31, - "%after-shift-error-token" => 32, - "%after-pop-stack" => 33, - "-temp-group" => 34, - "%token" => 35, - "%type" => 36, - "%nterm" => 37, - "%left" => 38, - "%right" => 39, - "%precedence" => 40, - "%nonassoc" => 41, - "%start" => 42, - "%rule" => 43, - "(" => 44, - ")" => 45, - ":" => 46, - "%inline" => 47, - "," => 48, - "|" => 49, - "%empty" => 50, - "%prec" => 51, - "?" => 52, - "+" => 53, - "*" => 54, - "[" => 55, - "]" => 56, - "{...}" => 57 } - -racc_nt_base = 58 + :REGEX => 9, + "%%" => 10, + "%{" => 11, + "%}" => 12, + "%require" => 13, + ";" => 14, + "%expect" => 15, + "%define" => 16, + "{" => 17, + "}" => 18, + "%param" => 19, + "%lex-param" => 20, + "%parse-param" => 21, + "%code" => 22, + "%initial-action" => 23, + "%no-stdlib" => 24, + "%locations" => 25, + "%union" => 26, + "%destructor" => 27, + "%printer" => 28, + "%error-token" => 29, + "%after-shift" => 30, + "%before-reduce" => 31, + "%after-reduce" => 32, + "%after-shift-error-token" => 33, + "%after-pop-stack" => 34, + "-temp-group" => 35, + "%token" => 36, + "%token-pattern" => 37, + "%token-action" => 38, + "%symbol-set" => 39, + "%lexer-context" => 40, + "%lex-prec" => 41, + "%lex-tie" => 42, + "%lex-no-tie" => 43, + "%type" => 44, + "%nterm" => 45, + "%left" => 46, + "%right" => 47, + "%precedence" => 48, + "%nonassoc" => 49, + "%start" => 50, + "<~" => 51, + "<-" => 52, + "-~" => 53, + "<<" => 54, + "-<" => 55, + " 56, + "-s" => 57, + "%rule" => 58, + "(" => 59, + ")" => 60, + ":" => 61, + "%inline" => 62, + "," => 63, + "|" => 64, + "%empty" => 65, + "%prec" => 66, + "?" => 67, + "+" => 68, + "*" => 69, + "[" => 70, + "]" => 71, + "{...}" => 72 } + +racc_nt_base = 73 racc_use_result_var = true @@ -1181,6 +1254,7 @@ def merge_locations(*locations) "INTEGER", "STRING", "TAG", + "REGEX", "\"%%\"", "\"%{\"", "\"%}\"", @@ -1208,6 +1282,13 @@ def merge_locations(*locations) "\"%after-pop-stack\"", "\"-temp-group\"", "\"%token\"", + "\"%token-pattern\"", + "\"%token-action\"", + "\"%symbol-set\"", + "\"%lexer-context\"", + "\"%lex-prec\"", + "\"%lex-tie\"", + "\"%lex-no-tie\"", "\"%type\"", "\"%nterm\"", "\"%left\"", @@ -1215,6 +1296,13 @@ def merge_locations(*locations) "\"%precedence\"", "\"%nonassoc\"", "\"%start\"", + "\"<~\"", + "\"<-\"", + "\"-~\"", + "\"<<\"", + "\"-<\"", + "\" 1 empties = rhs.select { |sym| sym.is_a?(Grammar::Node::RuleRhs::Empty) } @@ -2170,24 +2470,24 @@ def _reduce_106(val, _values, result) end .,., -module_eval(<<'.,.,', 'parser.y', 480) - def _reduce_107(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 584) + def _reduce_131(val, _values, result) result = [val[0]] result end .,., -module_eval(<<'.,.,', 'parser.y', 484) - def _reduce_108(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 588) + def _reduce_132(val, _values, result) result = val[0].append(val[2]) result end .,., -module_eval(<<'.,.,', 'parser.y', 490) - def _reduce_109(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 594) + def _reduce_133(val, _values, result) reset_precs result = [] @@ -2195,8 +2495,8 @@ def _reduce_109(val, _values, result) end .,., -module_eval(<<'.,.,', 'parser.y', 495) - def _reduce_110(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 599) + def _reduce_134(val, _values, result) node = Grammar::Node::RuleRhs::Empty.new(location: val[1].loc) result.append(node) @@ -2204,8 +2504,8 @@ def _reduce_110(val, _values, result) end .,., -module_eval(<<'.,.,', 'parser.y', 500) - def _reduce_111(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 604) + def _reduce_135(val, _values, result) on_action_error("intermediate %prec in a rule", val[1]) if @trailing_prec_seen node = Grammar::Node::RuleRhs::Symbol.new( token: val[1], alias_name: val[2], @@ -2217,8 +2517,8 @@ def _reduce_111(val, _values, result) end .,., -module_eval(<<'.,.,', 'parser.y', 509) - def _reduce_112(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 613) + def _reduce_136(val, _values, result) on_action_error("intermediate %prec in a rule", val[1]) if @trailing_prec_seen argument = Grammar::Node::RuleRhs::Symbol.new( token: val[1], location: val[1].loc @@ -2234,8 +2534,8 @@ def _reduce_112(val, _values, result) end .,., -module_eval(<<'.,.,', 'parser.y', 522) - def _reduce_113(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 626) + def _reduce_137(val, _values, result) on_action_error("intermediate %prec in a rule", val[1]) if @trailing_prec_seen node = Grammar::Node::RuleRhs::InstantiateRule.new( name: val[1].s_value, args: val[3], @@ -2248,8 +2548,8 @@ def _reduce_113(val, _values, result) end .,., -module_eval(<<'.,.,', 'parser.y', 532) - def _reduce_114(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 636) + def _reduce_138(val, _values, result) node = Grammar::Node::RuleRhs::Action.new( code: val[1], alias_name: val[2], tag: val[3], location: val[1].loc @@ -2260,8 +2560,8 @@ def _reduce_114(val, _values, result) end .,., -module_eval(<<'.,.,', 'parser.y', 540) - def _reduce_115(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 644) + def _reduce_139(val, _values, result) on_action_error("multiple %prec in a rule", val[0]) if prec_seen? if val[0].empty? @opening_prec_seen = true @@ -2279,28 +2579,28 @@ def _reduce_115(val, _values, result) end .,., -# reduce 116 omitted +# reduce 140 omitted -# reduce 117 omitted +# reduce 141 omitted -# reduce 118 omitted +# reduce 142 omitted -module_eval(<<'.,.,', 'parser.y', 560) - def _reduce_119(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 664) + def _reduce_143(val, _values, result) result = [val[0]] result end .,., -module_eval(<<'.,.,', 'parser.y', 561) - def _reduce_120(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 665) + def _reduce_144(val, _values, result) result = val[0].append(val[2]) result end .,., -module_eval(<<'.,.,', 'parser.y', 566) - def _reduce_121(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 670) + def _reduce_145(val, _values, result) result = Grammar::Node::RuleRhs::Symbol.new( token: val[0], location: val[0].loc ) @@ -2309,8 +2609,8 @@ def _reduce_121(val, _values, result) end .,., -module_eval(<<'.,.,', 'parser.y', 572) - def _reduce_122(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 676) + def _reduce_146(val, _values, result) symbol = Grammar::Node::RuleRhs::Symbol.new( token: val[0], location: val[0].loc ) @@ -2323,8 +2623,8 @@ def _reduce_122(val, _values, result) end .,., -module_eval(<<'.,.,', 'parser.y', 582) - def _reduce_123(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 686) + def _reduce_147(val, _values, result) result = Grammar::Node::RuleRhs::InstantiateRule.new( name: val[0].s_value, args: val[2], location: merge_locations(val[0].loc, val[3].loc) @@ -2334,8 +2634,8 @@ def _reduce_123(val, _values, result) end .,., -module_eval(<<'.,.,', 'parser.y', 591) - def _reduce_124(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 695) + def _reduce_148(val, _values, result) if prec_seen? on_action_error("multiple User_code after %prec", val[0]) if @code_after_prec @code_after_prec = true @@ -2346,39 +2646,39 @@ def _reduce_124(val, _values, result) end .,., -module_eval(<<'.,.,', 'parser.y', 599) - def _reduce_125(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 703) + def _reduce_149(val, _values, result) end_c_declaration result end .,., -module_eval(<<'.,.,', 'parser.y', 603) - def _reduce_126(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 707) + def _reduce_150(val, _values, result) result = val[2] result end .,., -module_eval(<<'.,.,', 'parser.y', 606) - def _reduce_127(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 710) + def _reduce_151(val, _values, result) result = val[1].s_value result end .,., -module_eval(<<'.,.,', 'parser.y', 611) - def _reduce_128(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 715) + def _reduce_152(val, _values, result) begin_c_declaration('\Z') result end .,., -module_eval(<<'.,.,', 'parser.y', 615) - def _reduce_129(val, _values, result) +module_eval(<<'.,.,', 'parser.y', 719) + def _reduce_153(val, _values, result) end_c_declaration result = Grammar::Node::EpilogueDecl.new(code: val[2], location: merge_locations(val[0].loc, val[2].loc)) @@ -2386,17 +2686,17 @@ def _reduce_129(val, _values, result) end .,., -# reduce 130 omitted +# reduce 154 omitted -# reduce 131 omitted +# reduce 155 omitted -# reduce 132 omitted +# reduce 156 omitted -# reduce 133 omitted +# reduce 157 omitted -# reduce 134 omitted +# reduce 158 omitted -# reduce 135 omitted +# reduce 159 omitted def _reduce_none(val, _values, result) val[0] diff --git a/parser.y b/parser.y index 17f21e90e..edce8e9db 100644 --- a/parser.y +++ b/parser.y @@ -2,7 +2,7 @@ class Lrama::Parser expect 0 error_on_expect_mismatch - token C_DECLARATION CHARACTER IDENT_COLON IDENTIFIER INTEGER STRING TAG + token C_DECLARATION CHARACTER IDENT_COLON IDENTIFIER INTEGER STRING TAG REGEX rule @@ -10,7 +10,7 @@ rule { ary = [] ary.concat(val[0]) if val[0] - ary.concat(val[1]) if val[1] + ary.concat(val[1].flatten) if val[1] ary.concat(val[3].flatten) ary.append(val[4]) if val[4] result = ary @@ -187,6 +187,36 @@ rule { result = Grammar::Node::TokenDecl.new(tokens: val[1], location: merge_locations(val[0].loc, val[1].last.loc)) } + | "%token-pattern" token_pattern_declarations + { result = val[1] } + | "%token-action" token_action_declaration+ + { result = val[1] } + | "%symbol-set" IDENTIFIER symbol+ + { + result = Grammar::Node::SymbolSetDecl.new( + name: val[1].s_value, symbols: val[2], location: merge_locations(val[0].loc, val[2].last.loc) + ) + } + | "%lexer-context" IDENTIFIER symbol+ + { + result = Grammar::Node::LexerContextDecl.new( + name: val[1].s_value, symbols: val[2], location: merge_locations(val[0].loc, val[2].last.loc) + ) + } + | "%lex-prec" lex_prec_chain + { result = val[1] } + | "%lex-tie" symbol symbol+ + { + result = Grammar::Node::LexTieDecl.new( + kind: :tie, operands: [val[1]] + val[2], location: merge_locations(val[0].loc, val[2].last.loc) + ) + } + | "%lex-no-tie" symbol symbol+ + { + result = Grammar::Node::LexTieDecl.new( + kind: :no_tie, operands: [val[1]] + val[2], location: merge_locations(val[0].loc, val[2].last.loc) + ) + } | "%type" symbol_declarations { result = Grammar::Node::TypeDecl.new( @@ -265,6 +295,80 @@ rule ) } + token_pattern_declarations: + TAG? token_pattern_declaration+ + { + val[1].each { |pattern| pattern.tag = val[0] } + result = val[1] + } + | token_pattern_declarations TAG token_pattern_declaration+ + { + val[2].each { |pattern| pattern.tag = val[1] } + result = val[0].concat(val[2]) + } + + token_pattern_declaration: + IDENTIFIER REGEX alias + { + result = Grammar::Node::TokenPatternDecl.new( + id: val[0], pattern: val[1], alias_name: val[2]&.s_value, + location: merge_locations(val[0].loc, val[1].loc, val[2]&.loc) + ) + } + + lex_prec_chain: + symbol lex_prec_op symbol + { + result = [Grammar::Node::LexPrecDecl.new( + left: val[0], operator: val[1], right: val[2], location: merge_locations(val[0].loc, val[2].loc) + )] + } + | lex_prec_chain lex_prec_op symbol + { + left = val[0].last.right + result = val[0] << Grammar::Node::LexPrecDecl.new( + left: left, operator: val[1], right: val[2], location: merge_locations(left.loc, val[2].loc) + ) + } + + lex_prec_op: + "<~" + { + result = Lrama::Grammar::LexPrec::IDENTITY_RIGHT_LONGEST + } + | "<-" + { + result = Lrama::Grammar::LexPrec::IDENTITY_RIGHT + } + | "-~" + { + result = Lrama::Grammar::LexPrec::LONGEST + } + | "<<" + { + result = Lrama::Grammar::LexPrec::TOKEN_RIGHT + } + | "-<" + { + result = Lrama::Grammar::LexPrec::TOKEN_RIGHT_LENGTH + } + | " Grammar::Symbol def ielr_defined?: () -> bool + + def pslr_defined?: () -> bool + + def token_patterns: () -> Array[Grammar::TokenPattern] + + def lex_prec: () -> Grammar::LexPrec + + def pslr_max_states: () -> Integer? + + def pslr_max_state_ratio: () -> Float? end include Symbols::Resolver::_DelegatedMethods @@ -76,6 +86,14 @@ module Lrama @start_nterm: Lrama::Lexer::Token::Base? + @token_patterns: Array[Grammar::TokenPattern] + + @lex_prec: Grammar::LexPrec + + @symbol_sets: Hash[String, Array[Lexer::Token::Base]] + + @lex_tie: Grammar::LexTie + @nodes: Array[Node::Base] extend Forwardable @@ -140,6 +158,22 @@ module Lrama attr_accessor nodes: Array[Node::Base] + attr_reader token_patterns: Array[Grammar::TokenPattern] + + attr_reader lex_prec: Grammar::LexPrec + + attr_reader symbol_sets: Hash[String, Array[Lexer::Token::Base]] + + attr_reader lex_tie: Grammar::LexTie + + attr_reader lexer_contexts: Hash[String, Grammar::LexerContext] + + attr_reader token_actions: Array[Grammar::TokenAction] + + # Argument symbol names for each parameterized rule expansion. + # @rbs () -> Hash[String, Array[String]] + def parameterized_expansion_args: () -> Hash[String, Array[String]] + # @rbs (Counter rule_counter, bool locations, Hash[String, String?] define) -> void def initialize: (Counter rule_counter, bool locations, Hash[String, String?] define) -> void @@ -234,8 +268,135 @@ module Lrama # @rbs () -> bool def ielr_defined?: () -> bool + # @rbs () -> bool + def pslr_defined?: () -> bool + + # @rbs () -> String? + def pslr_state_member: () -> String? + + # @rbs () -> Integer? + def pslr_max_states: () -> Integer? + + # @rbs () -> Float? + def pslr_max_state_ratio: () -> Float? + + # True when the generated parser owns lexical analysis completely + # (%define api.pslr.lexer generated, the paper's own model). + # @rbs () -> bool + def pslr_lexer_generated?: () -> bool + + # Base table construction for PSLR: extended IELR (default) or + # canonical LR(1) for debugging unresolved-conflict reports whose + # contexts would otherwise be merged (section 3.4.3). + # @rbs () -> String + def pslr_tables: () -> String + + # @rbs () -> bool + def pslr_canonical_tables?: () -> bool + + # Terminals that the pseudo-scanner cannot produce: real terminals + # used by the grammar that have no %token-pattern (explicit or + # synthesized). Pure mode requires this list to be empty; bridge + # mode reports it so users know which tokens their yylex must keep + # producing. + # @rbs () -> Array[String] + def uncovered_pslr_terminals: () -> Array[String] + + # LAC (lookahead correction) setting from %define parse.lac. + # PSLR parsers default to full because exploratory parses are what + # keep merged-state pseudo-scanning canonical-equivalent; other + # parser types default to none for Bison compatibility. + # @rbs () -> String + def parse_lac: () -> String + + # @rbs () -> bool + def parse_lac_full?: () -> bool + + # @rbs () -> bool + def parse_lac_explicit_none?: () -> bool + + # @rbs () -> Array[Grammar::TokenPattern] + def layout_token_patterns: () -> Array[Grammar::TokenPattern] + + # @rbs () -> Set[String] + def layout_token_names: () -> Set[String] + + # Add a token pattern from %token-pattern directive + # @rbs (id: Lexer::Token::Ident, pattern: Lexer::Token::Regex, ?alias_name: String?, ?tag: Lexer::Token::Tag?, lineno: Integer) -> Grammar::TokenPattern + def add_token_pattern: (id: Lexer::Token::Ident, pattern: Lexer::Token::Regex, lineno: Integer, ?alias_name: String?, ?tag: Lexer::Token::Tag?) -> Grammar::TokenPattern + + # Add a symbol set from %symbol-set directive. + # @rbs (name: String, symbols: Array[Lexer::Token::Base]) -> Array[Lexer::Token::Base] + def add_symbol_set: (name: String, symbols: Array[Lexer::Token::Base]) -> Array[Lexer::Token::Base] + + # Add lex-prec rules from %lex-prec directive. + # Stores as raw declaration for delayed expansion after implicit literal synthesis. + # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Grammar::LexPrec::Declaration + def add_lex_prec_rule: (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Grammar::LexPrec::Declaration + + # Finalize lexical declarations after implicit literal synthesis. + # Expands yyall and symbol-set operands using the post-synthesis token universe. + # Validates that identity-component operators are not used as self-pairs. + # @rbs () -> void + def finalize_lexical_declarations!: () -> void + + # Add lexical tie relationships from %lex-tie directive. + # @rbs (operands: Array[Lexer::Token::Base]) -> void + def add_lex_tie: (operands: Array[Lexer::Token::Base]) -> void + + # Add no-tie declarations from %lex-no-tie directive. + # @rbs (operands: Array[Lexer::Token::Base]) -> void + def add_lex_no_tie: (operands: Array[Lexer::Token::Base]) -> void + + # Add a lexer context from %lexer-context directive + # @rbs (name: String, symbols: Array[Lexer::Token::Base]) -> Grammar::LexerContext + def add_lexer_context: (name: String, symbols: Array[Lexer::Token::Base]) -> Grammar::LexerContext + + # Add a token action from %token-action directive + # @rbs (id: Lexer::Token::Ident, code: Lexer::Token::UserCode, lineno: Integer) -> Grammar::TokenAction + def add_token_action: (id: Lexer::Token::Ident, code: Lexer::Token::UserCode, lineno: Integer) -> Grammar::TokenAction + + # Find a token pattern by its name + # @rbs (String name) -> Grammar::TokenPattern? + def find_token_pattern: (String name) -> Grammar::TokenPattern? + + # @rbs (Set[String] tokens) -> Set[String] + def expand_lexical_ties: (Set[String] tokens) -> Set[String] + + # @rbs (ScannerFSA scanner_fsa) -> void + def finalize_lexical_ties!: (ScannerFSA scanner_fsa) -> void + + REGEX_LITERAL_ESCAPES: Array[String] + + REGEX_CONTROL_ESCAPES: Hash[String, String] + + # @rbs () -> void + def synthesize_implicit_literal_token_patterns!: () -> void + private + # Validate that identity-component operators are not applied to self-pairs. + # Self-pair is allowed only for length-only operators (-~ and -s). + # @rbs (Lexer::Token::Base left, Lexer::Token::Base right, Symbol operator, Integer lineno) -> void + def validate_lex_prec_self_pair!: (Lexer::Token::Base left, Lexer::Token::Base right, Symbol operator, Integer lineno) -> void + + # @rbs (Grammar::Symbol term) -> String? + def implicit_literal_regex_pattern: (Grammar::Symbol term) -> String? + + # @rbs (String literal) -> String + def escape_regex_literal: (String literal) -> String + + # @rbs () -> void + def validate_pslr_configuration!: () -> void + + # @rbs () -> void + def validate_parse_lac!: () -> void + + # Layout tokens are consumed by the pseudo-scanner and never reach + # the parser, so they must not appear in grammar rules (section 3.6). + # @rbs () -> void + def validate_no_layout_tokens_in_rules!: () -> void + # @rbs (Node::Base node) -> void def validate_character_literals_in: (Node::Base node) -> void @@ -245,6 +406,27 @@ module Lrama # @rbs () -> void def _evaluate_nodes: () -> void + # @rbs () -> void + def validate_pslr_lexer!: () -> void + + # @rbs () -> void + def validate_pslr_tables!: () -> void + + # @rbs (Lexer::Token::Base operand) -> Lexer::Token::Base + def canonical_lexical_operand: (Lexer::Token::Base operand) -> Lexer::Token::Base + + # @rbs (Lexer::Token::Base operand) -> Array[Lexer::Token::Base] + def expand_pslr_operand: (Lexer::Token::Base operand) -> Array[Lexer::Token::Base] + + # @rbs (Lexer::Token::Base operand) -> Grammar::LexTie::OperandGroup + def pslr_operand_group: (Lexer::Token::Base operand) -> Grammar::LexTie::OperandGroup + + # @rbs (String key) -> Integer? + def parse_pslr_positive_integer: (String key) -> Integer? + + # @rbs (String key) -> Float? + def parse_pslr_positive_float: (String key) -> Float? + # @rbs () -> void def sort_precedence: () -> void @@ -283,6 +465,9 @@ module Lrama # @rbs () -> void def set_lhs_and_rhs: () -> void + # @rbs () -> void + def resolve_lexical_aliases: () -> void + # Rule inherits precedence from the last term in RHS. # # https://www.gnu.org/software/bison/manual/html_node/How-Precedence.html diff --git a/sig/generated/lrama/grammar/lex_prec.rbs b/sig/generated/lrama/grammar/lex_prec.rbs new file mode 100644 index 000000000..b6e6c5e21 --- /dev/null +++ b/sig/generated/lrama/grammar/lex_prec.rbs @@ -0,0 +1,121 @@ +# Generated from lib/lrama/grammar/lex_prec.rb with RBS::Inline + +module Lrama + class Grammar + # Represents lexical precedence rules defined by %lex-prec. + # + # Lrama accepts ASCII spellings for the PSLR paper operators: + # <~ identity conflict: right token wins; length conflict: longest wins + # <- identity conflict: right token wins + # -~ length conflict: longest wins + # << identity and length conflicts: right token wins + # -< length conflict: right token wins + # void + def initialize: (left_operand: Lexer::Token::Base, operator: Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> void + end + + class Rule + attr_reader left_token: Lexer::Token::Base + + attr_reader operator: Symbol + + attr_reader right_token: Lexer::Token::Base + + attr_reader lineno: Integer + + # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> void + def initialize: (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> void + + # @rbs () -> String + def left_name: () -> String + + # @rbs () -> String + def right_name: () -> String + end + + attr_reader rules: Array[Rule] + + attr_reader declarations: Array[Declaration] + + attr_reader used_rules: Set[Integer] + + # @rbs () -> void + def initialize: () -> void + + # Mark a rule as used by conflict resolution. + # @rbs (Integer rule_index) -> void + def mark_used: (Integer rule_index) -> void + + # Returns rules that were never used in conflict resolution. + # @rbs () -> Array[Rule] + def useless_rules: () -> Array[Rule] + + # Store a raw declaration for delayed expansion. + # @rbs (left_operand: Lexer::Token::Base, operator: Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> Declaration + def add_declaration: (left_operand: Lexer::Token::Base, operator: Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> Declaration + + # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Rule + def add_rule: (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Rule + + # True when winner explicitly wins an identity conflict against loser. + # The relation is intentionally not transitive. + # @rbs (String winner, String loser, ?track: bool) -> bool + def identity_precedes?: (String winner, String loser, ?track: bool) -> bool + + # True when rule declares a longest-match length relation for the pair. + # @rbs (String token1, String token2) -> bool + def longest_pair?: (String token1, String token2) -> bool + + # True when rule declares a shortest-match length relation for the pair. + # @rbs (String token1, String token2) -> bool + def shortest_pair?: (String token1, String token2) -> bool + + # Returns the explicit right-token length winner for a pair, if any. + # @rbs (String token1, String token2) -> String? + def right_token_length_winner: (String token1, String token2) -> String? + + private + + # @rbs (String token1, String token2, Array[Symbol] operators) -> bool + def pair_rule?: (String token1, String token2, Array[Symbol] operators) -> bool + end + end +end diff --git a/sig/generated/lrama/grammar/lex_tie.rbs b/sig/generated/lrama/grammar/lex_tie.rbs new file mode 100644 index 000000000..7655ca7ba --- /dev/null +++ b/sig/generated/lrama/grammar/lex_tie.rbs @@ -0,0 +1,110 @@ +# Generated from lib/lrama/grammar/lex_tie.rb with RBS::Inline + +module Lrama + class Grammar + # Stores PSLR lexical ties and explicit no-tie declarations. + # + # Lexical ties expand acc(sp); they never resolve a scanner conflict by + # themselves. Conflict selection is still handled by %lex-prec. + class LexTie + class OperandGroup + attr_reader names: Array[String] + + attr_reader kind: ::Symbol + + # @rbs (names: Array[String], kind: ::Symbol) -> void + def initialize: (names: Array[String], kind: ::Symbol) -> void + end + + class Declaration + attr_reader kind: ::Symbol + + attr_reader groups: Array[OperandGroup] + + attr_reader lineno: Integer + + # @rbs (kind: ::Symbol, groups: Array[OperandGroup], lineno: Integer) -> void + def initialize: (kind: ::Symbol, groups: Array[OperandGroup], lineno: Integer) -> void + end + + class Decision + attr_reader kind: ::Symbol + + attr_reader specificity: Integer + + attr_reader lineno: Integer + + # @rbs (kind: ::Symbol, specificity: Integer, lineno: Integer) -> void + def initialize: (kind: ::Symbol, specificity: Integer, lineno: Integer) -> void + end + + attr_reader ties: Hash[String, Set[String]] + + attr_reader no_ties: Set[[ String, String ]] + + attr_reader declarations: Array[Declaration] + + # @rbs () -> void + def initialize: () -> void + + # @rbs (String left, String right) -> void + def add_tie: (String left, String right) -> void + + # @rbs (String left, String right) -> void + def add_no_tie: (String left, String right) -> void + + # @rbs (groups: Array[OperandGroup], ?lineno: Integer) -> void + def add_tie_declaration: (groups: Array[OperandGroup], ?lineno: Integer) -> void + + # @rbs (groups: Array[OperandGroup], ?lineno: Integer) -> void + def add_no_tie_declaration: (groups: Array[OperandGroup], ?lineno: Integer) -> void + + # @rbs (Array[String] token_names, Set[[String, String]] conflict_pairs) -> void + def finalize!: (Array[String] token_names, Set[[ String, String ]] conflict_pairs) -> void + + # @rbs (String name) -> Set[String] + def tied_names: (String name) -> Set[String] + + # @rbs (String left, String right) -> bool + def tied?: (String left, String right) -> bool + + # @rbs (String left, String right) -> bool + def no_tie?: (String left, String right) -> bool + + # @rbs () -> Array[[String, String]] + def no_ties_conflicting_with_ties: () -> Array[[ String, String ]] + + private + + # @rbs (Hash[[String, String], Decision] decisions, [String, String] pair, Decision decision) -> void + def apply_decision: (Hash[[ String, String ], Decision] decisions, [ String, String ] pair, Decision decision) -> void + + # @rbs (Declaration declaration, Array[String] token_names, Set[[String, String]] conflict_pairs) -> Array[[[String, String], Integer]] + def declaration_pairs: (Declaration declaration, Array[String] token_names, Set[[ String, String ]] conflict_pairs) -> Array[[ [ String, String ], Integer ]] + + # @rbs (OperandGroup group, Array[String] token_names) -> Array[String] + def names_for_group: (OperandGroup group, Array[String] token_names) -> Array[String] + + # @rbs (OperandGroup left, OperandGroup right) -> Integer + def group_specificity: (OperandGroup left, OperandGroup right) -> Integer + + # @rbs (Array[String] token_names, Hash[[String, String], Decision] decisions) -> void + def rebuild_relations: (Array[String] token_names, Hash[[ String, String ], Decision] decisions) -> void + + # @rbs (Hash[String, String] parents, String name) -> String + def root: (Hash[String, String] parents, String name) -> String + + # @rbs (Hash[String, String] parents, String left, String right) -> void + def union: (Hash[String, String] parents, String left, String right) -> void + + # Compute closure specificity between two tokens via tie graph BFS. + # Path specificity = min(edge specificities on the path). + # Result = max over all paths connecting left and right. + # @rbs (String left, String right, Hash[[String, String], Integer] tie_specificities) -> Integer + def tie_specificity_between: (String left, String right, Hash[[ String, String ], Integer] tie_specificities) -> Integer + + # @rbs (String left, String right) -> [String, String] + def pair_key: (String left, String right) -> [ String, String ] + end + end +end diff --git a/sig/generated/lrama/grammar/lexer_context.rbs b/sig/generated/lrama/grammar/lexer_context.rbs new file mode 100644 index 000000000..436576d98 --- /dev/null +++ b/sig/generated/lrama/grammar/lexer_context.rbs @@ -0,0 +1,30 @@ +# Generated from lib/lrama/grammar/lexer_context.rb with RBS::Inline + +module Lrama + class Grammar + # Represents a lexer context defined by %lexer-context directive. + # + # Example: + # %lexer-context BEG keyword_if keyword_unless '(' '[' '{' + # + # The bitmask value is automatically assigned by definition order (1 << index). + class LexerContext + attr_reader name: String + + attr_reader index: Integer + + attr_reader symbols: Array[Lexer::Token::Ident] + + # @rbs (name: String, index: Integer) -> void + def initialize: (name: String, index: Integer) -> void + + # Bitmask value for this context (1 << index). + # @rbs () -> Integer + def bitmask: () -> Integer + + # Add symbols that belong to this context. + # @rbs (Array[Lexer::Token::Ident] syms) -> void + def add_symbols: (Array[Lexer::Token::Ident] syms) -> void + end + end +end diff --git a/sig/generated/lrama/grammar/node/lex_prec_decl.rbs b/sig/generated/lrama/grammar/node/lex_prec_decl.rbs new file mode 100644 index 000000000..bf1d72623 --- /dev/null +++ b/sig/generated/lrama/grammar/node/lex_prec_decl.rbs @@ -0,0 +1,18 @@ +# Generated from lib/lrama/grammar/node/lex_prec_decl.rb with RBS::Inline + +module Lrama + class Grammar + module Node + class LexPrecDecl < Base + attr_reader left: Lexer::Token::Base + + attr_reader operator: ::Symbol + + attr_reader right: Lexer::Token::Base + + # @rbs (left: Lexer::Token::Base, operator: ::Symbol, right: Lexer::Token::Base, location: Lexer::Location) -> void + def initialize: (left: Lexer::Token::Base, operator: ::Symbol, right: Lexer::Token::Base, location: Lexer::Location) -> void + end + end + end +end diff --git a/sig/generated/lrama/grammar/node/lex_tie_decl.rbs b/sig/generated/lrama/grammar/node/lex_tie_decl.rbs new file mode 100644 index 000000000..eb5ef75e2 --- /dev/null +++ b/sig/generated/lrama/grammar/node/lex_tie_decl.rbs @@ -0,0 +1,16 @@ +# Generated from lib/lrama/grammar/node/lex_tie_decl.rb with RBS::Inline + +module Lrama + class Grammar + module Node + class LexTieDecl < Base + attr_reader operands: Array[Lexer::Token::Base] + + attr_reader kind: :tie | :no_tie + + # @rbs (operands: Array[Lexer::Token::Base], kind: :tie | :no_tie, location: Lexer::Location) -> void + def initialize: (operands: Array[Lexer::Token::Base], kind: :tie | :no_tie, location: Lexer::Location) -> void + end + end + end +end diff --git a/sig/generated/lrama/grammar/node/lexer_context_decl.rbs b/sig/generated/lrama/grammar/node/lexer_context_decl.rbs new file mode 100644 index 000000000..def38cee3 --- /dev/null +++ b/sig/generated/lrama/grammar/node/lexer_context_decl.rbs @@ -0,0 +1,16 @@ +# Generated from lib/lrama/grammar/node/lexer_context_decl.rb with RBS::Inline + +module Lrama + class Grammar + module Node + class LexerContextDecl < Base + attr_reader name: String + + attr_reader symbols: Array[Lexer::Token::Base] + + # @rbs (name: String, symbols: Array[Lexer::Token::Base], location: Lexer::Location) -> void + def initialize: (name: String, symbols: Array[Lexer::Token::Base], location: Lexer::Location) -> void + end + end + end +end diff --git a/sig/generated/lrama/grammar/node/symbol_set_decl.rbs b/sig/generated/lrama/grammar/node/symbol_set_decl.rbs new file mode 100644 index 000000000..433cc54da --- /dev/null +++ b/sig/generated/lrama/grammar/node/symbol_set_decl.rbs @@ -0,0 +1,16 @@ +# Generated from lib/lrama/grammar/node/symbol_set_decl.rb with RBS::Inline + +module Lrama + class Grammar + module Node + class SymbolSetDecl < Base + attr_reader name: String + + attr_reader symbols: Array[Lexer::Token::Base] + + # @rbs (name: String, symbols: Array[Lexer::Token::Base], location: Lexer::Location) -> void + def initialize: (name: String, symbols: Array[Lexer::Token::Base], location: Lexer::Location) -> void + end + end + end +end diff --git a/sig/generated/lrama/grammar/node/token_action_decl.rbs b/sig/generated/lrama/grammar/node/token_action_decl.rbs new file mode 100644 index 000000000..ec2ab5664 --- /dev/null +++ b/sig/generated/lrama/grammar/node/token_action_decl.rbs @@ -0,0 +1,16 @@ +# Generated from lib/lrama/grammar/node/token_action_decl.rb with RBS::Inline + +module Lrama + class Grammar + module Node + class TokenActionDecl < Base + attr_reader id: Lexer::Token::Ident + + attr_reader code: Lexer::Token::UserCode + + # @rbs (id: Lexer::Token::Ident, code: Lexer::Token::UserCode, location: Lexer::Location) -> void + def initialize: (id: Lexer::Token::Ident, code: Lexer::Token::UserCode, location: Lexer::Location) -> void + end + end + end +end diff --git a/sig/generated/lrama/grammar/node/token_pattern_decl.rbs b/sig/generated/lrama/grammar/node/token_pattern_decl.rbs new file mode 100644 index 000000000..2b2c7bf6e --- /dev/null +++ b/sig/generated/lrama/grammar/node/token_pattern_decl.rbs @@ -0,0 +1,20 @@ +# Generated from lib/lrama/grammar/node/token_pattern_decl.rb with RBS::Inline + +module Lrama + class Grammar + module Node + class TokenPatternDecl < Base + attr_reader id: Lexer::Token::Ident + + attr_reader pattern: Lexer::Token::Regex + + attr_reader alias_name: String? + + attr_accessor tag: Lexer::Token::Tag? + + # @rbs (id: Lexer::Token::Ident, pattern: Lexer::Token::Regex, alias_name: String?, location: Lexer::Location) -> void + def initialize: (id: Lexer::Token::Ident, pattern: Lexer::Token::Regex, alias_name: String?, location: Lexer::Location) -> void + end + end + end +end diff --git a/sig/generated/lrama/grammar/parameterized/resolver.rbs b/sig/generated/lrama/grammar/parameterized/resolver.rbs index 3aebcbc59..4a5f66ded 100644 --- a/sig/generated/lrama/grammar/parameterized/resolver.rbs +++ b/sig/generated/lrama/grammar/parameterized/resolver.rbs @@ -8,6 +8,8 @@ module Lrama attr_accessor created_lhs_list: Array[Grammar::Symbol::Id] + attr_reader expansion_args: Hash[String, Array[String]] + # @rbs () -> void def initialize: () -> void @@ -23,6 +25,12 @@ module Lrama # @rbs (String lhs_s_value) -> Grammar::Symbol::Id? def created_lhs: (String lhs_s_value) -> Grammar::Symbol::Id? + # Register the argument symbol names for a parameterized rule expansion. + # Used by LexerContextClassifier to inherit context from arguments. + # + # @rbs (String lhs_s_value, Array[String] args) -> void + def register_expansion_args: (String lhs_s_value, Array[String] args) -> void + # @rbs () -> Array[Rule] def redefined_rules: () -> Array[Rule] diff --git a/sig/generated/lrama/grammar/symbol.rbs b/sig/generated/lrama/grammar/symbol.rbs index 03d6edf3b..d08e7ff6c 100644 --- a/sig/generated/lrama/grammar/symbol.rbs +++ b/sig/generated/lrama/grammar/symbol.rbs @@ -76,6 +76,9 @@ module Lrama # @rbs () -> bool def character?: () -> bool + # @rbs () -> Integer + def character_code: () -> Integer + # @rbs () -> bool def eof_symbol?: () -> bool diff --git a/sig/generated/lrama/grammar/token_action.rbs b/sig/generated/lrama/grammar/token_action.rbs new file mode 100644 index 000000000..cd208edfd --- /dev/null +++ b/sig/generated/lrama/grammar/token_action.rbs @@ -0,0 +1,28 @@ +# Generated from lib/lrama/grammar/token_action.rb with RBS::Inline + +module Lrama + class Grammar + # Represents a token action defined by %token-action directive. + # + # Token actions are user code blocks associated with token patterns. + # When a token is matched by the pseudo-scanner, the associated code runs. + # Layout tokens are accumulated, and the accumulated text is available + # to the next non-layout token's action. + # + # Example: + # %token-action ID { printf("matched ID: %.*s\n", yyleng, yytext); } + class TokenAction + attr_reader token_id: Lexer::Token::Ident + + attr_reader code: Lexer::Token::UserCode + + attr_reader lineno: Integer + + # @rbs (token_id: Lexer::Token::Ident, code: Lexer::Token::UserCode, lineno: Integer) -> void + def initialize: (token_id: Lexer::Token::Ident, code: Lexer::Token::UserCode, lineno: Integer) -> void + + # @rbs () -> String + def token_name: () -> String + end + end +end diff --git a/sig/generated/lrama/grammar/token_pattern.rbs b/sig/generated/lrama/grammar/token_pattern.rbs new file mode 100644 index 000000000..2e23e14e8 --- /dev/null +++ b/sig/generated/lrama/grammar/token_pattern.rbs @@ -0,0 +1,34 @@ +# Generated from lib/lrama/grammar/token_pattern.rb with RBS::Inline + +module Lrama + class Grammar + # Represents a token pattern defined by %token-pattern directive + # Example: %token-pattern RSHIFT />>/ "right shift" + class TokenPattern + attr_reader id: Lexer::Token::Base + + attr_reader pattern: Lexer::Token::Regex + + attr_reader alias_name: String? + + attr_reader tag: Lexer::Token::Tag? + + attr_reader lineno: Integer + + attr_reader definition_order: Integer + + # @rbs (id: Lexer::Token::Base, pattern: Lexer::Token::Regex, ?alias_name: String?, ?tag: Lexer::Token::Tag?, lineno: Integer, definition_order: Integer) -> void + def initialize: (id: Lexer::Token::Base, pattern: Lexer::Token::Regex, lineno: Integer, definition_order: Integer, ?alias_name: String?, ?tag: Lexer::Token::Tag?) -> void + + # @rbs () -> String + def name: () -> String + + # Returns the regex pattern string (without slashes) + # @rbs () -> String + def regex_pattern: () -> String + + # @rbs () -> bool + def layout?: () -> bool + end + end +end diff --git a/sig/generated/lrama/lexer.rbs b/sig/generated/lrama/lexer.rbs index b0153819a..0649cc532 100644 --- a/sig/generated/lrama/lexer.rbs +++ b/sig/generated/lrama/lexer.rbs @@ -4,7 +4,7 @@ module Lrama class Lexer type token = lexer_token | c_token - type lexer_token = [ String, Token::Token ] | [ ::Symbol, Token::Tag ] | [ ::Symbol, Token::Char ] | [ ::Symbol, Token::Str ] | [ ::Symbol, Token::Int ] | [ ::Symbol, Token::Ident ] + type lexer_token = [ String, Token::Token ] | [ ::Symbol, Token::Tag ] | [ ::Symbol, Token::Char ] | [ ::Symbol, Token::Str ] | [ ::Symbol, Token::Int ] | [ ::Symbol, Token::Ident ] | [ ::Symbol, Token::Regex ] type c_token = [ :C_DECLARATION, Token::UserCode ] @@ -56,6 +56,9 @@ module Lrama # @rbs (StringScanner scanner) -> void def skip_trivia: (StringScanner scanner) -> void + # @rbs () -> Token::Regex? + def scan_regex_token: () -> Token::Regex? + # @rbs () -> void def lex_comment: () -> void diff --git a/sig/generated/lrama/lexer/token/regex.rbs b/sig/generated/lrama/lexer/token/regex.rbs new file mode 100644 index 000000000..b832c4be2 --- /dev/null +++ b/sig/generated/lrama/lexer/token/regex.rbs @@ -0,0 +1,15 @@ +# Generated from lib/lrama/lexer/token/regex.rb with RBS::Inline + +module Lrama + class Lexer + module Token + # Token class for regex patterns used in %token-pattern directive + # Example: /[a-zA-Z_][a-zA-Z0-9_]*/ + class Regex < Base + # Returns the regex pattern without the surrounding slashes + # @rbs () -> String + def pattern: () -> String + end + end + end +end diff --git a/spec/lrama/grammar/lex_prec_spec.rb b/spec/lrama/grammar/lex_prec_spec.rb new file mode 100644 index 000000000..8681a3a4f --- /dev/null +++ b/spec/lrama/grammar/lex_prec_spec.rb @@ -0,0 +1,50 @@ +# frozen_string_literal: true + +RSpec.describe Lrama::Grammar::LexPrec do + let(:lex_prec) { Lrama::Grammar::LexPrec.new } + + def ident(name) + Lrama::Lexer::Token::Ident.new(s_value: name) + end + + it "stores identity-right and longest-match rules" do + lex_prec.add_rule( + left_token: ident("ID"), + operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT_LONGEST, + right_token: ident("IF"), + lineno: 1 + ) + + expect(lex_prec.rules.size).to eq(1) + expect(lex_prec.identity_precedes?("IF", "ID")).to be true + expect(lex_prec.identity_precedes?("ID", "IF")).to be false + expect(lex_prec.longest_pair?("ID", "IF")).to be true + end + + it "does not infer transitive identity precedence" do + lex_prec.add_rule( + left_token: ident("A"), + operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, + right_token: ident("B"), + lineno: 1 + ) + lex_prec.add_rule( + left_token: ident("B"), + operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, + right_token: ident("C"), + lineno: 1 + ) + + expect(lex_prec.identity_precedes?("B", "A")).to be true + expect(lex_prec.identity_precedes?("C", "B")).to be true + expect(lex_prec.identity_precedes?("C", "A")).to be false + end + + it "separates lexical ties from precedence" do + tie = Lrama::Grammar::LexTie.new + tie.add_tie("ID", "IF") + + expect(tie.tied?("ID", "IF")).to be true + expect(lex_prec.identity_precedes?("IF", "ID")).to be false + end +end diff --git a/spec/lrama/grammar/token_action_spec.rb b/spec/lrama/grammar/token_action_spec.rb new file mode 100644 index 000000000..238d0a2c9 --- /dev/null +++ b/spec/lrama/grammar/token_action_spec.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +RSpec.describe Lrama::Grammar::TokenAction do + def ident(name) + Lrama::Lexer::Token::Ident.new(s_value: name) + end + + def user_code(code) + Lrama::Lexer::Token::UserCode.new(s_value: code) + end + + it "stores token action attributes" do + action = Lrama::Grammar::TokenAction.new( + token_id: ident("ID"), + code: user_code('printf("matched");'), + lineno: 5 + ) + + expect(action.token_name).to eq("ID") + expect(action.code.s_value).to eq('printf("matched");') + expect(action.lineno).to eq(5) + end +end diff --git a/spec/lrama/grammar/token_pattern_spec.rb b/spec/lrama/grammar/token_pattern_spec.rb new file mode 100644 index 000000000..2318865b9 --- /dev/null +++ b/spec/lrama/grammar/token_pattern_spec.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +RSpec.describe Lrama::Grammar::TokenPattern do + it "stores token pattern information" do + id = Lrama::Lexer::Token::Ident.new(s_value: "RSHIFT") + pattern = Lrama::Lexer::Token::Regex.new(s_value: "/>>>/") + + token_pattern = Lrama::Grammar::TokenPattern.new( + id: id, + pattern: pattern, + alias_name: "right shift", + tag: nil, + lineno: 1, + definition_order: 0 + ) + + expect(token_pattern.name).to eq("RSHIFT") + expect(token_pattern.regex_pattern).to eq(">>>") + expect(token_pattern.alias_name).to eq("right shift") + expect(token_pattern.definition_order).to eq(0) + end + + it "recognizes YYLAYOUT-prefixed layout tokens" do + pattern = Lrama::Lexer::Token::Regex.new(s_value: "/[ ]+/") + layout = Lrama::Grammar::TokenPattern.new( + id: Lrama::Lexer::Token::Ident.new(s_value: "YYLAYOUT_COMMENT"), + pattern: pattern, + lineno: 1, + definition_order: 0 + ) + normal = Lrama::Grammar::TokenPattern.new( + id: Lrama::Lexer::Token::Ident.new(s_value: "ID"), + pattern: pattern, + lineno: 1, + definition_order: 1 + ) + + expect(layout).to be_layout + expect(normal).not_to be_layout + end +end diff --git a/spec/lrama/lexer/token/regex_spec.rb b/spec/lrama/lexer/token/regex_spec.rb new file mode 100644 index 000000000..bc4fb38ea --- /dev/null +++ b/spec/lrama/lexer/token/regex_spec.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +RSpec.describe Lrama::Lexer::Token::Regex do + describe "#pattern" do + it "returns the pattern without surrounding slashes" do + regex = Lrama::Lexer::Token::Regex.new(s_value: "/>>>/") + expect(regex.pattern).to eq(">>>") + end + + it "handles character class patterns" do + regex = Lrama::Lexer::Token::Regex.new(s_value: "/[a-zA-Z_][a-zA-Z0-9_]*/") + expect(regex.pattern).to eq("[a-zA-Z_][a-zA-Z0-9_]*") + end + + it "handles escape sequences" do + regex = Lrama::Lexer::Token::Regex.new(s_value: "/\\+/") + expect(regex.pattern).to eq("\\+") + end + + it "handles empty pattern" do + regex = Lrama::Lexer::Token::Regex.new(s_value: "//") + expect(regex.pattern).to eq("") + end + + it "handles single character pattern" do + regex = Lrama::Lexer::Token::Regex.new(s_value: "/>/") + expect(regex.pattern).to eq(">") + end + end + + describe "#s_value" do + it "returns the original value including slashes" do + regex = Lrama::Lexer::Token::Regex.new(s_value: "/>>>/") + expect(regex.s_value).to eq("/>>>/") + end + end +end diff --git a/spec/lrama/parser_spec.rb b/spec/lrama/parser_spec.rb index 708157419..0b384cbb2 100644 --- a/spec/lrama/parser_spec.rb +++ b/spec/lrama/parser_spec.rb @@ -4083,7 +4083,7 @@ class : keyword_class { code 1 } tSTRING { code 2 } keyword_end { code 3 } expect(aux.epilogue_first_lineno).to eq(6) expect(aux.epilogue).to eq((<<~CODE).chomp) - + static int yyerror(void) { return 0; } @@ -5194,4 +5194,219 @@ class : keyword_class tSTRING keyword_end end end end + + describe "PSLR directives" do + describe "%token-pattern" do + it "parses a single token pattern" do + y = <<~GRAMMAR + %token-pattern RSHIFT />>/ "right shift" + %% + program: RSHIFT + GRAMMAR + + grammar = Lrama::Parser.new(y, "pslr_test.y").parse + grammar.prepare + grammar.validate! + + expect(grammar.token_patterns.size).to eq(1) + token_pattern = grammar.token_patterns.first + expect(token_pattern.name).to eq("RSHIFT") + expect(token_pattern.regex_pattern).to eq(">>") + expect(token_pattern.alias_name).to eq("\"right shift\"") + end + + it "parses multiple token patterns" do + y = <<~GRAMMAR + %token-pattern RSHIFT />>/ "right shift" + %token-pattern RANGLE />/ "right angle" + %token-pattern LANGLE / RSHIFT />>/ "right shift" + %% + program: RSHIFT + GRAMMAR + + grammar = Lrama::Parser.new(y, "pslr_test.y").parse + grammar.prepare + grammar.validate! + + expect(grammar.token_patterns.size).to eq(1) + token_pattern = grammar.token_patterns.first + expect(token_pattern.tag.s_value).to eq("") + end + + it "parses escaped slashes inside token patterns" do + y = <<~GRAMMAR + %token-pattern SLASH /\\// + %% + program: SLASH + GRAMMAR + + grammar = Lrama::Parser.new(y, "pslr_test.y").parse + grammar.prepare + grammar.validate! + + expect(grammar.token_patterns.first.regex_pattern).to eq("\\/") + end + + it "keeps empty token patterns available for scanner diagnostics" do + y = <<~GRAMMAR + %token-pattern EMPTY // + %% + program: EMPTY + GRAMMAR + + grammar = Lrama::Parser.new(y, "pslr_test.y").parse + grammar.prepare + grammar.validate! + + expect(grammar.token_patterns.first.regex_pattern).to eq("") + end + end + + describe "%lex-prec" do + it "parses shorter priority rule" do + y = <<~GRAMMAR + %token RANGLE RSHIFT + %lex-prec RANGLE -s RSHIFT + %% + program: RANGLE | RSHIFT + GRAMMAR + + grammar = Lrama::Parser.new(y, "pslr_test.y").parse + grammar.prepare + grammar.validate! + + expect(grammar.lex_prec.declarations.size).to eq(1) + grammar.finalize_lexical_declarations! + expect(grammar.lex_prec.shortest_pair?("RANGLE", "RSHIFT")).to be true + end + + it "parses identity-right longest rule" do + y = <<~GRAMMAR + %token IF ID + %lex-prec ID <~ IF + %% + program: IF | ID + GRAMMAR + + grammar = Lrama::Parser.new(y, "pslr_test.y").parse + grammar.prepare + grammar.validate! + + expect(grammar.lex_prec.declarations.size).to eq(1) + grammar.finalize_lexical_declarations! + expect(grammar.lex_prec.identity_precedes?("IF", "ID")).to be true + expect(grammar.lex_prec.longest_pair?("ID", "IF")).to be true + end + + it "parses chained lex-prec rules" do + y = <<~GRAMMAR + %token IF ELSE WHILE ID + %lex-prec ID <- WHILE <- ELSE <- IF + %% + program: IF | ELSE | WHILE | ID + GRAMMAR + + grammar = Lrama::Parser.new(y, "pslr_test.y").parse + grammar.prepare + grammar.validate! + + expect(grammar.lex_prec.declarations.size).to eq(3) + grammar.finalize_lexical_declarations! + expect(grammar.lex_prec.identity_precedes?("WHILE", "ID")).to be true + expect(grammar.lex_prec.identity_precedes?("ELSE", "WHILE")).to be true + expect(grammar.lex_prec.identity_precedes?("IF", "ELSE")).to be true + expect(grammar.lex_prec.identity_precedes?("IF", "ID")).to be false + end + + it "parses symbol sets and lexical ties" do + y = <<~GRAMMAR + %token IF WHILE ID RANGLE RSHIFT + %symbol-set keywords IF WHILE + %lex-tie ID keywords + %lex-no-tie RANGLE RSHIFT + %% + program: IF | WHILE | ID | RANGLE | RSHIFT + GRAMMAR + + grammar = Lrama::Parser.new(y, "pslr_test.y").parse + grammar.prepare + grammar.validate! + + expect(grammar.symbol_sets.fetch("keywords").map(&:s_value)).to eq(["IF", "WHILE"]) + expect(grammar.lex_tie.declarations.map(&:kind)).to eq([:tie, :no_tie]) + expect(grammar.lex_tie.no_tie?("RANGLE", "RSHIFT")).to be true + end + end + + describe "%define lr.type pslr" do + it "recognizes pslr lr.type" do + y = <<~GRAMMAR + %define lr.type pslr + %token ID + %% + program: ID + GRAMMAR + + grammar = Lrama::Parser.new(y, "pslr_test.y").parse + grammar.prepare + grammar.validate! + + expect(grammar.pslr_defined?).to be true + end + end + + describe "%token-action" do + it "parses a single token action" do + y = <<~GRAMMAR + %token ID + %token-action ID { printf("matched ID"); } + %% + program: ID + GRAMMAR + + grammar = Lrama::Parser.new(y, "pslr_test.y").parse + grammar.prepare + grammar.validate! + + expect(grammar.token_actions.size).to eq(1) + action = grammar.token_actions.first + expect(action.token_name).to eq("ID") + expect(action.code.s_value).to include("printf") + end + + it "parses multiple token actions" do + y = <<~GRAMMAR + %token ID NUM + %token-action ID { handle_id(); } NUM { handle_num(); } + %% + program: ID | NUM + GRAMMAR + + grammar = Lrama::Parser.new(y, "pslr_test.y").parse + grammar.prepare + grammar.validate! + + expect(grammar.token_actions.size).to eq(2) + expect(grammar.token_actions.map(&:token_name)).to eq(["ID", "NUM"]) + end + end + + end end From bdb5f0459e198e3b5c402ab656311534aec80bc6 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 21:11:19 +0900 Subject: [PATCH 02/24] pslr: add scanner FSA construction from token patterns Build a single byte-oriented DFA from all %token-pattern regexes via Thompson NFA construction and subset construction (Def 3.2.12/3.2.13). Accepting states keep their full accepting-token sets; identity and length conflicts are intentionally left unresolved inside the DFA so that the parser-state-aware resolver can decide them later (paper section 3.2.6). The regex dialect is a small ASCII subset: literals, escapes, alternation, grouping, quantifiers, character classes with ranges and negation, and dot. Patterns are validated at construction time: nullable patterns, empty patterns/groups/alternatives, dangling escapes, malformed classes and unsupported escapes are rejected (lexemes must be non-empty per Def 2.2.2). ScannerFSA#pairwise_conflict_pairs precomputes the token pairs that can actually be in an identity or length scanner conflict; the set is used to filter %lex-tie expansion and later pair-based analyses. --- lib/lrama.rb | 1 + lib/lrama/scanner_fsa.rb | 692 ++++++++++++++++++++++++++++ sig/generated/lrama/scanner_fsa.rbs | 197 ++++++++ spec/lrama/grammar_spec.rb | 242 ++++++++++ spec/lrama/scanner_fsa_spec.rb | 322 +++++++++++++ 5 files changed, 1454 insertions(+) create mode 100644 lib/lrama/scanner_fsa.rb create mode 100644 sig/generated/lrama/scanner_fsa.rbs create mode 100644 spec/lrama/scanner_fsa_spec.rb diff --git a/lib/lrama.rb b/lib/lrama.rb index 56ba0044d..6cffd7ddc 100644 --- a/lib/lrama.rb +++ b/lib/lrama.rb @@ -15,6 +15,7 @@ require_relative "lrama/output" require_relative "lrama/parser" require_relative "lrama/reporter" +require_relative "lrama/scanner_fsa" require_relative "lrama/state" require_relative "lrama/states" require_relative "lrama/tracer" diff --git a/lib/lrama/scanner_fsa.rb b/lib/lrama/scanner_fsa.rb new file mode 100644 index 000000000..1ed327534 --- /dev/null +++ b/lib/lrama/scanner_fsa.rb @@ -0,0 +1,692 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +require "set" + +module Lrama + # Scanner Finite State Automaton for PSLR(1) + # Built from token patterns defined by %token-pattern directives + # Based on Definitions 3.2.12, 3.2.13 from the PSLR dissertation + class ScannerFSA + # Represents a state in the scanner FSA + class State + attr_reader :id #: Integer + attr_reader :transitions #: Hash[String, Integer] + attr_reader :accepting_tokens #: Array[Grammar::TokenPattern] + + # @rbs (Integer id) -> void + def initialize(id) + @id = id + @transitions = {} + @accepting_tokens = [] + end + + # @rbs () -> bool + def accepting? + !@accepting_tokens.empty? + end + + # @rbs (String char, Integer target_state_id) -> void + def add_transition(char, target_state_id) + @transitions[char] = target_state_id + end + + # @rbs (Grammar::TokenPattern token_pattern) -> void + def add_accepting_token(token_pattern) + @accepting_tokens << token_pattern + end + end + + attr_reader :states #: Array[State] + attr_reader :initial_state #: State + attr_reader :token_patterns #: Array[Grammar::TokenPattern] + + # @rbs (Array[Grammar::TokenPattern] token_patterns) -> void + def initialize(token_patterns) + @token_patterns = token_patterns + @states = [] + @state_counter = 0 + build_fsa + end + + # Returns the accepting state for a given FSA state + # Definition 3.2.13 (state_to_accepting_state) + # @rbs (Integer state_id) -> State? + def state_to_accepting_state(state_id) + state = @states[state_id] + return nil unless state&.accepting? + state + end + + # Returns the set of tokens accepted at FSA state ss + # Definition 3.2.12 acc(ss) + # @rbs (Integer state_id) -> Array[Grammar::TokenPattern] + def acc_ss(state_id) + state = @states[state_id] + return [] unless state + state.accepting_tokens + end + + # Simulate the FSA on input string starting from initial state + # Returns all accepting states reached during the scan + # @rbs (String input) -> Array[{state: State, position: Integer, token: Grammar::TokenPattern}] + def scan(input) + results = [] + current_state_id = 0 + + input.each_char.with_index do |char, index| + current_state = @states[current_state_id] + break unless current_state + + next_state_id = current_state.transitions[char] + break unless next_state_id + + current_state_id = next_state_id + next_state = @states[next_state_id] + + if next_state.accepting? + next_state.accepting_tokens.each do |token_pattern| + results << { state: next_state, position: index + 1, token: token_pattern } + end + end + end + + results + end + + # Returns token pairs that can be in an identity or length scanner conflict. + # Pair keys are sorted token names. + # @rbs () -> Set[[String, String]] + def pairwise_conflict_pairs + pairs = Set.new + + @states.each do |state| + accepting_names = state.accepting_tokens.map(&:name).uniq + accepting_names.combination(2) do |left, right| + pairs << pair_key(left, right) + end + end + + @states.each do |start| + shorter_names = start.accepting_tokens.map(&:name).uniq + next if shorter_names.empty? + + visited = Set.new + stack = start.transitions.values.uniq + + until stack.empty? + state_id = stack.pop + next if visited.include?(state_id) + + visited << state_id + state = @states[state_id] + next unless state + + longer_names = state.accepting_tokens.map(&:name).uniq + shorter_names.product(longer_names).each do |left, right| + pairs << pair_key(left, right) if left != right + end + state.transitions.each_value {|next_id| stack << next_id } + end + end + + pairs + end + + # @rbs (String left, String right) -> bool + def pairwise_conflict?(left, right) + pairwise_conflict_pairs.include?(pair_key(left, right)) + end + + private + + # @rbs (String left, String right) -> [String, String] + def pair_key(left, right) + left <= right ? [left, right] : [right, left] + end + + # Build the FSA from token patterns + # Uses Thompson's construction for NFAs followed by subset construction for DFA + # @rbs () -> void + def build_fsa + return if @token_patterns.empty? + + # Create initial state + @initial_state = create_state + + # Build NFA for each token pattern and convert to DFA + nfa_states = build_nfa + convert_nfa_to_dfa(nfa_states) + end + + # @rbs () -> State + def create_state + state = State.new(@state_counter) + @state_counter += 1 + @states << state + state + end + + # Simple NFA state for regex compilation + class PatternError < StandardError; end + + class NFAState + attr_reader :id #: Integer + attr_accessor :transitions #: Hash[String?, Array[NFAState]] + attr_accessor :accepting_token #: Grammar::TokenPattern? + + # @rbs (Integer id) -> void + def initialize(id) + @id = id + @transitions = Hash.new { |h, k| h[k] = [] } + @accepting_token = nil + end + + # @rbs (String? char, NFAState target) -> void + def add_transition(char, target) + @transitions[char] << target + end + + # @rbs () -> bool + def accepting? + !@accepting_token.nil? + end + end + + class Fragment + attr_reader :start_state #: NFAState + attr_reader :end_state #: NFAState + attr_reader :nullable #: bool + + # @rbs (NFAState start_state, NFAState end_state, bool nullable) -> void + def initialize(start_state, end_state, nullable) + @start_state = start_state + @end_state = end_state + @nullable = nullable + end + + # @rbs () -> [NFAState, NFAState] + def to_ary + [@start_state, @end_state] + end + end + + # Build NFA from all token patterns + # @rbs () -> Array[NFAState] + def build_nfa + nfa_states = [] + nfa_counter = [0] + + # Create NFA start state + nfa_start = create_nfa_state(nfa_counter, nfa_states) + + @token_patterns.each do |token_pattern| + # Build NFA fragment for this pattern + begin + start_state, end_state = compile_regex(token_pattern.regex_pattern, nfa_counter, nfa_states) + rescue PatternError => e + raise PatternError, + "%token-pattern #{token_pattern.name} at line #{token_pattern.lineno} " \ + "has unsupported pattern /#{token_pattern.regex_pattern}/: #{e.message}" + end + + # Connect NFA start to this pattern's start with epsilon + nfa_start.add_transition(nil, start_state) + + # Mark end state as accepting + end_state.accepting_token = token_pattern + end + + nfa_states + end + + # @rbs (Array[Integer] counter, Array[NFAState] states) -> NFAState + def create_nfa_state(counter, states) + state = NFAState.new(counter[0]) + counter[0] += 1 + states << state + state + end + + ASCII_CHARS = (0..127).map(&:chr).freeze #: Array[String] + ANY_CHARS = (ASCII_CHARS - ["\n"]).freeze #: Array[String] + DIGIT_CHARS = ("0".."9").to_a.freeze #: Array[String] + WORD_CHARS = (("a".."z").to_a + ("A".."Z").to_a + DIGIT_CHARS + ["_"]).freeze #: Array[String] + WHITESPACE_CHARS = [" ", "\t", "\n", "\r", "\f", "\v"].freeze #: Array[String] + QUANTIFIERS = ["*", "+", "?"].freeze #: Array[String] + ESCAPED_LITERAL_CHARS = ["/", "\\", "*", "+", "?", "(", ")", "[", "]", "{", "}", ".", "|", "^", "$", "-"].freeze #: Array[String] + + # Compile a regex pattern to NFA fragment. The supported dialect is a small + # ASCII regular-expression subset for PSLR pseudo scanning. + # @rbs (String pattern, Array[Integer] counter, Array[NFAState] states) -> [NFAState, NFAState] + def compile_regex(pattern, counter, states) + raise PatternError, "empty patterns are not allowed" if pattern.empty? + + fragment, pos = compile_expression(pattern, 0, counter, states) + raise PatternError, "unexpected trailing input at offset #{pos}" if pos < pattern.length + raise PatternError, "nullable patterns are not allowed" if fragment.nullable + + [fragment.start_state, fragment.end_state] + end + + # @rbs (String pattern, Integer pos, Array[Integer] counter, Array[NFAState] states, ?String? stop_char) -> [Fragment, Integer] + def compile_expression(pattern, pos, counter, states, stop_char = nil) + fragment, pos = compile_sequence(pattern, pos, counter, states, stop_char) + raise PatternError, empty_sequence_message(stop_char) unless fragment + + alternatives = [fragment] + + while pos < pattern.length && pattern[pos] == "|" + pos += 1 + fragment, pos = compile_sequence(pattern, pos, counter, states, stop_char) + raise PatternError, "empty alternatives are not allowed" unless fragment + + alternatives << fragment + end + + if stop_char + raise PatternError, "unclosed group" unless pos < pattern.length && pattern[pos] == stop_char + + pos += 1 + elsif pos < pattern.length && pattern[pos] == ")" + raise PatternError, "unmatched close group at offset #{pos}" + end + + [alternate_fragments(alternatives, counter, states), pos] + end + + # @rbs (String pattern, Integer pos, Array[Integer] counter, Array[NFAState] states, String? stop_char) -> [Fragment?, Integer] + def compile_sequence(pattern, pos, counter, states, stop_char) + fragments = [] + i = pos + + while i < pattern.length + char = pattern[i] + break if char == "|" || (stop_char && char == stop_char) + + case char + when '\\' + frag, i = compile_escape(pattern, i, counter, states) + fragments << frag + next + when '[' + class_end = find_character_class_end(pattern, i) + raise PatternError, "unclosed character class at offset #{i}" unless class_end + + char_class = pattern[i + 1...class_end] + frag = compile_char_class(char_class, counter, states) + fragments << frag + i = class_end + when '*', '+', '?' + # Quantifier - modify the last fragment + if fragments.empty? + raise PatternError, "quantifier #{char} without preceding element at offset #{i}" + end + fragments << apply_quantifier(fragments.pop, char, counter, states) + when '|' + break + when '(' + frag, i = compile_expression(pattern, i + 1, counter, states, ")") + fragments << frag + next + when ')' + raise PatternError, "unmatched close group at offset #{i}" + when '.' + frag = compile_any_char(counter, states) + fragments << frag + when ']' + raise PatternError, "unmatched character class close at offset #{i}" + else + frag = compile_literal(char, counter, states) + fragments << frag + end + + i += 1 + end + + return [nil, i] if fragments.empty? + + [concatenate_fragments(fragments, counter, states), i] + end + + # @rbs (String? stop_char) -> String + def empty_sequence_message(stop_char) + stop_char ? "empty groups are not allowed" : "empty patterns are not allowed" + end + + # @rbs (String pattern, Integer offset, Array[Integer] counter, Array[NFAState] states) -> [Fragment, Integer] + def compile_escape(pattern, offset, counter, states) + raise PatternError, "dangling escape at offset #{offset}" if offset + 1 >= pattern.length + + escaped = pattern[offset + 1] + fragment = + case escaped + when "d" + compile_chars(DIGIT_CHARS, counter, states) + when "w" + compile_chars(WORD_CHARS, counter, states) + when "s" + compile_chars(WHITESPACE_CHARS, counter, states) + when "n" + compile_literal("\n", counter, states) + when "t" + compile_literal("\t", counter, states) + when "r" + compile_literal("\r", counter, states) + when "f" + compile_literal("\f", counter, states) + when "v" + compile_literal("\v", counter, states) + else + raise PatternError, "unsupported escape \\#{escaped} at offset #{offset}" if escaped.match?(/[[:alnum:]]/) + + unless ESCAPED_LITERAL_CHARS.include?(escaped) + raise PatternError, "unsupported escape \\#{escaped} at offset #{offset}" + end + compile_literal(escaped, counter, states) + end + + [fragment, offset + 2] + end + + # Compile a single literal character + # @rbs (String char, Array[Integer] counter, Array[NFAState] states) -> Fragment + def compile_literal(char, counter, states) + compile_chars([char], counter, states) + end + + # @rbs (Array[String] chars, Array[Integer] counter, Array[NFAState] states) -> Fragment + def compile_chars(chars, counter, states) + raise PatternError, "empty character classes are not allowed" if chars.empty? + + start_state = create_nfa_state(counter, states) + end_state = create_nfa_state(counter, states) + chars.uniq.each do |char| + start_state.add_transition(char, end_state) + end + Fragment.new(start_state, end_state, false) + end + + # Compile a character class [...] + # @rbs (String char_class, Array[Integer] counter, Array[NFAState] states) -> Fragment + def compile_char_class(char_class, counter, states) + compile_chars(expand_char_class(char_class), counter, states) + end + + # Expand character class string to array of characters + # @rbs (String char_class) -> Array[String] + def expand_char_class(char_class) + raise PatternError, "empty character classes are not allowed" if char_class.empty? + + chars = [] + i = 0 + negated = false + + if char_class[0] == '^' + negated = true + i = 1 + raise PatternError, "negated character classes must include at least one character" if i >= char_class.length + end + + while i < char_class.length + element_chars, i = read_char_class_element(char_class, i) + + if i < char_class.length && char_class[i] == "-" && i + 1 < char_class.length + i += 1 + range_end_chars, i = read_char_class_element(char_class, i) + chars.concat(expand_char_range(element_chars, range_end_chars)) + else + chars.concat(element_chars) + end + end + + if negated + chars = ASCII_CHARS - chars + end + + chars.uniq + end + + # @rbs (String pattern, Integer offset) -> Integer? + def find_character_class_end(pattern, offset) + i = offset + 1 + while i < pattern.length + if pattern[i] == "\\" + raise PatternError, "dangling escape in character class at offset #{i}" if i + 1 >= pattern.length + + i += 2 + next + end + + return i if pattern[i] == "]" + + i += 1 + end + + nil + end + + # @rbs (String char_class, Integer offset) -> [Array[String], Integer] + def read_char_class_element(char_class, offset) + raise PatternError, "dangling range operator in character class" if offset >= char_class.length + + char = char_class[offset] + if char == "\\" + raise PatternError, "dangling escape in character class" if offset + 1 >= char_class.length + + escaped = char_class[offset + 1] + return [escaped_char_class_chars(escaped, offset), offset + 2] + end + + [[char], offset + 1] + end + + # @rbs (String char, Integer offset) -> Array[String] + def escaped_char_class_chars(char, offset) + case char + when "d" + DIGIT_CHARS + when "w" + WORD_CHARS + when "s" + WHITESPACE_CHARS + when "t" + ["\t"] + when "n" + ["\n"] + when "r" + ["\r"] + when "f" + ["\f"] + when "v" + ["\v"] + else + raise PatternError, "unsupported escape \\#{char} in character class at offset #{offset}" if char.match?(/[[:alnum:]]/) + + [char] + end + end + + # @rbs (Array[String] start_chars, Array[String] end_chars) -> Array[String] + def expand_char_range(start_chars, end_chars) + if start_chars.size != 1 || end_chars.size != 1 + raise PatternError, "character class ranges must use single-character endpoints" + end + + start_char = start_chars.first + end_char = end_chars.first + if start_char.ord > end_char.ord + raise PatternError, "invalid character class range #{start_char}-#{end_char}" + end + + (start_char.ord..end_char.ord).map(&:chr) + end + + # Compile . (any character) + # @rbs (Array[Integer] counter, Array[NFAState] states) -> Fragment + def compile_any_char(counter, states) + compile_chars(ANY_CHARS, counter, states) + end + + # Apply a quantifier to a fragment + # @rbs (Fragment fragment, String quantifier, Array[Integer] counter, Array[NFAState] states) -> Fragment + def apply_quantifier(fragment, quantifier, counter, states) + frag_start = fragment.start_state + frag_end = fragment.end_state + + case quantifier + when '*' + # Zero or more + new_start = create_nfa_state(counter, states) + new_end = create_nfa_state(counter, states) + + new_start.add_transition(nil, frag_start) + new_start.add_transition(nil, new_end) + frag_end.add_transition(nil, frag_start) + frag_end.add_transition(nil, new_end) + + Fragment.new(new_start, new_end, true) + when '+' + # One or more + new_end = create_nfa_state(counter, states) + + frag_end.add_transition(nil, frag_start) + frag_end.add_transition(nil, new_end) + + Fragment.new(frag_start, new_end, fragment.nullable) + when '?' + # Zero or one + new_start = create_nfa_state(counter, states) + new_end = create_nfa_state(counter, states) + + new_start.add_transition(nil, frag_start) + new_start.add_transition(nil, new_end) + frag_end.add_transition(nil, new_end) + + Fragment.new(new_start, new_end, true) + else + fragment + end + end + + # @rbs (Array[Fragment] fragments, Array[Integer] counter, Array[NFAState] states) -> Fragment + def alternate_fragments(fragments, counter, states) + return fragments.first if fragments.size == 1 + + alt_start = create_nfa_state(counter, states) + alt_end = create_nfa_state(counter, states) + + fragments.each do |fragment| + alt_start.add_transition(nil, fragment.start_state) + fragment.end_state.add_transition(nil, alt_end) + end + + Fragment.new(alt_start, alt_end, fragments.any?(&:nullable)) + end + + # Concatenate multiple NFA fragments into one + # @rbs (Array[Fragment] fragments, Array[Integer] counter, Array[NFAState] states) -> Fragment + def concatenate_fragments(fragments, counter, states) + raise PatternError, "empty sequences are not allowed" if fragments.empty? + return fragments.first if fragments.size == 1 + + result_start = fragments.first.start_state + current_end = fragments.first.end_state + nullable = fragments.all?(&:nullable) + + fragments[1..-1].each do |fragment| + current_end.add_transition(nil, fragment.start_state) + current_end = fragment.end_state + end + + Fragment.new(result_start, current_end, nullable) + end + + # Convert NFA to DFA using subset construction + # @rbs (Array[NFAState] nfa_states) -> void + def convert_nfa_to_dfa(nfa_states) + return if nfa_states.empty? + + # Clear existing DFA states + @states = [] + @state_counter = 0 + + # Compute epsilon closure of start state + nfa_start = nfa_states[0] + start_closure = epsilon_closure([nfa_start]) + + # Map NFA state sets to DFA states + dfa_states = {} + work_list = [start_closure] + dfa_states[start_closure.map(&:id).sort] = create_state + + @initial_state = @states[0] + + # Mark accepting tokens for initial state + start_closure.each do |nfa_state| + if nfa_state.accepting? + @initial_state.add_accepting_token(nfa_state.accepting_token) + end + end + + while !work_list.empty? + current_nfa_set = work_list.shift + current_dfa = dfa_states[current_nfa_set.map(&:id).sort] + + # Find all possible transitions + transitions = {} + current_nfa_set.each do |nfa_state| + nfa_state.transitions.each do |char, targets| + next if char.nil? # Skip epsilon transitions + transitions[char] ||= [] + transitions[char].concat(targets) + end + end + + transitions.each do |char, targets| + target_closure = epsilon_closure(targets.uniq) + target_key = target_closure.map(&:id).sort + + unless dfa_states.key?(target_key) + new_dfa_state = create_state + dfa_states[target_key] = new_dfa_state + + # Mark accepting tokens + target_closure.each do |nfa_state| + if nfa_state.accepting? + new_dfa_state.add_accepting_token(nfa_state.accepting_token) + end + end + + work_list << target_closure + end + + current_dfa.add_transition(char, dfa_states[target_key].id) + end + end + end + + # Compute epsilon closure of a set of NFA states + # @rbs (Array[NFAState] nfa_states) -> Array[NFAState] + def epsilon_closure(nfa_states) + closure = nfa_states.dup + seen = Set.new(nfa_states.map(&:id)) + work_list = nfa_states.dup + + while !work_list.empty? + state = work_list.shift + epsilon_targets = state.transitions[nil] || [] + + epsilon_targets.each do |target| + unless seen.include?(target.id) + seen << target.id + closure << target + work_list << target + end + end + end + + closure + end + end +end diff --git a/sig/generated/lrama/scanner_fsa.rbs b/sig/generated/lrama/scanner_fsa.rbs new file mode 100644 index 000000000..7397a65d3 --- /dev/null +++ b/sig/generated/lrama/scanner_fsa.rbs @@ -0,0 +1,197 @@ +# Generated from lib/lrama/scanner_fsa.rb with RBS::Inline + +module Lrama + # Scanner Finite State Automaton for PSLR(1) + # Built from token patterns defined by %token-pattern directives + # Based on Definitions 3.2.12, 3.2.13 from the PSLR dissertation + class ScannerFSA + # Represents a state in the scanner FSA + class State + attr_reader id: Integer + + attr_reader transitions: Hash[String, Integer] + + attr_reader accepting_tokens: Array[Grammar::TokenPattern] + + # @rbs (Integer id) -> void + def initialize: (Integer id) -> void + + # @rbs () -> bool + def accepting?: () -> bool + + # @rbs (String char, Integer target_state_id) -> void + def add_transition: (String char, Integer target_state_id) -> void + + # @rbs (Grammar::TokenPattern token_pattern) -> void + def add_accepting_token: (Grammar::TokenPattern token_pattern) -> void + end + + attr_reader states: Array[State] + + attr_reader initial_state: State + + attr_reader token_patterns: Array[Grammar::TokenPattern] + + # @rbs (Array[Grammar::TokenPattern] token_patterns) -> void + def initialize: (Array[Grammar::TokenPattern] token_patterns) -> void + + # Returns the accepting state for a given FSA state + # Definition 3.2.13 (state_to_accepting_state) + # @rbs (Integer state_id) -> State? + def state_to_accepting_state: (Integer state_id) -> State? + + # Returns the set of tokens accepted at FSA state ss + # Definition 3.2.12 acc(ss) + # @rbs (Integer state_id) -> Array[Grammar::TokenPattern] + def acc_ss: (Integer state_id) -> Array[Grammar::TokenPattern] + + # Simulate the FSA on input string starting from initial state + # Returns all accepting states reached during the scan + # @rbs (String input) -> Array[{state: State, position: Integer, token: Grammar::TokenPattern}] + def scan: (String input) -> Array[{ state: State, position: Integer, token: Grammar::TokenPattern }] + + # Returns token pairs that can be in an identity or length scanner conflict. + # Pair keys are sorted token names. + # @rbs () -> Set[[String, String]] + def pairwise_conflict_pairs: () -> Set[[ String, String ]] + + # @rbs (String left, String right) -> bool + def pairwise_conflict?: (String left, String right) -> bool + + private + + # @rbs (String left, String right) -> [String, String] + def pair_key: (String left, String right) -> [ String, String ] + + # Build the FSA from token patterns + # Uses Thompson's construction for NFAs followed by subset construction for DFA + # @rbs () -> void + def build_fsa: () -> void + + # @rbs () -> State + def create_state: () -> State + + # Simple NFA state for regex compilation + class PatternError < StandardError + end + + class NFAState + attr_reader id: Integer + + attr_accessor transitions: Hash[String?, Array[NFAState]] + + attr_accessor accepting_token: Grammar::TokenPattern? + + # @rbs (Integer id) -> void + def initialize: (Integer id) -> void + + # @rbs (String? char, NFAState target) -> void + def add_transition: (String? char, NFAState target) -> void + + # @rbs () -> bool + def accepting?: () -> bool + end + + class Fragment + attr_reader start_state: NFAState + + attr_reader end_state: NFAState + + attr_reader nullable: bool + + # @rbs (NFAState start_state, NFAState end_state, bool nullable) -> void + def initialize: (NFAState start_state, NFAState end_state, bool nullable) -> void + + # @rbs () -> [NFAState, NFAState] + def to_ary: () -> [ NFAState, NFAState ] + end + + # Build NFA from all token patterns + # @rbs () -> Array[NFAState] + def build_nfa: () -> Array[NFAState] + + # @rbs (Array[Integer] counter, Array[NFAState] states) -> NFAState + def create_nfa_state: (Array[Integer] counter, Array[NFAState] states) -> NFAState + + ASCII_CHARS: Array[String] + + ANY_CHARS: Array[String] + + DIGIT_CHARS: Array[String] + + WORD_CHARS: Array[String] + + WHITESPACE_CHARS: Array[String] + + QUANTIFIERS: Array[String] + + ESCAPED_LITERAL_CHARS: Array[String] + + # Compile a regex pattern to NFA fragment. The supported dialect is a small + # ASCII regular-expression subset for PSLR pseudo scanning. + # @rbs (String pattern, Array[Integer] counter, Array[NFAState] states) -> [NFAState, NFAState] + def compile_regex: (String pattern, Array[Integer] counter, Array[NFAState] states) -> [ NFAState, NFAState ] + + # @rbs (String pattern, Integer pos, Array[Integer] counter, Array[NFAState] states, ?String? stop_char) -> [Fragment, Integer] + def compile_expression: (String pattern, Integer pos, Array[Integer] counter, Array[NFAState] states, ?String? stop_char) -> [ Fragment, Integer ] + + # @rbs (String pattern, Integer pos, Array[Integer] counter, Array[NFAState] states, String? stop_char) -> [Fragment?, Integer] + def compile_sequence: (String pattern, Integer pos, Array[Integer] counter, Array[NFAState] states, String? stop_char) -> [ Fragment?, Integer ] + + # @rbs (String? stop_char) -> String + def empty_sequence_message: (String? stop_char) -> String + + # @rbs (String pattern, Integer offset, Array[Integer] counter, Array[NFAState] states) -> [Fragment, Integer] + def compile_escape: (String pattern, Integer offset, Array[Integer] counter, Array[NFAState] states) -> [ Fragment, Integer ] + + # Compile a single literal character + # @rbs (String char, Array[Integer] counter, Array[NFAState] states) -> Fragment + def compile_literal: (String char, Array[Integer] counter, Array[NFAState] states) -> Fragment + + # @rbs (Array[String] chars, Array[Integer] counter, Array[NFAState] states) -> Fragment + def compile_chars: (Array[String] chars, Array[Integer] counter, Array[NFAState] states) -> Fragment + + # Compile a character class [...] + # @rbs (String char_class, Array[Integer] counter, Array[NFAState] states) -> Fragment + def compile_char_class: (String char_class, Array[Integer] counter, Array[NFAState] states) -> Fragment + + # Expand character class string to array of characters + # @rbs (String char_class) -> Array[String] + def expand_char_class: (String char_class) -> Array[String] + + # @rbs (String pattern, Integer offset) -> Integer? + def find_character_class_end: (String pattern, Integer offset) -> Integer? + + # @rbs (String char_class, Integer offset) -> [Array[String], Integer] + def read_char_class_element: (String char_class, Integer offset) -> [ Array[String], Integer ] + + # @rbs (String char, Integer offset) -> Array[String] + def escaped_char_class_chars: (String char, Integer offset) -> Array[String] + + # @rbs (Array[String] start_chars, Array[String] end_chars) -> Array[String] + def expand_char_range: (Array[String] start_chars, Array[String] end_chars) -> Array[String] + + # Compile . (any character) + # @rbs (Array[Integer] counter, Array[NFAState] states) -> Fragment + def compile_any_char: (Array[Integer] counter, Array[NFAState] states) -> Fragment + + # Apply a quantifier to a fragment + # @rbs (Fragment fragment, String quantifier, Array[Integer] counter, Array[NFAState] states) -> Fragment + def apply_quantifier: (Fragment fragment, String quantifier, Array[Integer] counter, Array[NFAState] states) -> Fragment + + # @rbs (Array[Fragment] fragments, Array[Integer] counter, Array[NFAState] states) -> Fragment + def alternate_fragments: (Array[Fragment] fragments, Array[Integer] counter, Array[NFAState] states) -> Fragment + + # Concatenate multiple NFA fragments into one + # @rbs (Array[Fragment] fragments, Array[Integer] counter, Array[NFAState] states) -> Fragment + def concatenate_fragments: (Array[Fragment] fragments, Array[Integer] counter, Array[NFAState] states) -> Fragment + + # Convert NFA to DFA using subset construction + # @rbs (Array[NFAState] nfa_states) -> void + def convert_nfa_to_dfa: (Array[NFAState] nfa_states) -> void + + # Compute epsilon closure of a set of NFA states + # @rbs (Array[NFAState] nfa_states) -> Array[NFAState] + def epsilon_closure: (Array[NFAState] nfa_states) -> Array[NFAState] + end +end diff --git a/spec/lrama/grammar_spec.rb b/spec/lrama/grammar_spec.rb index 35cd90ee0..7a86972bd 100644 --- a/spec/lrama/grammar_spec.rb +++ b/spec/lrama/grammar_spec.rb @@ -241,5 +241,247 @@ end end end + + context 'when PSLR state member is not a valid C identifier' do + before do + grammar.define = { + 'lr.type' => 'pslr', + 'api.pslr.state-member' => 'current-state' + } + end + + it 'raises an error with the invalid member name' do + expect { grammar.validate! } + .to raise_error(RuntimeError, '%define api.pslr.state-member must be a valid C identifier, got "current-state".') + end + end + + context 'when PSLR max states is not an integer' do + before do + grammar.define = { + 'lr.type' => 'pslr', + 'pslr.max-states' => 'many' + } + end + + it 'raises an error with the invalid value' do + expect { grammar.validate! } + .to raise_error(RuntimeError, '%define pslr.max-states must be an integer, got "many".') + end + end + + context 'when PSLR max state ratio is smaller than one' do + before do + grammar.define = { + 'lr.type' => 'pslr', + 'pslr.max-state-ratio' => '0.5' + } + end + + it 'raises an error with the invalid ratio' do + expect { grammar.validate! } + .to raise_error(RuntimeError, '%define pslr.max-state-ratio must be greater than or equal to 1.0, got "0.5".') + end + end + end + + describe "#finalize_lexical_ties!" do + def build_pslr_grammar(source) + grammar = Lrama::Parser.new(source, "lex_tie.y").parse + grammar.prepare + grammar.validate! + grammar + end + + it "keeps token-token ties even without a scanner conflict" do + grammar = build_pslr_grammar(<<~GRAMMAR) + %define lr.type pslr + %token-pattern A /a/ + %token-pattern B /b/ + %lex-tie A B + %% + start: A | B ; + GRAMMAR + + grammar.finalize_lexical_ties!(Lrama::ScannerFSA.new(grammar.token_patterns)) + + expect(grammar.lex_tie.tied?("A", "B")).to be true + end + + it "limits set-set ties to scanner-conflicting pairs" do + grammar = build_pslr_grammar(<<~GRAMMAR) + %define lr.type pslr + %token-pattern RANGLE />/ + %token-pattern RSHIFT />>/ + %token-pattern DOT /\\./ + %token-pattern COMMA /,/ + %symbol-set punct RANGLE RSHIFT DOT COMMA + %lex-tie punct punct + %% + start: RANGLE | RSHIFT | DOT | COMMA ; + GRAMMAR + + grammar.finalize_lexical_ties!(Lrama::ScannerFSA.new(grammar.token_patterns)) + + expect(grammar.lex_tie.tied?("RANGLE", "RSHIFT")).to be true + expect(grammar.lex_tie.tied?("DOT", "COMMA")).to be false + end + + it "limits set-token ties to scanner-conflicting pairs" do + grammar = build_pslr_grammar(<<~GRAMMAR) + %define lr.type pslr + %token-pattern ID /[a-z]+/ + %token-pattern KW_IF /if/ + %token-pattern KW_WHILE /while/ + %token-pattern PLUS /\\+/ + %symbol-set keywords KW_IF KW_WHILE + %lex-tie ID keywords + %lex-tie PLUS keywords + %% + start: ID | KW_IF | KW_WHILE | PLUS ; + GRAMMAR + + grammar.finalize_lexical_ties!(Lrama::ScannerFSA.new(grammar.token_patterns)) + + expect(grammar.lex_tie.tied?("ID", "KW_IF")).to be true + expect(grammar.lex_tie.tied?("ID", "KW_WHILE")).to be true + expect(grammar.lex_tie.tied?("PLUS", "KW_IF")).to be false + expect(grammar.lex_tie.tied?("PLUS", "KW_WHILE")).to be false + end + + it "limits yyall ties to scanner-conflicting pairs" do + grammar = build_pslr_grammar(<<~GRAMMAR) + %define lr.type pslr + %token-pattern PLUS /\\+/ + %token-pattern PLUSPLUS /\\+\\+/ + %token-pattern DOT /\\./ + %token-pattern SLASH /\\// + %lex-tie yyall yyall + %% + start: PLUS | PLUSPLUS | DOT | SLASH ; + GRAMMAR + + grammar.finalize_lexical_ties!(Lrama::ScannerFSA.new(grammar.token_patterns)) + + expect(grammar.lex_tie.tied?("PLUS", "PLUSPLUS")).to be true + expect(grammar.lex_tie.tied?("DOT", "SLASH")).to be false + expect(grammar.lex_tie.tied?("PLUS", "DOT")).to be false + expect(grammar.lex_tie.tied?("SLASH", "PLUSPLUS")).to be false + end + + it "lets a specific tie override generic yyall no-tie" do + grammar = build_pslr_grammar(<<~GRAMMAR) + %define lr.type pslr + %token-pattern IF /if/ + %token-pattern ID /[a-z]+/ + %symbol-set keywords IF + %lex-no-tie yyall yyall + %lex-tie ID keywords + %% + start: IF | ID ; + GRAMMAR + + grammar.finalize_lexical_ties!(Lrama::ScannerFSA.new(grammar.token_patterns)) + + expect(grammar.lex_tie.tied?("ID", "IF")).to be true + expect(grammar.lex_tie.no_tie?("ID", "IF")).to be false + end + + it "rejects a direct no-tie that conflicts with transitive ties" do + grammar = build_pslr_grammar(<<~GRAMMAR) + %define lr.type pslr + %token-pattern A /a/ + %token-pattern B /a/ + %token-pattern C /a/ + %lex-tie A B + %lex-tie B C + %lex-no-tie A C + %% + start: A | B | C ; + GRAMMAR + + expect do + grammar.finalize_lexical_ties!(Lrama::ScannerFSA.new(grammar.token_patterns)) + end.to raise_error(RuntimeError, /%lex-no-tie A C conflicts/) + end + end + + describe "#synthesize_implicit_literal_token_patterns!" do + it "adds exact-match token patterns for character literal terminals" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "implicit_literal.y").parse + %define lr.type pslr + %token-pattern ID /[a-z]+/ + %% + start: ID ';' ; + GRAMMAR + grammar.prepare + grammar.validate! + + grammar.synthesize_implicit_literal_token_patterns! + + literal_pattern = grammar.token_patterns.find {|pattern| pattern.name == "';'" } + expect(literal_pattern).not_to be_nil + expect(Lrama::ScannerFSA.new(grammar.token_patterns).scan(";").map {|result| result[:token].name }).to include("';'") + end + + it "escapes regex metacharacters in character literal patterns" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "implicit_escape.y").parse + %define lr.type pslr + %token-pattern ID /[a-z]+/ + %% + start + : ID '/' + | ID '[' + | ID ']' + | ID '+' + ; + GRAMMAR + grammar.prepare + grammar.validate! + + grammar.synthesize_implicit_literal_token_patterns! + + slash = grammar.token_patterns.find {|p| p.name == "'/'" } + lbracket = grammar.token_patterns.find {|p| p.name == "'['" } + rbracket = grammar.token_patterns.find {|p| p.name == "']'" } + plus = grammar.token_patterns.find {|p| p.name == "'+'" } + + expect(slash).not_to be_nil + expect(slash.regex_pattern).to eq("\\/") + expect(lbracket).not_to be_nil + expect(lbracket.regex_pattern).to eq("\\[") + expect(rbracket).not_to be_nil + expect(rbracket.regex_pattern).to eq("\\]") + expect(plus).not_to be_nil + expect(plus.regex_pattern).to eq("\\+") + end + + it "handles backslash and control character literals" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "implicit_ctrl.y").parse + %define lr.type pslr + %token-pattern ID /[a-z]+/ + %% + start + : ID '\\\\' + | ID '\\n' + | ID '\\t' + ; + GRAMMAR + grammar.prepare + grammar.validate! + + grammar.synthesize_implicit_literal_token_patterns! + + backslash = grammar.token_patterns.find {|p| p.name == "'\\\\'" } + newline = grammar.token_patterns.find {|p| p.name == "'\\n'" } + tab = grammar.token_patterns.find {|p| p.name == "'\\t'" } + + expect(backslash).not_to be_nil + expect(backslash.regex_pattern).to eq("\\\\") + expect(newline).not_to be_nil + expect(newline.regex_pattern).to eq("\\n") + expect(tab).not_to be_nil + expect(tab.regex_pattern).to eq("\\t") + end end end diff --git a/spec/lrama/scanner_fsa_spec.rb b/spec/lrama/scanner_fsa_spec.rb new file mode 100644 index 000000000..9912945ee --- /dev/null +++ b/spec/lrama/scanner_fsa_spec.rb @@ -0,0 +1,322 @@ +# frozen_string_literal: true + +RSpec.describe Lrama::ScannerFSA do + def token_pattern(name, regex, lineno: 1, order: 0) + Lrama::Grammar::TokenPattern.new( + id: Lrama::Lexer::Token::Ident.new(s_value: name), + pattern: Lrama::Lexer::Token::Regex.new(s_value: "/#{regex}/"), + lineno: lineno, + definition_order: order + ) + end + + describe "initialization" do + it "creates an empty FSA for no patterns" do + fsa = Lrama::ScannerFSA.new([]) + expect(fsa.states).to be_empty + end + + it "creates FSA for single literal pattern" do + id = Lrama::Lexer::Token::Ident.new(s_value: "PLUS") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/\\+/") + token_pattern = Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + fsa = Lrama::ScannerFSA.new([token_pattern]) + + expect(fsa.states).not_to be_empty + expect(fsa.initial_state).not_to be_nil + end + end + + describe "#scan" do + it "matches a single character pattern" do + id = Lrama::Lexer::Token::Ident.new(s_value: "RANGLE") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/>/") + token_pattern = Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + fsa = Lrama::ScannerFSA.new([token_pattern]) + + results = fsa.scan(">") + expect(results.size).to eq(1) + expect(results[0][:token].name).to eq("RANGLE") + expect(results[0][:position]).to eq(1) + end + + it "matches a multi-character pattern" do + id = Lrama::Lexer::Token::Ident.new(s_value: "RSHIFT") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/>>/") + token_pattern = Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + fsa = Lrama::ScannerFSA.new([token_pattern]) + + results = fsa.scan(">>") + expect(results.size).to eq(1) + expect(results[0][:token].name).to eq("RSHIFT") + expect(results[0][:position]).to eq(2) + end + + it "returns multiple matches for overlapping patterns" do + rangle_id = Lrama::Lexer::Token::Ident.new(s_value: "RANGLE") + rangle_regex = Lrama::Lexer::Token::Regex.new(s_value: "/>/") + rangle = Lrama::Grammar::TokenPattern.new( + id: rangle_id, + pattern: rangle_regex, + lineno: 1, + definition_order: 0 + ) + + rshift_id = Lrama::Lexer::Token::Ident.new(s_value: "RSHIFT") + rshift_regex = Lrama::Lexer::Token::Regex.new(s_value: "/>>/") + rshift = Lrama::Grammar::TokenPattern.new( + id: rshift_id, + pattern: rshift_regex, + lineno: 1, + definition_order: 1 + ) + + fsa = Lrama::ScannerFSA.new([rangle, rshift]) + + results = fsa.scan(">>") + + # Should match both RANGLE at position 1 and RSHIFT at position 2 + expect(results.size).to eq(2) + positions = results.map { |r| [r[:token].name, r[:position]] } + expect(positions).to include(["RANGLE", 1]) + expect(positions).to include(["RSHIFT", 2]) + end + + it "matches character class patterns" do + id = Lrama::Lexer::Token::Ident.new(s_value: "ID") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/[a-zA-Z_][a-zA-Z0-9_]*/") + id_pattern = Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + fsa = Lrama::ScannerFSA.new([id_pattern]) + + results = fsa.scan("hello_world123") + expect(results).not_to be_empty + # Should have matches at each position as the identifier grows + end + + it "matches digit patterns" do + id = Lrama::Lexer::Token::Ident.new(s_value: "INT") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/[0-9]+/") + int_pattern = Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + fsa = Lrama::ScannerFSA.new([int_pattern]) + + results = fsa.scan("12345") + expect(results).not_to be_empty + end + + it "matches escaped whitespace inside character classes" do + id = Lrama::Lexer::Token::Ident.new(s_value: "YYLAYOUT") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/[ \\t\\r\\n]+/") + token_pattern = Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + fsa = Lrama::ScannerFSA.new([token_pattern]) + + expect(fsa.scan("\t").map { |result| result[:token].name }).to include("YYLAYOUT") + expect(fsa.scan("\n").map { |result| result[:token].name }).to include("YYLAYOUT") + end + + it "matches escaped literals in and outside character classes" do + slash = token_pattern("SLASH", "\\/", order: 0) + rbrack = token_pattern("RBRACK", "[\\]]", order: 1) + backslash = token_pattern("BACKSLASH", "[\\\\]", order: 2) + + expect(Lrama::ScannerFSA.new([slash]).scan("/").map { |result| result[:token].name }).to include("SLASH") + expect(Lrama::ScannerFSA.new([rbrack]).scan("]").map { |result| result[:token].name }).to include("RBRACK") + expect(Lrama::ScannerFSA.new([backslash]).scan("\\").map { |result| result[:token].name }).to include("BACKSLASH") + end + + it "matches ranges and negated character classes over ASCII" do + not_star = token_pattern("NOT_STAR", "[^*]+") + fsa = Lrama::ScannerFSA.new([not_star]) + + expect(fsa.scan("abc/]").map { |result| result[:token].name }).to include("NOT_STAR") + expect(fsa.scan("a\nb").map { |result| result[:token].name }).to include("NOT_STAR") + expect(fsa.scan("*")).to be_empty + end + end + + describe "pattern validation" do + it "rejects empty token patterns" do + expect { Lrama::ScannerFSA.new([token_pattern("EMPTY", "", lineno: 42)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /EMPTY at line 42.*empty patterns/m) + end + + it "rejects dangling escapes" do + expect { Lrama::ScannerFSA.new([token_pattern("BAD_ESCAPE", "abc\\", lineno: 7)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /BAD_ESCAPE at line 7.*dangling escape/m) + end + + it "rejects unclosed character classes" do + expect { Lrama::ScannerFSA.new([token_pattern("BAD_CLASS", "[abc", lineno: 6)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /BAD_CLASS at line 6.*unclosed character class/m) + end + + it "rejects unsupported alphabetic escapes" do + expect { Lrama::ScannerFSA.new([token_pattern("BAD_ESCAPE", "\\q", lineno: 8)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /BAD_ESCAPE at line 8.*unsupported escape \\q/m) + end + + it "rejects malformed character class ranges" do + expect { Lrama::ScannerFSA.new([token_pattern("BAD_RANGE", "[z-a]", lineno: 9)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /BAD_RANGE at line 9.*invalid character class range z-a/m) + end + + it "rejects nullable token patterns" do + expect { Lrama::ScannerFSA.new([token_pattern("NULLABLE", "a*", lineno: 10)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /NULLABLE at line 10.*nullable patterns/m) + expect { Lrama::ScannerFSA.new([token_pattern("NULLABLE", "a?", lineno: 10)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /NULLABLE at line 10.*nullable patterns/m) + expect { Lrama::ScannerFSA.new([token_pattern("NULLABLE", "()", lineno: 10)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /NULLABLE at line 10.*empty groups/m) + end + + it "rejects empty alternatives" do + expect { Lrama::ScannerFSA.new([token_pattern("EMPTY_ALT", "a|", lineno: 11)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /EMPTY_ALT at line 11.*empty alternatives/m) + end + end + + describe "#pairwise_conflict_pairs" do + it "detects identity and length conflicts" do + rangle = Lrama::Grammar::TokenPattern.new( + id: Lrama::Lexer::Token::Ident.new(s_value: "RANGLE"), + pattern: Lrama::Lexer::Token::Regex.new(s_value: "/>/"), + lineno: 1, + definition_order: 0 + ) + rshift = Lrama::Grammar::TokenPattern.new( + id: Lrama::Lexer::Token::Ident.new(s_value: "RSHIFT"), + pattern: Lrama::Lexer::Token::Regex.new(s_value: "/>>/"), + lineno: 1, + definition_order: 1 + ) + keyword = Lrama::Grammar::TokenPattern.new( + id: Lrama::Lexer::Token::Ident.new(s_value: "IF"), + pattern: Lrama::Lexer::Token::Regex.new(s_value: "/if/"), + lineno: 1, + definition_order: 2 + ) + identifier = Lrama::Grammar::TokenPattern.new( + id: Lrama::Lexer::Token::Ident.new(s_value: "ID"), + pattern: Lrama::Lexer::Token::Regex.new(s_value: "/[a-z]+/"), + lineno: 1, + definition_order: 3 + ) + + pairs = Lrama::ScannerFSA.new([rangle, rshift, keyword, identifier]).pairwise_conflict_pairs + + expect(pairs).to include(["RANGLE", "RSHIFT"]) + expect(pairs).to include(["ID", "IF"]) + end + + it "checks pairwise conflicts for sorted token pairs" do + rangle = token_pattern("RANGLE", ">", order: 0) + rshift = token_pattern("RSHIFT", ">>", order: 1) + dot = token_pattern("DOT", "\\.", order: 2) + comma = token_pattern("COMMA", ",", order: 3) + fsa = Lrama::ScannerFSA.new([rangle, rshift, dot, comma]) + + expect(fsa.pairwise_conflict?("RSHIFT", "RANGLE")).to be true + expect(fsa.pairwise_conflict?("DOT", "COMMA")).to be false + end + end + + describe "#acc_ss" do + it "returns empty array for non-accepting state" do + id = Lrama::Lexer::Token::Ident.new(s_value: "AB") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/ab/") + token_pattern = Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + fsa = Lrama::ScannerFSA.new([token_pattern]) + + # Initial state shouldn't be accepting for non-empty pattern + tokens = fsa.acc_ss(0) + expect(tokens).to be_empty + end + + it "returns accepting tokens for accepting state" do + id = Lrama::Lexer::Token::Ident.new(s_value: "A") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/a/") + token_pattern = Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + fsa = Lrama::ScannerFSA.new([token_pattern]) + + # Scan to reach accepting state + results = fsa.scan("a") + expect(results).not_to be_empty + + accepting_state = results[0][:state] + tokens = fsa.acc_ss(accepting_state.id) + expect(tokens.map(&:name)).to include("A") + end + end + + describe "#state_to_accepting_state" do + it "returns nil for non-accepting state" do + id = Lrama::Lexer::Token::Ident.new(s_value: "AB") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/ab/") + token_pattern = Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + fsa = Lrama::ScannerFSA.new([token_pattern]) + + expect(fsa.state_to_accepting_state(0)).to be_nil + end + + it "returns the state itself for accepting state" do + id = Lrama::Lexer::Token::Ident.new(s_value: "A") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/a/") + token_pattern = Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + fsa = Lrama::ScannerFSA.new([token_pattern]) + + results = fsa.scan("a") + accepting_state = results[0][:state] + + expect(fsa.state_to_accepting_state(accepting_state.id)).to eq(accepting_state) + end + end +end From 6a4649ee27f9c2b8a1908244f5ae2f05c1268d9e Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 21:12:38 +0900 Subject: [PATCH 03/24] pslr: add length precedence resolution tables LengthPrecedences captures the length component of %lex-prec rules as a pairwise resolution table (Def 3.2.15): longest-match operators (<~ -~) prefer the longer match in both directions, shortest-match operators ( void + def initialize(operator, lineno) + @operator = operator + @lineno = lineno + end + end + + attr_reader :table #: Hash[[String, String], bool] + attr_reader :resolution_table #: Hash[[String, String], Symbol] + + # @rbs (Grammar::LexPrec lex_prec) -> void + def initialize(lex_prec) + @lex_prec = lex_prec + @rule_index_table = {} #: Hash[[String, String], Integer] + @resolution_table = build_resolution_table(lex_prec) + @table = @resolution_table.transform_values {|value| value == PREFER_NEW } + end + + # @rbs (String old_token, String new_token) -> bool + def normal_precedes?(old_token, new_token) + resolution(old_token, new_token) == PREFER_NEW + end + + # @rbs (String old_token, String new_token) -> bool + def precedes?(old_token, new_token) + normal_precedes?(old_token, new_token) + end + + # @rbs (String old_token, String new_token) -> bool + def fallback_precedes?(old_token, new_token) + resolution(old_token, new_token, fallback: true) == PREFER_NEW + end + + # Backward-compatible query used by existing specs. + # @rbs (String old_token, String new_token) -> bool + def prefer_shorter?(old_token, new_token) + resolution(old_token, new_token) == PREFER_OLD + end + + # @rbs (String old_token, String new_token, ?fallback: bool, ?track: bool) -> Symbol + def resolution(old_token, new_token, fallback: false, track: false) + result = @resolution_table.fetch([old_token, new_token]) do + return PREFER_NEW if old_token == new_token + return PREFER_NEW if fallback + + return UNRESOLVED + end + + if track && (rule_idx = @rule_index_table[[old_token, new_token]]) + @lex_prec.mark_used(rule_idx) + end + + result + end + + # @rbs (String old_token, String new_token) -> Symbol + def precedence(old_token, new_token) + case resolution(old_token, new_token) + when PREFER_NEW + RIGHT + when PREFER_OLD + LEFT + else + UNDEFINED + end + end + + # @rbs (Symbol operator) -> String + def self.operator_label(operator) + case operator + when Grammar::LexPrec::IDENTITY_RIGHT_LONGEST then "<~" + when Grammar::LexPrec::IDENTITY_RIGHT then "<-" + when Grammar::LexPrec::LONGEST then "-~" + when Grammar::LexPrec::TOKEN_RIGHT then "<<" + when Grammar::LexPrec::TOKEN_RIGHT_LENGTH then "-<" + when Grammar::LexPrec::IDENTITY_RIGHT_SHORTEST then " Hash[[String, String], Symbol] + def build_resolution_table(lex_prec) + table = {} + sources = {} + + lex_prec.rules.each_with_index do |rule, idx| + left = rule.left_name + right = rule.right_name + + case rule.operator + when Grammar::LexPrec::IDENTITY_RIGHT_LONGEST, Grammar::LexPrec::LONGEST + set_resolution!(table, sources, [left, right], PREFER_NEW, rule, idx) + set_resolution!(table, sources, [right, left], PREFER_NEW, rule, idx) + when Grammar::LexPrec::IDENTITY_RIGHT_SHORTEST, Grammar::LexPrec::SHORTEST + set_resolution!(table, sources, [left, right], PREFER_OLD, rule, idx) + set_resolution!(table, sources, [right, left], PREFER_OLD, rule, idx) + when Grammar::LexPrec::TOKEN_RIGHT, Grammar::LexPrec::TOKEN_RIGHT_LENGTH + set_resolution!(table, sources, [left, right], PREFER_NEW, rule, idx) + set_resolution!(table, sources, [right, left], PREFER_OLD, rule, idx) + end + end + + table + end + + # @rbs (Hash[[String, String], Symbol] table, Hash[[String, String], RuleSource] sources, [String, String] key, Symbol value, Grammar::LexPrec::Rule rule, Integer rule_index) -> void + def set_resolution!(table, sources, key, value, rule, rule_index) + existing = table[key] + if existing.nil? + table[key] = value + sources[key] = RuleSource.new(rule.operator, rule.lineno) + @rule_index_table[key] = rule_index + return + end + + return if existing == value + + source = sources.fetch(key) + old_token, new_token = key + raise LexicalPrecedenceConflictError, + "conflicting %lex-prec length rules for #{old_token} -> #{new_token}: " \ + "#{operator_label(source.operator)} at line #{source.lineno} resolves #{resolution_label(existing)}, " \ + "but #{operator_label(rule.operator)} at line #{rule.lineno} resolves #{resolution_label(value)}" + end + + # @rbs (Symbol operator) -> String + def operator_label(operator) + case operator + when Grammar::LexPrec::IDENTITY_RIGHT_LONGEST + "<~" + when Grammar::LexPrec::IDENTITY_RIGHT + "<-" + when Grammar::LexPrec::LONGEST + "-~" + when Grammar::LexPrec::TOKEN_RIGHT + "<<" + when Grammar::LexPrec::TOKEN_RIGHT_LENGTH + "-<" + when Grammar::LexPrec::IDENTITY_RIGHT_SHORTEST + " String + def resolution_label(value) + case value + when PREFER_NEW + "prefer-new" + when PREFER_OLD + "prefer-old" + else + value.to_s + end + end + end +end diff --git a/sig/generated/lrama/length_precedences.rbs b/sig/generated/lrama/length_precedences.rbs new file mode 100644 index 000000000..ca4c737d5 --- /dev/null +++ b/sig/generated/lrama/length_precedences.rbs @@ -0,0 +1,76 @@ +# Generated from lib/lrama/length_precedences.rb with RBS::Inline + +module Lrama + # Runtime length precedence matrix for PSLR pseudo-scanning. + # + # When a longer match for new_token is reached after an earlier match for + # old_token, #precedes? answers whether the longer match should replace it. + class LengthPrecedences + LEFT: Symbol + + RIGHT: Symbol + + UNDEFINED: Symbol + + PREFER_NEW: Symbol + + PREFER_OLD: Symbol + + UNRESOLVED: Symbol + + class LexicalPrecedenceConflictError < StandardError + end + + class RuleSource + attr_reader operator: Symbol + + attr_reader lineno: Integer + + # @rbs (Symbol operator, Integer lineno) -> void + def initialize: (Symbol operator, Integer lineno) -> void + end + + attr_reader table: Hash[[ String, String ], bool] + + attr_reader resolution_table: Hash[[ String, String ], Symbol] + + # @rbs (Grammar::LexPrec lex_prec) -> void + def initialize: (Grammar::LexPrec lex_prec) -> void + + # @rbs (String old_token, String new_token) -> bool + def normal_precedes?: (String old_token, String new_token) -> bool + + # @rbs (String old_token, String new_token) -> bool + def precedes?: (String old_token, String new_token) -> bool + + # @rbs (String old_token, String new_token) -> bool + def fallback_precedes?: (String old_token, String new_token) -> bool + + # Backward-compatible query used by existing specs. + # @rbs (String old_token, String new_token) -> bool + def prefer_shorter?: (String old_token, String new_token) -> bool + + # @rbs (String old_token, String new_token, ?fallback: bool, ?track: bool) -> Symbol + def resolution: (String old_token, String new_token, ?fallback: bool, ?track: bool) -> Symbol + + # @rbs (String old_token, String new_token) -> Symbol + def precedence: (String old_token, String new_token) -> Symbol + + # @rbs (Symbol operator) -> String + def self.operator_label: (Symbol operator) -> String + + private + + # @rbs (Grammar::LexPrec lex_prec) -> Hash[[String, String], Symbol] + def build_resolution_table: (Grammar::LexPrec lex_prec) -> Hash[[ String, String ], Symbol] + + # @rbs (Hash[[String, String], Symbol] table, Hash[[String, String], RuleSource] sources, [String, String] key, Symbol value, Grammar::LexPrec::Rule rule, Integer rule_index) -> void + def set_resolution!: (Hash[[ String, String ], Symbol] table, Hash[[ String, String ], RuleSource] sources, [ String, String ] key, Symbol value, Grammar::LexPrec::Rule rule, Integer rule_index) -> void + + # @rbs (Symbol operator) -> String + def operator_label: (Symbol operator) -> String + + # @rbs (Symbol value) -> String + def resolution_label: (Symbol value) -> String + end +end diff --git a/spec/lrama/length_precedences_spec.rb b/spec/lrama/length_precedences_spec.rb new file mode 100644 index 000000000..c8eef01d0 --- /dev/null +++ b/spec/lrama/length_precedences_spec.rb @@ -0,0 +1,129 @@ +# frozen_string_literal: true + +RSpec.describe Lrama::LengthPrecedences do + let(:lex_prec) { Lrama::Grammar::LexPrec.new } + + def ident(name) + Lrama::Lexer::Token::Ident.new(s_value: name) + end + + def add_rule(left, operator, right, lineno) + lex_prec.add_rule( + left_token: ident(left), + operator: operator, + right_token: ident(right), + lineno: lineno + ) + end + + describe "#resolution" do + it "defaults same-token autolength conflicts to longest match" do + length_prec = Lrama::LengthPrecedences.new(lex_prec) + + expect(length_prec.resolution("ID", "ID")).to eq(Lrama::LengthPrecedences::PREFER_NEW) + expect(length_prec.precedes?("ID", "ID")).to be true + end + + it "leaves different-token length conflicts unresolved without a rule" do + length_prec = Lrama::LengthPrecedences.new(lex_prec) + + expect(length_prec.resolution("A", "B")).to eq(Lrama::LengthPrecedences::UNRESOLVED) + expect(length_prec.precedence("A", "B")).to eq(:undefined) + end + + it "supports explicit shortest-match precedence" do + lex_prec.add_rule( + left_token: ident("COM"), + operator: Lrama::Grammar::LexPrec::SHORTEST, + right_token: ident("COM"), + lineno: 1 + ) + length_prec = Lrama::LengthPrecedences.new(lex_prec) + + expect(length_prec.resolution("COM", "COM")).to eq(Lrama::LengthPrecedences::PREFER_OLD) + expect(length_prec.prefer_shorter?("COM", "COM")).to be true + end + + it "supports explicit longest-match precedence" do + lex_prec.add_rule( + left_token: ident("ID"), + operator: Lrama::Grammar::LexPrec::LONGEST, + right_token: ident("IF"), + lineno: 1 + ) + length_prec = Lrama::LengthPrecedences.new(lex_prec) + + expect(length_prec.resolution("ID", "IF")).to eq(Lrama::LengthPrecedences::PREFER_NEW) + expect(length_prec.resolution("IF", "ID")).to eq(Lrama::LengthPrecedences::PREFER_NEW) + end + + it "supports right-token length precedence" do + lex_prec.add_rule( + left_token: ident("WORD"), + operator: Lrama::Grammar::LexPrec::TOKEN_RIGHT_LENGTH, + right_token: ident("NON"), + lineno: 1 + ) + length_prec = Lrama::LengthPrecedences.new(lex_prec) + + expect(length_prec.resolution("WORD", "NON")).to eq(Lrama::LengthPrecedences::PREFER_NEW) + expect(length_prec.resolution("NON", "WORD")).to eq(Lrama::LengthPrecedences::PREFER_OLD) + end + end + + describe "#fallback_precedes?" do + it "uses traditional longest match for unspecified fallback length conflicts" do + length_prec = Lrama::LengthPrecedences.new(lex_prec) + + expect(length_prec.normal_precedes?("A", "B")).to be false + expect(length_prec.fallback_precedes?("A", "B")).to be true + end + + it "respects explicit same-token shortest-match precedence" do + add_rule("COM", Lrama::Grammar::LexPrec::SHORTEST, "COM", 1) + length_prec = Lrama::LengthPrecedences.new(lex_prec) + + expect(length_prec.normal_precedes?("COM", "COM")).to be false + expect(length_prec.fallback_precedes?("COM", "COM")).to be false + end + + it "respects explicit right-token length precedence" do + add_rule("WORD", Lrama::Grammar::LexPrec::TOKEN_RIGHT_LENGTH, "NON", 1) + length_prec = Lrama::LengthPrecedences.new(lex_prec) + + expect(length_prec.fallback_precedes?("WORD", "NON")).to be true + expect(length_prec.fallback_precedes?("NON", "WORD")).to be false + end + end + + describe "#initialize" do + it "rejects contradictory shortest and longest rules for the same scan direction" do + add_rule("RANGLE", Lrama::Grammar::LexPrec::SHORTEST, "RSHIFT", 10) + add_rule("RANGLE", Lrama::Grammar::LexPrec::LONGEST, "RSHIFT", 12) + + expect { Lrama::LengthPrecedences.new(lex_prec) } + .to raise_error( + Lrama::LengthPrecedences::LexicalPrecedenceConflictError, + /RANGLE -> RSHIFT.*-s at line 10.*-~ at line 12/m + ) + end + + it "rejects contradictory right-token length winners in reverse declarations" do + add_rule("RANGLE", Lrama::Grammar::LexPrec::TOKEN_RIGHT_LENGTH, "RSHIFT", 20) + add_rule("RSHIFT", Lrama::Grammar::LexPrec::TOKEN_RIGHT_LENGTH, "RANGLE", 21) + + expect { Lrama::LengthPrecedences.new(lex_prec) } + .to raise_error( + Lrama::LengthPrecedences::LexicalPrecedenceConflictError, + /RSHIFT -> RANGLE.*-< at line 20.*-< at line 21/m + ) + end + + it "allows repeated declarations with the same length resolution" do + add_rule("RANGLE", Lrama::Grammar::LexPrec::LONGEST, "RSHIFT", 30) + add_rule("RSHIFT", Lrama::Grammar::LexPrec::LONGEST, "RANGLE", 31) + + expect { Lrama::LengthPrecedences.new(lex_prec) }.not_to raise_error + end + end +end From de4e5945f278eb9c3ecd1730cae9a4de89a01322 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 21:39:04 +0900 Subject: [PATCH 04/24] pslr: integrate pseudo-scanner into state computation Add States#compute_pslr, an IELR(1) pipeline extended with scanner awareness (paper section 3.4): * Phase 2 builds the scanner FSA and length precedence tables, and the lexical tie closure is finalized against the FSA conflict pairs * Phase 3 state splitting additionally requires PSLR compatibility: states merge only when their acceptable-token sets produce the same pseudo-scanner decisions, checked with unfiltered kernel lookaheads so lookahead filtering cannot mask scanner-visible differences * after conflict resolution, the scanner_accepts table is built with profile-based complete-conflict resolution (Def 3.2.17-3.2.20): each parser state row is computed by walking the DFA with (Ts, ts, Tl) conflict profiles; unresolved complete conflicts are recorded instead of falling back to declaration order * a fallback row over the whole token universe is computed for syntax-error handling, completing residual conflicts with traditional longest-match/declaration-order semantics * acc(sp) uses true reduce lookaheads (not default reductions), expands through lexical ties, and always includes layout tokens States#validate! now fails generation on unresolved scanner conflicts and on pslr.max-states / pslr.max-state-ratio guard violations, and warns about useless %lex-prec declarations. %lexer-context classification and context-based splitting are kept isolated as a Lrama/Ruby extension executed after the PSLR core. --- lib/lrama/command.rb | 11 +- lib/lrama/lexer_context_classifier.rb | 161 ++++++ lib/lrama/state.rb | 61 +- lib/lrama/state/pslr_inadequacy.rb | 79 +++ lib/lrama/state/scanner_accepts.rb | 489 ++++++++++++++++ lib/lrama/states.rb | 539 +++++++++++++++++- .../lrama/lexer_context_classifier.rbs | 78 +++ sig/generated/lrama/state.rbs | 19 +- sig/generated/lrama/state/pslr_inadequacy.rbs | 52 ++ sig/generated/lrama/state/scanner_accepts.rbs | 195 +++++++ sig/generated/lrama/states.rbs | 127 +++++ spec/lrama/lexer_context_classifier_spec.rb | 457 +++++++++++++++ spec/lrama/state/pslr_inadequacy_spec.rb | 234 ++++++++ spec/lrama/state/scanner_accepts_spec.rb | 406 +++++++++++++ spec/lrama/states_spec.rb | 506 ++++++++++++++++ spec/spec_helper.rb | 3 + spec/support/pslr_family_helper.rb | 159 ++++++ 17 files changed, 3533 insertions(+), 43 deletions(-) create mode 100644 lib/lrama/lexer_context_classifier.rb create mode 100644 lib/lrama/state/pslr_inadequacy.rb create mode 100644 lib/lrama/state/scanner_accepts.rb create mode 100644 sig/generated/lrama/lexer_context_classifier.rbs create mode 100644 sig/generated/lrama/state/pslr_inadequacy.rbs create mode 100644 sig/generated/lrama/state/scanner_accepts.rbs create mode 100644 spec/lrama/lexer_context_classifier_spec.rb create mode 100644 spec/lrama/state/pslr_inadequacy_spec.rb create mode 100644 spec/lrama/state/scanner_accepts_spec.rb create mode 100644 spec/support/pslr_family_helper.rb diff --git a/lib/lrama/command.rb b/lib/lrama/command.rb index b7042fcab..b9cab61b3 100644 --- a/lib/lrama/command.rb +++ b/lib/lrama/command.rb @@ -32,10 +32,10 @@ def execute_command_workflow text = read_input grammar = build_grammar(text) states, context = compute_status(grammar) + states.validate!(@logger) render_reports(states) if @options.report_file @tracer.trace(grammar) render_diagram(grammar) - states.validate!(@logger) render_output(context, grammar) @warnings.warn(grammar, states) end @@ -86,8 +86,15 @@ def prepare_grammar(grammar) def compute_status(grammar) states = Lrama::States.new(grammar, @tracer) states.compute - states.compute_ielr if grammar.ielr_defined? + if grammar.pslr_defined? + states.compute_pslr + elsif grammar.ielr_defined? + states.compute_ielr + end [states, Lrama::Context.new(states)] + rescue States::StateLimitExceeded => e + @logger.error(e.message) + exit false end def render_reports(states) diff --git a/lib/lrama/lexer_context_classifier.rb b/lib/lrama/lexer_context_classifier.rb new file mode 100644 index 000000000..e61c990a1 --- /dev/null +++ b/lib/lrama/lexer_context_classifier.rb @@ -0,0 +1,161 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + # Classifies parser states into lexer context categories. + # + # When LALR states are merged, states from different grammatical contexts + # (e.g., BEG vs CMDARG) share the same state number, making them + # indistinguishable to the lexer. This classifier analyzes kernel items + # to determine the lexer context of each state, enabling context-aware + # state splitting. + # + # Context definitions come from %lexer-context directives in the grammar file. + # Each directive maps a context name to a set of symbols: + # + # %lexer-context BEG keyword_if keyword_unless '(' '[' '{' + # %lexer-context CMDARG tIDENTIFIER tFID tCONSTANT + # + class LexerContextClassifier + # @rbs (Hash[String, Grammar::LexerContext] lexer_contexts, ?Hash[String, Array[String]] expansion_args) -> void + def initialize(lexer_contexts, expansion_args = {}) + @lexer_contexts = lexer_contexts + @expansion_args = expansion_args + @symbol_to_context = build_symbol_to_context_map + @context_names = build_context_names + end + + # Classify a state's kernel items into context groups. + # + # @rbs (State state) -> Hash[Integer, Array[State::Item]] + def classify(state) + groups = {} + + state.kernels.each do |item| + ctx = infer_item_context(item) + groups[ctx] ||= [] + groups[ctx] << item + end + + groups + end + + # Infer the lexer context for a single kernel item. + # + # @rbs (State::Item item) -> Integer + def infer_item_context(item) + # Position 0 means we're at the start of a rule (just entered via GOTO) + return default_beg_context if item.position == 0 + + prev_sym = item.rhs[item.position - 1] + classify_symbol_context(prev_sym) + end + + # Classify context based on the symbol before the dot. + # + # @rbs (Grammar::Symbol sym) -> Integer + def classify_symbol_context(sym) + name = sym.id.s_value + # Also try without surrounding quotes for single-char tokens + bare = name.gsub(/\A["']|["']\z/, "") + + # Direct match + ctx = @symbol_to_context[name] || @symbol_to_context[bare] + return ctx if ctx + + # Fallback: inherit context from parameterized rule expansion arguments + if (arg_names = @expansion_args[name]) + arg_names.each do |arg_name| + ctx = @symbol_to_context[arg_name] + return ctx if ctx + end + end + + 0 + end + + # For backward compatibility with states.rb split logic + # @rbs (Grammar::Symbol sym) -> Integer + def classify_terminal_context(sym) + classify_symbol_context(sym) + end + + # For backward compatibility with states.rb split logic + # @rbs (Grammar::Symbol sym) -> Integer + def classify_nonterminal_context(sym) + classify_symbol_context(sym) + end + + # Return a human-readable name for a context value. + # + # @rbs (Integer ctx) -> String + def context_name(ctx) + return "UNKNOWN" if ctx == 0 + + names = @context_names.select { |flag, _| (ctx & flag) != 0 }.values + names.empty? ? "UNKNOWN" : names.join("|") + end + + # Class-level context_name for use without an instance (e.g., output.rb). + # Requires lexer_contexts to build the name map. + # + # @rbs (Integer ctx, Hash[String, Grammar::LexerContext] lexer_contexts) -> String + def self.context_name(ctx, lexer_contexts) + return "UNKNOWN" if ctx == 0 + + names = [] + lexer_contexts.each_value do |lc| + names << lc.name if (ctx & lc.bitmask) != 0 + end + names.empty? ? "UNKNOWN" : names.join("|") + end + + # All context bitmasks OR'd together (for "is context known?" checks). + # @rbs () -> Integer + def all_contexts_mask + mask = 0 + @lexer_contexts.each_value { |lc| mask |= lc.bitmask } + mask + end + + # Return the ordered list of context definitions. + # @rbs () -> Array[Grammar::LexerContext] + def contexts + @lexer_contexts.values.sort_by(&:index) + end + + private + + # Build a map from symbol name → context bitmask. + # @rbs () -> Hash[String, Integer] + def build_symbol_to_context_map + map = {} + @lexer_contexts.each_value do |lc| + lc.symbols.each do |sym| + name = sym.s_value + # OR the bitmask in case a symbol appears in multiple contexts + map[name] = (map[name] || 0) | lc.bitmask + end + end + map + end + + # Build a map from bitmask value → context name. + # @rbs () -> Hash[Integer, String] + def build_context_names + names = {} + @lexer_contexts.each_value do |lc| + names[lc.bitmask] = lc.name + end + names + end + + # Return the bitmask for the first defined context (used as default for position-0 items). + # Returns 0 if no contexts are defined. + # @rbs () -> Integer + def default_beg_context + first = @lexer_contexts.values.min_by(&:index) + first ? first.bitmask : 0 + end + end +end diff --git a/lib/lrama/state.rb b/lib/lrama/state.rb index 220d900b2..1591a12d3 100644 --- a/lib/lrama/state.rb +++ b/lib/lrama/state.rb @@ -5,8 +5,10 @@ require_relative "state/action" require_relative "state/inadequacy_annotation" require_relative "state/item" +require_relative "state/pslr_inadequacy" require_relative "state/reduce_reduce_conflict" require_relative "state/resolved_conflict" +require_relative "state/scanner_accepts" require_relative "state/shift_reduce_conflict" module Lrama @@ -67,6 +69,7 @@ class State attr_accessor :follow_kernel_items #: Hash[Action::Goto, Hash[Item, bool]] attr_accessor :always_follows #: Hash[Action::Goto, Bitmap::bitmap] attr_accessor :goto_follows #: Hash[Action::Goto, Bitmap::bitmap] + attr_accessor :lexer_context #: Integer? # @rbs (Integer id, Grammar::Symbol accessing_symbol, Array[Item] kernels) -> void def initialize(id, accessing_symbol, kernels) @@ -90,6 +93,7 @@ def initialize(id, accessing_symbol, kernels) @follow_kernel_items = {} @always_follows = {} @goto_follows = {} + @lexer_context = nil @lhs_contributions = {} @lane_items = {} end @@ -162,6 +166,37 @@ def set_look_ahead(rule, look_ahead) reduce.look_ahead = look_ahead end + # @rbs (Action::Reduce reduce, ?lookahead_set lookaheads) -> Bitmap::bitmap + def acceptable_pslr_reduce_lookahead(reduce, lookaheads = item_lookahead_set) + if reduce.item.position.zero? + goto_follow_set(reduce.item.lhs, lookaheads) + else + lookaheads.fetch(reduce.item, 0) + end + end + + # @rbs (?lookahead_set? lookaheads) -> Array[Grammar::Symbol] + def pslr_error_tokens(lookaheads = nil) + unless lookaheads + return resolved_conflicts.select { |conflict| conflict.which == :error }.map(&:symbol) + end + + # During splitting, resolve the prospective lane in rule order, just as + # compute_shift_reduce_conflicts stops once a reduction removes the shift. + term_transitions.each_with_object([]) do |shift, errors| + token = shift.next_sym + precedence = token.precedence + next unless precedence && precedence.type == :nonassoc + + winner = reduces.sort_by { |reduce| reduce.rule.id }.find do |reduce| + rule_precedence = reduce.rule.precedence + rule_precedence && rule_precedence >= precedence && + acceptable_pslr_reduce_lookahead(reduce, lookaheads)[token.number] == 1 + end + errors << token if winner && winner.rule.precedence == precedence + end + end + # @rbs (Grammar::Rule rule, Hash[Grammar::Symbol, Array[Action::Goto]] sources) -> void def set_look_ahead_sources(rule, sources) reduce = reduces.find do |r| @@ -335,14 +370,14 @@ def kernel_indices # Definition 3.40 (propagate_lookaheads) # - # @rbs (State next_state) -> lookahead_set - def propagate_lookaheads(next_state) - filters = next_state.lookahead_set_filters + # @rbs (State next_state, ?lookahead_set? lookaheads, ?filter: bool) -> lookahead_set + def propagate_lookaheads(next_state, lookaheads = nil, filter: true) + filters = next_state.lookahead_set_filters if filter sets = {} #: lookahead_set sets.compare_by_identity next_state.kernels.each {|next_kernel| - filter = filters[next_kernel] - if filter == 0 + mask = filters && filters[next_kernel] + if mask == 0 sets[next_kernel] = 0 next end @@ -350,12 +385,12 @@ def propagate_lookaheads(next_state) lookahead_sets = if next_kernel.position > 1 kernel = kernels.find {|k| k.predecessor_item_of?(next_kernel) } - item_lookahead_set[kernel] + (lookaheads || item_lookahead_set).fetch(kernel) else goto_follow_set(next_kernel.lhs) end - sets[next_kernel] = lookahead_sets & filter + sets[next_kernel] = mask ? lookahead_sets & mask : lookahead_sets } sets end @@ -609,6 +644,12 @@ def items_for_rule(rule, position) candidates.select {|item| item.rule == rule } end + # @rbs () -> void + def clear_predecessors + @predecessors.clear + @predecessor_set = nil + end + # @rbs (State prev_state) -> void def append_predecessor(prev_state) seen = (@predecessor_set ||= {}.compare_by_identity) @@ -619,14 +660,14 @@ def append_predecessor(prev_state) # Definition 3.39 (compute_goto_follow_set) # - # @rbs (Grammar::Symbol nterm_token) -> Bitmap::bitmap - def goto_follow_set(nterm_token) + # @rbs (Grammar::Symbol nterm_token, ?lookahead_set? lookaheads) -> Bitmap::bitmap + def goto_follow_set(nterm_token, lookaheads = nil) return 0 if nterm_token.accept_symbol? goto = @lalr_isocore.transitions_by_symbol_number[nterm_token.number] #: Action::Goto? @kernels .select {|kernel| @lalr_isocore.follow_kernel_items[goto][kernel] } - .map {|kernel| item_lookahead_set[kernel] } + .map {|kernel| (lookaheads || item_lookahead_set).fetch(kernel) } .reduce(@lalr_isocore.always_follows[goto]) {|result, bitmap| result | bitmap } end diff --git a/lib/lrama/state/pslr_inadequacy.rb b/lib/lrama/state/pslr_inadequacy.rb new file mode 100644 index 000000000..451458cf5 --- /dev/null +++ b/lib/lrama/state/pslr_inadequacy.rb @@ -0,0 +1,79 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class State + # PSLR Inadequacy detection + # Based on Section 3.4.3 from the PSLR dissertation + # + # PSLR inadequacy occurs when state merging causes different + # pseudo-scanner behavior + class PslrInadequacy + # Inadequacy types + LR_RELATIVE = :lr_relative #: Symbol + PSLR_RELATIVE = :pslr_relative #: Symbol + + attr_reader :type #: Symbol + attr_reader :state #: State + attr_reader :conflicting_states #: Array[State] + attr_reader :details #: Hash[Symbol, untyped] + + # @rbs (type: Symbol, state: State, conflicting_states: Array[State], details: Hash[Symbol, untyped]) -> void + def initialize(type:, state:, conflicting_states:, details:) + @type = type + @state = state + @conflicting_states = conflicting_states + @details = details + end + + # @rbs () -> String + def to_s + message = "PSLR Inadequacy (#{type}): state #{state.id} conflicts with states #{conflicting_states.map(&:id).join(', ')}" + return message if details[:profiles].nil? + + profiles = details[:profiles].map do |profile, state_ids| + "#{state_ids.join(', ')} => #{profile.inspect}" + end + + "#{message} (profiles: #{profiles.join(' | ')})" + end + end + + # PSLR Compatibility checker + # Based on Definition 3.4.1 from the dissertation + class PslrCompatibilityChecker + # @rbs (ScannerAccepts scanner_accepts, LengthPrecedences length_prec) -> void + def initialize(scanner_accepts, length_prec) + @scanner_accepts = scanner_accepts + @length_prec = length_prec + end + + # Build a stable scanner profile for a parser state + # @rbs (State state, ScannerFSA scanner_fsa) -> Array[[Integer, String?]] + def profile(state, scanner_fsa) + scanner_fsa.states.each_with_object([]) do |fsa_state, result| + next unless fsa_state.accepting? + + token = @scanner_accepts[state.id, fsa_state.id] + result << [fsa_state.id, token&.name] + end + end + + # Partition states by scanner profile + # @rbs (Array[State] states, ScannerFSA scanner_fsa) -> Hash[Array[[Integer, String?]], Array[State]] + def group_by_profile(states, scanner_fsa) + states.group_by do |state| + profile(state, scanner_fsa) + end + end + + # Check if two states are PSLR-compatible + # Definition 3.4.1: States are compatible if for any input, + # the pseudo-scanner selects the same token + # @rbs (State s1, State s2, ScannerFSA scanner_fsa) -> bool + def compatible?(s1, s2, scanner_fsa) + profile(s1, scanner_fsa) == profile(s2, scanner_fsa) + end + end + end +end diff --git a/lib/lrama/state/scanner_accepts.rb b/lib/lrama/state/scanner_accepts.rb new file mode 100644 index 000000000..6ce02e5dc --- /dev/null +++ b/lib/lrama/state/scanner_accepts.rb @@ -0,0 +1,489 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +require "set" + +module Lrama + class State + # scanner_accepts[parser_state, accepting_scanner_state] for PSLR(1). + # + # Construction follows complete pseudo-scanner conflict profiles. A profile + # contains the shorter token set Ts, the selected shorter token ts, and the + # current/longest token set Tl. + # + # Normal parser-state rows are strict: unresolved pseudo-scanner + # conflicts are reported and are not resolved by token declaration order. + # + # The fallback row is used only for syntax-error handling. It first + # applies explicit PSLR lexical precedence declarations. For scanner + # conflicts that remain unresolved only in the fallback universe, it + # completes the decision with traditional scanner behavior: fallback + # length defaults are handled by LengthPrecedences#fallback_precedes?, + # and otherwise-unresolved identity conflicts are resolved by token + # declaration order. + # + # When %lex-scope declarations are present, each parser state may use + # a merged set of global + scope-active lexical precedence rules. + class ScannerAccepts + class Conflict + attr_reader :parser_state_id #: Integer? + attr_reader :scanner_state_id #: Integer + attr_reader :shorter_tokens #: Array[String] + attr_reader :selected_shorter_token #: String? + attr_reader :current_tokens #: Array[String] + + # @rbs (parser_state_id: Integer?, scanner_state_id: Integer, shorter_tokens: Array[String], selected_shorter_token: String?, current_tokens: Array[String]) -> void + def initialize(parser_state_id:, scanner_state_id:, shorter_tokens:, selected_shorter_token:, current_tokens:) + @parser_state_id = parser_state_id + @scanner_state_id = scanner_state_id + @shorter_tokens = shorter_tokens + @selected_shorter_token = selected_shorter_token + @current_tokens = current_tokens + end + end + + class ProfileOutcome + EMPTY = :empty #: Symbol + RESOLVED = :resolved #: Symbol + UNRESOLVED = :unresolved #: Symbol + + attr_reader :kind #: Symbol + attr_reader :token_name #: String? + attr_reader :conflict #: Conflict? + + # @rbs (kind: Symbol, ?token_name: String?, ?conflict: Conflict?) -> void + def initialize(kind:, token_name: nil, conflict: nil) + @kind = kind + @token_name = token_name + @conflict = conflict + end + + # @rbs () -> bool + def empty? + @kind == EMPTY + end + + # @rbs () -> bool + def resolved? + @kind == RESOLVED + end + + # @rbs () -> bool + def unresolved? + @kind == UNRESOLVED + end + end + + class ProfileResolver + # @rbs (Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void + def initialize(lex_prec, length_prec, fallback: false, token_order: {}) + @lex_prec = lex_prec + @length_prec = length_prec + @fallback = fallback + @token_order = token_order + end + + # @rbs (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome + def resolve(shorter_tokens, selected_shorter_token, current_tokens) + if @fallback + resolve_fallback(shorter_tokens, selected_shorter_token, current_tokens) + else + resolve_normal(shorter_tokens, selected_shorter_token, current_tokens) + end + end + + private + + # @rbs (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome + def resolve_normal(shorter_tokens, selected_shorter_token, current_tokens) + if current_tokens.empty? + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: selected_shorter_token) if selected_shorter_token + + return ProfileOutcome.new(kind: ProfileOutcome::EMPTY) + end + + if selected_shorter_token && current_tokens.all? {|token| length_prefers_old?(selected_shorter_token, token) } + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: selected_shorter_token) + end + + winners = current_tokens.select do |candidate| + identity_winner?(candidate, current_tokens) && + shorter_tokens.all? {|shorter| @length_prec.resolution(shorter, candidate) == LengthPrecedences::PREFER_NEW } + end + + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: winners.first) if winners.size == 1 + + ProfileOutcome.new(kind: ProfileOutcome::UNRESOLVED) + end + + # @rbs (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome + def resolve_fallback(shorter_tokens, selected_shorter_token, current_tokens) + if current_tokens.empty? + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: selected_shorter_token) if selected_shorter_token + + return ProfileOutcome.new(kind: ProfileOutcome::EMPTY) + end + + if selected_shorter_token && current_tokens.all? {|token| fallback_length_prefers_old?(selected_shorter_token, token) } + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: selected_shorter_token) + end + + explicit_winners = current_tokens.select do |candidate| + fallback_identity_winner?(candidate, current_tokens) && + shorter_tokens.all? {|shorter| @length_prec.fallback_precedes?(shorter, candidate) } + end + + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: explicit_winners.first) if explicit_winners.size == 1 + + declaration_order_winner = current_tokens.sort_by {|token| token_order_key(token) }.find do |candidate| + shorter_tokens.all? {|shorter| @length_prec.fallback_precedes?(shorter, candidate) } + end + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: declaration_order_winner) if declaration_order_winner + + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: selected_shorter_token) if selected_shorter_token + + ProfileOutcome.new(kind: ProfileOutcome::UNRESOLVED) + end + + # @rbs (String old_token, String new_token) -> bool + def length_prefers_old?(old_token, new_token) + @length_prec.resolution(old_token, new_token) == LengthPrecedences::PREFER_OLD + end + + # @rbs (String old_token, String new_token) -> bool + def fallback_length_prefers_old?(old_token, new_token) + !@length_prec.fallback_precedes?(old_token, new_token) + end + + # @rbs (String candidate, Set[String] current_tokens) -> bool + def identity_winner?(candidate, current_tokens) + current_tokens.all? do |other| + candidate == other || @lex_prec.identity_precedes?(candidate, other) + end + end + + # @rbs (String candidate, Set[String] current_tokens) -> bool + def fallback_identity_winner?(candidate, current_tokens) + current_tokens.all? do |other| + next true if candidate == other + + candidate_wins = @lex_prec.identity_precedes?(candidate, other) + other_wins = @lex_prec.identity_precedes?(other, candidate) + if candidate_wins && !other_wins + true + elsif other_wins + false + else + token_order_precedes?(candidate, other) + end + end + end + + # @rbs (String candidate, String other) -> bool + def token_order_precedes?(candidate, other) + (token_order_key(candidate) <=> token_order_key(other)) == -1 + end + + # @rbs (String token) -> [Integer, String] + def token_order_key(token) + [@token_order.fetch(token, @token_order.size), token] + end + end + + class CompleteProfileComputer + attr_reader :table #: Hash[Integer, Grammar::TokenPattern] + attr_reader :conflicts #: Array[Conflict] + + # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void + def initialize(scanner_fsa, lex_prec, length_prec, acceptable_tokens, parser_state_id = nil, fallback: false, token_order: {}) + @scanner_fsa = scanner_fsa + @resolver = ProfileResolver.new(lex_prec, length_prec, fallback: fallback, token_order: token_order) + @acceptable_tokens = acceptable_tokens + @parser_state_id = parser_state_id + @table = {} + @conflicts = [] + token_patterns_by_name = {} #: Hash[String, Grammar::TokenPattern] + @token_patterns_by_name = scanner_fsa.token_patterns.each_with_object(token_patterns_by_name) do |token_pattern, hash| + hash[token_pattern.name] ||= token_pattern + end + end + + # @rbs () -> void + def compute + visited = Set.new + visit_transitions(0, Set.new, nil, visited) + end + + private + + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void + def visit_transitions(fsa_state_id, shorter_tokens, selected_shorter_token, visited) + fsa_state = @scanner_fsa.states[fsa_state_id] + return unless fsa_state + + fsa_state.transitions.each_value do |next_state_id| + visit_state(next_state_id, shorter_tokens, selected_shorter_token, visited) + end + end + + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void + def visit_state(fsa_state_id, shorter_tokens, selected_shorter_token, visited) + fsa_state = @scanner_fsa.states[fsa_state_id] + return unless fsa_state + + current_tokens = current_acceptable_tokens(fsa_state) + key = profile_key(fsa_state_id, shorter_tokens, selected_shorter_token, current_tokens) + return if visited.include?(key) + + visited << key + result = @resolver.resolve(shorter_tokens, selected_shorter_token, current_tokens) + + if result.resolved? + if result.token_name && current_tokens.include?(result.token_name) + token_pattern = token_pattern_for(result.token_name) + existing = @table[fsa_state_id] + if existing && existing.name != token_pattern.name + @conflicts << Conflict.new( + parser_state_id: @parser_state_id, + scanner_state_id: fsa_state_id, + shorter_tokens: shorter_tokens.to_a.sort, + selected_shorter_token: existing.name, + current_tokens: current_tokens.to_a.sort + ) + else + @table[fsa_state_id] = token_pattern + end + end + elsif result.unresolved? + @conflicts << Conflict.new( + parser_state_id: @parser_state_id, + scanner_state_id: fsa_state_id, + shorter_tokens: shorter_tokens.to_a.sort, + selected_shorter_token: selected_shorter_token, + current_tokens: current_tokens.to_a.sort + ) + end + + next_shorter_tokens = shorter_tokens | current_tokens + next_selected = result.resolved? ? result.token_name : nil + visit_transitions(fsa_state_id, next_shorter_tokens, next_selected, visited) + end + + # @rbs (ScannerFSA::State fsa_state) -> Set[String] + def current_acceptable_tokens(fsa_state) + fsa_state.accepting_tokens.each_with_object(Set.new) do |token_pattern, tokens| + tokens << token_pattern.name if @acceptable_tokens.include?(token_pattern.name) + end + end + + # @rbs (String token_name) -> Grammar::TokenPattern + def token_pattern_for(token_name) + @token_patterns_by_name.fetch(token_name) + end + + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> [Integer, Array[String], String?, Array[String]] + def profile_key(fsa_state_id, shorter_tokens, selected_shorter_token, current_tokens) + [fsa_state_id, shorter_tokens.to_a.sort, selected_shorter_token, current_tokens.to_a.sort] + end + end + + class CompatibilityChecker + # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec) -> void + def initialize(scanner_fsa, lex_prec, length_prec) + @scanner_fsa = scanner_fsa + @resolver = ProfileResolver.new(lex_prec, length_prec) + end + + # @rbs (Set[String] left_tokens, Set[String] right_tokens) -> bool + def compatible?(left_tokens, right_tokens) + visit_transitions(0, Set.new, nil, Set.new, nil, left_tokens, right_tokens, Set.new) + end + + private + + # @rbs (Integer fsa_state_id, Set[String] left_shorter, String? left_selected, Set[String] right_shorter, String? right_selected, Set[String] left_acc, Set[String] right_acc, Set[untyped] visited) -> bool + def visit_transitions(fsa_state_id, left_shorter, left_selected, right_shorter, right_selected, left_acc, right_acc, visited) + fsa_state = @scanner_fsa.states[fsa_state_id] + return true unless fsa_state + + fsa_state.transitions.each_value do |next_state_id| + return false unless visit_state(next_state_id, left_shorter, left_selected, right_shorter, right_selected, left_acc, right_acc, visited) + end + + true + end + + # @rbs (Integer fsa_state_id, Set[String] left_shorter, String? left_selected, Set[String] right_shorter, String? right_selected, Set[String] left_acc, Set[String] right_acc, Set[untyped] visited) -> bool + def visit_state(fsa_state_id, left_shorter, left_selected, right_shorter, right_selected, left_acc, right_acc, visited) + fsa_state = @scanner_fsa.states[fsa_state_id] + return true unless fsa_state + + left_current = tokens_accepted_by(fsa_state, left_acc) + right_current = tokens_accepted_by(fsa_state, right_acc) + left_outcome = @resolver.resolve(left_shorter, left_selected, left_current) + right_outcome = @resolver.resolve(right_shorter, right_selected, right_current) + + return false unless outcomes_compatible?(left_outcome, right_outcome) + + key = [ + fsa_state_id, + left_shorter.to_a.sort, + left_outcome.kind, + left_outcome.token_name, + right_shorter.to_a.sort, + right_outcome.kind, + right_outcome.token_name + ] + return true if visited.include?(key) + + visited << key + + visit_transitions( + fsa_state_id, + left_shorter | left_current, + left_outcome.resolved? ? left_outcome.token_name : nil, + right_shorter | right_current, + right_outcome.resolved? ? right_outcome.token_name : nil, + left_acc, + right_acc, + visited + ) + end + + # @rbs (ScannerFSA::State fsa_state, Set[String] accepted_names) -> Set[String] + def tokens_accepted_by(fsa_state, accepted_names) + fsa_state.accepting_tokens.each_with_object(Set.new) do |token_pattern, tokens| + tokens << token_pattern.name if accepted_names.include?(token_pattern.name) + end + end + + # @rbs (ProfileOutcome left, ProfileOutcome right) -> bool + def outcomes_compatible?(left, right) + return true if left.empty? || right.empty? + return true if left.unresolved? && right.unresolved? + return false if left.unresolved? || right.unresolved? + + left.token_name == right.token_name + end + end + + FALLBACK_ROW_ID = -1 #: Integer + + attr_reader :table #: Hash[[Integer, Integer], Grammar::TokenPattern?] + attr_reader :fallback_table #: Hash[Integer, Grammar::TokenPattern] + attr_reader :conflicts #: Array[Conflict] + + # @rbs (Array[State] parser_states, ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?Grammar::LexTie? lex_tie, symbols: Array[Grammar::Symbol], ?layout_token_names: Set[String]) -> void + def initialize(parser_states, scanner_fsa, lex_prec, length_prec, lex_tie = nil, symbols:, layout_token_names: Set.new) + @parser_states = parser_states + @symbols = symbols + @scanner_fsa = scanner_fsa + @lex_prec = lex_prec + @length_prec = length_prec + @lex_tie = lex_tie + @layout_token_names = layout_token_names.to_set + @table = {} + @fallback_table = {} + @conflicts = [] + end + + # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens) -> [Hash[Integer, Grammar::TokenPattern], Array[Conflict]] + def self.compute_for_acceptable_tokens(scanner_fsa, lex_prec, length_prec, acceptable_tokens) + computer = CompleteProfileComputer.new(scanner_fsa, lex_prec, length_prec, acceptable_tokens) + computer.compute + [computer.table, computer.conflicts] + end + + # @rbs (State state, Array[Grammar::Symbol] symbols, ?State::lookahead_set? lookaheads) -> Set[String] + def self.acceptable_tokens(state, symbols, lookaheads = nil) + tokens = state.term_transitions.map { |shift| shift.next_sym.name }.to_set + state.reduces.each do |reduce| + bitmap = state.acceptable_pslr_reduce_lookahead(reduce, lookaheads || state.item_lookahead_set) + Bitmap.to_array(bitmap).each { |number| tokens << symbols.fetch(number).name } + end + state.pslr_error_tokens(lookaheads).each { |token| tokens.delete(token.name) } + tokens + end + + # @rbs () -> void + def build + @parser_states.each do |parser_state| + compute_for_parser_state(parser_state) + end + compute_fallback_row + end + + # @rbs (Integer parser_state_id, Integer accepting_state_id) -> Grammar::TokenPattern? + def [](parser_state_id, accepting_state_id) + @table[[parser_state_id, accepting_state_id]] + end + + # @rbs () -> bool + def unresolved_conflicts? + !@conflicts.empty? + end + + private + + # @rbs (State parser_state) -> void + def compute_for_parser_state(parser_state) + computer = CompleteProfileComputer.new( + @scanner_fsa, + @lex_prec, + @length_prec, + compute_acc_sp(parser_state), + parser_state.id + ) + computer.compute + + computer.table.each do |scanner_state_id, token_pattern| + @table[[parser_state.id, scanner_state_id]] = token_pattern + end + @conflicts.concat(computer.conflicts) + end + + # @rbs () -> void + def compute_fallback_row + all_tokens = @scanner_fsa.token_patterns.map(&:name).to_set + computer = CompleteProfileComputer.new( + @scanner_fsa, + @lex_prec, + @length_prec, + all_tokens, + FALLBACK_ROW_ID, + fallback: true, + token_order: token_order + ) + computer.compute + + computer.table.each do |scanner_state_id, token_pattern| + @fallback_table[scanner_state_id] = token_pattern + @table[[FALLBACK_ROW_ID, scanner_state_id]] = token_pattern + end + end + + # @rbs (State parser_state) -> Set[String] + def compute_acc_sp(parser_state) + tokens = self.class.acceptable_tokens(parser_state, @symbols) + expand_lexical_ties(tokens) | @layout_token_names + end + + # @rbs (Set[String] tokens) -> Set[String] + def expand_lexical_ties(tokens) + return tokens unless @lex_tie + + tokens.each_with_object(Set.new) do |token, expanded| + @lex_tie.tied_names(token).each {|name| expanded << name } + end + end + + # @rbs () -> Hash[String, Integer] + def token_order + initial = {} #: Hash[String, Integer] + @scanner_fsa.token_patterns.each_with_object(initial) do |token_pattern, order| + order[token_pattern.name] ||= token_pattern.definition_order + end + end + end + end +end diff --git a/lib/lrama/states.rb b/lib/lrama/states.rb index 021830697..63c995993 100644 --- a/lib/lrama/states.rb +++ b/lib/lrama/states.rb @@ -3,6 +3,7 @@ require "forwardable" require "set" +require_relative "lexer_context_classifier" require_relative "tracer/duration" require_relative "state/item" @@ -12,6 +13,8 @@ module Lrama # "Efficient Computation of LALR(1) Look-Ahead Sets" # https://dl.acm.org/doi/pdf/10.1145/69622.357187 class States + class StateLimitExceeded < StandardError; end + # TODO: rbs-inline 0.11.0 doesn't support instance variables. # Move these type declarations above instance variable definitions, once it's supported. # see: https://github.com/soutaro/rbs-inline/pull/149 @@ -35,17 +38,29 @@ class States # @la: Hash[state_id, Hash[rule_id, Bitmap::bitmap]] # @bitmap_to_terms_cache: Hash[Bitmap::bitmap, Array[Grammar::Symbol]] # @initial_items: Hash[Grammar::Rule, State::Item] + # @max_states: Integer? + # @max_state_ratio: Float? + # @pslr_split_enabled: bool? + # @pslr_compatibility_checker: State::ScannerAccepts::CompatibilityChecker? extend Forwardable include Lrama::Tracer::Duration def_delegators "@grammar", :symbols, :terms, :nterms, :rules, :precedences, - :accept_symbol, :eof_symbol, :undef_symbol, :find_symbol_by_s_value!, :ielr_defined? + :accept_symbol, :eof_symbol, :undef_symbol, :find_symbol_by_s_value!, :ielr_defined?, :pslr_defined?, + :token_patterns, :lex_prec, :lex_tie, :pslr_max_states, :pslr_max_state_ratio attr_reader :states #: Array[State] attr_reader :reads_relation #: Hash[State::Action::Goto, Array[State::Action::Goto]] attr_reader :includes_relation #: Hash[State::Action::Goto, Array[State::Action::Goto]] attr_reader :lookback_relation #: Hash[state_id, Hash[rule_id, Array[State::Action::Goto]]] + attr_reader :scanner_fsa #: ScannerFSA? + attr_reader :length_precedences #: LengthPrecedences? + attr_reader :scanner_accepts_table #: State::ScannerAccepts? + attr_reader :pslr_inadequacies #: Array[State::PslrInadequacy] + attr_reader :pslr_metrics #: Hash[Symbol, Integer | Float | nil] + attr_reader :lexer_context_classifier #: LexerContextClassifier? + attr_reader :lexical_tie_candidates #: Array[[String, String]] # @rbs (Grammar grammar, Tracer tracer) -> void def initialize(grammar, tracer) @@ -53,6 +68,10 @@ def initialize(grammar, tracer) @tracer = tracer @states = [] + if pslr_defined? + @max_states = pslr_max_states + @max_state_ratio = pslr_max_state_ratio + end # `DR(p, A) = {t ∈ T | p -(A)-> r -(t)-> }` # where p is state, A is nterm, t is term. @@ -109,6 +128,18 @@ def initialize(grammar, tracer) # second key is rule_id, # value is bitmap of term. @la = {} + @pslr_inadequacies = [] + @lexical_tie_candidates = [] + @pslr_metrics = { + base_states_count: nil, + total_states_count: nil, + split_state_count: 0, + growth_count: 0, + growth_ratio: nil, + token_pattern_count: 0, + scanner_fsa_state_count: 0, + inadequacies_count: 0 + } @bitmap_to_terms_cache = {} end @@ -149,6 +180,47 @@ def compute_ielr report_duration(:compute_default_reduction) { compute_default_reduction } end + # Compute PSLR(1) states + # Based on Section 3.4 of the PSLR dissertation + # @rbs () -> void + def compute_pslr + capture_pslr_metrics_before_split + # Preparation + report_duration(:clear_conflicts) { clear_conflicts } + # Phase 1 + report_duration(:compute_predecessors) { compute_predecessors } + report_duration(:compute_follow_kernel_items) { compute_follow_kernel_items } + always_follows = report_duration(:compute_always_follows) { compute_always_follows } + report_duration(:compute_goto_follows) { compute_goto_follows(always_follows) } + # Phase 2 + report_duration(:build_scanner_fsa) { build_scanner_fsa } + report_duration(:build_length_precedences) { build_length_precedences } + report_duration(:compute_inadequacy_annotations) { compute_inadequacy_annotations } + # Phase 3a: PSLR split (Scanner FSA-based) + @pslr_split_enabled = true + report_duration(:split_states) { split_states } + @pslr_split_enabled = false + # Phase 3b: Lexer context classification + context-based split. + # Lrama/Ruby extension, not part of the PSLR dissertation core. + # No-op unless %lexer-context directives are present. + if @grammar.lexer_contexts.any? + report_duration(:split_states_by_context) { split_states_by_context } + end + if @states.size != @pslr_metrics[:base_states_count] + @states.each(&:clear_predecessors) + compute_predecessors + end + # Phase 4 + report_duration(:clear_look_ahead_sets) { clear_look_ahead_sets } + report_duration(:compute_look_ahead_sets) { compute_look_ahead_sets } + # Phase 5 + report_duration(:compute_conflicts) { compute_conflicts(:ielr) } + report_duration(:compute_default_reduction) { compute_default_reduction } + report_duration(:build_scanner_accepts) { build_scanner_accepts } + report_duration(:handle_pslr_inadequacies) { handle_pslr_inadequacies } + finalize_pslr_metrics + end + # @rbs () -> Integer def states_count @states.count @@ -197,11 +269,30 @@ def rr_conflicts_count # @rbs (Logger logger) -> void def validate!(logger) validate_conflicts_within_threshold!(logger) + validate_pslr_scanner_conflicts!(logger) + validate_pslr_inadequacies!(logger) + validate_pslr_useless_lex_prec!(logger) + validate_pslr_lexical_tie_candidates!(logger) + end + + # Return the lexer context table as an array of context values, + # one per parser state (indexed by state id). + # + # @rbs () -> Array[Integer] + def lexer_context_table + @states.map { |state| state.lexer_context || 0 } + end + + # Check if lexer context classification has been performed. + # + # @rbs () -> bool + def lexer_context_enabled? + pslr_defined? && @lexer_context_classifier != nil end def compute_la_sources_for_conflicted_states reflexive = {} - @states.each do |state| + reachable_parser_states.each do |state| state.nterm_transitions.each do |goto| reflexive[goto] = [goto] end @@ -282,6 +373,7 @@ def create_state(accessing_symbol, kernels, states_created) # return [states_created[kernels], false] if states_created[kernels] + check_state_limit! if @max_states state = State.new(@states.count, accessing_symbol, kernels) @states << state states_created[kernels] = state @@ -750,6 +842,71 @@ def split_states @nterm_transitions = nil end + # Traverse pairs of parser state and lexer context. Reusing each pair also + # closes cycles through symbols without a declared context. + # @rbs () -> void + def split_states_by_context + classifier = LexerContextClassifier.new(@grammar.lexer_contexts, @grammar.parameterized_expansion_args) + @lexer_context_classifier = classifier + start = @states.first + start.lexer_context = classifier.infer_item_context(start.kernels.first) + variants = { start => { start.lexer_context => start } } + originals = {} #: Hash[State, State] + pending = [start] + + pending.each do |state| + state.transitions.each do |transition| + target = transition.to_state + original = originals.fetch(target, target) + context = classifier.classify_symbol_context(transition.next_sym) + context = state.lexer_context if context.zero? + by_context = (variants[original] ||= {}) + successor = by_context[context] + unless successor + successor = by_context.empty? ? original : copy_split_state(original) + originals[successor] = original + successor.lexer_context = context + by_context[context] = successor + pending << successor + end + state.update_transition(transition, successor) unless target.equal?(successor) + end + end + end + + # @rbs (State original, ?State::lookahead_set lookaheads) -> State + def copy_split_state(original, lookaheads = original.item_lookahead_set.dup) + check_state_limit! if @max_states || @max_state_ratio + base = original.lalr_isocore + state = State.new(@states.size, base.accessing_symbol, base.kernels) + state.closure = base.closure + state.compute_transitions_and_reduces + original.transitions.each do |transition| + state.set_items_to_state(transition.to_items, transition.to_state) + end + @states << state + state.lalr_isocore = base + state.ielr_isocores = base.ielr_isocores + base.ielr_isocores << state + state.lookaheads_recomputed = true + state.item_lookahead_set = lookaheads + state + end + + # @rbs () -> void + def capture_pslr_metrics_before_split + @pslr_metrics = { + base_states_count: @states.count, + total_states_count: @states.count, + split_state_count: 0, + growth_count: 0, + growth_ratio: 1.0, + token_pattern_count: token_patterns.size, + scanner_fsa_state_count: 0, + inadequacies_count: 0 + } + end + # @rbs () -> void def compute_inadequacy_annotations @states.each do |state| @@ -793,7 +950,7 @@ def merge_lookaheads(state, filtered_lookaheads) # @rbs (State state, State::Action::Shift | State::Action::Goto transition, State next_state) -> void def compute_state(state, transition, next_state) - if next_state.lalr_isocore.annotation_list.empty? + if !@pslr_split_enabled && next_state.lalr_isocore.annotation_list.empty? unless next_state.lookaheads_recomputed next_state.lookaheads_recomputed = true sets = {} #: State::lookahead_set @@ -804,35 +961,129 @@ def compute_state(state, transition, next_state) return end - propagating_lookaheads = state.propagate_lookaheads(next_state) + filtered = state.propagate_lookaheads(next_state) + lookaheads = @pslr_split_enabled ? state.propagate_lookaheads(next_state, filter: false) : filtered # @type var incoming_contributions: State::dominant_contributions incoming_contributions = {} - s = next_state.ielr_isocores.find {|st| st.is_compatible?(propagating_lookaheads, incoming_contributions) } - - if s.nil? - s = next_state.lalr_isocore - new_state = State.new(@states.count, s.accessing_symbol, s.kernels) - new_state.closure = s.closure - new_state.compute_transitions_and_reduces - s.transitions.each do |transition| - new_state.set_items_to_state(transition.to_items, transition.to_state) - end - @states << new_state - new_state.lalr_isocore = s - s.ielr_isocores << new_state - s.ielr_isocores.each do |st| - st.ielr_isocores = s.ielr_isocores + isocore = next_state.ielr_isocores.find do |candidate| + if @pslr_split_enabled + compatible_split_state?(candidate, filtered, lookaheads) + else + candidate.is_compatible?(filtered, incoming_contributions) end - new_state.lookaheads_recomputed = true - new_state.item_lookahead_set = propagating_lookaheads - state.update_transition(transition, new_state) - elsif(!s.lookaheads_recomputed) - s.lookaheads_recomputed = true - s.item_lookahead_set = propagating_lookaheads + end + + if isocore.nil? + isocore = copy_split_state(next_state.lalr_isocore, lookaheads) + state.update_transition(transition, isocore) + elsif !isocore.lookaheads_recomputed + isocore.lookaheads_recomputed = true + isocore.item_lookahead_set = lookaheads else - merge_lookaheads(s, propagating_lookaheads) - state.update_transition(transition, s) if state.items_to_state[transition.to_items].id != s.id + merge_lookaheads(isocore, lookaheads) + state.update_transition(transition, isocore) unless state.items_to_state[transition.to_items].equal?(isocore) + end + end + + # @rbs (State state, State::lookahead_set filtered_lookaheads, ?State::lookahead_set pslr_lookaheads) -> bool + def compatible_split_state?(state, filtered_lookaheads, pslr_lookaheads = nil) + pslr_lookaheads ||= filtered_lookaheads + + return false unless state.is_compatible?(filtered_lookaheads) + return true unless @pslr_split_enabled && @scanner_fsa + return true unless state.lookaheads_recomputed + + pslr_compatible_successors?(state, state.item_lookahead_set, pslr_lookaheads) + end + + # Shared shift prefixes must preserve scanner decisions made after those shifts. + # @rbs (State state, State::lookahead_set left, State::lookahead_set right) -> bool + def pslr_compatible_successors?(state, left, right) + pending = [[state.lalr_isocore, left, right]] #: Array[[State, State::lookahead_set, State::lookahead_set]] + visited = Set.new #: Set[[Integer, State::lookahead_set, State::lookahead_set]] + + until pending.empty? + current, left, right = pending.pop + next if left == right || !visited.add?([current.id, left, right]) + + left_acc = acceptable_tokens_for_pslr(current, left) + right_acc = acceptable_tokens_for_pslr(current, right) + return false unless pslr_compatible_accept_sets?(left_acc, right_acc) + + current.transitions.each do |transition| + successor = transition.to_state.lalr_isocore + pending << [successor, current.propagate_lookaheads(successor, left, filter: false), current.propagate_lookaheads(successor, right, filter: false)] + end end + + true + end + + # Canonical LR(1) compatibility for %define pslr.tables canonical-lr: + # states merge only when their kernel lookahead sets are identical, + # so unresolved-conflict reports are not merged across contexts. + # @rbs (State state, State::lookahead_set filtered_lookaheads) -> bool + def canonical_lookaheads_match?(state, filtered_lookaheads) + return true unless state.lookaheads_recomputed + + state.item_lookahead_set == filtered_lookaheads + end + + # @rbs (State state, ?State::lookahead_set filtered_lookaheads) -> Array[[Integer, String?]] + def pslr_state_signature(state, filtered_lookaheads = nil) + return [] unless @scanner_fsa + + acc_sp = acceptable_tokens_for_pslr(state, filtered_lookaheads) + table, conflicts = State::ScannerAccepts.compute_for_acceptable_tokens( + @scanner_fsa, + lex_prec, + @length_precedences || LengthPrecedences.new(lex_prec), + acc_sp + ) + + signature = @scanner_fsa.states.each_with_object([]) do |fsa_state, result| + next unless fsa_state.accepting? + + result << [fsa_state.id, table[fsa_state.id]&.name] + end + + conflicts.each do |conflict| + signature << [ + :unresolved, + conflict.scanner_state_id, + conflict.shorter_tokens, + conflict.selected_shorter_token, + conflict.current_tokens + ] + end + + signature + end + + # @rbs (Set[String] left_acc, Set[String] right_acc) -> bool + def pslr_compatible_accept_sets?(left_acc, right_acc) + return true unless @scanner_fsa + + @pslr_compatibility_checker ||= State::ScannerAccepts::CompatibilityChecker.new( + @scanner_fsa, + lex_prec, + @length_precedences || LengthPrecedences.new(lex_prec) + ) + @pslr_compatibility_checker.compatible?(left_acc, right_acc) + end + + # @rbs (State state, ?State::lookahead_set filtered_lookaheads, ?expand_ties: bool, ?include_layout: bool) -> Set[String] + def acceptable_tokens_for_pslr(state, filtered_lookaheads = nil, expand_ties: true, include_layout: true) + tokens = State::ScannerAccepts.acceptable_tokens(state, symbols, filtered_lookaheads) + tokens = @grammar.expand_lexical_ties(tokens) if expand_ties + tokens | layout_token_names_for_pslr(include_layout: include_layout) + end + + # @rbs (?include_layout: bool) -> Set[String] + def layout_token_names_for_pslr(include_layout: true) + return Set.new unless include_layout + + @grammar.layout_token_names end # @rbs (Logger logger) -> void @@ -884,5 +1135,239 @@ def clear_look_ahead_sets @_follow_sets = nil @_la = nil end + + # Build Scanner FSA from token patterns + # @rbs () -> void + def build_scanner_fsa + @grammar.synthesize_implicit_literal_token_patterns! + @grammar.finalize_lexical_declarations! + return if token_patterns.empty? + + @scanner_fsa = ScannerFSA.new(token_patterns) + @grammar.finalize_lexical_ties!(@scanner_fsa) + @pslr_compatibility_checker = nil + end + + # Build length precedences table + # @rbs () -> void + def build_length_precedences + @length_precedences = LengthPrecedences.new(lex_prec) + end + + # Build scanner_accepts table + # @rbs () -> void + def build_scanner_accepts + return unless @scanner_fsa + + collect_lexical_tie_candidates + + @scanner_accepts_table = State::ScannerAccepts.new( + reachable_parser_states, + @scanner_fsa, + lex_prec, + @length_precedences, + lex_tie, + symbols: symbols, layout_token_names: @grammar.layout_token_names + ) + @scanner_accepts_table.build + end + + # Handle PSLR inadequacies + # Detects and splits states where pseudo-scanner behavior differs + # @rbs () -> void + def handle_pslr_inadequacies + return unless @scanner_fsa && @scanner_accepts_table + + @pslr_inadequacies = detect_pslr_inadequacies + return if @pslr_inadequacies.empty? + + @tracer.warn("Detected #{@pslr_inadequacies.size} unresolved PSLR inadequacies") if @tracer.respond_to?(:warn) + end + + # @rbs () -> void + def finalize_pslr_metrics + return unless pslr_defined? + + base_states_count = @pslr_metrics[:base_states_count] || @states.count + total_states_count = @states.count + + @pslr_metrics = { + base_states_count: base_states_count, + total_states_count: total_states_count, + split_state_count: @states.count(&:split_state?), + growth_count: total_states_count - base_states_count, + growth_ratio: base_states_count.zero? ? nil : total_states_count.to_f / base_states_count, + token_pattern_count: token_patterns.size, + scanner_fsa_state_count: @scanner_fsa ? @scanner_fsa.states.size : 0, + inadequacies_count: @pslr_inadequacies.size + } + end + + # Detect PSLR inadequacies in isocore groups + # @rbs () -> Array[State::PslrInadequacy] + def detect_pslr_inadequacies + inadequacies = [] + + @states.each do |state| + state.transitions.each do |transition| + next_state = transition.to_state + next unless next_state + + propagating_lookaheads = state.propagate_lookaheads(next_state.lalr_isocore, filter: false) + expected_acc = acceptable_tokens_for_pslr(next_state, propagating_lookaheads) + actual_acc = acceptable_tokens_for_pslr(next_state) + + next if pslr_compatible_accept_sets?(expected_acc, actual_acc) + + matching_state = next_state.ielr_isocores.find do |candidate| + pslr_compatible_accept_sets?(acceptable_tokens_for_pslr(candidate), expected_acc) + end + + inadequacies << State::PslrInadequacy.new( + type: State::PslrInadequacy::PSLR_RELATIVE, + state: next_state, + conflicting_states: [matching_state, next_state].compact.uniq, + details: { + reason: "Transition reaches a state with an incompatible PSLR scanner profile", + from_state_id: state.id, + transition_symbol: transition.next_sym.name, + expected_profile: pslr_state_signature(next_state, propagating_lookaheads), + actual_profile: pslr_state_signature(next_state), + matching_state_id: matching_state&.id + } + ) + end + end + + inadequacies + end + + # @rbs () -> void + def collect_lexical_tie_candidates + @lexical_tie_candidates = [] + return unless @scanner_fsa + + pairs = @scanner_fsa.pairwise_conflict_pairs + return if pairs.empty? + + candidates = Set.new + reachable_parser_states.each do |state| + pre_tie_tokens = acceptable_tokens_for_pslr(state, nil, expand_ties: false, include_layout: false) + pairs.each do |left, right| + next unless pre_tie_tokens.include?(left) ^ pre_tie_tokens.include?(right) + next if lex_tie.tied?(left, right) + next if lex_tie.no_tie?(left, right) + + candidates << [left, right] + end + end + + @lexical_tie_candidates = candidates.to_a.sort + end + + # @rbs () -> Array[State] + def reachable_parser_states + return [] if @states.empty? + + visited = Set.new + stack = [@states.first] + reachable = [] + + until stack.empty? + state = stack.pop + next if visited.include?(state.id) + + visited << state.id + reachable << state + state.transitions.each do |transition| + stack << transition.to_state if transition.to_state + end + end + + reachable.sort_by(&:id) + end + + # @rbs (Logger logger) -> void + def validate_pslr_inadequacies!(logger) + return unless pslr_defined? + return if @pslr_inadequacies.empty? + + @pslr_inadequacies.each do |inadequacy| + logger.error(inadequacy.to_s) + end + + exit false + end + + # @rbs (Logger logger) -> void + def validate_pslr_scanner_conflicts!(logger) + return unless pslr_defined? + return unless @scanner_accepts_table + return unless @scanner_accepts_table.unresolved_conflicts? + + @scanner_accepts_table.conflicts.each do |conflict| + logger.error(pslr_scanner_conflict_message(conflict)) + end + + exit false + end + + # @rbs (State::ScannerAccepts::Conflict conflict) -> String + def pslr_scanner_conflict_message(conflict) + state = conflict.parser_state_id || "unknown" + shorter = conflict.shorter_tokens.empty? ? "(none)" : conflict.shorter_tokens.join(", ") + selected = conflict.selected_shorter_token || "(none)" + current = conflict.current_tokens.empty? ? "(none)" : conflict.current_tokens.join(", ") + + "unresolved PSLR scanner conflict in state #{state}, scanner state #{conflict.scanner_state_id}: " \ + "shorter matches: #{shorter}; selected shorter token: #{selected}; " \ + "current matches: #{current}; add an explicit %lex-prec rule or adjust lexical ties" + end + + # @rbs () -> void + def check_state_limit! + count = @states.size + 1 + base = @pslr_metrics[:base_states_count] + if @max_states && count > @max_states + raise StateLimitExceeded, "PSLR state growth exceeded pslr.max-states=#{@max_states} (next state count=#{count})" + end + if @max_state_ratio && base && count.to_f / base > @max_state_ratio + raise StateLimitExceeded, "PSLR state growth exceeded pslr.max-state-ratio=#{@max_state_ratio} (next state count=#{count}, base=#{base})" + end + end + + # Report %lex-prec rules that were never used in scanner conflict resolution. + # @rbs (Logger logger) -> void + def validate_pslr_useless_lex_prec!(logger) + return unless pslr_defined? + return unless @scanner_accepts_table + + useless = lex_prec.useless_rules + return if useless.empty? + + useless.each do |rule| + operator_label = LengthPrecedences.operator_label(rule.operator) + logger.warn( + "useless %lex-prec rule at line #{rule.lineno}: " \ + "#{rule.left_name} #{operator_label} #{rule.right_name} " \ + "does not resolve any PSLR scanner conflict" + ) + end + end + + # Report lexical tie candidates that are not covered by %lex-tie or %lex-no-tie. + # @rbs (Logger logger) -> void + def validate_pslr_lexical_tie_candidates!(logger) + return unless pslr_defined? + return if @lexical_tie_candidates.empty? + + @lexical_tie_candidates.each do |left, right| + logger.warn( + "PSLR lexical tie candidate: #{left} and #{right} have scanner conflicts " \ + "but are not always accepted together. " \ + "Add %lex-tie #{left} #{right} or %lex-no-tie #{left} #{right}." + ) + end + end end end diff --git a/sig/generated/lrama/lexer_context_classifier.rbs b/sig/generated/lrama/lexer_context_classifier.rbs new file mode 100644 index 000000000..5a969237d --- /dev/null +++ b/sig/generated/lrama/lexer_context_classifier.rbs @@ -0,0 +1,78 @@ +# Generated from lib/lrama/lexer_context_classifier.rb with RBS::Inline + +module Lrama + # Classifies parser states into lexer context categories. + # + # When LALR states are merged, states from different grammatical contexts + # (e.g., BEG vs CMDARG) share the same state number, making them + # indistinguishable to the lexer. This classifier analyzes kernel items + # to determine the lexer context of each state, enabling context-aware + # state splitting. + # + # Context definitions come from %lexer-context directives in the grammar file. + # Each directive maps a context name to a set of symbols: + # + # %lexer-context BEG keyword_if keyword_unless '(' '[' '{' + # %lexer-context CMDARG tIDENTIFIER tFID tCONSTANT + class LexerContextClassifier + # @rbs (Hash[String, Grammar::LexerContext] lexer_contexts, ?Hash[String, Array[String]] expansion_args) -> void + def initialize: (Hash[String, Grammar::LexerContext] lexer_contexts, ?Hash[String, Array[String]] expansion_args) -> void + + # Classify a state's kernel items into context groups. + # + # @rbs (State state) -> Hash[Integer, Array[State::Item]] + def classify: (State state) -> Hash[Integer, Array[State::Item]] + + # Infer the lexer context for a single kernel item. + # + # @rbs (State::Item item) -> Integer + def infer_item_context: (State::Item item) -> Integer + + # Classify context based on the symbol before the dot. + # + # @rbs (Grammar::Symbol sym) -> Integer + def classify_symbol_context: (Grammar::Symbol sym) -> Integer + + # For backward compatibility with states.rb split logic + # @rbs (Grammar::Symbol sym) -> Integer + def classify_terminal_context: (Grammar::Symbol sym) -> Integer + + # For backward compatibility with states.rb split logic + # @rbs (Grammar::Symbol sym) -> Integer + def classify_nonterminal_context: (Grammar::Symbol sym) -> Integer + + # Return a human-readable name for a context value. + # + # @rbs (Integer ctx) -> String + def context_name: (Integer ctx) -> String + + # Class-level context_name for use without an instance (e.g., output.rb). + # Requires lexer_contexts to build the name map. + # + # @rbs (Integer ctx, Hash[String, Grammar::LexerContext] lexer_contexts) -> String + def self.context_name: (Integer ctx, Hash[String, Grammar::LexerContext] lexer_contexts) -> String + + # All context bitmasks OR'd together (for "is context known?" checks). + # @rbs () -> Integer + def all_contexts_mask: () -> Integer + + # Return the ordered list of context definitions. + # @rbs () -> Array[Grammar::LexerContext] + def contexts: () -> Array[Grammar::LexerContext] + + private + + # Build a map from symbol name → context bitmask. + # @rbs () -> Hash[String, Integer] + def build_symbol_to_context_map: () -> Hash[String, Integer] + + # Build a map from bitmask value → context name. + # @rbs () -> Hash[Integer, String] + def build_context_names: () -> Hash[Integer, String] + + # Return the bitmask for the first defined context (used as default for position-0 items). + # Returns 0 if no contexts are defined. + # @rbs () -> Integer + def default_beg_context: () -> Integer + end +end diff --git a/sig/generated/lrama/state.rbs b/sig/generated/lrama/state.rbs index 71f8eb7ef..8a7788c73 100644 --- a/sig/generated/lrama/state.rbs +++ b/sig/generated/lrama/state.rbs @@ -98,6 +98,8 @@ module Lrama attr_accessor goto_follows: Hash[Action::Goto, Bitmap::bitmap] + attr_accessor lexer_context: Integer? + # @rbs (Integer id, Grammar::Symbol accessing_symbol, Array[Item] kernels) -> void def initialize: (Integer id, Grammar::Symbol accessing_symbol, Array[Item] kernels) -> void @@ -122,6 +124,12 @@ module Lrama # @rbs (Grammar::Rule rule, Array[Grammar::Symbol] look_ahead) -> void def set_look_ahead: (Grammar::Rule rule, Array[Grammar::Symbol] look_ahead) -> void + # @rbs (Action::Reduce reduce, ?lookahead_set lookaheads) -> Bitmap::bitmap + def acceptable_pslr_reduce_lookahead: (Action::Reduce reduce, ?lookahead_set lookaheads) -> Bitmap::bitmap + + # @rbs (?lookahead_set? lookaheads) -> Array[Grammar::Symbol] + def pslr_error_tokens: (?lookahead_set? lookaheads) -> Array[Grammar::Symbol] + # @rbs (Grammar::Rule rule, Hash[Grammar::Symbol, Array[Action::Goto]] sources) -> void def set_look_ahead_sources: (Grammar::Rule rule, Hash[Grammar::Symbol, Array[Action::Goto]] sources) -> void @@ -189,8 +197,8 @@ module Lrama # Definition 3.40 (propagate_lookaheads) # - # @rbs (State next_state) -> lookahead_set - def propagate_lookaheads: (State next_state) -> lookahead_set + # @rbs (State next_state, ?lookahead_set? lookaheads, ?filter: bool) -> lookahead_set + def propagate_lookaheads: (State next_state, ?lookahead_set? lookaheads, ?filter: bool) -> lookahead_set # Definition 3.43 (is_compatible) # @@ -242,13 +250,16 @@ module Lrama # @rbs (Grammar::Rule rule, Integer position) -> Array[Item] def items_for_rule: (Grammar::Rule rule, Integer position) -> Array[Item] + # @rbs () -> void + def clear_predecessors: () -> void + # @rbs (State prev_state) -> void def append_predecessor: (State prev_state) -> void # Definition 3.39 (compute_goto_follow_set) # - # @rbs (Grammar::Symbol nterm_token) -> Bitmap::bitmap - def goto_follow_set: (Grammar::Symbol nterm_token) -> Bitmap::bitmap + # @rbs (Grammar::Symbol nterm_token, ?lookahead_set? lookaheads) -> Bitmap::bitmap + def goto_follow_set: (Grammar::Symbol nterm_token, ?lookahead_set? lookaheads) -> Bitmap::bitmap # Definition 3.8 (Goto Follows Internal Relation) # diff --git a/sig/generated/lrama/state/pslr_inadequacy.rbs b/sig/generated/lrama/state/pslr_inadequacy.rbs new file mode 100644 index 000000000..54c25cff6 --- /dev/null +++ b/sig/generated/lrama/state/pslr_inadequacy.rbs @@ -0,0 +1,52 @@ +# Generated from lib/lrama/state/pslr_inadequacy.rb with RBS::Inline + +module Lrama + class State + # PSLR Inadequacy detection + # Based on Section 3.4.3 from the PSLR dissertation + # + # PSLR inadequacy occurs when state merging causes different + # pseudo-scanner behavior + class PslrInadequacy + # Inadequacy types + LR_RELATIVE: Symbol + + PSLR_RELATIVE: Symbol + + attr_reader type: Symbol + + attr_reader state: State + + attr_reader conflicting_states: Array[State] + + attr_reader details: Hash[Symbol, untyped] + + # @rbs (type: Symbol, state: State, conflicting_states: Array[State], details: Hash[Symbol, untyped]) -> void + def initialize: (type: Symbol, state: State, conflicting_states: Array[State], details: Hash[Symbol, untyped]) -> void + + # @rbs () -> String + def to_s: () -> String + end + + # PSLR Compatibility checker + # Based on Definition 3.4.1 from the dissertation + class PslrCompatibilityChecker + # @rbs (ScannerAccepts scanner_accepts, LengthPrecedences length_prec) -> void + def initialize: (ScannerAccepts scanner_accepts, LengthPrecedences length_prec) -> void + + # Build a stable scanner profile for a parser state + # @rbs (State state, ScannerFSA scanner_fsa) -> Array[[Integer, String?]] + def profile: (State state, ScannerFSA scanner_fsa) -> Array[[ Integer, String? ]] + + # Partition states by scanner profile + # @rbs (Array[State] states, ScannerFSA scanner_fsa) -> Hash[Array[[Integer, String?]], Array[State]] + def group_by_profile: (Array[State] states, ScannerFSA scanner_fsa) -> Hash[Array[[ Integer, String? ]], Array[State]] + + # Check if two states are PSLR-compatible + # Definition 3.4.1: States are compatible if for any input, + # the pseudo-scanner selects the same token + # @rbs (State s1, State s2, ScannerFSA scanner_fsa) -> bool + def compatible?: (State s1, State s2, ScannerFSA scanner_fsa) -> bool + end + end +end diff --git a/sig/generated/lrama/state/scanner_accepts.rbs b/sig/generated/lrama/state/scanner_accepts.rbs new file mode 100644 index 000000000..39ce04a98 --- /dev/null +++ b/sig/generated/lrama/state/scanner_accepts.rbs @@ -0,0 +1,195 @@ +# Generated from lib/lrama/state/scanner_accepts.rb with RBS::Inline + +module Lrama + class State + # scanner_accepts[parser_state, accepting_scanner_state] for PSLR(1). + # + # Construction follows complete pseudo-scanner conflict profiles. A profile + # contains the shorter token set Ts, the selected shorter token ts, and the + # current/longest token set Tl. + # + # Normal parser-state rows are strict: unresolved pseudo-scanner + # conflicts are reported and are not resolved by token declaration order. + # + # The fallback row is used only for syntax-error handling. It first + # applies explicit PSLR lexical precedence declarations. For scanner + # conflicts that remain unresolved only in the fallback universe, it + # completes the decision with traditional scanner behavior: fallback + # length defaults are handled by LengthPrecedences#fallback_precedes?, + # and otherwise-unresolved identity conflicts are resolved by token + # declaration order. + # + # When %lex-scope declarations are present, each parser state may use + # a merged set of global + scope-active lexical precedence rules. + class ScannerAccepts + class Conflict + attr_reader parser_state_id: Integer? + + attr_reader scanner_state_id: Integer + + attr_reader shorter_tokens: Array[String] + + attr_reader selected_shorter_token: String? + + attr_reader current_tokens: Array[String] + + # @rbs (parser_state_id: Integer?, scanner_state_id: Integer, shorter_tokens: Array[String], selected_shorter_token: String?, current_tokens: Array[String]) -> void + def initialize: (parser_state_id: Integer?, scanner_state_id: Integer, shorter_tokens: Array[String], selected_shorter_token: String?, current_tokens: Array[String]) -> void + end + + class ProfileOutcome + EMPTY: Symbol + + RESOLVED: Symbol + + UNRESOLVED: Symbol + + attr_reader kind: Symbol + + attr_reader token_name: String? + + attr_reader conflict: Conflict? + + # @rbs (kind: Symbol, ?token_name: String?, ?conflict: Conflict?) -> void + def initialize: (kind: Symbol, ?token_name: String?, ?conflict: Conflict?) -> void + + # @rbs () -> bool + def empty?: () -> bool + + # @rbs () -> bool + def resolved?: () -> bool + + # @rbs () -> bool + def unresolved?: () -> bool + end + + class ProfileResolver + # @rbs (Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void + def initialize: (Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void + + # @rbs (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome + def resolve: (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome + + private + + # @rbs (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome + def resolve_normal: (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome + + # @rbs (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome + def resolve_fallback: (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome + + # @rbs (String old_token, String new_token) -> bool + def length_prefers_old?: (String old_token, String new_token) -> bool + + # @rbs (String old_token, String new_token) -> bool + def fallback_length_prefers_old?: (String old_token, String new_token) -> bool + + # @rbs (String candidate, Set[String] current_tokens) -> bool + def identity_winner?: (String candidate, Set[String] current_tokens) -> bool + + # @rbs (String candidate, Set[String] current_tokens) -> bool + def fallback_identity_winner?: (String candidate, Set[String] current_tokens) -> bool + + # @rbs (String candidate, String other) -> bool + def token_order_precedes?: (String candidate, String other) -> bool + + # @rbs (String token) -> [Integer, String] + def token_order_key: (String token) -> [ Integer, String ] + end + + class CompleteProfileComputer + attr_reader table: Hash[Integer, Grammar::TokenPattern] + + attr_reader conflicts: Array[Conflict] + + # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void + def initialize: (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void + + # @rbs () -> void + def compute: () -> void + + private + + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void + def visit_transitions: (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void + + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void + def visit_state: (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void + + # @rbs (ScannerFSA::State fsa_state) -> Set[String] + def current_acceptable_tokens: (ScannerFSA::State fsa_state) -> Set[String] + + # @rbs (String token_name) -> Grammar::TokenPattern + def token_pattern_for: (String token_name) -> Grammar::TokenPattern + + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> [Integer, Array[String], String?, Array[String]] + def profile_key: (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> [ Integer, Array[String], String?, Array[String] ] + end + + class CompatibilityChecker + # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec) -> void + def initialize: (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec) -> void + + # @rbs (Set[String] left_tokens, Set[String] right_tokens) -> bool + def compatible?: (Set[String] left_tokens, Set[String] right_tokens) -> bool + + private + + # @rbs (Integer fsa_state_id, Set[String] left_shorter, String? left_selected, Set[String] right_shorter, String? right_selected, Set[String] left_acc, Set[String] right_acc, Set[untyped] visited) -> bool + def visit_transitions: (Integer fsa_state_id, Set[String] left_shorter, String? left_selected, Set[String] right_shorter, String? right_selected, Set[String] left_acc, Set[String] right_acc, Set[untyped] visited) -> bool + + # @rbs (Integer fsa_state_id, Set[String] left_shorter, String? left_selected, Set[String] right_shorter, String? right_selected, Set[String] left_acc, Set[String] right_acc, Set[untyped] visited) -> bool + def visit_state: (Integer fsa_state_id, Set[String] left_shorter, String? left_selected, Set[String] right_shorter, String? right_selected, Set[String] left_acc, Set[String] right_acc, Set[untyped] visited) -> bool + + # @rbs (ScannerFSA::State fsa_state, Set[String] accepted_names) -> Set[String] + def tokens_accepted_by: (ScannerFSA::State fsa_state, Set[String] accepted_names) -> Set[String] + + # @rbs (ProfileOutcome left, ProfileOutcome right) -> bool + def outcomes_compatible?: (ProfileOutcome left, ProfileOutcome right) -> bool + end + + FALLBACK_ROW_ID: Integer + + attr_reader table: Hash[[ Integer, Integer ], Grammar::TokenPattern?] + + attr_reader fallback_table: Hash[Integer, Grammar::TokenPattern] + + attr_reader conflicts: Array[Conflict] + + # @rbs (Array[State] parser_states, ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?Grammar::LexTie? lex_tie, symbols: Array[Grammar::Symbol], ?layout_token_names: Set[String]) -> void + def initialize: (Array[State] parser_states, ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?Grammar::LexTie? lex_tie, symbols: Array[Grammar::Symbol], ?layout_token_names: Set[String]) -> void + + # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens) -> [Hash[Integer, Grammar::TokenPattern], Array[Conflict]] + def self.compute_for_acceptable_tokens: (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens) -> [ Hash[Integer, Grammar::TokenPattern], Array[Conflict] ] + + # @rbs (State state, Array[Grammar::Symbol] symbols, ?State::lookahead_set? lookaheads) -> Set[String] + def self.acceptable_tokens: (State state, Array[Grammar::Symbol] symbols, ?State::lookahead_set? lookaheads) -> Set[String] + + # @rbs () -> void + def build: () -> void + + # @rbs (Integer parser_state_id, Integer accepting_state_id) -> Grammar::TokenPattern? + def []: (Integer parser_state_id, Integer accepting_state_id) -> Grammar::TokenPattern? + + # @rbs () -> bool + def unresolved_conflicts?: () -> bool + + private + + # @rbs (State parser_state) -> void + def compute_for_parser_state: (State parser_state) -> void + + # @rbs () -> void + def compute_fallback_row: () -> void + + # @rbs (State parser_state) -> Set[String] + def compute_acc_sp: (State parser_state) -> Set[String] + + # @rbs (Set[String] tokens) -> Set[String] + def expand_lexical_ties: (Set[String] tokens) -> Set[String] + + # @rbs () -> Hash[String, Integer] + def token_order: () -> Hash[String, Integer] + end + end +end diff --git a/sig/generated/lrama/states.rbs b/sig/generated/lrama/states.rbs index 26c5c6b10..725d37ed4 100644 --- a/sig/generated/lrama/states.rbs +++ b/sig/generated/lrama/states.rbs @@ -6,6 +6,9 @@ module Lrama # "Efficient Computation of LALR(1) Look-Ahead Sets" # https://dl.acm.org/doi/pdf/10.1145/69622.357187 class States + class StateLimitExceeded < StandardError + end + type state_id = Integer type rule_id = Integer @@ -38,6 +41,14 @@ module Lrama @initial_items: Hash[Grammar::Rule, State::Item] + @max_states: Integer? + + @max_state_ratio: Float? + + @pslr_split_enabled: bool? + + @pslr_compatibility_checker: State::ScannerAccepts::CompatibilityChecker? + extend Forwardable include Lrama::Tracer::Duration @@ -50,6 +61,20 @@ module Lrama attr_reader lookback_relation: Hash[state_id, Hash[rule_id, Array[State::Action::Goto]]] + attr_reader scanner_fsa: ScannerFSA? + + attr_reader length_precedences: LengthPrecedences? + + attr_reader scanner_accepts_table: State::ScannerAccepts? + + attr_reader pslr_inadequacies: Array[State::PslrInadequacy] + + attr_reader pslr_metrics: Hash[Symbol, Integer | Float | nil] + + attr_reader lexer_context_classifier: LexerContextClassifier? + + attr_reader lexical_tie_candidates: Array[[ String, String ]] + # @rbs (Grammar grammar, Tracer tracer) -> void def initialize: (Grammar grammar, Tracer tracer) -> void @@ -59,6 +84,11 @@ module Lrama # @rbs () -> void def compute_ielr: () -> void + # Compute PSLR(1) states + # Based on Section 3.4 of the PSLR dissertation + # @rbs () -> void + def compute_pslr: () -> void + # @rbs () -> Integer def states_count: () -> Integer @@ -83,6 +113,17 @@ module Lrama # @rbs (Logger logger) -> void def validate!: (Logger logger) -> void + # Return the lexer context table as an array of context values, + # one per parser state (indexed by state id). + # + # @rbs () -> Array[Integer] + def lexer_context_table: () -> Array[Integer] + + # Check if lexer context classification has been performed. + # + # @rbs () -> bool + def lexer_context_enabled?: () -> bool + def compute_la_sources_for_conflicted_states: () -> untyped private @@ -182,6 +223,17 @@ module Lrama # @rbs () -> void def split_states: () -> void + # Traverse pairs of parser state and lexer context. Reusing each pair also + # closes cycles through symbols without a declared context. + # @rbs () -> void + def split_states_by_context: () -> void + + # @rbs (State original, ?State::lookahead_set lookaheads) -> State + def copy_split_state: (State original, ?State::lookahead_set lookaheads) -> State + + # @rbs () -> void + def capture_pslr_metrics_before_split: () -> void + # @rbs () -> void def compute_inadequacy_annotations: () -> void @@ -191,6 +243,31 @@ module Lrama # @rbs (State state, State::Action::Shift | State::Action::Goto transition, State next_state) -> void def compute_state: (State state, State::Action::Shift | State::Action::Goto transition, State next_state) -> void + # @rbs (State state, State::lookahead_set filtered_lookaheads, ?State::lookahead_set pslr_lookaheads) -> bool + def compatible_split_state?: (State state, State::lookahead_set filtered_lookaheads, ?State::lookahead_set pslr_lookaheads) -> bool + + # Shared shift prefixes must preserve scanner decisions made after those shifts. + # @rbs (State state, State::lookahead_set left, State::lookahead_set right) -> bool + def pslr_compatible_successors?: (State state, State::lookahead_set left, State::lookahead_set right) -> bool + + # Canonical LR(1) compatibility for %define pslr.tables canonical-lr: + # states merge only when their kernel lookahead sets are identical, + # so unresolved-conflict reports are not merged across contexts. + # @rbs (State state, State::lookahead_set filtered_lookaheads) -> bool + def canonical_lookaheads_match?: (State state, State::lookahead_set filtered_lookaheads) -> bool + + # @rbs (State state, ?State::lookahead_set filtered_lookaheads) -> Array[[Integer, String?]] + def pslr_state_signature: (State state, ?State::lookahead_set filtered_lookaheads) -> Array[[ Integer, String? ]] + + # @rbs (Set[String] left_acc, Set[String] right_acc) -> bool + def pslr_compatible_accept_sets?: (Set[String] left_acc, Set[String] right_acc) -> bool + + # @rbs (State state, ?State::lookahead_set filtered_lookaheads, ?expand_ties: bool, ?include_layout: bool) -> Set[String] + def acceptable_tokens_for_pslr: (State state, ?State::lookahead_set filtered_lookaheads, ?expand_ties: bool, ?include_layout: bool) -> Set[String] + + # @rbs (?include_layout: bool) -> Set[String] + def layout_token_names_for_pslr: (?include_layout: bool) -> Set[String] + # @rbs (Logger logger) -> void def validate_conflicts_within_threshold!: (Logger logger) -> void @@ -205,5 +282,55 @@ module Lrama # @rbs () -> void def clear_look_ahead_sets: () -> void + + # Build Scanner FSA from token patterns + # @rbs () -> void + def build_scanner_fsa: () -> void + + # Build length precedences table + # @rbs () -> void + def build_length_precedences: () -> void + + # Build scanner_accepts table + # @rbs () -> void + def build_scanner_accepts: () -> void + + # Handle PSLR inadequacies + # Detects and splits states where pseudo-scanner behavior differs + # @rbs () -> void + def handle_pslr_inadequacies: () -> void + + # @rbs () -> void + def finalize_pslr_metrics: () -> void + + # Detect PSLR inadequacies in isocore groups + # @rbs () -> Array[State::PslrInadequacy] + def detect_pslr_inadequacies: () -> Array[State::PslrInadequacy] + + # @rbs () -> void + def collect_lexical_tie_candidates: () -> void + + # @rbs () -> Array[State] + def reachable_parser_states: () -> Array[State] + + # @rbs (Logger logger) -> void + def validate_pslr_inadequacies!: (Logger logger) -> void + + # @rbs (Logger logger) -> void + def validate_pslr_scanner_conflicts!: (Logger logger) -> void + + # @rbs (State::ScannerAccepts::Conflict conflict) -> String + def pslr_scanner_conflict_message: (State::ScannerAccepts::Conflict conflict) -> String + + # @rbs () -> void + def check_state_limit!: () -> void + + # Report %lex-prec rules that were never used in scanner conflict resolution. + # @rbs (Logger logger) -> void + def validate_pslr_useless_lex_prec!: (Logger logger) -> void + + # Report lexical tie candidates that are not covered by %lex-tie or %lex-no-tie. + # @rbs (Logger logger) -> void + def validate_pslr_lexical_tie_candidates!: (Logger logger) -> void end end diff --git a/spec/lrama/lexer_context_classifier_spec.rb b/spec/lrama/lexer_context_classifier_spec.rb new file mode 100644 index 000000000..0ad703ca1 --- /dev/null +++ b/spec/lrama/lexer_context_classifier_spec.rb @@ -0,0 +1,457 @@ +# frozen_string_literal: true + +RSpec.describe Lrama::LexerContextClassifier do + include PslrFamilyHelper + + # Helper to build a classifier with standard CRuby-like contexts + def build_classifier_with_contexts + lexer_contexts = {} + [ + ["BEG", %w[keyword_if keyword_unless keyword_while keyword_do tPLUS tMINUS tLPAREN tLBRACK tLBRACE]], + ["CMDARG", %w[tIDENTIFIER tFID tCONSTANT]], + ["END", %w[tINTEGER tFLOAT tSTRING_END keyword_end tRPAREN tRBRACK tRBRACE]], + ["ENDFN", %w[keyword_def]], + ["DOT", %w[tDOT tCOLON2 tANDDOT]], + ].each_with_index do |(name, syms), idx| + lc = Lrama::Grammar::LexerContext.new(name: name, index: idx) + syms.each do |s| + lc.add_symbols([double("token", s_value: s)]) + end + lexer_contexts[name] = lc + end + described_class.new(lexer_contexts) + end + + describe "context bitmask assignment" do + it "assigns non-overlapping bitmask flags by definition order" do + classifier = build_classifier_with_contexts + bitmasks = classifier.contexts.map(&:bitmask) + + # All bitmasks should be powers of 2 + bitmasks.each do |bm| + expect(bm).to be > 0 + expect(bm & (bm - 1)).to eq(0), "#{bm} is not a power of 2" + end + + # No two should overlap + bitmasks.combination(2).each do |a, b| + expect(a & b).to eq(0), "Bitmasks #{a} and #{b} overlap" + end + end + end + + describe ".context_name" do + let(:lexer_contexts) do + lcs = {} + lc = Lrama::Grammar::LexerContext.new(name: "BEG", index: 0) + lcs["BEG"] = lc + lc2 = Lrama::Grammar::LexerContext.new(name: "CMDARG", index: 1) + lcs["CMDARG"] = lc2 + lcs + end + + it "returns UNKNOWN for 0" do + expect(described_class.context_name(0, lexer_contexts)).to eq("UNKNOWN") + end + + it "returns single context name for single flag" do + expect(described_class.context_name(0x01, lexer_contexts)).to eq("BEG") + expect(described_class.context_name(0x02, lexer_contexts)).to eq("CMDARG") + end + + it "returns combined name for multiple flags" do + name = described_class.context_name(0x01 | 0x02, lexer_contexts) + expect(name).to include("BEG") + expect(name).to include("CMDARG") + end + end + + describe "#classify_symbol_context" do + let(:classifier) { build_classifier_with_contexts } + + it "classifies operator-like terminals" do + %w[tPLUS tMINUS].each do |name| + sym = double("symbol", id: double("id", s_value: name), term?: true) + ctx = classifier.classify_symbol_context(sym) + # BEG = 1 << 0 = 0x01 + expect(ctx).to eq(0x01), "Expected #{name} to be BEG" + end + end + + it "classifies identifier terminals as CMDARG" do + %w[tIDENTIFIER tFID tCONSTANT].each do |name| + sym = double("symbol", id: double("id", s_value: name), term?: true) + ctx = classifier.classify_symbol_context(sym) + # CMDARG = 1 << 1 = 0x02 + expect(ctx).to eq(0x02), "Expected #{name} to be CMDARG" + end + end + + it "classifies literal terminals as END" do + %w[tINTEGER tFLOAT tSTRING_END].each do |name| + sym = double("symbol", id: double("id", s_value: name), term?: true) + ctx = classifier.classify_symbol_context(sym) + # END = 1 << 2 = 0x04 + expect(ctx).to eq(0x04), "Expected #{name} to be END" + end + end + + it "classifies keyword_def as ENDFN" do + sym = double("symbol", id: double("id", s_value: "keyword_def"), term?: true) + ctx = classifier.classify_symbol_context(sym) + # ENDFN = 1 << 3 = 0x08 + expect(ctx).to eq(0x08) + end + + it "classifies dot tokens as DOT" do + %w[tDOT tCOLON2 tANDDOT].each do |name| + sym = double("symbol", id: double("id", s_value: name), term?: true) + ctx = classifier.classify_symbol_context(sym) + # DOT = 1 << 4 = 0x10 + expect(ctx).to eq(0x10), "Expected #{name} to be DOT" + end + end + + it "classifies open brackets as BEG" do + %w[tLPAREN tLBRACK tLBRACE].each do |name| + sym = double("symbol", id: double("id", s_value: name), term?: true) + ctx = classifier.classify_symbol_context(sym) + expect(ctx).to eq(0x01), "Expected #{name} to be BEG" + end + end + + it "classifies close brackets as END" do + %w[tRPAREN tRBRACK tRBRACE].each do |name| + sym = double("symbol", id: double("id", s_value: name), term?: true) + ctx = classifier.classify_symbol_context(sym) + expect(ctx).to eq(0x04), "Expected #{name} to be END" + end + end + + it "returns 0 for unknown symbols" do + sym = double("symbol", id: double("id", s_value: "unknown_token"), term?: true) + ctx = classifier.classify_symbol_context(sym) + expect(ctx).to eq(0) + end + end + + describe "#classify with grammar-defined contexts" do + context "with %lexer-context directives" do + let(:grammar) do + build_grammar(<<~GRAMMAR, "lexer_context/basic.y") + %define lr.type pslr + %token-pattern IF /if/ + %token-pattern ID /[a-z]+/ + %lex-prec ID <~ IF + + %lexer-context BEG IF + %lexer-context CMDARG ID + + %% + + program + : expr + ; + + expr + : ID + | expr '+' expr + ; + GRAMMAR + end + + it "classifies states without errors" do + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + + states.states.each do |state| + expect(state.lexer_context).not_to be_nil + end + end + end + + context "with operator-heavy grammar" do + let(:grammar) do + build_grammar(<<~GRAMMAR, "lexer_context/operators.y") + %define lr.type pslr + %token-pattern PLUS /\\+/ + %token-pattern STAR /\\*/ + %token-pattern ID /[a-z]+/ + %token-pattern NUM /[0-9]+/ + + %lexer-context BEG PLUS STAR + %lexer-context CMDARG ID + %lexer-context END NUM + + %% + + program + : expr + ; + + expr + : NUM + | ID + | expr PLUS expr + | expr STAR expr + ; + GRAMMAR + end + + it "classifies all states" do + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + + states.states.each do |state| + expect(state.lexer_context).not_to be_nil + end + end + end + end + + describe "integration with States" do + context "lexer_context_enabled?" do + it "returns false when no %lexer-context directives" do + grammar = build_grammar(<<~GRAMMAR, "lexer_context/no_ctx.y") + %define lr.type pslr + %token-pattern ID /[a-z]+/ + + %% + + program : ID ; + GRAMMAR + + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + + expect(states.lexer_context_enabled?).to eq(false) + end + + it "returns true when %lexer-context directives are present" do + grammar = build_grammar(<<~GRAMMAR, "lexer_context/with_ctx.y") + %define lr.type pslr + %token-pattern ID /[a-z]+/ + + %lexer-context BEG ID + + %% + + program : ID ; + GRAMMAR + + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + + expect(states.lexer_context_enabled?).to eq(true) + end + end + + context "lexer_context_table" do + it "returns an array with one entry per state" do + grammar = build_grammar(<<~GRAMMAR, "lexer_context/table.y") + %define lr.type pslr + %token-pattern ID /[a-z]+/ + %token-pattern NUM /[0-9]+/ + + %lexer-context BEG ID + %lexer-context END NUM + + %% + + program + : expr + ; + + expr + : NUM + | ID + | expr '+' expr + ; + GRAMMAR + + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + + table = states.lexer_context_table + expect(table.size).to eq(states.states_count) + expect(table.all? { |v| v.is_a?(Integer) }).to eq(true) + end + end + end + + describe "context-based state splitting" do + context "with operator vs identifier predecessor contexts" do + let(:grammar) do + build_grammar(<<~GRAMMAR, "lexer_context/split_expr.y") + %define lr.type pslr + %token-pattern tPLUS /\\+/ + %token-pattern tSTAR /\\*/ + %token-pattern tIDENTIFIER /[a-z]+/ + %token-pattern tINTEGER /[0-9]+/ + + %lexer-context BEG tPLUS tSTAR + %lexer-context CMDARG tIDENTIFIER + %lexer-context END tINTEGER + + %% + + program + : expr + ; + + expr + : tINTEGER + | tIDENTIFIER + | expr tPLUS expr + | expr tSTAR expr + ; + GRAMMAR + end + + it "classifies all states with non-nil context" do + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + + states.states.each do |state| + expect(state.lexer_context).not_to be_nil, + "State #{state.id} has nil lexer_context" + end + end + + it "has BEG context after operators" do + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + + # Find states after tPLUS or tSTAR + operator_target_states = [] + states.states.each do |state| + state.term_transitions.each do |shift| + name = shift.next_sym.id.s_value + if name == "tPLUS" || name == "tSTAR" + operator_target_states << shift.to_state + end + end + end + + lexer_contexts = grammar.lexer_contexts + beg_mask = lexer_contexts["BEG"].bitmask + + operator_target_states.each do |target| + ctx = target.lexer_context || 0 + ctx_name = described_class.context_name(ctx, lexer_contexts) + expect(ctx & beg_mask).not_to eq(0), + "State #{target.id} after operator should have BEG context, got #{ctx_name}" + end + end + end + + context "with def keyword creating ENDFN context" do + let(:grammar) do + build_grammar(<<~GRAMMAR, "lexer_context/endfn.y") + %define lr.type pslr + %token-pattern keyword_def /def/ + %token-pattern keyword_end /end/ + %token-pattern tIDENTIFIER /[a-z]+/ + %token-pattern tINTEGER /[0-9]+/ + + %lexer-context ENDFN keyword_def + %lexer-context END keyword_end tINTEGER + %lexer-context CMDARG tIDENTIFIER + + %% + + program + : defn + ; + + defn + : keyword_def tIDENTIFIER keyword_end + ; + GRAMMAR + end + + it "marks state after keyword_def as ENDFN" do + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + + lexer_contexts = grammar.lexer_contexts + endfn_mask = lexer_contexts["ENDFN"].bitmask + + # Find state reached after keyword_def + def_target = nil + states.states.each do |state| + state.term_transitions.each do |shift| + if shift.next_sym.id.s_value == "keyword_def" + def_target = shift.to_state + end + end + end + + expect(def_target).not_to be_nil + ctx = def_target.lexer_context || 0 + ctx_name = described_class.context_name(ctx, lexer_contexts) + expect(ctx & endfn_mask).not_to eq(0), + "State after keyword_def should have ENDFN context, got #{ctx_name}" + end + end + end + + describe "existing PSLR tests still pass" do + context "pure reduce profile" do + let(:grammar) do + build_grammar(<<~GRAMMAR, "states/pslr_pure_reduce.y") + %define lr.type pslr + %token-pattern RSHIFT />>/ + %token-pattern RANGLE />/ + %token-pattern ID /[a-z]+/ + %lex-prec RANGLE -~ RSHIFT + + %% + + program + : templ + | rshift_expr + ; + + templ + : a RANGLE + ; + + rshift_expr + : a RSHIFT ID + ; + + a + : ID + ; + GRAMMAR + end + + it "does not break PSLR" do + _, pslr_states = compute_ielr_and_pslr(grammar) + expect(pslr_states.pslr_inadequacies).to be_empty + end + end + + context "chained keyword split" do + let(:grammar) do + build_grammar(keyword_context_source(depth: 2), "states/pslr_keyword_ctx.y") + end + + it "does not break PSLR split" do + ielr_states, pslr_states = compute_ielr_and_pslr(grammar) + + expect(pslr_states.states_count).to be > ielr_states.states_count + expect(pslr_states.pslr_inadequacies).to be_empty + end + end + end +end diff --git a/spec/lrama/state/pslr_inadequacy_spec.rb b/spec/lrama/state/pslr_inadequacy_spec.rb new file mode 100644 index 000000000..cef7a5d62 --- /dev/null +++ b/spec/lrama/state/pslr_inadequacy_spec.rb @@ -0,0 +1,234 @@ +# frozen_string_literal: true + +RSpec.describe Lrama::State::PslrInadequacy do + let(:mock_state) do + instance_double(Lrama::State, id: 0) + end + + let(:mock_conflicting_states) do + [ + instance_double(Lrama::State, id: 1), + instance_double(Lrama::State, id: 2) + ] + end + + describe "#initialize" do + it "creates an LR-relative inadequacy" do + inadequacy = Lrama::State::PslrInadequacy.new( + type: Lrama::State::PslrInadequacy::LR_RELATIVE, + state: mock_state, + conflicting_states: mock_conflicting_states, + details: { reason: "test" } + ) + + expect(inadequacy.type).to eq(:lr_relative) + expect(inadequacy.state).to eq(mock_state) + expect(inadequacy.conflicting_states).to eq(mock_conflicting_states) + expect(inadequacy.details[:reason]).to eq("test") + end + + it "creates a PSLR-relative inadequacy" do + inadequacy = Lrama::State::PslrInadequacy.new( + type: Lrama::State::PslrInadequacy::PSLR_RELATIVE, + state: mock_state, + conflicting_states: mock_conflicting_states, + details: {} + ) + + expect(inadequacy.type).to eq(:pslr_relative) + end + end + + describe "#to_s" do + it "returns a human-readable description" do + inadequacy = Lrama::State::PslrInadequacy.new( + type: Lrama::State::PslrInadequacy::PSLR_RELATIVE, + state: mock_state, + conflicting_states: mock_conflicting_states, + details: {} + ) + + expect(inadequacy.to_s).to include("PSLR Inadequacy") + expect(inadequacy.to_s).to include("pslr_relative") + expect(inadequacy.to_s).to include("state 0") + expect(inadequacy.to_s).to include("1, 2") + end + end + + describe "constants" do + it "defines LR_RELATIVE constant" do + expect(Lrama::State::PslrInadequacy::LR_RELATIVE).to eq(:lr_relative) + end + + it "defines PSLR_RELATIVE constant" do + expect(Lrama::State::PslrInadequacy::PSLR_RELATIVE).to eq(:pslr_relative) + end + end +end + +RSpec.describe Lrama::State::PslrCompatibilityChecker do + let(:rangle) do + id = Lrama::Lexer::Token::Ident.new(s_value: "RANGLE") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/>/") + Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + end + + let(:rshift) do + id = Lrama::Lexer::Token::Ident.new(s_value: "RSHIFT") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/>>/") + Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 1 + ) + end + + let(:scanner_fsa) { Lrama::ScannerFSA.new([rangle, rshift]) } + let(:lex_prec) { Lrama::Grammar::LexPrec.new } + let(:length_prec) { Lrama::LengthPrecedences.new(lex_prec) } + let(:accepting_state_ids) { scanner_fsa.states.select(&:accepting?).map(&:id) } + let(:short_state_id) { accepting_state_ids.min } + let(:long_state_id) { accepting_state_ids.max } + + describe "#initialize" do + it "creates a compatibility checker" do + scanner_accepts = instance_double(Lrama::State::ScannerAccepts) + checker = Lrama::State::PslrCompatibilityChecker.new( + scanner_accepts, + length_prec + ) + + expect(checker).to be_a(Lrama::State::PslrCompatibilityChecker) + end + end + + describe "#compatible?" do + context "when both states select same tokens" do + it "returns true" do + scanner_accepts = instance_double(Lrama::State::ScannerAccepts) + allow(scanner_accepts).to receive(:[]).and_return(rangle) + + checker = Lrama::State::PslrCompatibilityChecker.new( + scanner_accepts, + length_prec + ) + + state1 = instance_double(Lrama::State, id: 0) + state2 = instance_double(Lrama::State, id: 1) + + expect(checker.compatible?(state1, state2, scanner_fsa)).to be true + end + end + + context "when both states have no tokens (nil)" do + it "returns true" do + scanner_accepts = instance_double(Lrama::State::ScannerAccepts) + allow(scanner_accepts).to receive(:[]).and_return(nil) + + checker = Lrama::State::PslrCompatibilityChecker.new( + scanner_accepts, + length_prec + ) + + state1 = instance_double(Lrama::State, id: 0) + state2 = instance_double(Lrama::State, id: 1) + + expect(checker.compatible?(state1, state2, scanner_fsa)).to be true + end + end + + context "when states select different tokens" do + it "returns false" do + scanner_accepts = instance_double(Lrama::State::ScannerAccepts) + + # State 0 selects RANGLE, State 1 selects RSHIFT + allow(scanner_accepts).to receive(:[]) do |state_id, _fsa_state_id| + if state_id == 0 + rangle + else + rshift + end + end + + checker = Lrama::State::PslrCompatibilityChecker.new( + scanner_accepts, + length_prec + ) + + state1 = instance_double(Lrama::State, id: 0) + state2 = instance_double(Lrama::State, id: 1) + + expect(checker.compatible?(state1, state2, scanner_fsa)).to be false + end + end + end + + describe "#profile" do + it "returns a stable accepting-state profile" do + scanner_accepts = instance_double(Lrama::State::ScannerAccepts) + allow(scanner_accepts).to receive(:[]) do |state_id, fsa_state_id| + if state_id == 0 + fsa_state_id == short_state_id ? rangle : rshift + else + fsa_state_id == short_state_id ? rangle : nil + end + end + + checker = Lrama::State::PslrCompatibilityChecker.new( + scanner_accepts, + length_prec + ) + + state = instance_double(Lrama::State, id: 0) + + expect(checker.profile(state, scanner_fsa)).to eq([ + [short_state_id, "RANGLE"], + [long_state_id, "RSHIFT"], + ]) + end + end + + describe "#group_by_profile" do + it "partitions states by scanner behavior" do + scanner_accepts = instance_double(Lrama::State::ScannerAccepts) + allow(scanner_accepts).to receive(:[]) do |state_id, fsa_state_id| + case [state_id, fsa_state_id] + when [0, short_state_id], [1, short_state_id] + rangle + when [0, long_state_id] + rshift + when [1, long_state_id] + nil + when [2, short_state_id] + rshift + when [2, long_state_id] + rshift + end + end + + checker = Lrama::State::PslrCompatibilityChecker.new( + scanner_accepts, + length_prec + ) + + state1 = instance_double(Lrama::State, id: 0) + state2 = instance_double(Lrama::State, id: 1) + state3 = instance_double(Lrama::State, id: 2) + + grouped = checker.group_by_profile([state1, state2, state3], scanner_fsa) + + expect(grouped.values.map(&:size)).to contain_exactly(1, 1, 1) + expect(grouped.keys).to include( + [[short_state_id, "RANGLE"], [long_state_id, "RSHIFT"]], + [[short_state_id, "RANGLE"], [long_state_id, nil]], + [[short_state_id, "RSHIFT"], [long_state_id, "RSHIFT"]], + ) + end + end +end diff --git a/spec/lrama/state/scanner_accepts_spec.rb b/spec/lrama/state/scanner_accepts_spec.rb new file mode 100644 index 000000000..5bb38ebfb --- /dev/null +++ b/spec/lrama/state/scanner_accepts_spec.rb @@ -0,0 +1,406 @@ +# frozen_string_literal: true + +RSpec.describe Lrama::State::ScannerAccepts do + def ident(name) + Lrama::Lexer::Token::Ident.new(s_value: name) + end + + def token_pattern(name, regex, order) + Lrama::Grammar::TokenPattern.new( + id: ident(name), + pattern: Lrama::Lexer::Token::Regex.new(s_value: "/#{regex}/"), + lineno: 1, + definition_order: order + ) + end + + def shift_for(name) + symbol = instance_double( + Lrama::Grammar::Symbol, + term?: true, + name: name + ) + instance_double(Lrama::State::Action::Shift, next_sym: symbol) + end + + def parser_state(id, token_names) + instance_double( + Lrama::State, + id: id, + term_transitions: token_names.map {|name| shift_for(name) }, + pslr_error_tokens: [], + reduces: [] + ) + end + + describe "#build and #[]" do + let(:rangle) { token_pattern("RANGLE", ">", 0) } + let(:rshift) { token_pattern("RSHIFT", ">>", 1) } + let(:scanner_fsa) { Lrama::ScannerFSA.new([rangle, rshift]) } + let(:lex_prec) { Lrama::Grammar::LexPrec.new } + let(:length_prec) { Lrama::LengthPrecedences.new(lex_prec) } + + it "builds scanner_accepts from parser acceptable tokens" do + state = parser_state(0, ["RANGLE"]) + scanner_accepts = Lrama::State::ScannerAccepts.new( + [state], + scanner_fsa, + lex_prec, + length_prec, + symbols: [] + ) + + scanner_accepts.build + + accepting = scanner_fsa.states.find {|s| s.accepting_tokens.map(&:name).include?("RANGLE") } + expect(scanner_accepts[0, accepting.id].name).to eq("RANGLE") + end + + it "includes layout tokens in every parser-state accept set" do + div = token_pattern("DIV", "/", 0) + layout = token_pattern("YYLAYOUT_WS", "[ \\t]+", 1) + scanner_fsa = Lrama::ScannerFSA.new([div, layout]) + state = parser_state(0, ["DIV"]) + scanner_accepts = Lrama::State::ScannerAccepts.new( + [state], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + layout_token_names: Set["YYLAYOUT_WS"], + symbols: [] + ) + + scanner_accepts.build + + accepting = scanner_fsa.states.find {|s| s.accepting_tokens.map(&:name).include?("YYLAYOUT_WS") } + expect(scanner_accepts[0, accepting.id].name).to eq("YYLAYOUT_WS") + end + end + + describe "complete conflict resolution" do + it "does not use declaration order for unresolved identity conflicts" do + tokens = [ + token_pattern("A", "a", 0), + token_pattern("B", "a", 1), + token_pattern("C", "a", 2) + ] + scanner_fsa = Lrama::ScannerFSA.new(tokens) + lex_prec = Lrama::Grammar::LexPrec.new + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, ["A", "B", "C"])], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + symbols: [] + ) + + scanner_accepts.build + + expect(scanner_accepts.unresolved_conflicts?).to be true + parser_rows = scanner_accepts.table.reject do |(parser_state_id, _scanner_state_id), _token| + parser_state_id == Lrama::State::ScannerAccepts::FALLBACK_ROW_ID + end + expect(parser_rows).to be_empty + expect(scanner_accepts.fallback_table.values.map(&:name)).to contain_exactly("A") + end + + it "selects a unique explicitly declared identity winner" do + tokens = [ + token_pattern("A", "a", 0), + token_pattern("B", "a", 1), + token_pattern("C", "a", 2) + ] + scanner_fsa = Lrama::ScannerFSA.new(tokens) + lex_prec = Lrama::Grammar::LexPrec.new + lex_prec.add_rule(left_token: ident("A"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("C"), lineno: 1) + lex_prec.add_rule(left_token: ident("B"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("C"), lineno: 1) + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, ["A", "B", "C"])], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + symbols: [] + ) + + scanner_accepts.build + + accepting = scanner_fsa.states.find(&:accepting?) + expect(scanner_accepts[0, accepting.id].name).to eq("C") + expect(scanner_accepts.unresolved_conflicts?).to be false + end + + it "keeps conflicts finite for looped scanner states" do + id = token_pattern("ID", "[a-z]+", 0) + kw = token_pattern("IF", "if", 1) + scanner_fsa = Lrama::ScannerFSA.new([id, kw]) + lex_prec = Lrama::Grammar::LexPrec.new + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, ["ID", "IF"])], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + symbols: [] + ) + + scanner_accepts.build + + expect(scanner_accepts.conflicts.size).to be < 10 + end + + it "keeps an empty outcome distinct from an unresolved conflict" do + resolver = Lrama::State::ScannerAccepts::ProfileResolver.new( + Lrama::Grammar::LexPrec.new, + Lrama::LengthPrecedences.new(Lrama::Grammar::LexPrec.new) + ) + + outcome = resolver.resolve(Set.new, nil, Set.new) + + expect(outcome).to be_empty + expect(outcome).not_to be_unresolved + end + + it "uses same-token autolength without fallback mode" do + resolver = Lrama::State::ScannerAccepts::ProfileResolver.new( + Lrama::Grammar::LexPrec.new, + Lrama::LengthPrecedences.new(Lrama::Grammar::LexPrec.new) + ) + + outcome = resolver.resolve(Set["ID"], "ID", Set["ID"]) + + expect(outcome).to be_resolved + expect(outcome.token_name).to eq("ID") + end + + it "uses declaration order only in fallback mode" do + lex_prec = Lrama::Grammar::LexPrec.new + length_prec = Lrama::LengthPrecedences.new(lex_prec) + normal = Lrama::State::ScannerAccepts::ProfileResolver.new( + lex_prec, + length_prec, + token_order: { "A" => 1, "B" => 0 } + ) + fallback = Lrama::State::ScannerAccepts::ProfileResolver.new( + lex_prec, + length_prec, + fallback: true, + token_order: { "A" => 1, "B" => 0 } + ) + + expect(normal.resolve(Set.new, nil, Set["A", "B"])).to be_unresolved + expect(fallback.resolve(Set.new, nil, Set["A", "B"]).token_name).to eq("B") + end + + it "uses explicit identity precedence before fallback declaration order" do + lex_prec = Lrama::Grammar::LexPrec.new + lex_prec.add_rule(left_token: ident("A"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("B"), lineno: 1) + fallback = Lrama::State::ScannerAccepts::ProfileResolver.new( + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + fallback: true, + token_order: { "A" => 0, "B" => 1 } + ) + + expect(fallback.resolve(Set.new, nil, Set["A", "B"]).token_name).to eq("B") + end + + it "preserves explicit identity precedence when fallback length precedence is needed" do + tokens = [ + token_pattern("X", "x", 0), + token_pattern("SHORT", "a", 1), + token_pattern("A", "ab", 2), + token_pattern("B", "ab", 3) + ] + scanner_fsa = Lrama::ScannerFSA.new(tokens) + lex_prec = Lrama::Grammar::LexPrec.new + lex_prec.add_rule(left_token: ident("A"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("B"), lineno: 1) + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, ["X"])], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + symbols: [] + ) + + scanner_accepts.build + + accepting_ab = scanner_fsa.states.find do |state| + state.accepting_tokens.map(&:name).sort == ["A", "B"] + end + expect(scanner_accepts.fallback_table.fetch(accepting_ab.id).name).to eq("B") + end + + it "uses declaration order for fallback-only explicit identity cycles" do + tokens = [ + token_pattern("X", "x", 0), + token_pattern("A", "a", 1), + token_pattern("B", "a", 2), + token_pattern("C", "a", 3) + ] + scanner_fsa = Lrama::ScannerFSA.new(tokens) + lex_prec = Lrama::Grammar::LexPrec.new + lex_prec.add_rule(left_token: ident("A"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("B"), lineno: 1) + lex_prec.add_rule(left_token: ident("B"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("C"), lineno: 2) + lex_prec.add_rule(left_token: ident("C"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("A"), lineno: 3) + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, ["X"])], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + symbols: [] + ) + + scanner_accepts.build + + accepting = scanner_fsa.states.find {|state| state.accepting_tokens.map(&:name).sort == ["A", "B", "C"] } + expect(scanner_accepts.fallback_table.fetch(accepting.id).name).to eq("A") + end + + it "keeps normal parser-state rows strict for explicit identity cycles" do + tokens = [ + token_pattern("A", "a", 0), + token_pattern("B", "a", 1), + token_pattern("C", "a", 2) + ] + scanner_fsa = Lrama::ScannerFSA.new(tokens) + lex_prec = Lrama::Grammar::LexPrec.new + lex_prec.add_rule(left_token: ident("A"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("B"), lineno: 1) + lex_prec.add_rule(left_token: ident("B"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("C"), lineno: 2) + lex_prec.add_rule(left_token: ident("C"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("A"), lineno: 3) + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, ["A", "B", "C"])], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + symbols: [] + ) + + scanner_accepts.build + + accepting = scanner_fsa.states.find {|state| state.accepting_tokens.map(&:name).sort == ["A", "B", "C"] } + expect(scanner_accepts[0, accepting.id]).to be_nil + expect(scanner_accepts.unresolved_conflicts?).to be true + end + end + + describe Lrama::State::ScannerAccepts::CompatibilityChecker do + let(:rangle) { token_pattern("RANGLE", ">", 0) } + let(:rshift) { token_pattern("RSHIFT", ">>", 1) } + let(:scanner_fsa) { Lrama::ScannerFSA.new([rangle, rshift]) } + let(:lex_prec) { Lrama::Grammar::LexPrec.new } + let(:checker) do + described_class.new(scanner_fsa, lex_prec, Lrama::LengthPrecedences.new(lex_prec)) + end + + it "treats a missing match on one side as irrelevant" do + a = token_pattern("A", "a", 0) + b = token_pattern("B", "b", 1) + fsa = Lrama::ScannerFSA.new([a, b]) + checker = described_class.new(fsa, lex_prec, Lrama::LengthPrecedences.new(lex_prec)) + + expect(checker.compatible?(Set["A"], Set["B"])).to be true + end + + it "rejects different resolved outcomes when both sides match" do + expect(checker.compatible?(Set["RANGLE"], Set["RSHIFT"])).to be false + end + + it "rejects resolved versus unresolved outcomes" do + a = token_pattern("A", "a", 0) + b = token_pattern("B", "a", 1) + fsa = Lrama::ScannerFSA.new([a, b]) + checker = described_class.new(fsa, lex_prec, Lrama::LengthPrecedences.new(lex_prec)) + + expect(checker.compatible?(Set["A"], Set["A", "B"])).to be false + end + + it "accepts unresolved outcomes on both sides" do + a = token_pattern("A", "a", 0) + b = token_pattern("B", "a", 1) + fsa = Lrama::ScannerFSA.new([a, b]) + checker = described_class.new(fsa, lex_prec, Lrama::LengthPrecedences.new(lex_prec)) + + expect(checker.compatible?(Set["A", "B"], Set["A", "B"])).to be true + end + end + + describe "lexical ties" do + it "expands acc(sp) through tie closure" do + id = token_pattern("ID", "[a-z]+", 0) + kw = token_pattern("IF", "if", 1) + scanner_fsa = Lrama::ScannerFSA.new([id, kw]) + lex_prec = Lrama::Grammar::LexPrec.new + lex_prec.add_rule(left_token: ident("ID"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT_LONGEST, right_token: ident("IF"), lineno: 1) + lex_tie = Lrama::Grammar::LexTie.new + lex_tie.add_tie("ID", "IF") + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, ["ID"])], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + lex_tie, + symbols: [] + ) + + scanner_accepts.build + + accepting = scanner_fsa.states.find {|state| state.accepting_tokens.map(&:name).include?("IF") } + expect(scanner_accepts[0, accepting.id].name).to eq("IF") + end + + it "does not expand tokens tied only through layout injection" do + div = token_pattern("DIV", "/", 0) + layout = token_pattern("YYLAYOUT_WS", "[ \\t]+", 1) + layout_alias = token_pattern("LAYOUT_ALIAS", "[ \\t]+", 2) + scanner_fsa = Lrama::ScannerFSA.new([div, layout, layout_alias]) + lex_prec = Lrama::Grammar::LexPrec.new + lex_tie = Lrama::Grammar::LexTie.new + lex_tie.add_tie("YYLAYOUT_WS", "LAYOUT_ALIAS") + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, ["DIV"])], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + lex_tie, + layout_token_names: Set["YYLAYOUT_WS"], + symbols: [] + ) + + acc_sp = scanner_accepts.send(:compute_acc_sp, parser_state(0, ["DIV"])) + + expect(acc_sp).to contain_exactly("DIV", "YYLAYOUT_WS") + end + end + + describe "pure reduce states" do + let(:rangle) { token_pattern("RANGLE", ">", 0) } + let(:rshift) { token_pattern("RSHIFT", ">>", 1) } + let(:scanner_fsa) { Lrama::ScannerFSA.new([rangle, rshift]) } + let(:lex_prec) { Lrama::Grammar::LexPrec.new } + let(:length_prec) { Lrama::LengthPrecedences.new(lex_prec) } + let(:reduce) { instance_double(Lrama::State::Action::Reduce) } + let(:parser_state) do + instance_double( + Lrama::State, + term_transitions: [], + pslr_error_tokens: [], + item_lookahead_set: {}, + reduces: [reduce], + ) + end + + it "uses propagated item lookaheads when explicit reduce lookahead is absent" do + symbols = [rangle, rshift].map { |token| instance_double(Lrama::Grammar::Symbol, name: token.name) } + allow(parser_state).to receive(:acceptable_pslr_reduce_lookahead).with(reduce, {}).and_return(0b11) + + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state], + scanner_fsa, + lex_prec, + length_prec, + symbols: symbols + ) + + expect(scanner_accepts.send(:compute_acc_sp, parser_state).to_a).to contain_exactly("RANGLE", "RSHIFT") + end + end +end diff --git a/spec/lrama/states_spec.rb b/spec/lrama/states_spec.rb index c341db91d..7d2df3237 100644 --- a/spec/lrama/states_spec.rb +++ b/spec/lrama/states_spec.rb @@ -3856,5 +3856,511 @@ class : keyword_class tSTRING keyword_end %prec tPLUS expect(logger).not_to have_received(:error) end end + + context "when unresolved PSLR inadequacies remain" do + let(:header) do + <<~STR + %define lr.type pslr + %token-pattern RSHIFT />>/ + %token-pattern RANGLE />/ + %lex-no-tie RANGLE RSHIFT + + %% + + program: RSHIFT | RANGLE + STR + end + + it "fails fast instead of silently generating a parser" do + grammar = Lrama::Parser.new(header, "states/pslr_inadequacy.y").parse + grammar.prepare + grammar.validate! + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.instance_variable_set( + :@pslr_inadequacies, + [ + Lrama::State::PslrInadequacy.new( + type: Lrama::State::PslrInadequacy::PSLR_RELATIVE, + state: instance_double(Lrama::State, id: 3), + conflicting_states: [instance_double(Lrama::State, id: 3), instance_double(Lrama::State, id: 4)], + details: { reason: "Scanner behavior differs between isocore states" } + ) + ] + ) + logger = Lrama::Logger.new + allow(logger).to receive(:error) + + expect { states.validate!(logger) }.to raise_error(SystemExit) + expect(logger).to have_received(:error).with(include("PSLR Inadequacy")) + end + end + end + + describe "PSLR split helpers" do + let(:y) do + <<~GRAMMAR + %define lr.type pslr + %token-pattern RSHIFT />>/ + %token-pattern RANGLE />/ + %lex-no-tie RANGLE RSHIFT + + %% + + program: RSHIFT | RANGLE + GRAMMAR + end + + let(:grammar) do + g = Lrama::Parser.new(y, "states/pslr_split.y").parse + g.prepare + g.validate! + g + end + + let(:states) { Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) } + let(:kernel_item) { instance_double(Lrama::State::Item, end_of_rule?: true) } + let(:reduce) { instance_double(Lrama::State::Action::Reduce, item: kernel_item, look_ahead: [grammar.find_symbol_by_s_value!("RSHIFT")]) } + let(:mock_state) do + instance_double( + Lrama::State, + is_compatible?: true, + pslr_error_tokens: [], + lookaheads_recomputed: true, + kernels: [kernel_item], + term_transitions: [], + reduces: [reduce], + item_lookahead_set: { kernel_item => grammar.find_symbol_by_s_value!("RSHIFT").number_bitmap }, + ) + end + + before do + states.instance_variable_set(:@scanner_fsa, Lrama::ScannerFSA.new(grammar.token_patterns)) + states.instance_variable_set(:@pslr_split_enabled, true) + end + + before do + allow(mock_state).to receive(:acceptable_pslr_reduce_lookahead) { |_reduce, lookaheads| lookaheads.fetch(kernel_item) } + end + + it "derives different PSLR signatures from different propagated lookaheads" do + current = states.send(:pslr_state_signature, mock_state) + filtered = states.send( + :pslr_state_signature, + mock_state, + { kernel_item => grammar.find_symbol_by_s_value!("RANGLE").number_bitmap }, + ) + + expect(current.map(&:last)).to include("RSHIFT") + expect(current.map(&:last)).not_to include("RANGLE") + expect(filtered.map(&:last)).to include("RANGLE") + expect(filtered.map(&:last)).not_to include("RSHIFT") + end + + it "treats states with different PSLR signatures as incompatible during splitting" do + allow(mock_state).to receive(:lalr_isocore).and_return(mock_state) + allow(mock_state).to receive(:id).and_return(0) + filtered_lookaheads = { kernel_item => grammar.find_symbol_by_s_value!("RANGLE").number_bitmap } + expect(states.send(:compatible_split_state?, mock_state, filtered_lookaheads)).to be false + end + + it "detects unresolved PSLR inadequacies per transition" do + propagated = { kernel_item => grammar.find_symbol_by_s_value!("RANGLE").number_bitmap } + matching_state = instance_double(Lrama::State, id: 8) + next_state = instance_double(Lrama::State, id: 4) + transition_symbol = instance_double( + Lrama::Grammar::Symbol, + name: "RSHIFT", + ) + transition = instance_double(Lrama::State::Action::Shift, to_state: next_state, next_sym: transition_symbol) + from_state = instance_double( + Lrama::State, + id: 1, + transitions: [transition], + propagate_lookaheads: propagated, + ) + + allow(next_state).to receive(:lalr_isocore).and_return(next_state) + allow(next_state).to receive(:ielr_isocores).and_return([next_state, matching_state]) + allow(states).to receive(:pslr_state_signature).with(next_state, propagated).and_return([[1, "RANGLE"]]) + allow(states).to receive(:pslr_state_signature).with(next_state).and_return([[1, "RSHIFT"]]) + allow(states).to receive(:pslr_state_signature).with(matching_state).and_return([[1, "RANGLE"]]) + allow(states).to receive(:acceptable_tokens_for_pslr).with(next_state, propagated).and_return(Set["RANGLE"]) + allow(states).to receive(:acceptable_tokens_for_pslr).with(next_state).and_return(Set["RSHIFT"]) + allow(states).to receive(:acceptable_tokens_for_pslr).with(matching_state).and_return(Set["RANGLE"]) + states.instance_variable_set(:@states, [from_state]) + + inadequacies = states.send(:detect_pslr_inadequacies) + + expect(inadequacies.size).to eq(1) + expect(inadequacies.first.details[:matching_state_id]).to eq(8) + expect(inadequacies.first.details[:transition_symbol]).to eq("RSHIFT") + end + + it "merges propagated lookaheads into an existing split state" do + current_lookaheads = { kernel_item => grammar.find_symbol_by_s_value!("RSHIFT").number_bitmap } + incoming_lookaheads = { kernel_item => grammar.find_symbol_by_s_value!("RANGLE").number_bitmap } + target_state = instance_double(Lrama::State, lookaheads_recomputed: true) + transition = instance_double(Lrama::State::Action::Shift, to_state: target_state) + split_state = instance_double( + Lrama::State, + kernels: [kernel_item], + item_lookahead_set: current_lookaheads, + transitions: [transition], + ) + + allow(split_state).to receive(:item_lookahead_set=) + allow(states).to receive(:compute_state) + + states.send(:merge_lookaheads, split_state, incoming_lookaheads) + + expect(split_state).to have_received(:item_lookahead_set=).with( + kernel_item => current_lookaheads[kernel_item] | incoming_lookaheads[kernel_item], + ) + expect(states).to have_received(:compute_state).with(split_state, transition, target_state) + end + end + + describe "PSLR pure-reduce profile regression" do + let(:y) do + <<~GRAMMAR + %define lr.type pslr + %token-pattern RSHIFT />>/ + %token-pattern RANGLE />/ + %token-pattern ID /[a-z]+/ + %lex-prec RANGLE -~ RSHIFT + + %% + + program + : templ + | rshift_expr + ; + + templ + : a RANGLE + ; + + rshift_expr + : a RSHIFT ID + ; + + a + : ID + ; + GRAMMAR + end + + let(:grammar) do + g = Lrama::Parser.new(y, "states/pslr_pure_reduce.y").parse + g.prepare + g.validate! + g + end + + it "keeps pure reduce states scanner-compatible without forcing a split" do + ielr_states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + ielr_states.compute + ielr_states.compute_ielr + + pslr_states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + pslr_states.compute + pslr_states.compute_pslr + + reduce_state = pslr_states.states.find do |state| + state.reduces.any? { |reduce| reduce.rule.display_name == "a -> ID" } + end + + expect(pslr_states.states_count).to eq(ielr_states.states_count) + expect(pslr_states.pslr_inadequacies).to be_empty + expect(pslr_states.send(:acceptable_tokens_for_pslr, reduce_state).to_a).to contain_exactly("RANGLE", "RSHIFT") + end + end + + describe "PSLR chained keyword split regression" do + let(:y) do + <<~GRAMMAR + %define lr.type pslr + %token-pattern P /p/ + %token-pattern Q /q/ + %token-pattern X /x/ + %token-pattern IF /if/ + %token-pattern ID /[a-z]+/ + %lex-prec ID <~ IF + + %% + + program + : kw_context + | id_context + ; + + kw_context + : P shared IF + ; + + id_context + : Q shared ID + ; + + shared + : n1 + ; + + n1 + : n2 + ; + + n2 + : X + ; + GRAMMAR + end + + let(:grammar) do + g = Lrama::Parser.new(y, "states/pslr_keyword_context.y").parse + g.prepare + g.validate! + g + end + + it "splits every chained reduce state by scanner profile" do + ielr_states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + ielr_states.compute + ielr_states.compute_ielr + + pslr_states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + pslr_states.compute + pslr_states.compute_pslr + + reduce_states = pslr_states.states + .select { |state| state.reduces.any? } + .group_by { |state| state.reduces.first.rule.display_name } + + expect(pslr_states.states_count).to be > ielr_states.states_count + expect(pslr_states.pslr_inadequacies).to be_empty + + ["shared -> n1", "n1 -> n2", "n2 -> X"].each do |rule_name| + states_for_rule = reduce_states.fetch(rule_name) + token_sets = states_for_rule.map { |state| pslr_states.send(:acceptable_tokens_for_pslr, state) } + + expect(states_for_rule.size).to eq(2) + expect(states_for_rule.count(&:split_state?)).to eq(1) + expect(token_sets.any? { |set| set.include?("IF") && !set.include?("ID") }).to be(true) + expect(token_sets.any? { |set| set.include?("ID") && !set.include?("IF") }).to be(true) + end + end + end + + describe "PSLR chained shift/angle split regression" do + let(:y) do + <<~GRAMMAR + %define lr.type pslr + %token-pattern LT />/ + %token-pattern RANGLE />/ + %token-pattern ID /[a-z]+/ + %lex-no-tie RANGLE RSHIFT + + %% + + program + : template_expr + | shift_expr + ; + + template_expr + : LT shared RANGLE + ; + + shift_expr + : START shared RSHIFT ID + ; + + shared + : n1 + ; + + n1 + : n2 + ; + + n2 + : MARK + ; + GRAMMAR + end + + let(:grammar) do + g = Lrama::Parser.new(y, "states/pslr_shift_chain.y").parse + g.prepare + g.validate! + g + end + + it "splits every chained reduce state by shift/angle scanner profile" do + ielr_states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + ielr_states.compute + ielr_states.compute_ielr + + pslr_states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + pslr_states.compute + pslr_states.compute_pslr + + reduce_states = pslr_states.states + .select { |state| state.reduces.any? } + .group_by { |state| state.reduces.first.rule.display_name } + + expect(pslr_states.states_count).to be > ielr_states.states_count + expect(pslr_states.pslr_inadequacies).to be_empty + + ["shared -> n1", "n1 -> n2", "n2 -> MARK"].each do |rule_name| + states_for_rule = reduce_states.fetch(rule_name) + token_sets = states_for_rule.map { |state| pslr_states.send(:acceptable_tokens_for_pslr, state) } + + expect(states_for_rule.size).to eq(2) + expect(states_for_rule.count(&:split_state?)).to eq(1) + expect(token_sets.any? { |set| set.include?("RANGLE") && !set.include?("RSHIFT") }).to be(true) + expect(token_sets.any? { |set| set.include?("RSHIFT") && !set.include?("RANGLE") }).to be(true) + end + end + end + + describe "PSLR mixed family regressions" do + { + "empty shared wrapper" => { + path: "states/pslr_mixed_empty.y", + grows: true, + grammar: <<~GRAMMAR, + %define lr.type pslr + %token-pattern LT />/ + %token-pattern RANGLE />/ + %lex-prec ID <~ IF + %lex-no-tie RANGLE RSHIFT + + %% + + program + : kw + | ident + | templ + | shift_expr + ; + + kw + : P shared IF + ; + + ident + : Q shared ID + ; + + templ + : LT shared RANGLE + ; + + shift_expr + : START shared RSHIFT ID + ; + + shared + : opt n1 + ; + + opt + : + ; + + n1 + : MARK + ; + GRAMMAR + }, + "chain2 shared wrapper" => { + path: "states/pslr_mixed_chain2.y", + grows: true, + grammar: <<~GRAMMAR, + %define lr.type pslr + %token-pattern LT />/ + %token-pattern RANGLE />/ + %lex-prec ID <~ IF + %lex-no-tie RANGLE RSHIFT + + %% + + program + : kw + | ident + | templ + | shift_expr + ; + + kw + : P shared IF + ; + + ident + : Q shared ID + ; + + templ + : LT shared RANGLE + ; + + shift_expr + : START shared RSHIFT ID + ; + + shared + : n1 + ; + + n1 + : n2 + ; + + n2 + : MARK + ; + GRAMMAR + } + }.each do |label, attrs| + it "keeps #{label} scanner-compatible" do + grammar = Lrama::Parser.new(attrs[:grammar], attrs[:path]).parse + grammar.prepare + grammar.validate! + + ielr_states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + ielr_states.compute + ielr_states.compute_ielr + + pslr_states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + pslr_states.compute + pslr_states.compute_pslr + + if attrs[:grows] + expect(pslr_states.states_count).to be > ielr_states.states_count + else + expect(pslr_states.states_count).to eq(ielr_states.states_count) + end + expect(pslr_states.pslr_inadequacies).to be_empty + end + end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index bf3ea2c51..bd601f05e 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -41,6 +41,9 @@ end require "lrama" +Dir[File.expand_path("support/**/*.rb", __dir__)].sort.each do |file| + require file +end module RSpecHelper def symbol_id(name, kind: :ident) diff --git a/spec/support/pslr_family_helper.rb b/spec/support/pslr_family_helper.rb new file mode 100644 index 000000000..77934b9b8 --- /dev/null +++ b/spec/support/pslr_family_helper.rb @@ -0,0 +1,159 @@ +# frozen_string_literal: true + +module PslrFamilyHelper + def build_grammar(source, path) + grammar = Lrama::Parser.new(source, path).parse + grammar.prepare + grammar.validate! + grammar + end + + def compute_ielr_and_pslr(grammar) + ielr_states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + ielr_states.compute + ielr_states.compute_ielr + + pslr_states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + pslr_states.compute + pslr_states.compute_pslr + + [ielr_states, pslr_states] + end + + def acceptable_tokens(states, state) + states.send(:acceptable_tokens_for_pslr, state).to_a + end + + def shared_chain_rules(name:, terminal:, depth:, prefix: "n") + return <<~RULES if depth.zero? + #{name} + : #{terminal} + ; + RULES + + rules = [<<~RULE] + #{name} + : #{prefix}1 + ; + RULE + + 1.upto(depth - 1) do |index| + rules << <<~RULE + #{prefix}#{index} + : #{prefix}#{index + 1} + ; + RULE + end + + rules << <<~RULE + #{prefix}#{depth} + : #{terminal} + ; + RULE + + rules.join("\n") + end + + def keyword_context_source(depth:) + <<~GRAMMAR + %define lr.type pslr + %token-pattern P /p/ + %token-pattern Q /q/ + %token-pattern X /x/ + %token-pattern IF /if/ + %token-pattern ID /[a-z]+/ + %lex-prec ID <~ IF + + %% + + program + : kw_context + | id_context + ; + + kw_context + : P shared IF + ; + + id_context + : Q shared ID + ; + + #{shared_chain_rules(name: "shared", terminal: "X", depth: depth)} + GRAMMAR + end + + def shift_angle_source(depth:) + <<~GRAMMAR + %define lr.type pslr + %token-pattern LT />/ + %token-pattern RANGLE />/ + %token-pattern ID /[a-z]+/ + %lex-no-tie RANGLE RSHIFT + + %% + + program + : template_expr + | shift_expr + ; + + template_expr + : LT shared RANGLE + ; + + shift_expr + : START shared RSHIFT ID + ; + + #{shared_chain_rules(name: "shared", terminal: "MARK", depth: depth)} + GRAMMAR + end + + def mixed_context_source(depth:) + <<~GRAMMAR + %define lr.type pslr + %token-pattern LT />/ + %token-pattern RANGLE />/ + %lex-prec ID <~ IF + %lex-no-tie RANGLE RSHIFT + + %% + + program + : kw_context + | id_context + | template_expr + | shift_expr + ; + + kw_context + : P shared IF + ; + + id_context + : Q shared ID + ; + + template_expr + : LT shared RANGLE + ; + + shift_expr + : START shared RSHIFT ID + ; + + #{shared_chain_rules(name: "shared", terminal: "MARK", depth: depth)} + GRAMMAR + end +end From 1fcb1d31ea5d39b3340a14d977d94a7ac4d8b890 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 21:40:35 +0900 Subject: [PATCH 05/24] pslr: emit pseudo-scanner tables and runtime in generated parsers Generate the PSLR(1) runtime as part of the yacc.c template output: * yy_scanner_transition / yy_state_to_accepting (Def 3.2.13), yy_scanner_accepts rows per parser state plus the fallback row (Def 3.2.14, section 3.5.1), length precedence tables for the normal and fallback faces, token-pattern-to-token-id mapping and layout flags * yy_pseudo_scan / yy_pseudo_scan_full implement Def 3.2.16: walk the DFA, prefer matches per the length precedence tables, fall back to the syntax-error row when no normal-row match exists, and flag layout tokens for skipping * %token-action bodies are emitted with yytext/yyleng and accumulated layout text (yypslr_layout_text/leng) available * yy_state_accepts_token and yy_state_eventually_accepts_token allow a hand-written lexer to query acceptability of a token in a state; the eventual variant follows default-reduction chains (Lrama extension) * a LAC (lookahead correction) checker performs exploratory parses so scanner decisions taken from merged states cannot commit erroneous semantic actions (section 3.5.2) * bridge-mode macros (YYSETSTATE_CONTEXT, YYPSLR_PSEUDO_SCAN*) let an existing yylex consult the pseudo-scanner through %define api.pslr.state-member Integration fixtures cover template argument lists, keyword contexts, layout comments, implicit literals and fallback precedence. --- lib/lrama/output.rb | 731 ++++++++++++++++++ spec/fixtures/integration/pslr_context.l | 50 ++ spec/fixtures/integration/pslr_context.y | 75 ++ .../integration/pslr_fallback_precedence.l | 73 ++ .../integration/pslr_fallback_precedence.y | 93 +++ .../integration/pslr_implicit_literal.l | 30 + .../integration/pslr_implicit_literal.y | 66 ++ .../integration/pslr_keyword_context.l | 41 + .../integration/pslr_keyword_context.y | 87 +++ .../integration/pslr_layout_comment.l | 36 + .../integration/pslr_layout_comment.y | 70 ++ .../fixtures/integration/pslr_mixed_context.l | 69 ++ .../fixtures/integration/pslr_mixed_context.y | 102 +++ spec/fixtures/integration/pslr_shift_chain.l | 58 ++ spec/fixtures/integration/pslr_shift_chain.y | 88 +++ .../pslr_template_argument_lists.l | 36 + .../pslr_template_argument_lists.y | 91 +++ spec/fixtures/integration/pslr_token_action.y | 69 ++ spec/lrama/integration_spec.rb | 382 +++++++++ spec/lrama/output_spec.rb | 312 ++++++++ template/bison/_yacc.h | 4 + template/bison/yacc.c | 271 ++++++- 22 files changed, 2832 insertions(+), 2 deletions(-) create mode 100644 spec/fixtures/integration/pslr_context.l create mode 100644 spec/fixtures/integration/pslr_context.y create mode 100644 spec/fixtures/integration/pslr_fallback_precedence.l create mode 100644 spec/fixtures/integration/pslr_fallback_precedence.y create mode 100644 spec/fixtures/integration/pslr_implicit_literal.l create mode 100644 spec/fixtures/integration/pslr_implicit_literal.y create mode 100644 spec/fixtures/integration/pslr_keyword_context.l create mode 100644 spec/fixtures/integration/pslr_keyword_context.y create mode 100644 spec/fixtures/integration/pslr_layout_comment.l create mode 100644 spec/fixtures/integration/pslr_layout_comment.y create mode 100644 spec/fixtures/integration/pslr_mixed_context.l create mode 100644 spec/fixtures/integration/pslr_mixed_context.y create mode 100644 spec/fixtures/integration/pslr_shift_chain.l create mode 100644 spec/fixtures/integration/pslr_shift_chain.y create mode 100644 spec/fixtures/integration/pslr_template_argument_lists.l create mode 100644 spec/fixtures/integration/pslr_template_argument_lists.y create mode 100644 spec/fixtures/integration/pslr_token_action.y diff --git a/lib/lrama/output.rb b/lib/lrama/output.rb index b5a8abc65..b9d8b3a93 100644 --- a/lib/lrama/output.rb +++ b/lib/lrama/output.rb @@ -384,6 +384,737 @@ def percent_code(name) end.join end + # PSLR Output Helper Methods + # Based on PSLR::OutputHelper - generates PSLR-specific C code + + # Check if the grammar requested PSLR output. + def pslr_enabled? + @grammar.pslr_defined? + end + + # Check if PSLR scanner tables are available. + def pslr_scanner_enabled? + scanner_fsa = @context.states.scanner_fsa + !scanner_fsa.nil? && !scanner_fsa.states.empty? + end + + def pslr_function_declarations + return "" unless pslr_enabled? + + declarations = [<<~C_CODE] + int yy_state_accepts_token (int yystate, int yychar); + C_CODE + + if pslr_scanner_enabled? + declarations << <<~C_CODE + #ifndef YYPSLR_SCAN_RESULT_DEFINED + # define YYPSLR_SCAN_RESULT_DEFINED + typedef struct yypslr_scan_result { + int token; + int length; + int is_layout; + int is_character_token; + } yypslr_scan_result; + #endif + + int yy_pseudo_scan_result (int parser_state, const char *input, yypslr_scan_result *result); + int yy_pseudo_scan (int parser_state, const char *input, int *match_length); + int yy_pslr_token_is_layout (int token); + C_CODE + + declarations << <<~C_CODE + #define YYPSLR_ENABLED 1 + #define YYPSLR_NO_MATCH YYEMPTY + + #ifndef YYPSLR_PSEUDO_SCAN_STATE + # define YYPSLR_PSEUDO_SCAN_STATE(ParserState, Input, MatchLength) \\ + yy_pseudo_scan ((ParserState), (Input), (MatchLength)) + #endif + + #ifndef YYPSLR_PSEUDO_SCAN_RESULT_STATE + # define YYPSLR_PSEUDO_SCAN_RESULT_STATE(ParserState, Input, Result) \\ + yy_pseudo_scan_result ((ParserState), (Input), (Result)) + #endif + + #ifndef YYPSLR_TOKEN_IS_LAYOUT + # define YYPSLR_TOKEN_IS_LAYOUT(Token) yy_pslr_token_is_layout ((Token)) + #endif + + int yypslr_scan_with_layout (int parser_state, const char **input, + yypslr_scan_result *result); + + #ifndef YYPSLR_SCAN_WITH_LAYOUT + # define YYPSLR_SCAN_WITH_LAYOUT(ParserState, InputPtr, Result) \\ + yypslr_scan_with_layout ((ParserState), (InputPtr), (Result)) + #endif + C_CODE + end + + if (member = pslr_state_member) + declarations << <<~C_CODE + #ifndef YYGETSTATE_CONTEXT + # define YYGETSTATE_CONTEXT(Context) ((Context)->#{member}) + #endif + C_CODE + + if pslr_scanner_enabled? + declarations << <<~C_CODE + #ifndef YYPSLR_PSEUDO_SCAN + # define YYPSLR_PSEUDO_SCAN(Context, Input, MatchLength) \\ + ((Context) != 0 \\ + ? YYPSLR_PSEUDO_SCAN_STATE (YYGETSTATE_CONTEXT (Context), (Input), (MatchLength)) \\ + : YYEMPTY) + #endif + + #ifndef YYPSLR_PSEUDO_SCAN_RESULT + # define YYPSLR_PSEUDO_SCAN_RESULT(Context, Input, Result) \\ + ((Context) != 0 \\ + ? YYPSLR_PSEUDO_SCAN_RESULT_STATE (YYGETSTATE_CONTEXT (Context), (Input), (Result)) \\ + : YYEMPTY) + #endif + C_CODE + end + + if !parse_param_name.empty? + declarations << <<~C_CODE + #ifndef YYSETSTATE_CONTEXT + # define YYSETSTATE_CONTEXT(CurrentState) \\ + do { \\ + if (#{parse_param_name} != 0) { \\ + YYGETSTATE_CONTEXT (#{parse_param_name}) = (CurrentState); \\ + } \\ + } while (0) + #endif + C_CODE + end + end + + declarations.join("\n") + end + + def pslr_state_member + member = @grammar.pslr_state_member + member&.strip + end + + def pslr_accepting_states + return [] unless pslr_scanner_enabled? + + @context.states.scanner_fsa.states.select(&:accepting?) + end + + def pslr_token_pattern_count + @context.states.token_patterns.size + end + + def pslr_token_id(token_pattern) + @context.states.find_symbol_by_s_value!(token_pattern.name).token_id + end + + # Generate Scanner FSA transition table as C code + def scanner_transition_table + return "" unless pslr_scanner_enabled? + scanner_fsa = @context.states.scanner_fsa + + lines = [] + lines << "/* Scanner FSA transition table */" + lines << "#define YY_SCANNER_NUM_STATES #{scanner_fsa.states.size}" + lines << "#define YY_SCANNER_INVALID_STATE (-1)" + lines << "" + lines << "static const int yy_scanner_transition[YY_SCANNER_NUM_STATES][256] = {" + + scanner_fsa.states.each_with_index do |state, idx| + transitions = Array.new(256, -1) + state.transitions.each do |char, target_id| + transitions[char.ord] = target_id + end + lines << " /* state #{idx} */ {#{transitions.join(', ')}}#{idx < scanner_fsa.states.size - 1 ? ',' : ''}" + end + + lines << "};" + lines.join("\n") + end + + # Generate state_to_accepting table as C code + def state_to_accepting_table + return "" unless pslr_scanner_enabled? + scanner_fsa = @context.states.scanner_fsa + accepting_indices = Array.new(scanner_fsa.states.size, -1) + + pslr_accepting_states.each_with_index do |state, index| + accepting_indices[state.id] = index + end + + lines = [] + lines << "" + lines << "/* FSA state -> accepting state index mapping */" + lines << "#define YY_ACCEPTING_NONE (-1)" + lines << "" + lines << "static const int yy_state_to_accepting[YY_SCANNER_NUM_STATES] = {" + lines << " #{accepting_indices.join(', ')}" + lines << "};" + lines.join("\n") + end + + def token_pattern_token_ids_table + return "" unless pslr_scanner_enabled? + + lines = [] + lines << "" + lines << "/* token pattern index -> parser token id */" + lines << "#define YY_PSLR_EMPTY_PATTERN (-1)" + lines << "#define YY_NUM_TOKEN_PATTERNS #{pslr_token_pattern_count}" + lines << "" + lines << "static const int yy_token_pattern_to_token_id[YY_NUM_TOKEN_PATTERNS] = {" + lines << " #{@context.states.token_patterns.map {|token_pattern| pslr_token_id(token_pattern) }.join(', ')}" + lines << "};" + lines << "" + lines << "static const int yy_token_pattern_is_layout[YY_NUM_TOKEN_PATTERNS] = {" + lines << " #{@context.states.token_patterns.map {|token_pattern| token_pattern.layout? ? 1 : 0 }.join(', ')}" + lines << "};" + lines << "" + lines << "int" + lines << "yy_pslr_token_is_layout (int token)" + lines << "{" + lines << " int i;" + lines << " for (i = 0; i < YY_NUM_TOKEN_PATTERNS; i++)" + lines << " if (yy_token_pattern_to_token_id[i] == token)" + lines << " return yy_token_pattern_is_layout[i];" + lines << " return 0;" + lines << "}" + lines.join("\n") + end + + # Generate token IDs for accepting states as C code + def accepting_tokens_table + return "" unless pslr_scanner_enabled? + scanner_fsa = @context.states.scanner_fsa + + lines = [] + lines << "" + lines << "/* Accepting state token IDs */" + lines << "" + + # Collect all unique tokens + all_tokens = @context.states.token_patterns.map(&:name) + lines << "/* Token pattern names: #{all_tokens.join(', ')} */" + lines << "" + + # Generate accepting tokens for each FSA state + scanner_fsa.states.each do |state| + next unless state.accepting? + + token_names = state.accepting_tokens.map(&:name) + lines << "/* State #{state.id} accepts: #{token_names.join(', ')} */" + end + + lines.join("\n") + end + + # Generate scanner_accepts table as C code + def scanner_accepts_table_code + return "" unless pslr_scanner_enabled? + scanner_fsa = @context.states.scanner_fsa + scanner_accepts = @context.states.scanner_accepts_table + return "" unless scanner_accepts + + lines = [] + lines << "" + lines << "/* scanner_accepts[parser_state][accepting_state] -> token pattern index */" + lines << "/* YY_PSLR_EMPTY_PATTERN means no token accepted */" + lines << "" + + num_parser_states = @context.states.states.size + num_accepting_states = pslr_accepting_states.size + + lines << "#define YY_NUM_PARSER_STATES #{num_parser_states}" + lines << "#define YY_NUM_ACCEPTING_STATES #{num_accepting_states}" + lines << "" + + if num_accepting_states > 0 + lines << "static const int yy_scanner_accepts[YY_NUM_PARSER_STATES][YY_NUM_ACCEPTING_STATES] = {" + token_pattern_indexes = @context.states.token_patterns.each_with_index.to_h + + @context.states.states.each_with_index do |parser_state, ps_idx| + row = [] + pslr_accepting_states.each do |fsa_state| + token = scanner_accepts[parser_state.id, fsa_state.id] + if token + row << token_pattern_indexes.fetch(token) + else + row << -1 + end + end + + lines << " /* parser state #{ps_idx} */ {#{row.join(', ')}}#{ps_idx < num_parser_states - 1 ? ',' : ''}" + end + + lines << "};" + lines << "" + lines << "static const int yy_scanner_fallback_accepts[YY_NUM_ACCEPTING_STATES] = {" + fallback_row = pslr_accepting_states.map do |fsa_state| + token = scanner_accepts.fallback_table[fsa_state.id] + token ? token_pattern_indexes.fetch(token) : -1 + end + lines << " #{fallback_row.join(', ')}" + lines << "};" + end + + lines.join("\n") + end + + # Generate length_precedences table as C code + def length_precedences_table_code + return "" unless pslr_scanner_enabled? + length_precedences = @context.states.length_precedences + return "" unless length_precedences + + lines = [] + lines << "" + lines << "/* yy_pslr_length_precedes[old_token][new_token] is true when a longer" + lines << " match for new_token replaces an earlier match for old_token. */" + lines << "" + + num_tokens = pslr_token_pattern_count + if num_tokens > 0 + lines << length_precedence_matrix_code( + "yy_pslr_length_precedes", + num_tokens, + :normal_precedes? + ) + + lines << "" + lines << "/* yy_pslr_fallback_length_precedes keeps explicit PSLR length" + lines << " precedence and otherwise uses traditional longest-match fallback. */" + lines << "" + + lines << length_precedence_matrix_code( + "yy_pslr_fallback_length_precedes", + num_tokens, + :fallback_precedes? + ) + end + + lines.join("\n") + end + + def length_precedence_matrix_code(table_name, num_tokens, query_method) + length_precedences = @context.states.length_precedences + lines = [] + + lines << "static const int #{table_name}[#{num_tokens}][#{num_tokens}] = {" + @context.states.token_patterns.each_with_index do |t1, i| + row = @context.states.token_patterns.map do |t2| + length_precedences.public_send(query_method, t1.name, t2.name) ? 1 : 0 + end + lines << " /* #{t1.name} */ {#{row.join(', ')}}#{i < num_tokens - 1 ? ',' : ''}" + end + lines << "};" + + lines.join("\n") + end + + def pslr_lac_function + return "" unless pslr_enabled? + + <<~C_CODE + + static int + yy_lac_check_ (yy_state_t *yyss, yy_state_t *yyssp, yysymbol_kind_t yytoken) + { + YYPTRDIFF_T yylac_len = yyssp - yyss + 1; + yy_state_t *yylac_base = YY_CAST (yy_state_t *, + YYMALLOC (YY_CAST (YYSIZE_T, YYMAXDEPTH * YYSIZEOF (yy_state_t)))); + yy_state_t *yylac_top; + + if (!yylac_base) + return 1; + + if (YYMAXDEPTH < yylac_len) + { + YYFREE (yylac_base); + return 1; + } + + YYCOPY (yylac_base, yyss, yylac_len); + yylac_top = yylac_base + yylac_len - 1; + + for (;;) + { + int yystate = *yylac_top; + int yyn = yypact[yystate]; + + if (!yypact_value_is_default (yyn)) + { + yyn += yytoken; + if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == yytoken) + { + yyn = yytable[yyn]; + if (0 < yyn) + { + YYFREE (yylac_base); + return 1; + } + if (yytable_value_is_error (yyn)) + { + YYFREE (yylac_base); + return 0; + } + yyn = -yyn; + } + else + { + yyn = yydefact[yystate]; + if (yyn == 0) + { + YYFREE (yylac_base); + return 0; + } + } + } + else + { + yyn = yydefact[yystate]; + if (yyn == 0) + { + YYFREE (yylac_base); + return 0; + } + } + + yylac_top -= yyr2[yyn]; + { + const int yylhs = yyr1[yyn] - YYNTOKENS; + const int yyi = yypgoto[yylhs] + *yylac_top; + yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yylac_top + ? yytable[yyi] + : yydefgoto[yylhs]); + } + + if (yylac_base + YYMAXDEPTH - 1 <= yylac_top) + { + YYFREE (yylac_base); + return 1; + } + + *++yylac_top = YY_CAST (yy_state_t, yystate); + } + } + C_CODE + end + + # Generate pseudo_scan function as C code + def pseudo_scan_function + return "" unless pslr_scanner_enabled? + + <<~C_CODE + + /* + * pseudo_scan: PSLR(1) scanning function + * Based on Definition 3.2.16 from the PSLR dissertation + * + * Input: + * parser_state: Current parser state + * input: Input buffer pointer + * match_length: Output parameter for matched length + * + * Returns: Selected parser token ID. If neither the parser-state row + * nor fallback row matches, returns YYUNDEF and consumes one byte. + */ + int + yy_pseudo_scan_result (int parser_state, const char *input, yypslr_scan_result *result) + { + int ss = 0; /* FSA initial state */ + int ibest = 0; + int pbest = YY_PSLR_EMPTY_PATTERN; + int fallback_ibest = 0; + int fallback_pbest = YY_PSLR_EMPTY_PATTERN; + int i = 0; + + if (result == NULL) { + return YYEMPTY; + } + + result->token = YYEMPTY; + result->length = 0; + result->is_layout = 0; + result->is_character_token = 0; + + if (parser_state < 0 || parser_state >= YY_NUM_PARSER_STATES || input == NULL) { + return YYEMPTY; + } + + if (input[0] == '\\0') { + result->token = YYEOF; + return result->token; + } + + while (input[i] != '\\0') { + int c = (unsigned char)input[i]; + int next_ss = yy_scanner_transition[ss][c]; + + if (next_ss == YY_SCANNER_INVALID_STATE) { + break; + } + + ss = next_ss; + i++; + + /* Check if this is an accepting state */ + int sa = yy_state_to_accepting[ss]; + if (sa != YY_ACCEPTING_NONE) { + int pattern_index = yy_scanner_accepts[parser_state][sa]; + if (pattern_index != YY_PSLR_EMPTY_PATTERN) { + if (pbest == YY_PSLR_EMPTY_PATTERN || + yy_pslr_length_precedes[pbest][pattern_index]) { + pbest = pattern_index; + ibest = i; + } + } + + pattern_index = yy_scanner_fallback_accepts[sa]; + if (pattern_index != YY_PSLR_EMPTY_PATTERN) { + if (fallback_pbest == YY_PSLR_EMPTY_PATTERN || + yy_pslr_fallback_length_precedes[fallback_pbest][pattern_index]) { + fallback_pbest = pattern_index; + fallback_ibest = i; + } + } + } + } + + if (pbest != YY_PSLR_EMPTY_PATTERN) { + result->token = yy_token_pattern_to_token_id[pbest]; + result->length = ibest; + result->is_layout = yy_token_pattern_is_layout[pbest]; + return result->token; + } + + if (fallback_pbest != YY_PSLR_EMPTY_PATTERN) { + result->token = yy_token_pattern_to_token_id[fallback_pbest]; + result->length = fallback_ibest; + result->is_layout = yy_token_pattern_is_layout[fallback_pbest]; + return result->token; + } + + result->token = YYUNDEF; + result->length = 1; + result->is_character_token = 1; + return result->token; + } + + int + yy_pseudo_scan(int parser_state, const char *input, int *match_length) + { + yypslr_scan_result result; + int token = yy_pseudo_scan_result (parser_state, input, &result); + + if (match_length != NULL) { + *match_length = result.length; + } + + return token; + } + C_CODE + end + + # Check if lexer context table is available. + def lexer_context_enabled? + @context.states.lexer_context_enabled? + end + + # Generate #define constants for lexer contexts, emitted early in the output + # so that user code in %{ ... %} can reference them. + def lexer_context_defines_code + return "" unless lexer_context_enabled? + + classifier = @context.states.lexer_context_classifier + lines = [] + lines << "/* Lexer context constants — generated from %lexer-context directives */" + classifier.contexts.each do |lc| + lines << "#define YY_CTX_%-8s 0x%02x" % [lc.name, lc.bitmask] + end + lines.join("\n") + end + + # Generate the lexer context table as C code. + def lexer_context_table_code + return "" unless lexer_context_enabled? + + table = @context.states.lexer_context_table + lexer_contexts = @grammar.lexer_contexts + lines = [] + + lines << "/* Lexer Context Classification Table */" + lines << "/* Maps parser state -> lexer context flags */" + lines << "" + lines << "static const unsigned char yy_lexer_context[] = {" + + table.each_with_index do |ctx, idx| + ctx_name = LexerContextClassifier.context_name(ctx, lexer_contexts) + comma = idx < table.size - 1 ? "," : "" + lines << " /* state #{idx} */ #{ctx}#{comma} /* #{ctx_name} */" + end + + lines << "};" + lines << "" + lines << "int" + lines << "yy_lexer_context_is(int yystate, int ctx_mask) {" + lines << " if (yystate < 0 || yystate >= #{table.size}) return 0;" + lines << " return yy_lexer_context[yystate] & ctx_mask;" + lines << "}" + + lines.join("\n") + end + + # Check if token actions are defined + def pslr_token_actions_enabled? + pslr_enabled? && !@grammar.token_actions.empty? + end + + # Generate layout accumulation declarations + def pslr_layout_declarations + return "" unless pslr_scanner_enabled? + + <<~C_CODE + + #ifndef YYPSLR_LAYOUT_DEFINED + # define YYPSLR_LAYOUT_DEFINED + + typedef struct yypslr_layout { + const char *text; + int length; + } yypslr_layout; + + # ifndef YYPSLR_LAYOUT_BUFFER_SIZE + # define YYPSLR_LAYOUT_BUFFER_SIZE 4096 + # endif + + static char yypslr_layout_buffer[YYPSLR_LAYOUT_BUFFER_SIZE]; + static int yypslr_layout_length = 0; + + static void + yypslr_layout_clear (void) + { + yypslr_layout_length = 0; + } + + static void + yypslr_layout_append (const char *text, int length) + { + if (yypslr_layout_length + length < YYPSLR_LAYOUT_BUFFER_SIZE) + { + memcpy (yypslr_layout_buffer + yypslr_layout_length, text, length); + yypslr_layout_length += length; + yypslr_layout_buffer[yypslr_layout_length] = '\\0'; + } + } + + # define YYPSLR_LAYOUT_TEXT yypslr_layout_buffer + # define YYPSLR_LAYOUT_LENGTH yypslr_layout_length + # define YYPSLR_LAYOUT_CLEAR() yypslr_layout_clear () + # define YYPSLR_LAYOUT_APPEND(Text, Len) yypslr_layout_append ((Text), (Len)) + + #endif /* YYPSLR_LAYOUT_DEFINED */ + C_CODE + end + + # Generate token action dispatch function + def pslr_token_action_function + return "" unless pslr_token_actions_enabled? + + lines = [] + lines << "" + lines << "/* PSLR token action dispatch */" + lines << "/* Generated from %token-action declarations */" + lines << "" + lines << "static void" + lines << "yypslr_token_action (int token, const char *yytext, int yyleng)" + lines << "{" + + @grammar.token_actions.each_with_index do |action, idx| + token_id = @context.states.find_symbol_by_s_value!(action.token_name).token_id + keyword = idx == 0 ? "if" : "else if" + lines << " #{keyword} (token == #{token_id})" + lines << " {" + lines << "#line #{action.lineno} \"#{@grammar_file_path}\"" + lines << " {#{action.code.s_value}}" + lines << "#line [@oline@] [@ofile@]" + lines << " }" + end + + lines << "}" + lines << "" + lines << "#define YYPSLR_TOKEN_ACTION(Token, Text, Len) \\" + lines << " yypslr_token_action ((Token), (Text), (Len))" + lines.join("\n") + end + + # Generate enhanced pseudo_scan_result with layout accumulation + def pslr_layout_scan_function + return "" unless pslr_scanner_enabled? + + <<~C_CODE + + /* + * yypslr_scan_with_layout: scan with layout accumulation. + * + * Repeatedly invokes yy_pseudo_scan_result to consume input. + * Layout tokens are accumulated in the layout buffer; + * non-layout tokens are returned to the caller with the + * accumulated layout available via YYPSLR_LAYOUT_TEXT. + */ + int + yypslr_scan_with_layout (int parser_state, const char **input, + yypslr_scan_result *result) + { + YYPSLR_LAYOUT_CLEAR (); + + for (;;) + { + int token = yy_pseudo_scan_result (parser_state, *input, result); + + if (token == YYEMPTY || token == YYEOF) + return token; + + if (result->is_layout) + { + YYPSLR_LAYOUT_APPEND (*input, result->length); + #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, result->length);" : ""} + *input += result->length; + continue; + } + + #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, result->length);" : ""} + return token; + } + } + C_CODE + end + + # Generate all PSLR C code + def pslr_tables_and_functions + return "" unless pslr_scanner_enabled? + + parts = [ + "/* PSLR(1) Scanner Tables and Functions */", + "/* Generated by Lrama PSLR implementation */", + "", + scanner_transition_table, + state_to_accepting_table, + token_pattern_token_ids_table, + accepting_tokens_table, + scanner_accepts_table_code, + length_precedences_table_code, + pslr_layout_declarations, + pseudo_scan_function, + pslr_layout_scan_function, + pslr_token_action_function, + ] + + parts.join("\n") + end + private def include_header_path(output_file_path, header_file_path) diff --git a/spec/fixtures/integration/pslr_context.l b/spec/fixtures/integration/pslr_context.l new file mode 100644 index 000000000..06cbd121d --- /dev/null +++ b/spec/fixtures/integration/pslr_context.l @@ -0,0 +1,50 @@ +%option noinput nounput noyywrap never-interactive + +%{ +#include +#include "pslr_context.h" + +#define YY_DECL int yylex(YYSTYPE *yylval, struct parse_params *p) +%} + +ID_PATTERN [a-zA-Z_][a-zA-Z0-9_]* + +%% + +{ID_PATTERN} { + (void)yylval; + return ID; +} + +"<" { + return LANGLE; +} + +[>]{1,2} { + int match_length = 0; + int token = YYPSLR_PSEUDO_SCAN(p, yytext, &match_length); + + if (token == YYEMPTY) { + token = (yyleng == 2) ? RSHIFT : RANGLE; + match_length = yyleng; + } + + if (0 < match_length && match_length < yyleng) { + yyless(match_length); + } + + return token; +} + +[[:space:]]+ {} + +<> { + return YYEOF; +} + +. { + fprintf(stderr, "Illegal character '%s'\n", yytext); + return YYUNDEF; +} + +%% diff --git a/spec/fixtures/integration/pslr_context.y b/spec/fixtures/integration/pslr_context.y new file mode 100644 index 000000000..74de59abd --- /dev/null +++ b/spec/fixtures/integration/pslr_context.y @@ -0,0 +1,75 @@ +%{ +#include + +#define YY_DECL int yylex(YYSTYPE *lval, struct parse_params *p) + +#include "pslr_context.h" +#include "pslr_context-lexer.h" + +extern int yylex(YYSTYPE *lval, struct parse_params *p); +static int yyerror(YYLTYPE *loc, struct parse_params *p, const char *str); +%} + +%code requires { + struct parse_params { + int current_state; + }; +} + +%define api.pure +%define lr.type pslr +%define api.pslr.state-member current_state + +%lex-param {struct parse_params *p} +%parse-param {struct parse_params *p} + +%token-pattern RSHIFT />>/ +%token-pattern RANGLE />/ +%token-pattern LANGLE / +#include "pslr_fallback_precedence.h" + +#define YY_DECL int yylex(YYSTYPE *yylval, struct parse_params *p) + +static const char * +token_name(int token) +{ + switch (token) { + case X: + return "X"; + case COM: + return "COM"; + case A: + return "A"; + case B: + return "B"; + case SHORT: + return "SHORT"; + case IA: + return "IA"; + case IB: + return "IB"; + case CYC_A: + return "CYC_A"; + case CYC_B: + return "CYC_B"; + case CYC_C: + return "CYC_C"; + case ZA: + return "ZA"; + case ZB: + return "ZB"; + case PA: + return "PA"; + case PB: + return "PB"; + case NON: + return "NON"; + case WORD: + return "WORD"; + default: + return "UNKNOWN"; + } +} +%} + +%% + +(.|\n)+ { + yypslr_scan_result result; + int token; + + (void)yylval; + token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, &result); + if (result.length <= 0) { + result.length = 1; + } + printf("%s %d\n", token_name(token), result.length); + if (result.length < yyleng) { + yyless(result.length); + } + return token; +} + +<> { + return YYEOF; +} + +%% diff --git a/spec/fixtures/integration/pslr_fallback_precedence.y b/spec/fixtures/integration/pslr_fallback_precedence.y new file mode 100644 index 000000000..86f708a5e --- /dev/null +++ b/spec/fixtures/integration/pslr_fallback_precedence.y @@ -0,0 +1,93 @@ +%{ +#include +#include + +#define YY_DECL int yylex(YYSTYPE *lval, struct parse_params *p) + +#include "pslr_fallback_precedence.h" +#include "pslr_fallback_precedence-lexer.h" + +extern int yylex(YYSTYPE *lval, struct parse_params *p); +static int yyerror(YYLTYPE *loc, struct parse_params *p, const char *str); +%} + +%code requires { + struct parse_params { + int current_state; + }; +} + +%define api.pure +%define lr.type pslr +%define api.pslr.state-member current_state + +%lex-param {struct parse_params *p} +%parse-param {struct parse_params *p} + +%token-pattern X /x/ +%token-pattern COM /\/\*(.|\n)*\*\// +%token-pattern A /a/ +%token-pattern B /ab/ +%token-pattern SHORT /c/ +%token-pattern IA /cd/ +%token-pattern IB /cd/ +%token-pattern CYC_A /~/ +%token-pattern CYC_B /~/ +%token-pattern CYC_C /~/ +%token-pattern ZA /z/ +%token-pattern ZB /z/ +%token-pattern PA /@/ +%token-pattern PB /@/ +%token-pattern NON /non-/ +%token-pattern WORD /[a-z-]+/ + +%lex-prec COM -s COM +%lex-prec WORD -< NON +%lex-prec PA <- PB +%lex-prec IA <- IB +%lex-prec CYC_A <- CYC_B +%lex-prec CYC_B <- CYC_C +%lex-prec CYC_C <- CYC_A + +%% + +start + : X { printf("ok\n"); } + ; + +%% + +static int +yyerror(YYLTYPE *loc, struct parse_params *p, const char *str) +{ + (void)loc; + (void)p; + (void)str; + return 0; +} + +int +main(int argc, char *argv[]) +{ + struct parse_params params = { 0 }; + + if (argc == 2 && strcmp(argv[1], "__empty__") == 0) { + yypslr_scan_result result; + int match_length = -1; + int token = YYPSLR_PSEUDO_SCAN_RESULT(¶ms, "", &result); + int wrapper_token = YYPSLR_PSEUDO_SCAN(¶ms, "", &match_length); + int ok = token == YYEOF && result.token == YYEOF && wrapper_token == YYEOF && + result.length == 0 && result.is_layout == 0 && result.is_character_token == 0 && + match_length == 0; + + printf("%s %d %d %d %d\n", ok ? "EOF" : "BAD", result.length, result.is_layout, + result.is_character_token, match_length); + return ok ? 0 : 1; + } + + if (argc == 2) { + yy_scan_string(argv[1]); + } + + return yyparse(¶ms); +} diff --git a/spec/fixtures/integration/pslr_implicit_literal.l b/spec/fixtures/integration/pslr_implicit_literal.l new file mode 100644 index 000000000..31121d203 --- /dev/null +++ b/spec/fixtures/integration/pslr_implicit_literal.l @@ -0,0 +1,30 @@ +%option noinput nounput noyywrap never-interactive + +%{ +#include "pslr_implicit_literal.h" + +#define YY_DECL int yylex(YYSTYPE *yylval, struct parse_params *p) +%} + +%% + +(.|\n)+ { + yypslr_scan_result result; + int token; + + (void)yylval; + token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, &result); + if (result.length <= 0) { + result.length = 1; + } + if (result.length < yyleng) { + yyless(result.length); + } + return token; +} + +<> { + return YYEOF; +} + +%% diff --git a/spec/fixtures/integration/pslr_implicit_literal.y b/spec/fixtures/integration/pslr_implicit_literal.y new file mode 100644 index 000000000..1f9526429 --- /dev/null +++ b/spec/fixtures/integration/pslr_implicit_literal.y @@ -0,0 +1,66 @@ +%{ +#include +#include + +#define YY_DECL int yylex(YYSTYPE *lval, struct parse_params *p) + +#include "pslr_implicit_literal.h" +#include "pslr_implicit_literal-lexer.h" + +extern int yylex(YYSTYPE *lval, struct parse_params *p); +static int yyerror(YYLTYPE *loc, struct parse_params *p, const char *str); +%} + +%code requires { + struct parse_params { + int current_state; + }; +} + +%define api.pure +%define lr.type pslr +%define api.pslr.state-member current_state + +%lex-param {struct parse_params *p} +%parse-param {struct parse_params *p} + +%token-pattern ID /[a-z]+/ + +%% + +start + : ID ';' { printf("ok\n"); } + ; + +%% + +static int +yyerror(YYLTYPE *loc, struct parse_params *p, const char *str) +{ + (void)loc; + (void)p; + (void)str; + return 0; +} + +int +main(int argc, char *argv[]) +{ + struct parse_params params = { 0 }; + + if (argc == 2 && strcmp(argv[1], "__fallback_semi__") == 0) { + yypslr_scan_result result; + int token = YYPSLR_PSEUDO_SCAN_RESULT(¶ms, ";", &result); + int ok = token == ';' && result.token == ';' && result.length == 1 && + result.is_character_token == 0; + + printf("%s %d %d\n", ok ? "SEMI" : "BAD", result.length, result.is_character_token); + return ok ? 0 : 1; + } + + if (argc == 2) { + yy_scan_string(argv[1]); + } + + return yyparse(¶ms); +} diff --git a/spec/fixtures/integration/pslr_keyword_context.l b/spec/fixtures/integration/pslr_keyword_context.l new file mode 100644 index 000000000..a54322064 --- /dev/null +++ b/spec/fixtures/integration/pslr_keyword_context.l @@ -0,0 +1,41 @@ +%option noinput nounput noyywrap never-interactive + +%{ +#include +#include "pslr_keyword_context.h" + +#define YY_DECL int yylex(YYSTYPE *yylval, struct parse_params *p) +%} + +%% + +[a-z]+ { + (void)yylval; + + int match_length = 0; + int token = YYPSLR_PSEUDO_SCAN(p, yytext, &match_length); + + if (token == YYEMPTY) { + token = ID; + match_length = yyleng; + } + + if (0 < match_length && match_length < yyleng) { + yyless(match_length); + } + + return token; +} + +[[:space:]]+ {} + +<> { + return YYEOF; +} + +. { + fprintf(stderr, "Illegal character '%s'\n", yytext); + return YYUNDEF; +} + +%% diff --git a/spec/fixtures/integration/pslr_keyword_context.y b/spec/fixtures/integration/pslr_keyword_context.y new file mode 100644 index 000000000..6f5f6b509 --- /dev/null +++ b/spec/fixtures/integration/pslr_keyword_context.y @@ -0,0 +1,87 @@ +%{ +#include + +#define YY_DECL int yylex(YYSTYPE *lval, struct parse_params *p) + +#include "pslr_keyword_context.h" +#include "pslr_keyword_context-lexer.h" + +extern int yylex(YYSTYPE *lval, struct parse_params *p); +static int yyerror(YYLTYPE *loc, struct parse_params *p, const char *str); +%} + +%code requires { + struct parse_params { + int current_state; + }; +} + +%define api.pure +%define lr.type pslr +%define api.pslr.state-member current_state + +%lex-param {struct parse_params *p} +%parse-param {struct parse_params *p} + +%token-pattern P /p/ +%token-pattern Q /q/ +%token-pattern X /x/ +%token-pattern IF /if/ +%token-pattern ID /[a-z]+/ + +%lex-prec ID <~ IF + +%% + +program + : kw_context { printf("kw\n"); } + | id_context { printf("id\n"); } + ; + +kw_context + : P shared IF + ; + +id_context + : Q shared ID + ; + +shared + : n1 + ; + +n1 + : n2 + ; + +n2 + : X + ; + +%% + +static int +yyerror(YYLTYPE *loc, struct parse_params *p, const char *str) +{ + (void)loc; + (void)p; + fprintf(stderr, "parse error: %s\n", str); + return 0; +} + +int +main(int argc, char *argv[]) +{ + struct parse_params params = { 0 }; + + if (argc == 2) { + yy_scan_string(argv[1]); + } + + if (yyparse(¶ms)) { + fprintf(stderr, "syntax error\n"); + return 1; + } + + return 0; +} diff --git a/spec/fixtures/integration/pslr_layout_comment.l b/spec/fixtures/integration/pslr_layout_comment.l new file mode 100644 index 000000000..82fc8fa77 --- /dev/null +++ b/spec/fixtures/integration/pslr_layout_comment.l @@ -0,0 +1,36 @@ +%option noinput nounput noyywrap never-interactive + +%{ +#include +#include "pslr_layout_comment.h" + +#define YY_DECL int yylex(YYSTYPE *yylval, struct parse_params *p) +%} + +%% + +(.|\n)+ { + yypslr_scan_result result; + int token; + + (void)yylval; + token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, &result); + if (result.length <= 0) { + result.length = 1; + } + if (result.length < yyleng) { + yyless(result.length); + } + /* Layout tokens are scanner-only. Consume them and keep the same parser + state while scanning the remaining input. */ + if (result.is_layout) { + return yylex(yylval, p); + } + return token; +} + +<> { + return YYEOF; +} + +%% diff --git a/spec/fixtures/integration/pslr_layout_comment.y b/spec/fixtures/integration/pslr_layout_comment.y new file mode 100644 index 000000000..185fb927a --- /dev/null +++ b/spec/fixtures/integration/pslr_layout_comment.y @@ -0,0 +1,70 @@ +%{ +#include + +#define YY_DECL int yylex(YYSTYPE *lval, struct parse_params *p) + +#include "pslr_layout_comment.h" +#include "pslr_layout_comment-lexer.h" + +extern int yylex(YYSTYPE *lval, struct parse_params *p); +static int yyerror(YYLTYPE *loc, struct parse_params *p, const char *str); +%} + +%code requires { + struct parse_params { + int current_state; + }; +} + +%define api.pure +%define lr.type pslr +%define api.pslr.state-member current_state + +%lex-param {struct parse_params *p} +%parse-param {struct parse_params *p} + +%token ID +%token DIV "/" +%token SEMI ";" + +%token-pattern ID /[a-zA-Z][a-zA-Z0-9_]*/ +%token-pattern DIV /\// +%token-pattern SEMI /;/ +%token-pattern YYLAYOUT_COMMENT /\/\*([^*]|\*+[^*/])*\*+\// +%token-pattern YYLAYOUT_WS /[ \t\r\n]+/ + +%lex-prec DIV -~ YYLAYOUT_COMMENT + +%% + +start + : ID DIV ID SEMI { printf("ok\n"); } + ; + +%% + +static int +yyerror(YYLTYPE *loc, struct parse_params *p, const char *str) +{ + (void)loc; + (void)p; + fprintf(stderr, "parse error: %s\n", str); + return 0; +} + +int +main(int argc, char *argv[]) +{ + struct parse_params params = { 0 }; + + if (argc == 2) { + yy_scan_string(argv[1]); + } + + if (yyparse(¶ms)) { + fprintf(stderr, "syntax error\n"); + return 1; + } + + return 0; +} diff --git a/spec/fixtures/integration/pslr_mixed_context.l b/spec/fixtures/integration/pslr_mixed_context.l new file mode 100644 index 000000000..5c75c7a31 --- /dev/null +++ b/spec/fixtures/integration/pslr_mixed_context.l @@ -0,0 +1,69 @@ +%option noinput nounput noyywrap never-interactive + +%{ +#include +#include "pslr_mixed_context.h" + +#define YY_DECL int yylex(YYSTYPE *yylval, struct parse_params *p) +%} + +%% + +[a-z]+ { + (void)yylval; + + int match_length = 0; + int token = YYPSLR_PSEUDO_SCAN(p, yytext, &match_length); + + if (token == YYEMPTY) { + token = ID; + match_length = yyleng; + } + + if (0 < match_length && match_length < yyleng) { + yyless(match_length); + } + + return token; +} + +"<" { + return LT; +} + +"@" { + return START; +} + +"#" { + return MARK; +} + +[>]{1,2} { + int match_length = 0; + int token = YYPSLR_PSEUDO_SCAN(p, yytext, &match_length); + + if (token == YYEMPTY) { + token = (yyleng == 2) ? RSHIFT : RANGLE; + match_length = yyleng; + } + + if (0 < match_length && match_length < yyleng) { + yyless(match_length); + } + + return token; +} + +[[:space:]]+ {} + +<> { + return YYEOF; +} + +. { + fprintf(stderr, "Illegal character '%s'\n", yytext); + return YYUNDEF; +} + +%% diff --git a/spec/fixtures/integration/pslr_mixed_context.y b/spec/fixtures/integration/pslr_mixed_context.y new file mode 100644 index 000000000..38eba8c90 --- /dev/null +++ b/spec/fixtures/integration/pslr_mixed_context.y @@ -0,0 +1,102 @@ +%{ +#include + +#define YY_DECL int yylex(YYSTYPE *lval, struct parse_params *p) + +#include "pslr_mixed_context.h" +#include "pslr_mixed_context-lexer.h" + +extern int yylex(YYSTYPE *lval, struct parse_params *p); +static int yyerror(YYLTYPE *loc, struct parse_params *p, const char *str); +%} + +%code requires { + struct parse_params { + int current_state; + }; +} + +%define api.pure +%define lr.type pslr +%define api.pslr.state-member current_state + +%lex-param {struct parse_params *p} +%parse-param {struct parse_params *p} + +%token-pattern LT />/ +%token-pattern RANGLE />/ + +%lex-prec ID <~ IF +%lex-no-tie RANGLE RSHIFT + +%% + +program + : kw_context { printf("kw\n"); } + | id_context { printf("id\n"); } + | template_expr { printf("template\n"); } + | shift_expr { printf("shift\n"); } + ; + +kw_context + : P shared IF + ; + +id_context + : Q shared ID + ; + +template_expr + : LT shared RANGLE + ; + +shift_expr + : START shared RSHIFT ID + ; + +shared + : n1 + ; + +n1 + : n2 + ; + +n2 + : MARK + ; + +%% + +static int +yyerror(YYLTYPE *loc, struct parse_params *p, const char *str) +{ + (void)loc; + (void)p; + fprintf(stderr, "parse error: %s\n", str); + return 0; +} + +int +main(int argc, char *argv[]) +{ + struct parse_params params = { 0 }; + + if (argc == 2) { + yy_scan_string(argv[1]); + } + + if (yyparse(¶ms)) { + fprintf(stderr, "syntax error\n"); + return 1; + } + + return 0; +} diff --git a/spec/fixtures/integration/pslr_shift_chain.l b/spec/fixtures/integration/pslr_shift_chain.l new file mode 100644 index 000000000..885ba62e8 --- /dev/null +++ b/spec/fixtures/integration/pslr_shift_chain.l @@ -0,0 +1,58 @@ +%option noinput nounput noyywrap never-interactive + +%{ +#include +#include "pslr_shift_chain.h" + +#define YY_DECL int yylex(YYSTYPE *yylval, struct parse_params *p) +%} + +ID_PATTERN [a-z]+ + +%% + +{ID_PATTERN} { + (void)yylval; + return ID; +} + +"<" { + return LT; +} + +"@" { + return START; +} + +"#" { + return MARK; +} + +[>]{1,2} { + int match_length = 0; + int token = YYPSLR_PSEUDO_SCAN(p, yytext, &match_length); + + if (token == YYEMPTY) { + token = (yyleng == 2) ? RSHIFT : RANGLE; + match_length = yyleng; + } + + if (0 < match_length && match_length < yyleng) { + yyless(match_length); + } + + return token; +} + +[[:space:]]+ {} + +<> { + return YYEOF; +} + +. { + fprintf(stderr, "Illegal character '%s'\n", yytext); + return YYUNDEF; +} + +%% diff --git a/spec/fixtures/integration/pslr_shift_chain.y b/spec/fixtures/integration/pslr_shift_chain.y new file mode 100644 index 000000000..d7b63d759 --- /dev/null +++ b/spec/fixtures/integration/pslr_shift_chain.y @@ -0,0 +1,88 @@ +%{ +#include + +#define YY_DECL int yylex(YYSTYPE *lval, struct parse_params *p) + +#include "pslr_shift_chain.h" +#include "pslr_shift_chain-lexer.h" + +extern int yylex(YYSTYPE *lval, struct parse_params *p); +static int yyerror(YYLTYPE *loc, struct parse_params *p, const char *str); +%} + +%code requires { + struct parse_params { + int current_state; + }; +} + +%define api.pure +%define lr.type pslr +%define api.pslr.state-member current_state + +%lex-param {struct parse_params *p} +%parse-param {struct parse_params *p} + +%token-pattern LT />/ +%token-pattern RANGLE />/ +%token-pattern ID /[a-z]+/ + +%lex-no-tie RANGLE RSHIFT + +%% + +program + : template_expr { printf("template\n"); } + | shift_expr { printf("shift\n"); } + ; + +template_expr + : LT shared RANGLE + ; + +shift_expr + : START shared RSHIFT ID + ; + +shared + : n1 + ; + +n1 + : n2 + ; + +n2 + : MARK + ; + +%% + +static int +yyerror(YYLTYPE *loc, struct parse_params *p, const char *str) +{ + (void)loc; + (void)p; + fprintf(stderr, "parse error: %s\n", str); + return 0; +} + +int +main(int argc, char *argv[]) +{ + struct parse_params params = { 0 }; + + if (argc == 2) { + yy_scan_string(argv[1]); + } + + if (yyparse(¶ms)) { + fprintf(stderr, "syntax error\n"); + return 1; + } + + return 0; +} diff --git a/spec/fixtures/integration/pslr_template_argument_lists.l b/spec/fixtures/integration/pslr_template_argument_lists.l new file mode 100644 index 000000000..aedab7edf --- /dev/null +++ b/spec/fixtures/integration/pslr_template_argument_lists.l @@ -0,0 +1,36 @@ +%option noinput nounput noyywrap never-interactive + +%{ +#include +#include "pslr_template_argument_lists.h" + +#define YY_DECL int yylex(YYSTYPE *yylval, struct parse_params *p) +%} + +%% + +(.|\n)+ { + yypslr_scan_result result; + int token; + + (void)yylval; + token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, &result); + if (result.length <= 0) { + result.length = 1; + } + if (result.length < yyleng) { + yyless(result.length); + } + /* Layout tokens are scanner-only. Consume them and keep the same parser + state while scanning the remaining input. */ + if (result.is_layout) { + return yylex(yylval, p); + } + return token; +} + +<> { + return YYEOF; +} + +%% diff --git a/spec/fixtures/integration/pslr_template_argument_lists.y b/spec/fixtures/integration/pslr_template_argument_lists.y new file mode 100644 index 000000000..baf265b57 --- /dev/null +++ b/spec/fixtures/integration/pslr_template_argument_lists.y @@ -0,0 +1,91 @@ +%{ +#include + +#define YY_DECL int yylex(YYSTYPE *lval, struct parse_params *p) + +#include "pslr_template_argument_lists.h" +#include "pslr_template_argument_lists-lexer.h" + +extern int yylex(YYSTYPE *lval, struct parse_params *p); +static int yyerror(YYLTYPE *loc, struct parse_params *p, const char *str); +%} + +%code requires { + struct parse_params { + int current_state; + }; +} + +%define api.pure +%define lr.type pslr +%define api.pslr.state-member current_state + +%lex-param {struct parse_params *p} +%parse-param {struct parse_params *p} + +%token ID +%token LT "<" +%token RANGLE ">" +%token RSHIFT ">>" +%token SEMI ";" + +%token-pattern ID /[a-zA-Z][a-zA-Z0-9_]*/ +%token-pattern LT // +%token-pattern RSHIFT />>/ +%token-pattern SEMI /;/ +%token-pattern YYLAYOUT /[ \t\r\n]+/ + +%lex-no-tie RANGLE RSHIFT + +%% + +start + : decl SEMI { printf("decl\n"); } + | expr SEMI { printf("expr\n"); } + ; + +decl + : type id + ; + +type + : id LT type RANGLE + | ID + ; + +expr + : id RSHIFT id + ; + +id + : ID + ; + +%% + +static int +yyerror(YYLTYPE *loc, struct parse_params *p, const char *str) +{ + (void)loc; + (void)p; + fprintf(stderr, "parse error: %s\n", str); + return 0; +} + +int +main(int argc, char *argv[]) +{ + struct parse_params params = { 0 }; + + if (argc == 2) { + yy_scan_string(argv[1]); + } + + if (yyparse(¶ms)) { + fprintf(stderr, "syntax error\n"); + return 1; + } + + return 0; +} diff --git a/spec/fixtures/integration/pslr_token_action.y b/spec/fixtures/integration/pslr_token_action.y new file mode 100644 index 000000000..8c36b986f --- /dev/null +++ b/spec/fixtures/integration/pslr_token_action.y @@ -0,0 +1,69 @@ +%{ +#include + +#define YY_DECL int yylex(YYSTYPE *lval, struct parse_params *p) + +#include "pslr_token_action.h" +#include "pslr_token_action-lexer.h" + +extern int yylex(YYSTYPE *lval, struct parse_params *p); +static int yyerror(YYLTYPE *loc, struct parse_params *p, const char *str); +%} + +%code requires { + struct parse_params { + int current_state; + }; +} + +%define api.pure +%define lr.type pslr +%define api.pslr.state-member current_state + +%lex-param {struct parse_params *p} +%parse-param {struct parse_params *p} + +%token ID NUM SEMI + +%token-pattern ID /[a-zA-Z][a-zA-Z0-9_]*/ +%token-pattern NUM /[0-9]+/ +%token-pattern YYLAYOUT_WS /[ \t\r\n]+/ + +%token-action ID { /* token action for ID */ } +%token-action NUM { /* token action for NUM */ } + +%lex-prec ID -~ NUM + +%% + +start + : ID NUM ';' { printf("ok\n"); } + ; + +%% + +static int +yyerror(YYLTYPE *loc, struct parse_params *p, const char *str) +{ + (void)loc; + (void)p; + fprintf(stderr, "parse error: %s\n", str); + return 0; +} + +int +main(int argc, char *argv[]) +{ + struct parse_params params = { 0 }; + + if (argc == 2) { + yy_scan_string(argv[1]); + } + + if (yyparse(¶ms)) { + fprintf(stderr, "syntax error\n"); + return 1; + } + + return 0; +} diff --git a/spec/lrama/integration_spec.rb b/spec/lrama/integration_spec.rb index 0332f514a..2330c89a3 100644 --- a/spec/lrama/integration_spec.rb +++ b/spec/lrama/integration_spec.rb @@ -259,6 +259,160 @@ def generate_object(grammar_file_path, c_path, obj_path, command_args: []) end end + describe "PSLR parser and lexer integration" do + it "selects the longer token in shift contexts" do + test_parser("pslr_context", "foo>>bar", "shift\n") + end + + it "can prefer the shorter match in template contexts" do + test_parser("pslr_context", "foo>", "template\n") + end + + it "splits keyword and identifier contexts with the same lexeme" do + test_parser("pslr_keyword_context", "p x if", "kw\n") + test_parser("pslr_keyword_context", "q x if", "id\n") + end + + it "keeps chained shift and template contexts distinct" do + test_parser("pslr_shift_chain", "< # >", "template\n") + test_parser("pslr_shift_chain", "@ # >> foo", "shift\n") + end + + it "handles mixed keyword, identifier, template, and shift contexts in one grammar" do + test_parser("pslr_mixed_context", "p # if", "kw\n") + test_parser("pslr_mixed_context", "q # if", "id\n") + test_parser("pslr_mixed_context", "< # >", "template\n") + test_parser("pslr_mixed_context", "@ # >> foo", "shift\n") + end + + it "handles template argument lists without a short-token lex-prec override" do + test_parser("pslr_template_argument_lists", "vector> v;", "decl\n") + test_parser("pslr_template_argument_lists", "a >> b;", "expr\n") + end + + it "discards layout comments that share a prefix with normal tokens" do + test_parser("pslr_layout_comment", "a/* comment */ / b;", "ok\n") + end + + it "reports unresolved layout scanner conflicts without an explicit length rule" do + grammar_text = File.read(fixture_path("integration/pslr_layout_comment.y")) + .sub("%lex-prec DIV -~ YYLAYOUT_COMMENT\n", "") + grammar = Lrama::Parser.new(grammar_text, "integration/pslr_layout_comment_no_prec.y").parse + grammar.prepare + grammar.validate! + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + logger = Lrama::Logger.new + allow(logger).to receive(:error) + + expect { states.validate!(logger) }.to raise_error(SystemExit) + expect(logger).to have_received(:error).with(a_string_including("DIV", "YYLAYOUT_COMMENT")) + end + + it "honors fallback shortest-match length precedence" do + test_parser("pslr_fallback_precedence", "/*a*/ b /*c*/", "COM 5\n", expect_success: false) + end + + it "uses traditional longest match for unspecified fallback length conflicts" do + test_parser("pslr_fallback_precedence", "ab", "B 2\n", expect_success: false) + end + + it "honors fallback right-token length precedence" do + test_parser("pslr_fallback_precedence", "non-euclidean", "NON 4\n", expect_success: false) + end + + it "uses declaration order for unspecified fallback identity conflicts" do + test_parser("pslr_fallback_precedence", "z", "ZA 1\n", expect_success: false) + end + + it "uses explicit identity precedence before fallback declaration order" do + test_parser("pslr_fallback_precedence", "@", "PB 1\n", expect_success: false) + end + + it "preserves explicit identity precedence when fallback length precedence is needed" do + test_parser("pslr_fallback_precedence", "cd", "IB 2\n", expect_success: false) + end + + it "uses declaration order for fallback-only explicit identity cycles" do + test_parser("pslr_fallback_precedence", "~", "CYC_A 1\n", expect_success: false) + end + + it "returns YYEOF for empty input in PSLR pseudo-scan helpers" do + test_parser("pslr_fallback_precedence", "__empty__", "EOF 0 0 0 0\n") + end + + it "synthesizes implicit literal token patterns for parser-state rows" do + test_parser("pslr_implicit_literal", "x;", "ok\n") + end + + it "uses implicit literal token patterns in the fallback row" do + test_parser("pslr_implicit_literal", "__fallback_semi__", "SEMI 1 0\n") + end + + it "does not use fallback longest rules for normal parser-state rows" do + grammar_text = <<~GRAMMAR + %define lr.type pslr + %token-pattern A /a/ + %token-pattern B /ab/ + + %% + + start + : A + | B + ; + GRAMMAR + grammar = Lrama::Parser.new(grammar_text, "integration/pslr_normal_conflict.y").parse + grammar.prepare + grammar.validate! + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + logger = Lrama::Logger.new + allow(logger).to receive(:error) + + expect { states.validate!(logger) }.to raise_error(SystemExit) + expect(logger).to have_received(:error).with(a_string_including("unresolved PSLR scanner conflict", "A", "B")) + end + + it "does not use fallback declaration order for normal parser-state identity cycles" do + grammar_text = <<~GRAMMAR + %define lr.type pslr + %token-pattern A /a/ + %token-pattern B /a/ + %token-pattern C /a/ + + %lex-prec A <- B + %lex-prec B <- C + %lex-prec C <- A + + %% + + start + : A + | B + | C + ; + GRAMMAR + grammar = Lrama::Parser.new(grammar_text, "integration/pslr_normal_identity_cycle.y").parse + grammar.prepare + grammar.validate! + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + logger = Lrama::Logger.new + allow(logger).to receive(:error) + + expect { states.validate!(logger) }.to raise_error(SystemExit) + expect(logger).to have_received(:error).with(a_string_including("unresolved PSLR scanner conflict", "A", "B", "C")) + end + + it "consumes an unmatched PSLR character token before reporting an error" do + test_parser("pslr_template_argument_lists", "$", "", expect_success: false) + end + end + describe "user defined parameterized rules" do it "prints messages corresponding to rules" do expected = <<~STR @@ -436,4 +590,232 @@ def generate_object(grammar_file_path, c_path, obj_path, command_args: []) end end end + + describe "PSLR context-dependent lexing" do + describe "Scanner FSA with overlapping patterns" do + let(:rangle) do + id = Lrama::Lexer::Token::Ident.new(s_value: "RANGLE") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/>/") + Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + end + + let(:rshift) do + id = Lrama::Lexer::Token::Ident.new(s_value: "RSHIFT") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/>>/") + Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 1 + ) + end + + let(:scanner_fsa) { Lrama::ScannerFSA.new([rangle, rshift]) } + + it "recognizes both RANGLE and RSHIFT as possible matches for '>>'" do + results = scanner_fsa.scan(">>") + + token_names = results.map { |r| r[:token].name } + expect(token_names).to include("RANGLE") + expect(token_names).to include("RSHIFT") + end + + it "RANGLE matches at position 1, RSHIFT matches at position 2" do + results = scanner_fsa.scan(">>") + + rangle_match = results.find { |r| r[:token].name == "RANGLE" } + rshift_match = results.find { |r| r[:token].name == "RSHIFT" } + + expect(rangle_match[:position]).to eq(1) + expect(rshift_match[:position]).to eq(2) + end + end + + describe "Length precedence resolution" do + let(:lex_prec) { Lrama::Grammar::LexPrec.new } + + before do + left = Lrama::Lexer::Token::Ident.new(s_value: "RANGLE") + right = Lrama::Lexer::Token::Ident.new(s_value: "RSHIFT") + lex_prec.add_rule( + left_token: left, + operator: Lrama::Grammar::LexPrec::SHORTEST, + right_token: right, + lineno: 1 + ) + end + + let(:length_prec) { Lrama::LengthPrecedences.new(lex_prec) } + + it "indicates RANGLE (shorter) should be preferred over RSHIFT (longer)" do + expect(length_prec.prefer_shorter?("RANGLE", "RSHIFT")).to be true + end + + it "returns :left precedence for RANGLE vs RSHIFT" do + expect(length_prec.precedence("RANGLE", "RSHIFT")).to eq(:left) + end + end + + describe "Keyword vs identifier precedence" do + let(:lex_prec) { Lrama::Grammar::LexPrec.new } + + before do + left = Lrama::Lexer::Token::Ident.new(s_value: "ID") + right = Lrama::Lexer::Token::Ident.new(s_value: "IF") + lex_prec.add_rule( + left_token: left, + operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT_LONGEST, + right_token: right, + lineno: 1 + ) + end + + it "indicates IF has higher priority than ID" do + expect(lex_prec.identity_precedes?("IF", "ID")).to be true + end + + it "indicates ID does not have higher priority than IF" do + expect(lex_prec.identity_precedes?("ID", "IF")).to be false + end + end + + describe "Full PSLR grammar compilation" do + let(:grammar_text) do + <<~GRAMMAR + %define lr.type pslr + %token-pattern RSHIFT />>/ "right shift" + %token-pattern RANGLE />/ "right angle" + %token-pattern LANGLE />") + token_names = results.map { |r| r[:token].name } + + expect(token_names).to include("RANGLE") + expect(token_names).to include("RSHIFT") + end + + describe "context-dependent token selection" do + it "scanner_accepts table is built" do + expect(states.scanner_accepts_table).not_to be_nil + end + + it "different parser states may accept different tokens for same FSA state" do + scanner_accepts = states.scanner_accepts_table + scanner_fsa = states.scanner_fsa + + results = scanner_fsa.scan(">>") + rshift_result = results.find { |r| r[:token].name == "RSHIFT" } + rangle_result = results.find { |r| r[:token].name == "RANGLE" } + + expect(rshift_result).not_to be_nil + expect(rangle_result).not_to be_nil + expect(scanner_accepts.table).to be_a(Hash) + end + end + + describe "generated C code output" do + let(:out) { StringIO.new } + let(:context) { Lrama::Context.new(states) } + let(:output) do + Lrama::Output.new( + out: out, + output_file_path: "pslr_test.c", + template_name: "bison/yacc.c", + grammar_file_path: "pslr_test.y", + context: context, + grammar: grammar + ) + end + + before do + output.render + out.rewind + end + + let(:rendered) { out.read } + + it "includes yy_scanner_transition table" do + expect(rendered).to include("yy_scanner_transition") + expect(rendered).to include("YY_SCANNER_NUM_STATES") + end + + it "includes yy_state_to_accepting mapping" do + expect(rendered).to include("yy_state_to_accepting") + expect(rendered).to include("YY_ACCEPTING_NONE") + end + + it "includes yy_pslr_length_precedes table" do + expect(rendered).to include("yy_pslr_length_precedes") + end + + it "includes yy_pseudo_scan function" do + expect(rendered).to include("yy_pseudo_scan") + expect(rendered).to include("parser_state") + expect(rendered).to include("match_length") + end + + it "pseudo_scan function uses length precedences for token selection" do + expect(rendered).to include("yy_pslr_length_precedes[pbest][pattern_index]") + end + end + end + end end diff --git a/spec/lrama/output_spec.rb b/spec/lrama/output_spec.rb index 760fcbb1d..934d33703 100644 --- a/spec/lrama/output_spec.rb +++ b/spec/lrama/output_spec.rb @@ -357,4 +357,316 @@ end end end + + describe "PSLR methods" do + let(:token_pattern) do + id = Lrama::Lexer::Token::Ident.new(s_value: "ID") + regex = Lrama::Lexer::Token::Regex.new(s_value: "/[a-z]+/") + Lrama::Grammar::TokenPattern.new( + id: id, + pattern: regex, + lineno: 1, + definition_order: 0 + ) + end + + let(:scanner_fsa) { Lrama::ScannerFSA.new([token_pattern]) } + + let(:mock_states) do + instance_double( + Lrama::States, + scanner_fsa: scanner_fsa, + scanner_accepts_table: nil, + length_precedences: nil, + token_patterns: [token_pattern], + states: [], + find_symbol_by_s_value!: instance_double(Lrama::Grammar::Symbol, token_id: 301), + lexer_context_enabled?: false + ) + end + + let(:mock_context) do + instance_double(Lrama::Context, states: mock_states) + end + + let(:mock_grammar) do + instance_double( + Lrama::Grammar, + eof_symbol: nil, + error_symbol: nil, + undef_symbol: nil, + accept_symbol: nil, + locations: false, + parse_param: "struct parse_params *p", + lex_param: "struct parse_params *p", + pslr_defined?: true, + pslr_state_member: "current_state", + token_actions: [] + ) + end + + let(:pslr_output) do + out = StringIO.new + Lrama::Output.new( + out: out, + output_file_path: "test.c", + template_name: "bison/yacc.c", + grammar_file_path: "test.y", + context: mock_context, + grammar: mock_grammar + ) + end + + describe "#pslr_enabled?" do + it "returns true when grammar requested PSLR output" do + expect(pslr_output.pslr_enabled?).to be true + end + + it "returns false when grammar did not request PSLR output" do + allow(mock_grammar).to receive(:pslr_defined?).and_return(false) + expect(pslr_output.pslr_enabled?).to be false + end + end + + describe "#pslr_scanner_enabled?" do + it "returns true when scanner FSA is built with states" do + expect(pslr_output.pslr_scanner_enabled?).to be true + end + + it "returns false when scanner FSA is nil" do + allow(mock_states).to receive(:scanner_fsa).and_return(nil) + expect(pslr_output.pslr_scanner_enabled?).to be false + end + + it "returns false when scanner FSA has no states" do + empty_fsa = Lrama::ScannerFSA.new([]) + allow(mock_states).to receive(:scanner_fsa).and_return(empty_fsa) + expect(pslr_output.pslr_scanner_enabled?).to be false + end + end + + describe "#scanner_transition_table" do + it "generates C code for scanner transitions" do + result = pslr_output.scanner_transition_table + expect(result).to include("YY_SCANNER_NUM_STATES") + expect(result).to include("yy_scanner_transition") + end + end + + describe "#pseudo_scan_function" do + it "generates the pseudo_scan C function" do + result = pslr_output.pseudo_scan_function + expect(result).to include("yy_pseudo_scan") + expect(result).to include("parser_state") + expect(result).to include("match_length") + expect(result).to include("yy_token_pattern_to_token_id") + expect(result).to include("yy_pslr_fallback_length_precedes") + expect(result).to include("result->token = YYEOF") + end + end + + describe "#pslr_tables_and_functions" do + it "generates all PSLR C code" do + result = pslr_output.pslr_tables_and_functions + expect(result).to include("PSLR(1) Scanner Tables and Functions") + expect(result).to include("YY_SCANNER_NUM_STATES") + expect(result).to include("yy_scanner_transition") + expect(result).to include("yy_pseudo_scan") + expect(result).to include("yy_token_pattern_to_token_id") + end + + it "generates layout accumulation code" do + result = pslr_output.pslr_tables_and_functions + expect(result).to include("yypslr_layout_buffer") + expect(result).to include("YYPSLR_LAYOUT_TEXT") + expect(result).to include("YYPSLR_LAYOUT_LENGTH") + expect(result).to include("yypslr_scan_with_layout") + end + end + + describe "#pslr_lac_function" do + it "generates a LAC checker for PSLR parsers" do + result = pslr_output.pslr_lac_function + + expect(result).to include("yy_lac_check_") + expect(result).to include("yydefact") + end + end + + describe "#state_to_accepting_table" do + it "generates state to accepting mapping" do + result = pslr_output.state_to_accepting_table + expect(result).to include("yy_state_to_accepting") + expect(result).to include("YY_ACCEPTING_NONE") + end + end + + describe "#lexer_context_table_code" do + context "when lexer context is not enabled" do + it "returns empty string" do + result = pslr_output.lexer_context_table_code + expect(result).to eq("") + end + end + + context "when lexer context is enabled" do + let(:lexer_contexts) do + lcs = {} + lcs["BEG"] = Lrama::Grammar::LexerContext.new(name: "BEG", index: 0) + lcs["END"] = Lrama::Grammar::LexerContext.new(name: "END", index: 1) + lcs + end + + let(:classifier) { Lrama::LexerContextClassifier.new(lexer_contexts) } + + before do + allow(mock_states).to receive(:lexer_context_enabled?).and_return(true) + allow(mock_states).to receive(:lexer_context_table).and_return([0x01, 0x02, 0x01, 0x00]) + allow(mock_states).to receive(:lexer_context_classifier).and_return(classifier) + allow(mock_grammar).to receive(:lexer_contexts).and_return(lexer_contexts) + end + + it "generates the C context table" do + result = pslr_output.lexer_context_table_code + expect(result).to include("yy_lexer_context") + expect(result).to include("yy_lexer_context_is") + expect(result).to include("/* state 0 */") + expect(result).to include("/* state 3 */") + end + + it "generates defines via lexer_context_defines_code" do + result = pslr_output.lexer_context_defines_code + expect(result).to include("YY_CTX_BEG") + expect(result).to include("YY_CTX_END") + end + end + end + + describe "#pslr_function_declarations" do + it "declares the PSLR helper entry points" do + result = pslr_output.pslr_function_declarations + expect(result).to include("int yy_state_accepts_token") + expect(result).to include("int yy_pseudo_scan") + expect(result).to include("YYPSLR_PSEUDO_SCAN_STATE") + expect(result).to include("YYPSLR_PSEUDO_SCAN") + expect(result).to include("YYSETSTATE_CONTEXT(CurrentState)") + end + end + + describe "#length_precedences_table_code" do + let(:mock_length_prec) { Lrama::LengthPrecedences.new(Lrama::Grammar::LexPrec.new) } + + before do + allow(mock_states).to receive(:length_precedences).and_return(mock_length_prec) + end + + it "generates length precedences table" do + result = pslr_output.length_precedences_table_code + expect(result).to include("yy_pslr_length_precedes") + expect(result).to include("yy_pslr_fallback_length_precedes") + expect(result).to include("old_token") + end + + it "keeps traditional longest defaults out of the normal row table" do + a = Lrama::Grammar::TokenPattern.new( + id: Lrama::Lexer::Token::Ident.new(s_value: "A"), + pattern: Lrama::Lexer::Token::Regex.new(s_value: "/a/"), + lineno: 1, + definition_order: 0 + ) + b = Lrama::Grammar::TokenPattern.new( + id: Lrama::Lexer::Token::Ident.new(s_value: "B"), + pattern: Lrama::Lexer::Token::Regex.new(s_value: "/ab/"), + lineno: 1, + definition_order: 1 + ) + allow(mock_states).to receive(:token_patterns).and_return([a, b]) + + result = pslr_output.length_precedences_table_code + + expect(result).to include("static const int yy_pslr_length_precedes[2][2] = {\n /* A */ {1, 0},") + expect(result).to include("static const int yy_pslr_fallback_length_precedes[2][2] = {\n /* A */ {1, 1},") + end + end + + describe "#accepting_tokens_table" do + it "generates accepting tokens information" do + result = pslr_output.accepting_tokens_table + expect(result).to include("Accepting state token IDs") + end + end + end + + describe "PSLR integration in render" do + let(:pslr_grammar_text) do + <<~GRAMMAR + %code requires { + struct parse_params { + int current_state; + }; + } + %define lr.type pslr + %define api.pslr.state-member current_state + %parse-param {struct parse_params *p} + %lex-param {struct parse_params *p} + %token-pattern RSHIFT />>/ "right shift" + %token-pattern RANGLE />/ "right angle" + %lex-prec RANGLE -s RSHIFT + %% + program: RSHIFT | RANGLE + GRAMMAR + end + + let(:pslr_grammar) do + grammar = Lrama::Parser.new(pslr_grammar_text, "pslr_test.y").parse + grammar.prepare + grammar.validate! + grammar + end + + let(:pslr_states) do + s = Lrama::States.new(pslr_grammar, Lrama::Tracer.new(Lrama::Logger.new)) + s.compute + s.compute_pslr + s + end + + let(:pslr_context) { Lrama::Context.new(pslr_states) } + let(:pslr_out) { StringIO.new } + + let(:pslr_full_output) do + Lrama::Output.new( + out: pslr_out, + output_file_path: "pslr_test.c", + template_name: "bison/yacc.c", + grammar_file_path: "pslr_test.y", + header_out: header_out, + header_file_path: "pslr_test.h", + context: pslr_context, + grammar: pslr_grammar + ) + end + + it "includes PSLR tables in rendered output" do + pslr_full_output.render + pslr_out.rewind + header_out.rewind + rendered = pslr_out.read + rendered_header = header_out.read + + expect(rendered).to include("PSLR(1) Scanner Tables and Functions") + expect(rendered).to include("YY_SCANNER_NUM_STATES") + expect(rendered).to include("yy_scanner_transition") + expect(rendered).to include("yy_pseudo_scan") + expect(rendered).to include("yy_token_pattern_to_token_id") + expect(rendered).to include("yy_scanner_fallback_accepts") + expect(rendered).to include("yy_token_pattern_is_layout") + expect(rendered).to include("yy_lac_check_") + expect(rendered_header).to include("int yy_state_accepts_token") + expect(rendered_header).to include("int yy_pseudo_scan") + expect(rendered_header).to include("yypslr_scan_result") + expect(rendered_header).to include("YYSETSTATE_CONTEXT(CurrentState)") + expect(rendered_header).to include("YYPSLR_PSEUDO_SCAN(Context, Input, MatchLength)") + end + end end diff --git a/template/bison/_yacc.h b/template/bison/_yacc.h index 3e270c917..7cf4b6b21 100644 --- a/template/bison/_yacc.h +++ b/template/bison/_yacc.h @@ -71,6 +71,10 @@ struct YYLTYPE <%-# b4_declare_yyparse -%> int yyparse (<%= output.parse_param %>); +<%- if output.pslr_enabled? -%> +<%= output.pslr_function_declarations %> +<%- end -%> + <%= output.percent_code("provides") %> <%-# b4_cpp_guard_close([b4_spec_mapped_header_file]) -%> diff --git a/template/bison/yacc.c b/template/bison/yacc.c index abf8d6897..fe78543a0 100644 --- a/template/bison/yacc.c +++ b/template/bison/yacc.c @@ -68,6 +68,10 @@ #define YYPULL 1 +<%- if output.lexer_context_enabled? -%> +<%= output.lexer_context_defines_code %> +<%- end -%> + <%# b4_user_pre_prologue -%> <%- if output.aux.prologue -%> /* First part of user prologue. */ @@ -582,6 +586,206 @@ static const <%= output.int_type_for(output.context.yyr2) %> yyr2[] = <%= output.int_array_to_string(output.context.yyr2) %> }; +<%- if output.pslr_enabled? -%> +<%= output.pslr_function_declarations %> +<%- end -%> + +<%- if output.pslr_enabled? -%> +<%= output.pslr_tables_and_functions %> +<%- end -%> + +<%- if output.lexer_context_enabled? -%> +<%= output.lexer_context_table_code %> +<%- end -%> + +<%- if output.pslr_enabled? -%> +#ifndef YYSETSTATE_CONTEXT +# define YYSETSTATE_CONTEXT(CurrentState) ((void) 0) +#endif +<%- end -%> + +int +yy_state_accepts_token (int yystate, int yychar) +{ + yysymbol_kind_t yytoken = YYTRANSLATE (yychar); + int yyn = yypact[yystate]; + + if (yypact_value_is_default (yyn)) + return 0; + + yyn += yytoken; + if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) + return 0; + + yyn = yytable[yyn]; + if (yyn <= 0) + return !yytable_value_is_error (yyn); + + return 1; +} + +/* + * Like yy_state_accepts_token, but also follows chains of default reductions + * where the rule has zero symbols on the right-hand side (yyr2 == 0). + * This allows the lexer to see tokens that become visible only after + * empty productions are reduced (e.g., opt_terms -> epsilon). + * + * Returns 1 if the token would be accepted in the current state or in a + * state reachable via a chain of empty default reductions; 0 otherwise. + */ +int +yy_state_eventually_accepts_token (int yystate, int yychar) +{ + yysymbol_kind_t yytoken = YYTRANSLATE (yychar); + /* Limit iteration to prevent infinite loops from cyclic empty reductions. */ + int visited[64]; + int visited_count = 0; + + for (;;) + { + int yyn; + + /* 1. Check the current state's action table for the token. */ + yyn = yypact[yystate]; + if (!yypact_value_is_default (yyn)) + { + yyn += yytoken; + if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == yytoken) + { + yyn = yytable[yyn]; + if (yyn > 0 || !yytable_value_is_error (yyn)) + return 1; + } + } + + /* 2. Try to follow the default reduction if it's an empty rule. */ + { + int rule = yydefact[yystate]; + int lhs, goto_state; + int i; + + if (rule == 0 || yyr2[rule] != 0) + return 0; /* No default or non-empty rule: can't proceed. */ + + /* Cycle detection. */ + for (i = 0; i < visited_count; i++) + if (visited[i] == yystate) + return 0; + if (visited_count < 64) + visited[visited_count++] = yystate; + else + return 0; + + /* Compute GOTO state after reducing by the empty rule. */ + lhs = yyr1[rule] - YYNTOKENS; + goto_state = yypgoto[lhs] + yystate; + if (0 <= goto_state && goto_state <= YYLAST + && yycheck[goto_state] == yystate) + yystate = yytable[goto_state]; + else + yystate = yydefgoto[lhs]; + } + } +} + +/* + * Like yy_state_eventually_accepts_token, but also follows non-empty + * default reductions by using the actual parser stack to determine + * GOTO states. This allows the lexer to see tokens that become visible + * after reductions like stmt -> expr (yyr2 > 0). + * + * stack_base and stack_top point to the parser's state stack (yy_state_t). + * Returns 1 if the token is reachable; 0 otherwise. + */ +int +yy_state_deep_accepts_token (int yystate, int yychar, + const void *stack_base_v, const void *stack_top_v) +{ + typedef short yy_state_t_compat; + yysymbol_kind_t yytoken = YYTRANSLATE (yychar); + const yy_state_t_compat *stack_base = (const yy_state_t_compat *)stack_base_v; + const yy_state_t_compat *stack_top = (const yy_state_t_compat *)stack_top_v; + int visited[64]; + int visited_count = 0; + int stack_consumed = 0; /* how many stack items we've "popped" */ + + if (!stack_base || !stack_top) + return 0; + + for (;;) + { + int yyn; + + /* 1. Check the current state's action table for the token. */ + yyn = yypact[yystate]; + if (!yypact_value_is_default (yyn)) + { + yyn += yytoken; + if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == yytoken) + { + yyn = yytable[yyn]; + if (yyn > 0 || !yytable_value_is_error (yyn)) + return 1; + } + } + + /* 2. Try to follow the default reduction. */ + { + int rule = yydefact[yystate]; + int rhs_len, lhs, goto_state, uncovered_state; + int i; + + if (rule == 0) + return 0; /* No default action. */ + + /* Cycle detection. */ + for (i = 0; i < visited_count; i++) + if (visited[i] == yystate) + return 0; + if (visited_count < 64) + visited[visited_count++] = yystate; + else + return 0; + + rhs_len = yyr2[rule]; + + if (rhs_len == 0) + { + /* Empty reduction: use current state for GOTO (same as eventually_accepts). */ + lhs = yyr1[rule] - YYNTOKENS; + goto_state = yypgoto[lhs] + yystate; + if (0 <= goto_state && goto_state <= YYLAST + && yycheck[goto_state] == yystate) + yystate = yytable[goto_state]; + else + yystate = yydefgoto[lhs]; + } + else + { + /* Non-empty reduction: need to look at the stack. */ + int total_depth = stack_consumed + rhs_len; + const yy_state_t_compat *target = stack_top - total_depth; + + if (target < stack_base) + return 0; /* Stack too shallow. */ + + uncovered_state = (int)*target; + lhs = yyr1[rule] - YYNTOKENS; + goto_state = yypgoto[lhs] + uncovered_state; + if (0 <= goto_state && goto_state <= YYLAST + && yycheck[goto_state] == uncovered_state) + yystate = yytable[goto_state]; + else + yystate = yydefgoto[lhs]; + + /* After a non-empty reduction, the stack effectively shrank. + * But since we consumed rhs_len items and pushed 1 (the GOTO state), + * net consumption is rhs_len - 1. */ + stack_consumed += rhs_len - 1; + } + } + } +} enum { YYENOMEM = -2 }; @@ -858,10 +1062,14 @@ int yydebug; # define YYMAXDEPTH 10000 #endif +<%- if output.pslr_enabled? -%> +<%= output.pslr_lac_function %> +<%- end -%> /* Context of a parse error. */ typedef struct { + yy_state_t *yyss; yy_state_t *yyssp; yysymbol_kind_t yytoken; YYLTYPE *yylloc; @@ -879,6 +1087,23 @@ yypcontext_expected_tokens (const yypcontext_t *yyctx, { /* Actual size of YYARG. */ int yycount = 0; +<%- if output.pslr_enabled? -%> + int yyx; + for (yyx = 0; yyx < YYNTOKENS; ++yyx) + if (yyx != YYSYMBOL_YYerror + && yy_lac_check_ (yyctx->yyss, yyctx->yyssp, YY_CAST (yysymbol_kind_t, yyx))) + { + if (!yyarg) + ++yycount; + else if (yycount == yyargn) + return 0; + else + yyarg[yycount++] = YY_CAST (yysymbol_kind_t, yyx); + } + if (yyarg && yycount == 0 && 0 < yyargn) + yyarg[0] = YYSYMBOL_YYEMPTY; + return yycount; +<%- else -%> int yyn = yypact[+*yyctx->yyssp]; if (!yypact_value_is_default (yyn)) { @@ -905,6 +1130,7 @@ yypcontext_expected_tokens (const yypcontext_t *yyctx, if (yyarg && yycount == 0 && 0 < yyargn) yyarg[0] = YYSYMBOL_YYEMPTY; return yycount; +<%- end -%> } @@ -1582,6 +1808,9 @@ YYLTYPE yylloc = yyloc_default; YY_IGNORE_USELESS_CAST_BEGIN *yyssp = YY_CAST (yy_state_t, yystate); YY_IGNORE_USELESS_CAST_END +<%- if output.pslr_enabled? -%> + YYSETSTATE_CONTEXT (yystate); +<%- end -%> YY_STACK_PRINT (yyss, yyssp<%= output.user_args %>); if (yyss + yystacksize - 1 <= yyssp) @@ -1668,6 +1897,40 @@ YYLTYPE yylloc = yyloc_default; /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; +<%- if output.pslr_enabled? -%> + if (yypact_value_is_default (yyn) && yydefact[yystate] != 0) + { + if (yychar == YYEMPTY) + { + YYDPRINTF ((stderr, "Reading a token\n")); + yychar = yylex <%= output.yylex_formals %>; + } + + if (yychar <= <%= output.eof_symbol.id.s_value %>) + { + yychar = <%= output.eof_symbol.id.s_value %>; + yytoken = <%= output.eof_symbol.enum_name %>; + YYDPRINTF ((stderr, "Now at end of input.\n")); + } + else if (yychar == <%= output.error_symbol.id.s_value %>) + { + yychar = <%= output.undef_symbol.id.s_value %>; + yytoken = <%= output.error_symbol.enum_name %>; + yyerror_range[1] = yylloc; + goto yyerrlab1; + } + else + { + yytoken = YYTRANSLATE (yychar); + YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc<%= output.user_args %>); + } + + if (!yy_lac_check_ (yyss, yyssp, yytoken)) + goto yyerrlab; + + goto yydefault; + } +<%- end -%> if (yypact_value_is_default (yyn)) goto yydefault; @@ -1736,6 +1999,11 @@ YYLTYPE yylloc = yyloc_default; YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc<%= output.user_args %>); } +<%- if output.pslr_enabled? -%> + if (!yy_lac_check_ (yyss, yyssp, yytoken)) + goto yyerrlab; +<%- end -%> + /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; @@ -1854,7 +2122,7 @@ YYLTYPE yylloc = yyloc_default; ++yynerrs; { yypcontext_t yyctx - = {yyssp, yytoken, &yylloc}; + = {yyss, yyssp, yytoken, &yylloc}; char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = yysyntax_error (&yymsg_alloc, &yymsg, &yyctx<%= output.user_args %>); @@ -2065,4 +2333,3 @@ YYLTYPE yylloc = yyloc_default; #line <%= output.aux.epilogue_first_lineno - 1 %> "<%= output.grammar_file_path %>" <%= output.aux.epilogue -%> <%- end -%> - From fd73358f030ba0777ed4fb35c9130cbabfef4a65 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 21:43:24 +0900 Subject: [PATCH 06/24] pslr: add PSLR reporting, tie-candidate warnings and CLI wiring * --report=pslr renders scanner metrics: state growth before/after splitting, token pattern and FSA state counts, per-state scanner_accepts rows and unresolved-conflict details * warn about lexical tie candidates (Def 3.3.3): token pairs that have a scanner conflict but appear one-sided in some parser state, unless an explicit %lex-tie/%lex-no-tie already covers the pair * Command runs compute_pslr for %define lr.type pslr grammars and validates states before writing any parser output, so unresolved scanner conflicts and state-growth guard violations abort generation * document the PSLR(1) directives in NEWS --- NEWS.md | 136 ++++++ lib/lrama/option_parser.rb | 3 +- lib/lrama/reporter.rb | 3 + lib/lrama/reporter/pslr.rb | 42 ++ lib/lrama/warnings.rb | 3 + lib/lrama/warnings/lexical_tie_candidates.rb | 27 ++ sig/generated/lrama/reporter/pslr.rbs | 18 + .../lrama/warnings/lexical_tie_candidates.rbs | 13 + spec/fixtures/command/pslr_growth_limit.y | 36 ++ spec/fixtures/command/pslr_pure_reduce.y | 26 ++ spec/lrama/command_spec.rb | 150 +++++++ spec/lrama/option_parser_spec.rb | 12 +- spec/lrama/pslr_family_regressions_spec.rb | 394 ++++++++++++++++++ spec/lrama/pslr_generated_families_spec.rb | 49 +++ 14 files changed, 909 insertions(+), 3 deletions(-) create mode 100644 lib/lrama/reporter/pslr.rb create mode 100644 lib/lrama/warnings/lexical_tie_candidates.rb create mode 100644 sig/generated/lrama/reporter/pslr.rbs create mode 100644 sig/generated/lrama/warnings/lexical_tie_candidates.rbs create mode 100644 spec/fixtures/command/pslr_growth_limit.y create mode 100644 spec/fixtures/command/pslr_pure_reduce.y create mode 100644 spec/lrama/pslr_family_regressions_spec.rb create mode 100644 spec/lrama/pslr_generated_families_spec.rb diff --git a/NEWS.md b/NEWS.md index 693b46f01..8a1a52ae6 100644 --- a/NEWS.md +++ b/NEWS.md @@ -40,6 +40,142 @@ program: args_list(f_opt(number), opt_tail(string), number) https://github.com/ruby/lrama/pull/779 +### [EXPERIMENTAL] Support core PSLR(1) parser generation + +Added experimental support for generating a PSLR(1)-style parser based on this dissertation. +https://open.clemson.edu/all_dissertations/519/ + +This adds the following PSLR-related grammar directives and integration points: + +- `%define lr.type pslr` enables PSLR parser generation +- `%token-pattern` declares token candidates and their regular expressions for PSLR-aware lexical disambiguation +- `%lex-prec` declares explicit lexical precedence for overlapping token patterns +- `%symbol-set` declares reusable sets of terminal tokens for PSLR lexical declarations +- `%lex-tie` expands parser-state acceptable-token sets for tied terminals +- `%lex-no-tie` records an explicit no-tie decision for terminals with overlapping token patterns +- `YYLAYOUT*` token patterns are recognized in every parser state and discarded by PSLR-aware lexers +- `%define pslr.max-states` and `%define pslr.max-state-ratio` are Lrama-specific safety guards for state growth +- `%define api.pslr.state-member` names the parser-state field to be shared with the lexer when using the generated helper macros + +Typical usage looks like this: + +```yacc +%define api.pure +%define lr.type pslr +%define api.pslr.state-member current_state + +%parse-param {struct parse_params *p} +%lex-param {struct parse_params *p} + +%token-pattern RSHIFT />>/ "right shift" +%token-pattern RANGLE />/ "right angle" +%token-pattern ID /[a-z]+/ + +%lex-no-tie RANGLE RSHIFT +``` + +In this setup, `%token-pattern` lists the tokens that the generated pseudo-scanner FSA should consider, and +`%lex-no-tie` records that `RANGLE` and `RSHIFT` should not be treated as tied tokens. In a template-closing +parser state only `RANGLE` is syntactically acceptable, while a shift-expression state accepts `RSHIFT`; PSLR +state splitting and scanner profiles choose between the two without a global shortest-match rule. Use `%lex-prec` +for real lexical precedence relations, such as comment patterns that need a shortest-match or longest-match rule +in every parser context. + +For normal parser-state scanner rows, unresolved pseudo-scanner conflicts are not resolved by token declaration +order. They are reported as errors so the grammar can add an explicit `%lex-prec`, `%lex-tie`, or `%lex-no-tie` +declaration. For syntax-error handling, Lrama also emits a fallback scanner row. The fallback row first applies +explicit PSLR lexical precedence declarations. If a scanner conflict remains unresolved only because it is not a +pseudo-scanner conflict for any parser state, the fallback row completes the decision with scanner-default rules: +length conflicts use longest match and identity conflicts use token declaration order only for token pairs without +an explicit identity precedence relation. These defaults are composed with the explicit graph, so explicit identity +precedence is still honored when fallback length precedence is needed. For normal parser-state rows, explicit +precedence cycles remain unresolved and are reported as PSLR scanner conflicts. For the syntax-error fallback row +only, if explicit PSLR precedence plus fallback length defaults still do not determine a unique identity winner, +Lrama completes the fallback decision with traditional token declaration order so that a token-pattern match is +returned whenever `M(input, T0)` is non-empty. If no token pattern matches at all, the PSLR helper consumes one +byte and returns `YYUNDEF` as a character-token fallback, so error paths do not loop forever. + +`%lex-prec` uses ASCII spellings for the PSLR lexical precedence operators: + +| Lrama | Meaning | +|---|---| +| `<~` | identity conflict: right token wins; length conflict: longest match wins | +| `<-` | identity conflict: right token wins | +| `-~` | length conflict: longest match wins | +| `<<` | identity and length conflicts: right token wins | +| `-<` | length conflict: right token wins | +| `` versus `>>`; those cases should be handled by PSLR state +splitting plus `%lex-no-tie` when the tokens are intentionally not tied. + +Contradictory length precedence declarations are rejected instead of being silently overwritten. For example, +declaring both `%lex-prec A -~ B` and `%lex-prec A -s B` reports the token pair, the two operators and lines, and +the scan direction where the contradiction occurs. + +Lexical ties are separate from precedence. For example: + +```yacc +%token-pattern IF /if/ +%token-pattern ID /[a-z]+/ +%symbol-set keywords IF +%lex-tie ID keywords +%lex-prec ID <~ keywords +``` + +Here, `IF` can be considered when the parser state accepts `ID`, but `%lex-tie` does not choose a winner. +The `%lex-prec ID <~ keywords` declaration resolves the `if` identity conflict in favor of `IF` while keeping +longer identifiers such as `ifx` as `ID`. + +When both operands of `%lex-tie` are explicit tokens, Lrama ties them even if their token patterns do not conflict. +When either operand is a `%symbol-set` or `yyall`, Lrama follows the PSLR paper and ties only token pairs that have +a pairwise scanner conflict. This avoids unnecessary transitive lexical ties and the pseudo-scanner conflicts they +would create. + +`%lex-no-tie` suppresses lexical tie candidate warnings; it does not break a final transitive tie closure. Generic +declarations such as `%lex-no-tie yyall yyall` can suppress broad candidate reports, and a more specific `%lex-tie` +can still tie the relevant token pair. + +Token patterns named `YYLAYOUT` or starting with `YYLAYOUT` are layout tokens. They are included in every +parser-state scanner row and should be consumed and skipped by the PSLR-aware lexer instead of being returned to +the parser. The generated helpers include `YYPSLR_TOKEN_IS_LAYOUT(Token)` and the structured +`YYPSLR_PSEUDO_SCAN_RESULT(...)` API for this purpose. + +`yy_pseudo_scan_result` is a low-level scanner helper and may report a layout token with `result->is_layout = 1`. +A PSLR-aware `yylex` must consume that text, keep the same parser state, and scan the remaining input instead of +passing the layout token to the parser. + +The generated PSLR scanner FSA considers terminals declared with `%token-pattern` and character literal terminals +for which Lrama can synthesize an exact-match implicit token pattern. Grammar terminals without either a token +pattern or a supported literal spelling remain outside the generated pseudo-scanner helper. Thus, the paper's `T0` +fallback token set corresponds here to the set of terminals known to the generated scanner FSA. Parser-state rows +use the subset accepted by the current state plus tied tokens and layout tokens. The fallback row uses the whole +generated scanner universe so error handling can still identify and consume a token when the current parser state +has no normal scanner decision. + +`%token-pattern` currently uses an ASCII byte-oriented regular-expression subset for PSLR pseudo scanning. +Supported constructs are literals, escaped literals such as `\/`, `\*`, `\+`, `\?`, `\(`, `\)`, `\[`, `\]`, +and `\\`, grouping with `(...)`, alternation with `|`, repetition operators `*`, `+`, `?`, character classes with +escapes such as `[\]]`, `[\\]`, and `[\n\t\r]`, ranges such as `[a-z]`, negated classes such as `[^*]`, common +escapes such as `\n`, `\t`, and `\r`, and `.`. The `.` operator matches ASCII bytes except newline; negated +character classes range over ASCII bytes. Unicode properties and full Ruby/Onigmo regexp syntax are not supported. +Unsupported or malformed constructs are rejected during generation rather than silently reinterpreted. Nullable +token patterns such as `//`, `/()/`, `/a*/`, `/a?/`, and `/a|/` are generation errors because PSLR token lexemes +must be non-empty. + +When the parser and lexer share a context through `%parse-param` / `%lex-param`, the generated header also +provides helpers such as `YYPSLR_PSEUDO_SCAN(...)`, so the lexer can choose a token based on the current parser +state. The paper-compatible scanning path needs the lexer to pass the unconsumed input prefix, not only an +already-decided token fragment, so legacy external lexer bridges may still be limited by the text they provide. + +PSLR parsers enable a lightweight LAC check in the generated parser so syntax errors caused by LR state merging, +default reductions, or `%nonassoc` error actions are detected before user semantic actions are run for the bad +lookahead. PSLR support is still experimental. Scoped lexical declarations, lexical nonterminals, and `%lex` +are not implemented yet. If you find any bugs, please report them. + ## Lrama 0.7.1 (2025-12-24) ### Optimize IELR diff --git a/lib/lrama/option_parser.rb b/lib/lrama/option_parser.rb index f1ba90a13..7af45630f 100644 --- a/lib/lrama/option_parser.rb +++ b/lib/lrama/option_parser.rb @@ -96,6 +96,7 @@ def parse_by_option_parser(argv) o.on_tail ' solved describe shift/reduce conflicts solving' o.on_tail ' counterexamples, cex generate conflict counterexamples' o.on_tail ' ielr show IELR isocores with lookahead diffs and split reasons' + o.on_tail ' pslr report PSLR split and scanner metrics' o.on_tail ' rules list unused rules' o.on_tail ' terms list unused terminals' o.on_tail ' verbose report detailed internal state and analysis results' @@ -140,7 +141,7 @@ def parse_by_option_parser(argv) end ALIASED_REPORTS = { cex: :counterexamples }.freeze #: Hash[Symbol, Symbol] - VALID_REPORTS = %i[states itemsets lookaheads solved counterexamples ielr rules terms verbose].freeze #: Array[Symbol] + VALID_REPORTS = %i[states itemsets lookaheads solved counterexamples ielr pslr rules terms verbose].freeze #: Array[Symbol] # @rbs (Array[String]) -> Hash[Symbol, bool] def validate_report(report) diff --git a/lib/lrama/reporter.rb b/lib/lrama/reporter.rb index 6a452d4b9..b7fe0743e 100644 --- a/lib/lrama/reporter.rb +++ b/lib/lrama/reporter.rb @@ -6,6 +6,7 @@ require_relative 'reporter/ielr' require_relative 'reporter/precedences' require_relative 'reporter/profile' +require_relative 'reporter/pslr' require_relative 'reporter/rules' require_relative 'reporter/states' require_relative 'reporter/terms' @@ -21,6 +22,7 @@ def initialize(**options) @terms = Terms.new(**options) @conflicts = Conflicts.new @precedences = Precedences.new + @pslr = Pslr.new(**options) @grammar = Grammar.new(**options) @ielr = Ielr.new(**options) @states = States.new(**options) @@ -33,6 +35,7 @@ def report(io, states) report_duration(:report_terms) { @terms.report(io, states) } report_duration(:report_conflicts) { @conflicts.report(io, states) } report_duration(:report_precedences) { @precedences.report(io, states) } + report_duration(:report_pslr) { @pslr.report(io, states) } report_duration(:report_grammar) { @grammar.report(io, states) } report_duration(:report_ielr) { @ielr.report(io, states) } report_duration(:report_states) { @states.report(io, states, ielr: states.ielr_defined?) } diff --git a/lib/lrama/reporter/pslr.rb b/lib/lrama/reporter/pslr.rb new file mode 100644 index 000000000..766c5855b --- /dev/null +++ b/lib/lrama/reporter/pslr.rb @@ -0,0 +1,42 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Reporter + class Pslr + # @rbs (?pslr: bool, **bool _) -> void + def initialize(pslr: false, **_) + @pslr = pslr + end + + # @rbs (IO io, Lrama::States states) -> void + def report(io, states) + return unless @pslr + return unless states.pslr_defined? + + metrics = states.pslr_metrics + + io << "PSLR Summary\n\n" + io << " Base states: #{metrics[:base_states_count]}\n" + io << " Total states: #{metrics[:total_states_count]}\n" + io << " Split states: #{metrics[:split_state_count]}\n" + io << " State growth: +#{metrics[:growth_count]} (#{format_ratio(metrics[:growth_ratio])})\n" + io << " Token patterns: #{metrics[:token_pattern_count]}\n" + io << " Scanner states: #{metrics[:scanner_fsa_state_count]}\n" + io << " Inadequacies: #{metrics[:inadequacies_count]}\n" + io << " Max states: #{states.pslr_max_states || 'unbounded'}\n" + io << " Max ratio: #{states.pslr_max_state_ratio || 'unbounded'}\n" + io << "\n" + end + + private + + # @rbs (Numeric?) -> String + def format_ratio(value) + return "n/a" if value.nil? + + "#{format('%.2f', value)}x" + end + end + end +end diff --git a/lib/lrama/warnings.rb b/lib/lrama/warnings.rb index 30085c926..c1acf5692 100644 --- a/lib/lrama/warnings.rb +++ b/lib/lrama/warnings.rb @@ -9,6 +9,7 @@ require_relative 'warnings/required' require_relative 'warnings/token_redeclarations' require_relative 'warnings/useless_precedence' +require_relative 'warnings/lexical_tie_candidates' module Lrama class Warnings @@ -22,6 +23,7 @@ def initialize(logger, warnings) @required = Required.new(logger, warnings) @token_redeclarations = TokenRedeclarations.new(logger) @useless_precedence = UselessPrecedence.new(logger, warnings) + @lexical_tie_candidates = LexicalTieCandidates.new(logger, warnings) end # @rbs (Lrama::Grammar grammar, Lrama::States states) -> void @@ -34,6 +36,7 @@ def warn(grammar, states) @redefined_rules.warn(grammar) @required.warn(grammar) @useless_precedence.warn(grammar, states) + @lexical_tie_candidates.warn(states) end end end diff --git a/lib/lrama/warnings/lexical_tie_candidates.rb b/lib/lrama/warnings/lexical_tie_candidates.rb new file mode 100644 index 000000000..e45cccb2e --- /dev/null +++ b/lib/lrama/warnings/lexical_tie_candidates.rb @@ -0,0 +1,27 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Warnings + class LexicalTieCandidates + # @rbs (Logger logger, bool warnings) -> void + def initialize(logger, warnings) + @logger = logger + @warnings = warnings + end + + # @rbs (Lrama::States states) -> void + def warn(states) + return unless @warnings + return unless states.respond_to?(:lexical_tie_candidates) + + states.lexical_tie_candidates.each do |left, right| + @logger.warn( + "lexical tie candidate: #{left} and #{right} conflict lexically but are not tied; " \ + "add %lex-tie #{left} #{right} or %lex-no-tie #{left} #{right}" + ) + end + end + end + end +end diff --git a/sig/generated/lrama/reporter/pslr.rbs b/sig/generated/lrama/reporter/pslr.rbs new file mode 100644 index 000000000..c9de08058 --- /dev/null +++ b/sig/generated/lrama/reporter/pslr.rbs @@ -0,0 +1,18 @@ +# Generated from lib/lrama/reporter/pslr.rb with RBS::Inline + +module Lrama + class Reporter + class Pslr + # @rbs (?pslr: bool, **bool _) -> void + def initialize: (?pslr: bool, **bool _) -> void + + # @rbs (IO io, Lrama::States states) -> void + def report: (IO io, Lrama::States states) -> void + + private + + # @rbs (Numeric?) -> String + def format_ratio: (Numeric?) -> String + end + end +end diff --git a/sig/generated/lrama/warnings/lexical_tie_candidates.rbs b/sig/generated/lrama/warnings/lexical_tie_candidates.rbs new file mode 100644 index 000000000..43e569a41 --- /dev/null +++ b/sig/generated/lrama/warnings/lexical_tie_candidates.rbs @@ -0,0 +1,13 @@ +# Generated from lib/lrama/warnings/lexical_tie_candidates.rb with RBS::Inline + +module Lrama + class Warnings + class LexicalTieCandidates + # @rbs (Logger logger, bool warnings) -> void + def initialize: (Logger logger, bool warnings) -> void + + # @rbs (Lrama::States states) -> void + def warn: (Lrama::States states) -> void + end + end +end diff --git a/spec/fixtures/command/pslr_growth_limit.y b/spec/fixtures/command/pslr_growth_limit.y new file mode 100644 index 000000000..095ed6ae8 --- /dev/null +++ b/spec/fixtures/command/pslr_growth_limit.y @@ -0,0 +1,36 @@ +%define lr.type pslr + +%token-pattern P /p/ +%token-pattern Q /q/ +%token-pattern X /x/ +%token-pattern IF /if/ +%token-pattern ID /[a-z]+/ + +%lex-prec ID <~ IF + +%% + +program + : kw_context + | id_context + ; + +kw_context + : P shared IF + ; + +id_context + : Q shared ID + ; + +shared + : n1 + ; + +n1 + : n2 + ; + +n2 + : X + ; diff --git a/spec/fixtures/command/pslr_pure_reduce.y b/spec/fixtures/command/pslr_pure_reduce.y new file mode 100644 index 000000000..99e8ec6ef --- /dev/null +++ b/spec/fixtures/command/pslr_pure_reduce.y @@ -0,0 +1,26 @@ +%define lr.type pslr + +%token-pattern RSHIFT />>/ +%token-pattern RANGLE />/ +%token-pattern ID /[a-z]+/ + +%lex-prec RANGLE -~ RSHIFT + +%% + +program + : templ + | rshift_expr + ; + +templ + : a RANGLE + ; + +rshift_expr + : a RSHIFT ID + ; + +a + : ID + ; diff --git a/spec/lrama/command_spec.rb b/spec/lrama/command_spec.rb index b568b30eb..6256b62a5 100644 --- a/spec/lrama/command_spec.rb +++ b/spec/lrama/command_spec.rb @@ -207,5 +207,155 @@ end end end + + context "when a PSLR grammar needs pure-reduce lookahead to choose tokens" do + let(:outfile) { File.join(Dir.tmpdir, "pslr-pure-reduce.c") } + + before do + File.delete(outfile) if File.exist?(outfile) + end + + after do + File.delete(outfile) if File.exist?(outfile) + end + + it "emits parser output successfully" do + command = Lrama::Command.new(["-o", outfile, fixture_path("command/pslr_pure_reduce.y")]) + + expect(command.run).to be_nil + expect(File).to exist(outfile) + end + end + + context "when validation aborts" do + let(:outfile) { File.join(Dir.tmpdir, "validate-abort.c") } + + before do + File.delete(outfile) if File.exist?(outfile) + end + + after do + File.delete(outfile) if File.exist?(outfile) + end + + it "fails before writing parser output" do + allow_any_instance_of(Lrama::States).to receive(:validate!).and_raise(SystemExit) + + command = Lrama::Command.new(["-o", outfile, fixture_path("command/basic.y")]) + + expect { command.run }.to raise_error(SystemExit) + expect(File).not_to exist(outfile) + end + end + + context "when validation fails with requested reports" do + let(:outfile) { File.join(Dir.tmpdir, "invalid-parser.c") } + let(:report_file) { File.join(Dir.tmpdir, "invalid-parser.output") } + + before do + allow(STDIN).to receive(:read).and_return(source) + end + + after do + File.delete(outfile) if File.exist?(outfile) + File.delete(report_file) if File.exist?(report_file) + end + + shared_examples "a diagnostic report without parser output" do + it "writes the requested report before aborting" do + command = Lrama::Command.new([ + "--report=pslr,states", + "--report-file=#{report_file}", + "-o", outfile, + "-", "invalid.y" + ]) + + expect do + expect { command.run }.to raise_error(SystemExit) + end.to output(error_message).to_stderr_from_any_process + + expect(File).to exist(report_file) + expect(File.read(report_file)).to include(report_message, "State 0") + expect(File).not_to exist(outfile) + end + end + + context "with an unresolved PSLR scanner conflict" do + let(:source) do + <<~GRAMMAR + %define lr.type pslr + %token-pattern A /a/ + %token-pattern B /a/ + %% + start: A | B; + GRAMMAR + end + let(:error_message) { /unresolved PSLR scanner conflict/ } + let(:report_message) { "PSLR Unresolved Scanner Conflicts" } + + include_examples "a diagnostic report without parser output" + end + + context "with a LALR %expect mismatch" do + let(:source) do + <<~GRAMMAR + %expect 0 + %% + start: 'a' | start start; + GRAMMAR + end + let(:error_message) { /shift\/reduce conflicts: 1 found, 0 expected/ } + let(:report_message) { "conflicts: 1 shift/reduce" } + + include_examples "a diagnostic report without parser output" + end + end + + it "preserves parser and report files when a split would exceed the state limit" do + Dir.mktmpdir do |dir| + outfile = File.join(dir, "parse.c") + report = File.join(dir, "parse.output") + File.write(outfile, "previous parser") + File.write(report, "previous report") + command = Lrama::Command.new(["-Dpslr.max-states=15", "--report=pslr", "--report-file=#{report}", + "-o", outfile, fixture_path("command/pslr_growth_limit.y")]) + + expect do + expect { command.run }.to raise_error(SystemExit) { |error| expect(error).not_to be_success } + end.to output(/error: PSLR state growth exceeded pslr.max-states=15/).to_stderr_from_any_process + expect(File.read(outfile)).to eq("previous parser") + expect(File.read(report)).to eq("previous report") + end + end + + context "when PSLR report output is requested" do + let(:outfile) { File.join(Dir.tmpdir, "pslr-report.c") } + let(:report_file) { File.join(Dir.tmpdir, "pslr-report.output") } + + before do + File.delete(outfile) if File.exist?(outfile) + File.delete(report_file) if File.exist?(report_file) + end + + after do + File.delete(outfile) if File.exist?(outfile) + File.delete(report_file) if File.exist?(report_file) + end + + it "writes PSLR metrics into the report file" do + command = Lrama::Command.new([ + "--report=pslr", + "--report-file=#{report_file}", + "-o", outfile, + fixture_path("command/pslr_growth_limit.y") + ]) + + expect(command.run).to be_nil + report = File.read(report_file) + expect(report).to include("PSLR Summary") + expect(report).to include("Base states:") + expect(report).to include("Total states:") + end + end end end diff --git a/spec/lrama/option_parser_spec.rb b/spec/lrama/option_parser_spec.rb index 6d6293744..944a8590a 100644 --- a/spec/lrama/option_parser_spec.rb +++ b/spec/lrama/option_parser_spec.rb @@ -81,6 +81,7 @@ solved describe shift/reduce conflicts solving counterexamples, cex generate conflict counterexamples ielr show IELR isocores with lookahead diffs and split reasons + pslr report PSLR split and scanner metrics rules list unused rules terms list unused terminals verbose report detailed internal state and analysis results @@ -129,13 +130,20 @@ end end + context "when pslr is passed" do + it "returns option hash pslr flag enabled" do + opts = option_parser.send(:validate_report, ["pslr"]) + expect(opts).to eq({grammar: true, pslr: true}) + end + end + context "when all is passed" do it "returns option hash all flags enabled" do opts = option_parser.send(:validate_report, ["all"]) expect(opts).to eq({ grammar: true, states: true, itemsets: true, lookaheads: true, solved: true, counterexamples: true, - ielr: true, + ielr: true, pslr: true, rules: true, terms: true, verbose: true }) end @@ -145,7 +153,7 @@ expect(opts).to eq({ grammar: true, states: true, itemsets: true, lookaheads: true, solved: true, counterexamples: true, - ielr: true, + ielr: true, pslr: true, rules: true, terms: true, verbose: true }) end diff --git a/spec/lrama/pslr_family_regressions_spec.rb b/spec/lrama/pslr_family_regressions_spec.rb new file mode 100644 index 000000000..0001e911e --- /dev/null +++ b/spec/lrama/pslr_family_regressions_spec.rb @@ -0,0 +1,394 @@ +# frozen_string_literal: true + +RSpec.describe "PSLR family regressions" do + include PslrFamilyHelper + + describe "pure-reduce profile" do + let(:grammar) do + build_grammar(<<~GRAMMAR, "states/pslr_pure_reduce.y") + %define lr.type pslr + %token-pattern RSHIFT />>/ + %token-pattern RANGLE />/ + %token-pattern ID /[a-z]+/ + %lex-prec RANGLE -~ RSHIFT + + %% + + program + : templ + | rshift_expr + ; + + templ + : a RANGLE + ; + + rshift_expr + : a RSHIFT ID + ; + + a + : ID + ; + GRAMMAR + end + + it "keeps pure reduce states scanner-compatible without forcing a split" do + ielr_states, pslr_states = compute_ielr_and_pslr(grammar) + + reduce_state = pslr_states.states.find do |state| + state.reduces.any? { |reduce| reduce.rule.display_name == "a -> ID" } + end + + expect(pslr_states.states_count).to eq(ielr_states.states_count) + expect(pslr_states.pslr_inadequacies).to be_empty + expect(acceptable_tokens(pslr_states, reduce_state)).to contain_exactly("RANGLE", "RSHIFT") + end + end + + describe "chained keyword split" do + let(:grammar) do + build_grammar(<<~GRAMMAR, "states/pslr_keyword_context.y") + %define lr.type pslr + %token-pattern P /p/ + %token-pattern Q /q/ + %token-pattern X /x/ + %token-pattern IF /if/ + %token-pattern ID /[a-z]+/ + %lex-prec ID <~ IF + + %% + + program + : kw_context + | id_context + ; + + kw_context + : P shared IF + ; + + id_context + : Q shared ID + ; + + shared + : n1 + ; + + n1 + : n2 + ; + + n2 + : X + ; + GRAMMAR + end + + it "splits every chained reduce state by scanner profile" do + ielr_states, pslr_states = compute_ielr_and_pslr(grammar) + + reduce_states = pslr_states.states + .select { |state| state.reduces.any? } + .group_by { |state| state.reduces.first.rule.display_name } + + expect(pslr_states.states_count).to be > ielr_states.states_count + expect(pslr_states.pslr_inadequacies).to be_empty + + ["shared -> n1", "n1 -> n2", "n2 -> X"].each do |rule_name| + states_for_rule = reduce_states.fetch(rule_name) + token_sets = states_for_rule.map { |state| acceptable_tokens(pslr_states, state) } + + expect(states_for_rule.size).to eq(2) + expect(states_for_rule.count(&:split_state?)).to eq(1) + expect(token_sets.any? { |set| set.include?("IF") && !set.include?("ID") }).to be(true) + expect(token_sets.any? { |set| set.include?("ID") && !set.include?("IF") }).to be(true) + end + end + end + + describe "chained shift/angle split" do + let(:grammar) do + build_grammar(<<~GRAMMAR, "states/pslr_shift_chain.y") + %define lr.type pslr + %token-pattern LT />/ + %token-pattern RANGLE />/ + %token-pattern ID /[a-z]+/ + %lex-no-tie RANGLE RSHIFT + + %% + + program + : template_expr + | shift_expr + ; + + template_expr + : LT shared RANGLE + ; + + shift_expr + : START shared RSHIFT ID + ; + + shared + : n1 + ; + + n1 + : n2 + ; + + n2 + : MARK + ; + GRAMMAR + end + + it "splits every chained reduce state by shift/angle scanner profile" do + ielr_states, pslr_states = compute_ielr_and_pslr(grammar) + + reduce_states = pslr_states.states + .select { |state| state.reduces.any? } + .group_by { |state| state.reduces.first.rule.display_name } + + expect(pslr_states.states_count).to be > ielr_states.states_count + expect(pslr_states.pslr_inadequacies).to be_empty + + ["shared -> n1", "n1 -> n2", "n2 -> MARK"].each do |rule_name| + states_for_rule = reduce_states.fetch(rule_name) + token_sets = states_for_rule.map { |state| acceptable_tokens(pslr_states, state) } + + expect(states_for_rule.size).to eq(2) + expect(states_for_rule.count(&:split_state?)).to eq(1) + expect(token_sets.any? { |set| set.include?("RANGLE") && !set.include?("RSHIFT") }).to be(true) + expect(token_sets.any? { |set| set.include?("RSHIFT") && !set.include?("RANGLE") }).to be(true) + end + end + end + + describe "mixed families" do + { + "empty shared wrapper" => { + path: "states/pslr_mixed_empty.y", + grows: true, + grammar: <<~GRAMMAR, + %define lr.type pslr + %token-pattern LT />/ + %token-pattern RANGLE />/ + %lex-prec ID <~ IF + %lex-no-tie RANGLE RSHIFT + + %% + + program + : kw + | ident + | templ + | shift_expr + ; + + kw + : P shared IF + ; + + ident + : Q shared ID + ; + + templ + : LT shared RANGLE + ; + + shift_expr + : START shared RSHIFT ID + ; + + shared + : opt n1 + ; + + opt + : + ; + + n1 + : MARK + ; + GRAMMAR + }, + "chain2 shared wrapper" => { + path: "states/pslr_mixed_chain2.y", + grows: true, + grammar: <<~GRAMMAR, + %define lr.type pslr + %token-pattern LT />/ + %token-pattern RANGLE />/ + %lex-prec ID <~ IF + %lex-no-tie RANGLE RSHIFT + + %% + + program + : kw + | ident + | templ + | shift_expr + ; + + kw + : P shared IF + ; + + ident + : Q shared ID + ; + + templ + : LT shared RANGLE + ; + + shift_expr + : START shared RSHIFT ID + ; + + shared + : n1 + ; + + n1 + : n2 + ; + + n2 + : MARK + ; + GRAMMAR + } + }.each do |label, attrs| + it "keeps #{label} scanner-compatible" do + grammar = build_grammar(attrs[:grammar], attrs[:path]) + ielr_states, pslr_states = compute_ielr_and_pslr(grammar) + + if attrs[:grows] + expect(pslr_states.states_count).to be > ielr_states.states_count + else + expect(pslr_states.states_count).to eq(ielr_states.states_count) + end + expect(pslr_states.pslr_inadequacies).to be_empty + end + end + end + + describe "lexical tie candidates" do + it "reports scanner-conflicting tokens that appear one-sided in parser states" do + grammar = build_grammar(<<~GRAMMAR, "states/pslr_lexical_tie_candidate.y") + %define lr.type pslr + %token-pattern P /p/ + %token-pattern Q /q/ + %token-pattern MARK /#/ + %token-pattern IF /if/ + %token-pattern ID /[a-z]+/ + %lex-prec ID <~ IF + + %% + + start + : P MARK IF + | Q MARK ID + ; + GRAMMAR + + _ielr_states, pslr_states = compute_ielr_and_pslr(grammar) + + expect(pslr_states.lexical_tie_candidates).to include(["ID", "IF"]) + end + + it "suppresses candidates with yyall no-tie" do + grammar = build_grammar(<<~GRAMMAR, "states/pslr_lexical_tie_no_tie.y") + %define lr.type pslr + %token-pattern P /p/ + %token-pattern Q /q/ + %token-pattern MARK /#/ + %token-pattern IF /if/ + %token-pattern ID /[a-z]+/ + %lex-prec ID <~ IF + %lex-no-tie yyall yyall + + %% + + start + : P MARK IF + | Q MARK ID + ; + GRAMMAR + + _ielr_states, pslr_states = compute_ielr_and_pslr(grammar) + + expect(pslr_states.lexical_tie_candidates).to be_empty + end + end + + describe "template argument lists" do + it "splits RANGLE and RSHIFT contexts without short-token precedence" do + grammar = build_grammar(<<~GRAMMAR, "states/pslr_template_argument_lists.y") + %define lr.type pslr + %token-pattern ID /[a-zA-Z][a-zA-Z0-9_]*/ + %token-pattern LT // + %token-pattern RSHIFT />>/ + %token-pattern SEMI /;/ + %token-pattern YYLAYOUT /[ \\t\\r\\n]+/ + %lex-no-tie RANGLE RSHIFT + + %% + + start + : decl SEMI + | expr SEMI + ; + + decl + : type id + ; + + type + : id LT type RANGLE + | ID + ; + + expr + : id RSHIFT id + ; + + id + : ID + ; + GRAMMAR + + ielr_states, pslr_states = compute_ielr_and_pslr(grammar) + + expect(pslr_states.states_count).to be >= ielr_states.states_count + expect(pslr_states.pslr_inadequacies).to be_empty + expect(pslr_states.lexical_tie_candidates).not_to include(["RANGLE", "RSHIFT"]) + end + end +end diff --git a/spec/lrama/pslr_generated_families_spec.rb b/spec/lrama/pslr_generated_families_spec.rb new file mode 100644 index 000000000..795d25d69 --- /dev/null +++ b/spec/lrama/pslr_generated_families_spec.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +RSpec.describe "PSLR generated family coverage" do + include PslrFamilyHelper + + families = [ + { + label: "keyword/id", + builder: :keyword_context_source, + path_prefix: "generated/pslr_keyword_depth", + split_expected: true + }, + { + label: "shift/angle", + builder: :shift_angle_source, + path_prefix: "generated/pslr_shift_depth", + split_expected: true + }, + { + label: "mixed", + builder: :mixed_context_source, + path_prefix: "generated/pslr_mixed_depth", + split_expected: true + } + ].freeze + + families.each do |family| + (0..3).each do |depth| + it "#{family[:label]} depth=#{depth} keeps PSLR inadequacies resolved" do + grammar = build_grammar( + public_send(family[:builder], depth: depth), + "#{family[:path_prefix]}_#{depth}.y" + ) + ielr_states, pslr_states = compute_ielr_and_pslr(grammar) + + aggregate_failures do + expect(pslr_states.pslr_inadequacies).to be_empty + expect(pslr_states.states_count).to be >= ielr_states.states_count + expect(pslr_states.pslr_metrics[:growth_count]).to eq(pslr_states.states_count - pslr_states.pslr_metrics[:base_states_count]) + + next unless family[:split_expected] + next unless 1 <= depth + + expect(pslr_states.states_count).to be > ielr_states.states_count + end + end + end + end +end From 2cc7a6d20eb548982a21b6a94268a64c0dc9c687 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 21:53:14 +0900 Subject: [PATCH 07/24] pslr: switch pseudo-scan runtime to length-delimited input Ruby sources may contain NUL bytes, so a NUL-terminated scan API cannot represent every valid input. yy_pseudo_scan_result and yy_pseudo_scan now take (input, input_len) and treat input_len == 0 as end of input; the YYPSLR_PSEUDO_SCAN* bridge macros and yypslr_scan_with_layout gain the corresponding length argument, and the layout loop keeps the remaining length in sync as it consumes layout tokens. The scan result reports from_fallback when the token came from the fallback row or from character-token handling, letting callers detect a guaranteed upcoming syntax error before handing the token to the parser. The YYEOF token action now runs before returning YYEOF so a grammar can recover trailing layout (paper section 3.6). --- lib/lrama/output.rb | 78 ++++++++++++------- spec/fixtures/integration/pslr_context.l | 2 +- .../integration/pslr_fallback_precedence.l | 2 +- .../integration/pslr_fallback_precedence.y | 4 +- .../integration/pslr_implicit_literal.l | 2 +- .../integration/pslr_implicit_literal.y | 2 +- .../integration/pslr_keyword_context.l | 2 +- .../integration/pslr_layout_comment.l | 2 +- .../fixtures/integration/pslr_mixed_context.l | 4 +- spec/fixtures/integration/pslr_shift_chain.l | 2 +- .../pslr_template_argument_lists.l | 2 +- spec/lrama/output_spec.rb | 14 +++- 12 files changed, 74 insertions(+), 42 deletions(-) diff --git a/lib/lrama/output.rb b/lib/lrama/output.rb index b9d8b3a93..f23a1da65 100644 --- a/lib/lrama/output.rb +++ b/lib/lrama/output.rb @@ -407,6 +407,8 @@ def pslr_function_declarations if pslr_scanner_enabled? declarations << <<~C_CODE + #include + #ifndef YYPSLR_SCAN_RESULT_DEFINED # define YYPSLR_SCAN_RESULT_DEFINED typedef struct yypslr_scan_result { @@ -414,11 +416,12 @@ def pslr_function_declarations int length; int is_layout; int is_character_token; + int from_fallback; } yypslr_scan_result; #endif - int yy_pseudo_scan_result (int parser_state, const char *input, yypslr_scan_result *result); - int yy_pseudo_scan (int parser_state, const char *input, int *match_length); + int yy_pseudo_scan_result (int parser_state, const char *input, size_t input_len, yypslr_scan_result *result); + int yy_pseudo_scan (int parser_state, const char *input, size_t input_len, int *match_length); int yy_pslr_token_is_layout (int token); C_CODE @@ -427,13 +430,13 @@ def pslr_function_declarations #define YYPSLR_NO_MATCH YYEMPTY #ifndef YYPSLR_PSEUDO_SCAN_STATE - # define YYPSLR_PSEUDO_SCAN_STATE(ParserState, Input, MatchLength) \\ - yy_pseudo_scan ((ParserState), (Input), (MatchLength)) + # define YYPSLR_PSEUDO_SCAN_STATE(ParserState, Input, InputLen, MatchLength) \\ + yy_pseudo_scan ((ParserState), (Input), (InputLen), (MatchLength)) #endif #ifndef YYPSLR_PSEUDO_SCAN_RESULT_STATE - # define YYPSLR_PSEUDO_SCAN_RESULT_STATE(ParserState, Input, Result) \\ - yy_pseudo_scan_result ((ParserState), (Input), (Result)) + # define YYPSLR_PSEUDO_SCAN_RESULT_STATE(ParserState, Input, InputLen, Result) \\ + yy_pseudo_scan_result ((ParserState), (Input), (InputLen), (Result)) #endif #ifndef YYPSLR_TOKEN_IS_LAYOUT @@ -441,11 +444,11 @@ def pslr_function_declarations #endif int yypslr_scan_with_layout (int parser_state, const char **input, - yypslr_scan_result *result); + size_t *input_len, yypslr_scan_result *result); #ifndef YYPSLR_SCAN_WITH_LAYOUT - # define YYPSLR_SCAN_WITH_LAYOUT(ParserState, InputPtr, Result) \\ - yypslr_scan_with_layout ((ParserState), (InputPtr), (Result)) + # define YYPSLR_SCAN_WITH_LAYOUT(ParserState, InputPtr, InputLenPtr, Result) \\ + yypslr_scan_with_layout ((ParserState), (InputPtr), (InputLenPtr), (Result)) #endif C_CODE end @@ -460,16 +463,16 @@ def pslr_function_declarations if pslr_scanner_enabled? declarations << <<~C_CODE #ifndef YYPSLR_PSEUDO_SCAN - # define YYPSLR_PSEUDO_SCAN(Context, Input, MatchLength) \\ + # define YYPSLR_PSEUDO_SCAN(Context, Input, InputLen, MatchLength) \\ ((Context) != 0 \\ - ? YYPSLR_PSEUDO_SCAN_STATE (YYGETSTATE_CONTEXT (Context), (Input), (MatchLength)) \\ + ? YYPSLR_PSEUDO_SCAN_STATE (YYGETSTATE_CONTEXT (Context), (Input), (InputLen), (MatchLength)) \\ : YYEMPTY) #endif #ifndef YYPSLR_PSEUDO_SCAN_RESULT - # define YYPSLR_PSEUDO_SCAN_RESULT(Context, Input, Result) \\ + # define YYPSLR_PSEUDO_SCAN_RESULT(Context, Input, InputLen, Result) \\ ((Context) != 0 \\ - ? YYPSLR_PSEUDO_SCAN_RESULT_STATE (YYGETSTATE_CONTEXT (Context), (Input), (Result)) \\ + ? YYPSLR_PSEUDO_SCAN_RESULT_STATE (YYGETSTATE_CONTEXT (Context), (Input), (InputLen), (Result)) \\ : YYEMPTY) #endif C_CODE @@ -811,25 +814,30 @@ def pseudo_scan_function /* * pseudo_scan: PSLR(1) scanning function - * Based on Definition 3.2.16 from the PSLR dissertation + * Based on Definition 3.2.16 from the PSLR dissertation, + * extended with the fallback row of section 3.5.1. * * Input: * parser_state: Current parser state - * input: Input buffer pointer - * match_length: Output parameter for matched length + * input: Unconsumed input pointer (may contain NUL bytes) + * input_len: Number of remaining input bytes + * result: Output parameter for the match * - * Returns: Selected parser token ID. If neither the parser-state row - * nor fallback row matches, returns YYUNDEF and consumes one byte. + * Returns: Selected parser token ID. YYEOF when input_len is zero. + * If neither the parser-state row nor the fallback row matches, + * returns YYUNDEF and consumes one byte (character-token handling); + * from_fallback is set for both cases because a syntax error is + * then guaranteed. */ int - yy_pseudo_scan_result (int parser_state, const char *input, yypslr_scan_result *result) + yy_pseudo_scan_result (int parser_state, const char *input, size_t input_len, yypslr_scan_result *result) { int ss = 0; /* FSA initial state */ int ibest = 0; int pbest = YY_PSLR_EMPTY_PATTERN; int fallback_ibest = 0; int fallback_pbest = YY_PSLR_EMPTY_PATTERN; - int i = 0; + size_t i = 0; if (result == NULL) { return YYEMPTY; @@ -839,17 +847,18 @@ def pseudo_scan_function result->length = 0; result->is_layout = 0; result->is_character_token = 0; + result->from_fallback = 0; if (parser_state < 0 || parser_state >= YY_NUM_PARSER_STATES || input == NULL) { return YYEMPTY; } - if (input[0] == '\\0') { + if (input_len == 0) { result->token = YYEOF; return result->token; } - while (input[i] != '\\0') { + while (i < input_len) { int c = (unsigned char)input[i]; int next_ss = yy_scanner_transition[ss][c]; @@ -868,7 +877,7 @@ def pseudo_scan_function if (pbest == YY_PSLR_EMPTY_PATTERN || yy_pslr_length_precedes[pbest][pattern_index]) { pbest = pattern_index; - ibest = i; + ibest = (int)i; } } @@ -877,7 +886,7 @@ def pseudo_scan_function if (fallback_pbest == YY_PSLR_EMPTY_PATTERN || yy_pslr_fallback_length_precedes[fallback_pbest][pattern_index]) { fallback_pbest = pattern_index; - fallback_ibest = i; + fallback_ibest = (int)i; } } } @@ -894,20 +903,22 @@ def pseudo_scan_function result->token = yy_token_pattern_to_token_id[fallback_pbest]; result->length = fallback_ibest; result->is_layout = yy_token_pattern_is_layout[fallback_pbest]; + result->from_fallback = 1; return result->token; } result->token = YYUNDEF; result->length = 1; result->is_character_token = 1; + result->from_fallback = 1; return result->token; } int - yy_pseudo_scan(int parser_state, const char *input, int *match_length) + yy_pseudo_scan(int parser_state, const char *input, size_t input_len, int *match_length) { yypslr_scan_result result; - int token = yy_pseudo_scan_result (parser_state, input, &result); + int token = yy_pseudo_scan_result (parser_state, input, input_len, &result); if (match_length != NULL) { *match_length = result.length; @@ -1063,25 +1074,34 @@ def pslr_layout_scan_function * Layout tokens are accumulated in the layout buffer; * non-layout tokens are returned to the caller with the * accumulated layout available via YYPSLR_LAYOUT_TEXT. + * The YYEOF token action (if any) runs before returning YYEOF so + * trailing layout can be recovered (paper section 3.6). */ int yypslr_scan_with_layout (int parser_state, const char **input, - yypslr_scan_result *result) + size_t *input_len, yypslr_scan_result *result) { YYPSLR_LAYOUT_CLEAR (); for (;;) { - int token = yy_pseudo_scan_result (parser_state, *input, result); + int token = yy_pseudo_scan_result (parser_state, *input, *input_len, result); - if (token == YYEMPTY || token == YYEOF) + if (token == YYEMPTY) return token; + if (token == YYEOF) + { + #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, 0);" : ""} + return token; + } + if (result->is_layout) { YYPSLR_LAYOUT_APPEND (*input, result->length); #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, result->length);" : ""} *input += result->length; + *input_len -= (size_t)result->length; continue; } diff --git a/spec/fixtures/integration/pslr_context.l b/spec/fixtures/integration/pslr_context.l index 06cbd121d..89f639bed 100644 --- a/spec/fixtures/integration/pslr_context.l +++ b/spec/fixtures/integration/pslr_context.l @@ -22,7 +22,7 @@ ID_PATTERN [a-zA-Z_][a-zA-Z0-9_]* [>]{1,2} { int match_length = 0; - int token = YYPSLR_PSEUDO_SCAN(p, yytext, &match_length); + int token = YYPSLR_PSEUDO_SCAN(p, yytext, strlen(yytext), &match_length); if (token == YYEMPTY) { token = (yyleng == 2) ? RSHIFT : RANGLE; diff --git a/spec/fixtures/integration/pslr_fallback_precedence.l b/spec/fixtures/integration/pslr_fallback_precedence.l index e5f7031b0..0f8c6639a 100644 --- a/spec/fixtures/integration/pslr_fallback_precedence.l +++ b/spec/fixtures/integration/pslr_fallback_precedence.l @@ -55,7 +55,7 @@ token_name(int token) int token; (void)yylval; - token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, &result); + token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, strlen(yytext), &result); if (result.length <= 0) { result.length = 1; } diff --git a/spec/fixtures/integration/pslr_fallback_precedence.y b/spec/fixtures/integration/pslr_fallback_precedence.y index 86f708a5e..8984ac839 100644 --- a/spec/fixtures/integration/pslr_fallback_precedence.y +++ b/spec/fixtures/integration/pslr_fallback_precedence.y @@ -74,8 +74,8 @@ main(int argc, char *argv[]) if (argc == 2 && strcmp(argv[1], "__empty__") == 0) { yypslr_scan_result result; int match_length = -1; - int token = YYPSLR_PSEUDO_SCAN_RESULT(¶ms, "", &result); - int wrapper_token = YYPSLR_PSEUDO_SCAN(¶ms, "", &match_length); + int token = YYPSLR_PSEUDO_SCAN_RESULT(¶ms, "", 0, &result); + int wrapper_token = YYPSLR_PSEUDO_SCAN(¶ms, "", 0, &match_length); int ok = token == YYEOF && result.token == YYEOF && wrapper_token == YYEOF && result.length == 0 && result.is_layout == 0 && result.is_character_token == 0 && match_length == 0; diff --git a/spec/fixtures/integration/pslr_implicit_literal.l b/spec/fixtures/integration/pslr_implicit_literal.l index 31121d203..4e5b4cdf4 100644 --- a/spec/fixtures/integration/pslr_implicit_literal.l +++ b/spec/fixtures/integration/pslr_implicit_literal.l @@ -13,7 +13,7 @@ int token; (void)yylval; - token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, &result); + token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, strlen(yytext), &result); if (result.length <= 0) { result.length = 1; } diff --git a/spec/fixtures/integration/pslr_implicit_literal.y b/spec/fixtures/integration/pslr_implicit_literal.y index 1f9526429..903a05ad4 100644 --- a/spec/fixtures/integration/pslr_implicit_literal.y +++ b/spec/fixtures/integration/pslr_implicit_literal.y @@ -50,7 +50,7 @@ main(int argc, char *argv[]) if (argc == 2 && strcmp(argv[1], "__fallback_semi__") == 0) { yypslr_scan_result result; - int token = YYPSLR_PSEUDO_SCAN_RESULT(¶ms, ";", &result); + int token = YYPSLR_PSEUDO_SCAN_RESULT(¶ms, ";", 1, &result); int ok = token == ';' && result.token == ';' && result.length == 1 && result.is_character_token == 0; diff --git a/spec/fixtures/integration/pslr_keyword_context.l b/spec/fixtures/integration/pslr_keyword_context.l index a54322064..4214a96f7 100644 --- a/spec/fixtures/integration/pslr_keyword_context.l +++ b/spec/fixtures/integration/pslr_keyword_context.l @@ -13,7 +13,7 @@ (void)yylval; int match_length = 0; - int token = YYPSLR_PSEUDO_SCAN(p, yytext, &match_length); + int token = YYPSLR_PSEUDO_SCAN(p, yytext, strlen(yytext), &match_length); if (token == YYEMPTY) { token = ID; diff --git a/spec/fixtures/integration/pslr_layout_comment.l b/spec/fixtures/integration/pslr_layout_comment.l index 82fc8fa77..68039d05f 100644 --- a/spec/fixtures/integration/pslr_layout_comment.l +++ b/spec/fixtures/integration/pslr_layout_comment.l @@ -14,7 +14,7 @@ int token; (void)yylval; - token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, &result); + token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, strlen(yytext), &result); if (result.length <= 0) { result.length = 1; } diff --git a/spec/fixtures/integration/pslr_mixed_context.l b/spec/fixtures/integration/pslr_mixed_context.l index 5c75c7a31..e3ab95ede 100644 --- a/spec/fixtures/integration/pslr_mixed_context.l +++ b/spec/fixtures/integration/pslr_mixed_context.l @@ -13,7 +13,7 @@ (void)yylval; int match_length = 0; - int token = YYPSLR_PSEUDO_SCAN(p, yytext, &match_length); + int token = YYPSLR_PSEUDO_SCAN(p, yytext, strlen(yytext), &match_length); if (token == YYEMPTY) { token = ID; @@ -41,7 +41,7 @@ [>]{1,2} { int match_length = 0; - int token = YYPSLR_PSEUDO_SCAN(p, yytext, &match_length); + int token = YYPSLR_PSEUDO_SCAN(p, yytext, strlen(yytext), &match_length); if (token == YYEMPTY) { token = (yyleng == 2) ? RSHIFT : RANGLE; diff --git a/spec/fixtures/integration/pslr_shift_chain.l b/spec/fixtures/integration/pslr_shift_chain.l index 885ba62e8..0b8b32122 100644 --- a/spec/fixtures/integration/pslr_shift_chain.l +++ b/spec/fixtures/integration/pslr_shift_chain.l @@ -30,7 +30,7 @@ ID_PATTERN [a-z]+ [>]{1,2} { int match_length = 0; - int token = YYPSLR_PSEUDO_SCAN(p, yytext, &match_length); + int token = YYPSLR_PSEUDO_SCAN(p, yytext, strlen(yytext), &match_length); if (token == YYEMPTY) { token = (yyleng == 2) ? RSHIFT : RANGLE; diff --git a/spec/fixtures/integration/pslr_template_argument_lists.l b/spec/fixtures/integration/pslr_template_argument_lists.l index aedab7edf..3d0a93526 100644 --- a/spec/fixtures/integration/pslr_template_argument_lists.l +++ b/spec/fixtures/integration/pslr_template_argument_lists.l @@ -14,7 +14,7 @@ int token; (void)yylval; - token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, &result); + token = YYPSLR_PSEUDO_SCAN_RESULT(p, yytext, strlen(yytext), &result); if (result.length <= 0) { result.length = 1; } diff --git a/spec/lrama/output_spec.rb b/spec/lrama/output_spec.rb index 934d33703..c040e97a4 100644 --- a/spec/lrama/output_spec.rb +++ b/spec/lrama/output_spec.rb @@ -463,6 +463,18 @@ expect(result).to include("yy_pslr_fallback_length_precedes") expect(result).to include("result->token = YYEOF") end + + it "takes a length-delimited input instead of a NUL-terminated string" do + result = pslr_output.pseudo_scan_function + expect(result).to include("size_t input_len") + expect(result).to include("while (i < input_len)") + expect(result).not_to include("input[i] != '\\0'") + end + + it "marks fallback-row and character-token matches with from_fallback" do + result = pslr_output.pseudo_scan_function + expect(result.scan("result->from_fallback = 1;").size).to eq(2) + end end describe "#pslr_tables_and_functions" do @@ -666,7 +678,7 @@ expect(rendered_header).to include("int yy_pseudo_scan") expect(rendered_header).to include("yypslr_scan_result") expect(rendered_header).to include("YYSETSTATE_CONTEXT(CurrentState)") - expect(rendered_header).to include("YYPSLR_PSEUDO_SCAN(Context, Input, MatchLength)") + expect(rendered_header).to include("YYPSLR_PSEUDO_SCAN(Context, Input, InputLen, MatchLength)") end end end From a04914273a954ecb0e526acbd4878eb6cb9b11bf Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 22:00:00 +0900 Subject: [PATCH 08/24] pslr: add conflict witnesses and real %lex-prec usage tracking Unresolved-scanner-conflict reports now carry a witness: an example input that drives the DFA to the conflicting profile. The witness is collected during the profile DFS and included in the error message so users can reproduce the conflict without reverse-engineering scanner state ids. Useless-%lex-prec detection previously relied on usage marks that nothing recorded, so it could not distinguish referenced rules from dead ones. The profile resolver now marks the identity and length rules that actually decide a normal-row resolution (winner selection in both the shorter-token-wins and longer-token-wins cases). The fallback row intentionally does not mark: it spans the whole token universe and would make every declaration look used. Compatibility probes during state splitting do not mark either. --- lib/lrama/state/scanner_accepts.rb | 74 ++++++++++++++++++------ lib/lrama/states.rb | 3 +- spec/lrama/state/scanner_accepts_spec.rb | 48 +++++++++++++++ 3 files changed, 106 insertions(+), 19 deletions(-) diff --git a/lib/lrama/state/scanner_accepts.rb b/lib/lrama/state/scanner_accepts.rb index 6ce02e5dc..0595ed38d 100644 --- a/lib/lrama/state/scanner_accepts.rb +++ b/lib/lrama/state/scanner_accepts.rb @@ -31,14 +31,16 @@ class Conflict attr_reader :shorter_tokens #: Array[String] attr_reader :selected_shorter_token #: String? attr_reader :current_tokens #: Array[String] + attr_reader :witness #: String? - # @rbs (parser_state_id: Integer?, scanner_state_id: Integer, shorter_tokens: Array[String], selected_shorter_token: String?, current_tokens: Array[String]) -> void - def initialize(parser_state_id:, scanner_state_id:, shorter_tokens:, selected_shorter_token:, current_tokens:) + # @rbs (parser_state_id: Integer?, scanner_state_id: Integer, shorter_tokens: Array[String], selected_shorter_token: String?, current_tokens: Array[String], ?witness: String?) -> void + def initialize(parser_state_id:, scanner_state_id:, shorter_tokens:, selected_shorter_token:, current_tokens:, witness: nil) @parser_state_id = parser_state_id @scanner_state_id = scanner_state_id @shorter_tokens = shorter_tokens @selected_shorter_token = selected_shorter_token @current_tokens = current_tokens + @witness = witness end end @@ -75,12 +77,13 @@ def unresolved? end class ProfileResolver - # @rbs (Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void - def initialize(lex_prec, length_prec, fallback: false, token_order: {}) + # @rbs (Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?fallback: bool, ?token_order: Hash[String, Integer], ?track_rule_usage: bool) -> void + def initialize(lex_prec, length_prec, fallback: false, token_order: {}, track_rule_usage: false) @lex_prec = lex_prec @length_prec = length_prec @fallback = fallback @token_order = token_order + @track_rule_usage = track_rule_usage end # @rbs (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome @@ -103,6 +106,7 @@ def resolve_normal(shorter_tokens, selected_shorter_token, current_tokens) end if selected_shorter_token && current_tokens.all? {|token| length_prefers_old?(selected_shorter_token, token) } + mark_shorter_win_rules_used(selected_shorter_token, current_tokens) return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: selected_shorter_token) end @@ -111,7 +115,11 @@ def resolve_normal(shorter_tokens, selected_shorter_token, current_tokens) shorter_tokens.all? {|shorter| @length_prec.resolution(shorter, candidate) == LengthPrecedences::PREFER_NEW } end - return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: winners.first) if winners.size == 1 + if winners.size == 1 + winner = winners.first #: String + mark_longer_win_rules_used(winner, shorter_tokens, current_tokens) + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: winner) + end ProfileOutcome.new(kind: ProfileOutcome::UNRESOLVED) end @@ -179,6 +187,33 @@ def fallback_identity_winner?(candidate, current_tokens) end end + # Mark the %lex-prec rules that made the profile decision as used. + # Only normal-row scanner_accepts construction tracks usage: + # the fallback row spans the whole token universe and exploratory + # resolutions (state compatibility probes) must not mark rules. + # @rbs (String selected_shorter_token, Set[String] current_tokens) -> void + def mark_shorter_win_rules_used(selected_shorter_token, current_tokens) + return unless @track_rule_usage + + current_tokens.each do |token| + @length_prec.resolution(selected_shorter_token, token, track: true) + end + end + + # @rbs (String winner, Set[String] shorter_tokens, Set[String] current_tokens) -> void + def mark_longer_win_rules_used(winner, shorter_tokens, current_tokens) + return unless @track_rule_usage + + current_tokens.each do |other| + next if other == winner + + @lex_prec.identity_precedes?(winner, other, track: true) + end + shorter_tokens.each do |shorter| + @length_prec.resolution(shorter, winner, track: true) + end + end + # @rbs (String candidate, String other) -> bool def token_order_precedes?(candidate, other) (token_order_key(candidate) <=> token_order_key(other)) == -1 @@ -195,9 +230,9 @@ class CompleteProfileComputer attr_reader :conflicts #: Array[Conflict] # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void - def initialize(scanner_fsa, lex_prec, length_prec, acceptable_tokens, parser_state_id = nil, fallback: false, token_order: {}) + def initialize(scanner_fsa, lex_prec, length_prec, acceptable_tokens, parser_state_id = nil, fallback: false, token_order: {}, track_rule_usage: false) @scanner_fsa = scanner_fsa - @resolver = ProfileResolver.new(lex_prec, length_prec, fallback: fallback, token_order: token_order) + @resolver = ProfileResolver.new(lex_prec, length_prec, fallback: fallback, token_order: token_order, track_rule_usage: track_rule_usage) @acceptable_tokens = acceptable_tokens @parser_state_id = parser_state_id @table = {} @@ -211,23 +246,23 @@ def initialize(scanner_fsa, lex_prec, length_prec, acceptable_tokens, parser_sta # @rbs () -> void def compute visited = Set.new - visit_transitions(0, Set.new, nil, visited) + visit_transitions(0, Set.new, nil, visited, "") end private - # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void - def visit_transitions(fsa_state_id, shorter_tokens, selected_shorter_token, visited) + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited, String path) -> void + def visit_transitions(fsa_state_id, shorter_tokens, selected_shorter_token, visited, path) fsa_state = @scanner_fsa.states[fsa_state_id] return unless fsa_state - fsa_state.transitions.each_value do |next_state_id| - visit_state(next_state_id, shorter_tokens, selected_shorter_token, visited) + fsa_state.transitions.each do |char, next_state_id| + visit_state(next_state_id, shorter_tokens, selected_shorter_token, visited, path + char) end end - # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void - def visit_state(fsa_state_id, shorter_tokens, selected_shorter_token, visited) + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited, String path) -> void + def visit_state(fsa_state_id, shorter_tokens, selected_shorter_token, visited, path) fsa_state = @scanner_fsa.states[fsa_state_id] return unless fsa_state @@ -248,7 +283,8 @@ def visit_state(fsa_state_id, shorter_tokens, selected_shorter_token, visited) scanner_state_id: fsa_state_id, shorter_tokens: shorter_tokens.to_a.sort, selected_shorter_token: existing.name, - current_tokens: current_tokens.to_a.sort + current_tokens: current_tokens.to_a.sort, + witness: path ) else @table[fsa_state_id] = token_pattern @@ -260,13 +296,14 @@ def visit_state(fsa_state_id, shorter_tokens, selected_shorter_token, visited) scanner_state_id: fsa_state_id, shorter_tokens: shorter_tokens.to_a.sort, selected_shorter_token: selected_shorter_token, - current_tokens: current_tokens.to_a.sort + current_tokens: current_tokens.to_a.sort, + witness: path ) end next_shorter_tokens = shorter_tokens | current_tokens next_selected = result.resolved? ? result.token_name : nil - visit_transitions(fsa_state_id, next_shorter_tokens, next_selected, visited) + visit_transitions(fsa_state_id, next_shorter_tokens, next_selected, visited, path) end # @rbs (ScannerFSA::State fsa_state) -> Set[String] @@ -432,7 +469,8 @@ def compute_for_parser_state(parser_state) @lex_prec, @length_prec, compute_acc_sp(parser_state), - parser_state.id + parser_state.id, + track_rule_usage: true ) computer.compute diff --git a/lib/lrama/states.rb b/lib/lrama/states.rb index 63c995993..d626a2ec2 100644 --- a/lib/lrama/states.rb +++ b/lib/lrama/states.rb @@ -1318,8 +1318,9 @@ def pslr_scanner_conflict_message(conflict) shorter = conflict.shorter_tokens.empty? ? "(none)" : conflict.shorter_tokens.join(", ") selected = conflict.selected_shorter_token || "(none)" current = conflict.current_tokens.empty? ? "(none)" : conflict.current_tokens.join(", ") + witness = conflict.witness ? " witness input: #{conflict.witness.inspect};" : "" - "unresolved PSLR scanner conflict in state #{state}, scanner state #{conflict.scanner_state_id}: " \ + "unresolved PSLR scanner conflict in state #{state}, scanner state #{conflict.scanner_state_id}:#{witness} " \ "shorter matches: #{shorter}; selected shorter token: #{selected}; " \ "current matches: #{current}; add an explicit %lex-prec rule or adjust lexical ties" end diff --git a/spec/lrama/state/scanner_accepts_spec.rb b/spec/lrama/state/scanner_accepts_spec.rb index 5bb38ebfb..43bff5942 100644 --- a/spec/lrama/state/scanner_accepts_spec.rb +++ b/spec/lrama/state/scanner_accepts_spec.rb @@ -282,6 +282,54 @@ def parser_state(id, token_names) end end + describe "conflict witnesses" do + it "attaches an example input to unresolved conflicts" do + tokens = [ + token_pattern("A", "ab", 0), + token_pattern("B", "ab", 1) + ] + scanner_fsa = Lrama::ScannerFSA.new(tokens) + lex_prec = Lrama::Grammar::LexPrec.new + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, ["A", "B"])], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec) + ) + + scanner_accepts.build + + witnesses = scanner_accepts.conflicts.map(&:witness) + expect(witnesses).to include("ab") + end + end + + describe "%lex-prec usage tracking" do + it "marks rules referenced by normal-row resolution and keeps unreferenced ones useless" do + tokens = [ + token_pattern("A", "a", 0), + token_pattern("B", "a", 1), + token_pattern("X", "x", 2), + token_pattern("Y", "y", 3) + ] + scanner_fsa = Lrama::ScannerFSA.new(tokens) + lex_prec = Lrama::Grammar::LexPrec.new + lex_prec.add_rule(left_token: ident("A"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("B"), lineno: 1) + lex_prec.add_rule(left_token: ident("X"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("Y"), lineno: 2) + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, ["A", "B", "X", "Y"])], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec) + ) + + scanner_accepts.build + + useless = lex_prec.useless_rules + expect(useless.map {|rule| [rule.left_name, rule.right_name] }).to eq([["X", "Y"]]) + end + end + describe Lrama::State::ScannerAccepts::CompatibilityChecker do let(:rangle) { token_pattern("RANGLE", ">", 0) } let(:rshift) { token_pattern("RSHIFT", ">>", 1) } From 3764ec7aae14964010b6291a4e8d3f5c3b6a025f Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 22:06:36 +0900 Subject: [PATCH 09/24] lac: make lookahead correction configurable via %define parse.lac LAC is orthogonal to PSLR (paper section 3.5.2), so expose it as %define parse.lac with the Bison-compatible values full and none: * PSLR parsers default to full; exploratory parses are what keep pseudo-scanning on merged states equivalent to canonical LR(1) * LALR/IELR parsers can now opt in with parse.lac full to get immediate error detection and accurate expected-token lists * parse.lac none on a PSLR parser is honored but warned about, because token selections from merged states may then run semantic actions before the syntax error is reported * invalid values are rejected at grammar validation time All LAC template blocks (checker function, lookahead verification, eager lookahead fetch at default reductions, expected-token enumeration) are now gated on the LAC setting instead of lr.type. --- lib/lrama/grammar.rb | 2 + lib/lrama/output.rb | 9 +++- lib/lrama/warnings.rb | 3 ++ lib/lrama/warnings/parse_lac.rb | 26 ++++++++++ spec/lrama/output_spec.rb | 88 +++++++++++++++++++++++++++++++++ spec/lrama/warnings_spec.rb | 27 ++++++++++ template/bison/yacc.c | 8 +-- 7 files changed, 158 insertions(+), 5 deletions(-) create mode 100644 lib/lrama/warnings/parse_lac.rb diff --git a/lib/lrama/grammar.rb b/lib/lrama/grammar.rb index fecfdb6f4..aa8e40742 100644 --- a/lib/lrama/grammar.rb +++ b/lib/lrama/grammar.rb @@ -677,6 +677,8 @@ def escape_regex_literal(literal) # @rbs () -> void def validate_pslr_configuration! + validate_parse_lac! + return unless pslr_defined? member = pslr_state_member diff --git a/lib/lrama/output.rb b/lib/lrama/output.rb index f23a1da65..623f05cb5 100644 --- a/lib/lrama/output.rb +++ b/lib/lrama/output.rb @@ -392,6 +392,13 @@ def pslr_enabled? @grammar.pslr_defined? end + # Check if LAC (lookahead correction) is enabled. + # Defaults to full for PSLR parsers; any parser type can opt in + # with %define parse.lac full (section 3.5.2 is orthogonal to PSLR). + def lac_enabled? + @grammar.parse_lac_full? + end + # Check if PSLR scanner tables are available. def pslr_scanner_enabled? scanner_fsa = @context.states.scanner_fsa @@ -718,7 +725,7 @@ def length_precedence_matrix_code(table_name, num_tokens, query_method) end def pslr_lac_function - return "" unless pslr_enabled? + return "" unless lac_enabled? <<~C_CODE diff --git a/lib/lrama/warnings.rb b/lib/lrama/warnings.rb index c1acf5692..7a820af68 100644 --- a/lib/lrama/warnings.rb +++ b/lib/lrama/warnings.rb @@ -10,6 +10,7 @@ require_relative 'warnings/token_redeclarations' require_relative 'warnings/useless_precedence' require_relative 'warnings/lexical_tie_candidates' +require_relative 'warnings/parse_lac' module Lrama class Warnings @@ -24,6 +25,7 @@ def initialize(logger, warnings) @token_redeclarations = TokenRedeclarations.new(logger) @useless_precedence = UselessPrecedence.new(logger, warnings) @lexical_tie_candidates = LexicalTieCandidates.new(logger, warnings) + @parse_lac = ParseLac.new(logger, warnings) end # @rbs (Lrama::Grammar grammar, Lrama::States states) -> void @@ -37,6 +39,7 @@ def warn(grammar, states) @required.warn(grammar) @useless_precedence.warn(grammar, states) @lexical_tie_candidates.warn(states) + @parse_lac.warn(grammar) end end end diff --git a/lib/lrama/warnings/parse_lac.rb b/lib/lrama/warnings/parse_lac.rb new file mode 100644 index 000000000..aec57ac88 --- /dev/null +++ b/lib/lrama/warnings/parse_lac.rb @@ -0,0 +1,26 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Warnings + class ParseLac + # @rbs (Logger logger, bool warnings) -> void + def initialize(logger, warnings) + @logger = logger + @warnings = warnings + end + + # @rbs (Lrama::Grammar grammar) -> void + def warn(grammar) + return unless @warnings + return unless grammar.pslr_defined? + return unless grammar.parse_lac_explicit_none? + + @logger.warn( + "parse.lac is disabled for a PSLR parser; " \ + "tokens selected in merged states may trigger semantic actions before a syntax error is detected" + ) + end + end + end +end diff --git a/spec/lrama/output_spec.rb b/spec/lrama/output_spec.rb index c040e97a4..f44b20a68 100644 --- a/spec/lrama/output_spec.rb +++ b/spec/lrama/output_spec.rb @@ -401,6 +401,7 @@ lex_param: "struct parse_params *p", pslr_defined?: true, pslr_state_member: "current_state", + parse_lac_full?: true, token_actions: [] ) end @@ -681,4 +682,91 @@ expect(rendered_header).to include("YYPSLR_PSEUDO_SCAN(Context, Input, InputLen, MatchLength)") end end + + describe "LAC (%define parse.lac)" do + def render_grammar(text) + grammar = Lrama::Parser.new(text, "lac_test.y").parse + grammar.prepare + grammar.validate! + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + if grammar.pslr_defined? + states.compute_pslr + elsif grammar.ielr_defined? + states.compute_ielr + end + out = StringIO.new + Lrama::Output.new( + out: out, + output_file_path: "lac_test.c", + template_name: "bison/yacc.c", + grammar_file_path: "lac_test.y", + context: Lrama::Context.new(states), + grammar: grammar + ).render + out.rewind + out.read + end + + it "is enabled by default for PSLR parsers" do + rendered = render_grammar(<<~GRAMMAR) + %define lr.type pslr + %token-pattern RSHIFT />>/ + %token-pattern RANGLE />/ + %lex-prec RANGLE -s RSHIFT + %% + program: RSHIFT | RANGLE + GRAMMAR + + expect(rendered).to include("yy_lac_check_") + end + + it "can be disabled with parse.lac none" do + rendered = render_grammar(<<~GRAMMAR) + %define lr.type pslr + %define parse.lac none + %token-pattern RSHIFT />>/ + %token-pattern RANGLE />/ + %lex-prec RANGLE -s RSHIFT + %% + program: RSHIFT | RANGLE + GRAMMAR + + expect(rendered).not_to include("yy_lac_check_") + end + + it "can be enabled independently of PSLR with parse.lac full" do + rendered = render_grammar(<<~GRAMMAR) + %define lr.type ielr + %define parse.lac full + %token NUM + %% + program: NUM + GRAMMAR + + expect(rendered).to include("yy_lac_check_") + end + + it "is disabled by default for non-PSLR parsers" do + rendered = render_grammar(<<~GRAMMAR) + %token NUM + %% + program: NUM + GRAMMAR + + expect(rendered).not_to include("yy_lac_check_") + end + + it "rejects invalid parse.lac values" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "lac_test.y").parse + %define parse.lac sometimes + %token NUM + %% + program: NUM + GRAMMAR + grammar.prepare + + expect { grammar.validate! }.to raise_error(/parse\.lac must be "full" or "none"/) + end + end end diff --git a/spec/lrama/warnings_spec.rb b/spec/lrama/warnings_spec.rb index f3c198415..a2d6cba26 100644 --- a/spec/lrama/warnings_spec.rb +++ b/spec/lrama/warnings_spec.rb @@ -142,5 +142,32 @@ class : keyword_class tSTRING keyword_end %prec tPLUS expect(logger).to have_received(:warn).with("parameterized rule redefined: foo(Y)") end end + + context "when a PSLR grammar disables LAC explicitly" do + let(:y) do + <<~STR + %define lr.type pslr + %define parse.lac none + %token-pattern RSHIFT />>/ + %token-pattern RANGLE />/ + %lex-prec RANGLE -s RSHIFT + %% + program: RSHIFT | RANGLE + STR + end + + it "warns that error detection may be delayed" do + grammar = Lrama::Parser.new(y, "states/pslr_lac_none.y").parse + grammar.prepare + grammar.validate! + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + logger = Lrama::Logger.new + allow(logger).to receive(:warn) + Lrama::Warnings.new(logger, true).warn(grammar, states) + expect(logger).to have_received(:warn).with(a_string_including("parse.lac is disabled for a PSLR parser")) + end + end end end diff --git a/template/bison/yacc.c b/template/bison/yacc.c index fe78543a0..6e603b6b4 100644 --- a/template/bison/yacc.c +++ b/template/bison/yacc.c @@ -1062,7 +1062,7 @@ int yydebug; # define YYMAXDEPTH 10000 #endif -<%- if output.pslr_enabled? -%> +<%- if output.lac_enabled? -%> <%= output.pslr_lac_function %> <%- end -%> @@ -1087,7 +1087,7 @@ yypcontext_expected_tokens (const yypcontext_t *yyctx, { /* Actual size of YYARG. */ int yycount = 0; -<%- if output.pslr_enabled? -%> +<%- if output.lac_enabled? -%> int yyx; for (yyx = 0; yyx < YYNTOKENS; ++yyx) if (yyx != YYSYMBOL_YYerror @@ -1897,7 +1897,7 @@ YYLTYPE yylloc = yyloc_default; /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; -<%- if output.pslr_enabled? -%> +<%- if output.lac_enabled? -%> if (yypact_value_is_default (yyn) && yydefact[yystate] != 0) { if (yychar == YYEMPTY) @@ -1999,7 +1999,7 @@ YYLTYPE yylloc = yyloc_default; YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc<%= output.user_args %>); } -<%- if output.pslr_enabled? -%> +<%- if output.lac_enabled? -%> if (!yy_lac_check_ (yyss, yyssp, yytoken)) goto yyerrlab; <%- end -%> From 8631ec43378b288deb14155ad1e196bbd1ba5db3 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 22:09:22 +0900 Subject: [PATCH 10/24] pslr: use pair-based state compatibility for splitting Phase 3 previously re-ran the dual-profile resolver walk over the whole scanner FSA for every candidate merge, which is the cost the paper's section 3.4.3 warns about. Precompute the FSA's conflict pairs once and reduce the compatibility test to a presence check per pair: two accept sets are compatible when every conflict pair is present identically in both, or absent from one side entirely (unresolved/unresolved pairs merge because their presence patterns match). Only pairs touching the symmetric difference of the two accept sets are examined, so merges that differ in conflict-free tokens are accepted in O(diff). Layout tokens live in every accept set and thus never distinguish states, which realizes the split-stable layout optimization of section 3.6 without extra bookkeeping. --- lib/lrama/pslr/pairwise_resolution.rb | 75 +++++++++++++++++++++ lib/lrama/states.rb | 11 ++- spec/lrama/pslr/pairwise_resolution_spec.rb | 49 ++++++++++++++ 3 files changed, 129 insertions(+), 6 deletions(-) create mode 100644 lib/lrama/pslr/pairwise_resolution.rb create mode 100644 spec/lrama/pslr/pairwise_resolution_spec.rb diff --git a/lib/lrama/pslr/pairwise_resolution.rb b/lib/lrama/pslr/pairwise_resolution.rb new file mode 100644 index 000000000..c7102ff96 --- /dev/null +++ b/lib/lrama/pslr/pairwise_resolution.rb @@ -0,0 +1,75 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +require "set" + +module Lrama + module Pslr + # Pair-based PSLR state compatibility (paper section 3.4.3). + # + # The scanner FSA is scanned once to find every token pair that can be + # in an identity or length scanner conflict. Two acceptable-token sets + # are then compatible when no conflict pair distinguishes them: + # + # * both sets contain the same subset of the pair (the pseudo-scanner + # resolves the conflict identically, or leaves it identically + # unresolved -- unresolved/unresolved states merge), or + # * one set contains neither token of the pair (its match set for + # inputs manifesting the conflict is empty for this pair). + # + # Reducing the check to pairs is the precomputation the paper + # recommends for phase 3: the per-pair verdict no longer depends on + # the rest of the accept set, so state splitting does not have to + # re-run the profile resolver for every candidate merge. Layout + # tokens are members of every accept set, so pairs won by layout can + # never distinguish two states (the split-stable layout optimization + # of section 3.6 falls out of the presence test). + class PairwiseResolution + attr_reader :conflict_pairs #: Set[[String, String]] + + # @rbs (ScannerFSA scanner_fsa) -> void + def initialize(scanner_fsa) + @conflict_pairs = scanner_fsa.pairwise_conflict_pairs + pairs_by_token = Hash.new {|h, k| h[k] = [] } #: Hash[String, Array[[String, String]]] + @pairs_by_token = @conflict_pairs.each_with_object(pairs_by_token) do |pair, hash| + hash[pair[0]] << pair + hash[pair[1]] << pair + end + end + + # @rbs (Set[String] left_acc, Set[String] right_acc) -> bool + def compatible_accept_sets?(left_acc, right_acc) + return true if left_acc == right_acc + + # Only conflict pairs touching the symmetric difference can + # distinguish the two accept sets. + diff = (left_acc - right_acc) | (right_acc - left_acc) + return true if diff.empty? + + checked = Set.new #: Set[[String, String]] + diff.all? do |token| + @pairs_by_token[token].all? do |pair| + next true unless checked.add?(pair) + + pair_compatible?(pair, left_acc, right_acc) + end + end + end + + private + + # @rbs ([String, String] pair, Set[String] left_acc, Set[String] right_acc) -> bool + def pair_compatible?(pair, left_acc, right_acc) + left_presence = presence(pair, left_acc) + right_presence = presence(pair, right_acc) + + left_presence == right_presence || left_presence == 0 || right_presence == 0 + end + + # @rbs ([String, String] pair, Set[String] acc) -> Integer + def presence(pair, acc) + (acc.include?(pair[0]) ? 1 : 0) | (acc.include?(pair[1]) ? 2 : 0) + end + end + end +end diff --git a/lib/lrama/states.rb b/lib/lrama/states.rb index d626a2ec2..4bef1d8bf 100644 --- a/lib/lrama/states.rb +++ b/lib/lrama/states.rb @@ -4,6 +4,7 @@ require "forwardable" require "set" require_relative "lexer_context_classifier" +require_relative "pslr/pairwise_resolution" require_relative "tracer/duration" require_relative "state/item" @@ -1060,16 +1061,14 @@ def pslr_state_signature(state, filtered_lookaheads = nil) signature end + # Pair-based PSLR compatibility (Def 3.4.3, reduced to token pairs as + # recommended by section 3.4.3 for splitting performance). # @rbs (Set[String] left_acc, Set[String] right_acc) -> bool def pslr_compatible_accept_sets?(left_acc, right_acc) return true unless @scanner_fsa - @pslr_compatibility_checker ||= State::ScannerAccepts::CompatibilityChecker.new( - @scanner_fsa, - lex_prec, - @length_precedences || LengthPrecedences.new(lex_prec) - ) - @pslr_compatibility_checker.compatible?(left_acc, right_acc) + @pslr_pairwise_resolution ||= Pslr::PairwiseResolution.new(@scanner_fsa) + @pslr_pairwise_resolution.compatible_accept_sets?(left_acc, right_acc) end # @rbs (State state, ?State::lookahead_set filtered_lookaheads, ?expand_ties: bool, ?include_layout: bool) -> Set[String] diff --git a/spec/lrama/pslr/pairwise_resolution_spec.rb b/spec/lrama/pslr/pairwise_resolution_spec.rb new file mode 100644 index 000000000..7ce6f3c8a --- /dev/null +++ b/spec/lrama/pslr/pairwise_resolution_spec.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +RSpec.describe Lrama::Pslr::PairwiseResolution do + def token_pattern(name, regex, order) + Lrama::Grammar::TokenPattern.new( + id: Lrama::Lexer::Token::Ident.new(s_value: name), + pattern: Lrama::Lexer::Token::Regex.new(s_value: "/#{regex}/"), + lineno: 1, + definition_order: order + ) + end + + let(:rangle) { token_pattern("RANGLE", ">", 0) } + let(:rshift) { token_pattern("RSHIFT", ">>", 1) } + let(:identifier) { token_pattern("ID", "[a-z]+", 2) } + let(:keyword) { token_pattern("IF", "if", 3) } + let(:layout) { token_pattern("YYLAYOUT_WS", "[ ]+", 4) } + let(:scanner_fsa) { Lrama::ScannerFSA.new([rangle, rshift, identifier, keyword, layout]) } + let(:pairwise) { described_class.new(scanner_fsa) } + + it "treats identical accept sets as compatible" do + acc = Set["RANGLE", "RSHIFT"] + expect(pairwise.compatible_accept_sets?(acc, acc.dup)).to be true + end + + it "splits states that pick different tokens of a conflict pair" do + expect(pairwise.compatible_accept_sets?(Set["RANGLE"], Set["RSHIFT"])).to be false + end + + it "splits a resolved state from a state seeing the full conflict" do + expect(pairwise.compatible_accept_sets?(Set["ID"], Set["ID", "IF"])).to be false + end + + it "treats states as compatible when one side has no match for the pair" do + expect(pairwise.compatible_accept_sets?(Set["RANGLE"], Set["ID"])).to be true + end + + it "ignores tokens without scanner conflicts" do + expect(pairwise.compatible_accept_sets?(Set["RANGLE", "ID"], Set["RANGLE"])).to be true + end + + it "never splits on layout tokens because they are in every accept set" do + left = Set["RANGLE", "YYLAYOUT_WS"] + right = Set["RANGLE", "RSHIFT", "YYLAYOUT_WS"] + + expect(pairwise.compatible_accept_sets?(left, right)).to be false + expect(pairwise.compatible_accept_sets?(Set["ID", "YYLAYOUT_WS"], Set["YYLAYOUT_WS", "ID"])).to be true + end +end From 3d8cc20b92234c8212ba68c706b7c8a79dd92598 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 22:17:41 +0900 Subject: [PATCH 11/24] pslr: add pure mode where the generated parser owns lexing %define api.pslr.lexer generated emits a complete lexer: yylex is generated, drives yypslr_scan_with_layout with the parser state kept current by yysetstate, skips layout tokens, runs %token-action bodies and advances an internal input cursor. Callers hand the input to the parser with yypslr_set_input(input, len) before yyparse; no hand-written lexer is involved, matching the paper's model. %token-action bodies now receive the semantic value slot: yylval inside an action refers to the YYSTYPE the caller passed, both in pure mode and through the bridge's YYPSLR_SCAN_WITH_LAYOUT macro (whose signature gains the value pointer). The dispatch is also emitted before the scan loop that calls it, so token actions compile. Pure mode requires full coverage: generation aborts when a terminal has no %token-pattern. Bridge mode instead warns with the list of uncovered terminals the user lexer must keep producing. --- lib/lrama/grammar.rb | 1 + lib/lrama/output.rb | 104 +++++++++++++++++++++++--- lib/lrama/states.rb | 18 +++++ lib/lrama/warnings.rb | 3 + lib/lrama/warnings/pslr_coverage.rb | 34 +++++++++ spec/fixtures/integration/pslr_pure.y | 63 ++++++++++++++++ spec/lrama/integration_spec.rb | 60 +++++++++++++++ spec/lrama/output_spec.rb | 1 + template/bison/yacc.c | 4 + 9 files changed, 276 insertions(+), 12 deletions(-) create mode 100644 lib/lrama/warnings/pslr_coverage.rb create mode 100644 spec/fixtures/integration/pslr_pure.y diff --git a/lib/lrama/grammar.rb b/lib/lrama/grammar.rb index aa8e40742..2886723ae 100644 --- a/lib/lrama/grammar.rb +++ b/lib/lrama/grammar.rb @@ -678,6 +678,7 @@ def escape_regex_literal(literal) # @rbs () -> void def validate_pslr_configuration! validate_parse_lac! + validate_pslr_lexer! return unless pslr_defined? diff --git a/lib/lrama/output.rb b/lib/lrama/output.rb index 623f05cb5..fb6dc3864 100644 --- a/lib/lrama/output.rb +++ b/lib/lrama/output.rb @@ -399,6 +399,12 @@ def lac_enabled? @grammar.parse_lac_full? end + # Pure mode: the generated parser owns lexical analysis + # (%define api.pslr.lexer generated). + def pslr_pure_mode? + pslr_enabled? && @grammar.pslr_lexer_generated? && pslr_scanner_enabled? + end + # Check if PSLR scanner tables are available. def pslr_scanner_enabled? scanner_fsa = @context.states.scanner_fsa @@ -451,15 +457,25 @@ def pslr_function_declarations #endif int yypslr_scan_with_layout (int parser_state, const char **input, - size_t *input_len, yypslr_scan_result *result); + size_t *input_len, YYSTYPE *yylvalp, + yypslr_scan_result *result); #ifndef YYPSLR_SCAN_WITH_LAYOUT - # define YYPSLR_SCAN_WITH_LAYOUT(ParserState, InputPtr, InputLenPtr, Result) \\ - yypslr_scan_with_layout ((ParserState), (InputPtr), (InputLenPtr), (Result)) + # define YYPSLR_SCAN_WITH_LAYOUT(ParserState, InputPtr, InputLenPtr, LvalPtr, Result) \\ + yypslr_scan_with_layout ((ParserState), (InputPtr), (InputLenPtr), (LvalPtr), (Result)) #endif C_CODE end + if pslr_pure_mode? + declarations << <<~C_CODE + /* Pure mode (%define api.pslr.lexer generated): the generated + parser owns lexical analysis. Give it the input before + calling yyparse. */ + void yypslr_set_input (const char *input, size_t input_len); + C_CODE + end + if (member = pslr_state_member) declarations << <<~C_CODE #ifndef YYGETSTATE_CONTEXT @@ -1037,7 +1053,10 @@ def pslr_layout_declarations C_CODE end - # Generate token action dispatch function + # Generate token action dispatch function. + # yylval inside a %token-action refers to the semantic value slot the + # caller passes in, so token actions work with both the generated + # (pure-mode) lexer and a user yylex driving the bridge macros. def pslr_token_action_function return "" unless pslr_token_actions_enabled? @@ -1046,9 +1065,13 @@ def pslr_token_action_function lines << "/* PSLR token action dispatch */" lines << "/* Generated from %token-action declarations */" lines << "" + lines << "#define yylval (*yylvalp)" lines << "static void" - lines << "yypslr_token_action (int token, const char *yytext, int yyleng)" + lines << "yypslr_token_action (int token, const char *yytext, int yyleng, YYSTYPE *yylvalp)" lines << "{" + lines << " YY_USE (yytext);" + lines << " YY_USE (yyleng);" + lines << " YY_USE (yylvalp);" @grammar.token_actions.each_with_index do |action, idx| token_id = @context.states.find_symbol_by_s_value!(action.token_name).token_id @@ -1062,9 +1085,10 @@ def pslr_token_action_function end lines << "}" + lines << "#undef yylval" lines << "" - lines << "#define YYPSLR_TOKEN_ACTION(Token, Text, Len) \\" - lines << " yypslr_token_action ((Token), (Text), (Len))" + lines << "#define YYPSLR_TOKEN_ACTION(Token, Text, Len, LvalPtr) \\" + lines << " yypslr_token_action ((Token), (Text), (Len), (LvalPtr))" lines.join("\n") end @@ -1086,9 +1110,11 @@ def pslr_layout_scan_function */ int yypslr_scan_with_layout (int parser_state, const char **input, - size_t *input_len, yypslr_scan_result *result) + size_t *input_len, YYSTYPE *yylvalp, + yypslr_scan_result *result) { YYPSLR_LAYOUT_CLEAR (); + YY_USE (yylvalp); for (;;) { @@ -1099,26 +1125,79 @@ def pslr_layout_scan_function if (token == YYEOF) { - #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, 0);" : ""} + #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, 0, yylvalp);" : ""} return token; } if (result->is_layout) { YYPSLR_LAYOUT_APPEND (*input, result->length); - #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, result->length);" : ""} + #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, result->length, yylvalp);" : ""} *input += result->length; *input_len -= (size_t)result->length; continue; } - #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, result->length);" : ""} + #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, result->length, yylvalp);" : ""} return token; } } C_CODE end + # Generate the pure-mode lexer: yylex is emitted by the generator and + # drives the pseudo-scanner with the current parser state, so no user + # lexer is involved (%define api.pslr.lexer generated, section 3.1). + def pslr_generated_lexer_function + return "" unless pslr_pure_mode? + + params = ["YYSTYPE *yylvalp"] + params << "YYLTYPE *yyllocp" if @grammar.locations + params << lex_param unless lex_param.empty? + unused = [] + unused << " YY_USE (yyllocp);" if @grammar.locations + unused << " YY_USE (#{lex_param_name});" unless lex_param.empty? + + <<~C_CODE + + /* Pure-mode PSLR lexer: generated, owns the input cursor. */ + static const char *yypslr_input_cursor = 0; + static size_t yypslr_input_remain = 0; + static int yypslr_parser_state = 0; + + void + yypslr_set_input (const char *input, size_t input_len) + { + yypslr_input_cursor = input; + yypslr_input_remain = input_len; + yypslr_parser_state = 0; + } + + #define YYPSLR_SET_PARSER_STATE(State) (yypslr_parser_state = (State)) + + static int + yylex (#{params.join(", ")}) + { + yypslr_scan_result yypslr_result; + int yypslr_token; + #{unused.join("\n")} + + yypslr_token = yypslr_scan_with_layout (yypslr_parser_state, + &yypslr_input_cursor, + &yypslr_input_remain, + yylvalp, + &yypslr_result); + + if (yypslr_token == YYEMPTY || yypslr_token == YYEOF) + return yypslr_token; + + yypslr_input_cursor += yypslr_result.length; + yypslr_input_remain -= (size_t) yypslr_result.length; + return yypslr_token; + } + C_CODE + end + # Generate all PSLR C code def pslr_tables_and_functions return "" unless pslr_scanner_enabled? @@ -1135,8 +1214,9 @@ def pslr_tables_and_functions length_precedences_table_code, pslr_layout_declarations, pseudo_scan_function, - pslr_layout_scan_function, pslr_token_action_function, + pslr_layout_scan_function, + pslr_generated_lexer_function, ] parts.join("\n") diff --git a/lib/lrama/states.rb b/lib/lrama/states.rb index 4bef1d8bf..a4491a9ae 100644 --- a/lib/lrama/states.rb +++ b/lib/lrama/states.rb @@ -272,6 +272,7 @@ def validate!(logger) validate_conflicts_within_threshold!(logger) validate_pslr_scanner_conflicts!(logger) validate_pslr_inadequacies!(logger) + validate_pslr_pure_coverage!(logger) validate_pslr_useless_lex_prec!(logger) validate_pslr_lexical_tie_candidates!(logger) end @@ -1311,6 +1312,23 @@ def validate_pslr_scanner_conflicts!(logger) exit false end + # Pure mode owns lexical analysis completely, so every terminal must + # be producible by the pseudo-scanner. + # @rbs (Logger logger) -> void + def validate_pslr_pure_coverage!(logger) + return unless pslr_defined? + return unless @grammar.pslr_lexer_generated? + + uncovered = @grammar.uncovered_pslr_terminals + return if uncovered.empty? + + logger.error( + "api.pslr.lexer generated requires a %token-pattern for every terminal; " \ + "missing: #{uncovered.join(', ')}" + ) + exit false + end + # @rbs (State::ScannerAccepts::Conflict conflict) -> String def pslr_scanner_conflict_message(conflict) state = conflict.parser_state_id || "unknown" diff --git a/lib/lrama/warnings.rb b/lib/lrama/warnings.rb index 7a820af68..394e9c324 100644 --- a/lib/lrama/warnings.rb +++ b/lib/lrama/warnings.rb @@ -11,6 +11,7 @@ require_relative 'warnings/useless_precedence' require_relative 'warnings/lexical_tie_candidates' require_relative 'warnings/parse_lac' +require_relative 'warnings/pslr_coverage' module Lrama class Warnings @@ -26,6 +27,7 @@ def initialize(logger, warnings) @useless_precedence = UselessPrecedence.new(logger, warnings) @lexical_tie_candidates = LexicalTieCandidates.new(logger, warnings) @parse_lac = ParseLac.new(logger, warnings) + @pslr_coverage = PslrCoverage.new(logger, warnings) end # @rbs (Lrama::Grammar grammar, Lrama::States states) -> void @@ -40,6 +42,7 @@ def warn(grammar, states) @useless_precedence.warn(grammar, states) @lexical_tie_candidates.warn(states) @parse_lac.warn(grammar) + @pslr_coverage.warn(grammar) end end end diff --git a/lib/lrama/warnings/pslr_coverage.rb b/lib/lrama/warnings/pslr_coverage.rb new file mode 100644 index 000000000..2a614c0d2 --- /dev/null +++ b/lib/lrama/warnings/pslr_coverage.rb @@ -0,0 +1,34 @@ +# rbs_inline: enabled +# frozen_string_literal: true + +module Lrama + class Warnings + class PslrCoverage + # @rbs (Logger logger, bool warnings) -> void + def initialize(logger, warnings) + @logger = logger + @warnings = warnings + end + + # Bridge mode allows partial coverage: terminals without a + # %token-pattern must keep coming from the user lexer. List them so + # the boundary between generated and hand-written scanning is + # explicit. + # @rbs (Lrama::Grammar grammar) -> void + def warn(grammar) + return unless @warnings + return unless grammar.pslr_defined? + return if grammar.pslr_lexer_generated? + return if grammar.token_patterns.empty? + + uncovered = grammar.uncovered_pslr_terminals + return if uncovered.empty? + + @logger.warn( + "PSLR pseudo-scanner does not cover these terminals; " \ + "the user lexer must produce them: #{uncovered.join(', ')}" + ) + end + end + end +end diff --git a/spec/fixtures/integration/pslr_pure.y b/spec/fixtures/integration/pslr_pure.y new file mode 100644 index 000000000..fdecd1c24 --- /dev/null +++ b/spec/fixtures/integration/pslr_pure.y @@ -0,0 +1,63 @@ +/* + * Integration test for PSLR pure mode (%define api.pslr.lexer generated). + * The generated parser owns lexical analysis: no user yylex, layout is + * skipped by the generated scan loop, and %token-action builds semantic + * values from the matched lexeme. + */ + +%{ +#include +#include +#include "pslr_pure.h" + +static int yyerror(YYLTYPE *loc, const char *str); +%} + +%define lr.type pslr +%define api.pslr.lexer generated + +%token NUM PLUS + +%token-pattern NUM /[0-9]+/ +%token-pattern PLUS /\+/ +%token-pattern YYLAYOUT_WS /[ \t\r\n]+/ + +%token-action NUM { + int yypslr_value = 0; + int yypslr_i; + for (yypslr_i = 0; yypslr_i < yyleng; yypslr_i++) { + yypslr_value = yypslr_value * 10 + (yytext[yypslr_i] - '0'); + } + yylval = yypslr_value; +} + +%% + +program: expr { printf("=> %d\n", $1); } + ; + +expr: NUM + | expr PLUS NUM { $$ = $1 + $3; } + ; + +%% + +static int yyerror(YYLTYPE *loc, const char *str) +{ + (void)loc; + fprintf(stderr, "parse error: %s\n", str); + return 0; +} + +int main(int argc, char *argv[]) +{ + const char *input = argc == 2 ? argv[1] : ""; + + yypslr_set_input(input, strlen(input)); + + if (yyparse()) { + fprintf(stderr, "syntax error\n"); + return 1; + } + return 0; +} diff --git a/spec/lrama/integration_spec.rb b/spec/lrama/integration_spec.rb index 2330c89a3..987dd981a 100644 --- a/spec/lrama/integration_spec.rb +++ b/spec/lrama/integration_spec.rb @@ -413,6 +413,66 @@ def generate_object(grammar_file_path, c_path, obj_path, command_args: []) end end + describe "PSLR pure mode (api.pslr.lexer generated)" do + def compile_pure_parser + tmpdir = Dir.tmpdir + grammar_file_path = fixture_path("integration/pslr_pure.y") + c_path = tmpdir + "/pslr_pure#{file_extension}" + h_path = tmpdir + "/pslr_pure.h" + obj_path = tmpdir + "/pslr_pure" + + unless IntegrationHelper.compiled_parsers["pslr_pure"] && File.exist?(obj_path) + Lrama::Command.new(%W[-H#{h_path} -o#{c_path} #{grammar_file_path}]).run + exec_command("#{compiler} -Wall -O0 -g -I#{tmpdir} #{c_path} -o #{obj_path}") + IntegrationHelper.compiled_parsers["pslr_pure"] = true + end + + obj_path + end + + it "parses input with the generated lexer, skipping layout and running token actions" do + obj_path = compile_pure_parser + + out, _err, status = Open3.capture3(obj_path, "1 + 23 +\t4") + expect(status.success?).to be true + expect(out).to eq("=> 28\n") + end + + it "reports a syntax error for invalid input" do + obj_path = compile_pure_parser + + _out, _err, status = Open3.capture3(obj_path, "1 + + 2") + expect(status.success?).to be false + end + + it "rejects pure mode when a terminal has no token pattern" do + grammar_text = <<~GRAMMAR + %define lr.type pslr + %define api.pslr.lexer generated + %token NUM UNCOVERED + %token-pattern NUM /[0-9]+/ + + %% + + start + : NUM + | UNCOVERED + ; + GRAMMAR + grammar = Lrama::Parser.new(grammar_text, "integration/pslr_pure_uncovered.y").parse + grammar.prepare + grammar.validate! + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + logger = Lrama::Logger.new + allow(logger).to receive(:error) + + expect { states.validate!(logger) }.to raise_error(SystemExit) + expect(logger).to have_received(:error).with(a_string_including("UNCOVERED")) + end + end + describe "user defined parameterized rules" do it "prints messages corresponding to rules" do expected = <<~STR diff --git a/spec/lrama/output_spec.rb b/spec/lrama/output_spec.rb index f44b20a68..b3a3dae8b 100644 --- a/spec/lrama/output_spec.rb +++ b/spec/lrama/output_spec.rb @@ -402,6 +402,7 @@ pslr_defined?: true, pslr_state_member: "current_state", parse_lac_full?: true, + pslr_lexer_generated?: false, token_actions: [] ) end diff --git a/template/bison/yacc.c b/template/bison/yacc.c index 6e603b6b4..153d07e02 100644 --- a/template/bison/yacc.c +++ b/template/bison/yacc.c @@ -602,6 +602,9 @@ static const <%= output.int_type_for(output.context.yyr2) %> yyr2[] = #ifndef YYSETSTATE_CONTEXT # define YYSETSTATE_CONTEXT(CurrentState) ((void) 0) #endif +#ifndef YYPSLR_SET_PARSER_STATE +# define YYPSLR_SET_PARSER_STATE(State) ((void) 0) +#endif <%- end -%> int @@ -1810,6 +1813,7 @@ YYLTYPE yylloc = yyloc_default; YY_IGNORE_USELESS_CAST_END <%- if output.pslr_enabled? -%> YYSETSTATE_CONTEXT (yystate); + YYPSLR_SET_PARSER_STATE (yystate); <%- end -%> YY_STACK_PRINT (yyss, yyssp<%= output.user_args %>); From 8ce801df3292014677605a8dc187427f8a9d3632 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 22:28:03 +0900 Subject: [PATCH 12/24] pslr: add {NAME} references, canonical-lr tables and richer reports * %token-pattern bodies can reference earlier patterns with {NAME}, the idiom the paper uses for shortest-match comment scanning (Fig 3.2c/3.2d). Undefined, forward, self and malformed references are rejected; a literal brace is written \{. * The scanner alphabet is now bytes (0-255) rather than 7-bit ASCII: negated character classes and dot pass multi-byte UTF-8 sequences through unmodified, and Ruby-side scanning walks bytes to match the generated C runtime. * Layout tokens are rejected in grammar rules at validation time; the parser never sees them, so such rules could never match. * %define pslr.tables canonical-lr switches state splitting to canonical LR(1) compatibility (kernel lookahead-set equality) for debugging conflict reports whose contexts IELR merging would blend. * --report=pslr now renders per-state acceptable-token sets, scanner_accepts rows including the fallback row, unresolved-conflict details with witnesses, useless %lex-prec rules and lexical tie candidates in addition to the split metrics summary. --- lib/lrama/grammar.rb | 3 + lib/lrama/reporter/pslr.rb | 94 +++++++++++++++++++++++++++++++- lib/lrama/scanner_fsa.rb | 50 +++++++++++++++-- lib/lrama/states.rb | 14 ++++- spec/lrama/grammar_spec.rb | 31 +++++++++++ spec/lrama/integration_spec.rb | 46 ++++++++++++++++ spec/lrama/reporter/pslr_spec.rb | 55 +++++++++++++++++++ spec/lrama/scanner_fsa_spec.rb | 42 ++++++++++++++ 8 files changed, 326 insertions(+), 9 deletions(-) create mode 100644 spec/lrama/reporter/pslr_spec.rb diff --git a/lib/lrama/grammar.rb b/lib/lrama/grammar.rb index 2886723ae..9efcbdc72 100644 --- a/lib/lrama/grammar.rb +++ b/lib/lrama/grammar.rb @@ -679,9 +679,12 @@ def escape_regex_literal(literal) def validate_pslr_configuration! validate_parse_lac! validate_pslr_lexer! + validate_pslr_tables! return unless pslr_defined? + validate_no_layout_tokens_in_rules! + member = pslr_state_member if member && member !~ /\A[a-zA-Z_][a-zA-Z0-9_]*\z/ raise %(%define api.pslr.state-member must be a valid C identifier, got "#{member}".) diff --git a/lib/lrama/reporter/pslr.rb b/lib/lrama/reporter/pslr.rb index 766c5855b..ccbf3015a 100644 --- a/lib/lrama/reporter/pslr.rb +++ b/lib/lrama/reporter/pslr.rb @@ -14,6 +14,18 @@ def report(io, states) return unless @pslr return unless states.pslr_defined? + report_summary(io, states) + report_acceptable_tokens(io, states) + report_scanner_accepts(io, states) + report_unresolved_conflicts(io, states) + report_useless_lex_prec(io, states) + report_tie_candidates(io, states) + end + + private + + # @rbs (IO io, Lrama::States states) -> void + def report_summary(io, states) metrics = states.pslr_metrics io << "PSLR Summary\n\n" @@ -29,7 +41,87 @@ def report(io, states) io << "\n" end - private + # @rbs (IO io, Lrama::States states) -> void + def report_acceptable_tokens(io, states) + return unless states.scanner_fsa + + io << "PSLR Acceptable Tokens (acc with ties and layout)\n\n" + states.states.each do |state| + tokens = states.pslr_acceptable_tokens(state).to_a.sort + io << " State #{state.id}: #{tokens.join(' ')}\n" + end + io << "\n" + end + + # @rbs (IO io, Lrama::States states) -> void + def report_scanner_accepts(io, states) + scanner_accepts = states.scanner_accepts_table + scanner_fsa = states.scanner_fsa + return unless scanner_accepts && scanner_fsa + + accepting_states = scanner_fsa.states.select(&:accepting?) + + io << "PSLR Scanner Accepts\n\n" + states.states.each do |state| + cells = accepting_states.filter_map do |fsa_state| + token = scanner_accepts[state.id, fsa_state.id] + "ss#{fsa_state.id}=>#{token.name}" if token + end + next if cells.empty? + + io << " State #{state.id}: #{cells.join(' ')}\n" + end + + fallback_cells = accepting_states.filter_map do |fsa_state| + token = scanner_accepts.fallback_table[fsa_state.id] + "ss#{fsa_state.id}=>#{token.name}" if token + end + io << " Fallback: #{fallback_cells.join(' ')}\n" unless fallback_cells.empty? + io << "\n" + end + + # @rbs (IO io, Lrama::States states) -> void + def report_unresolved_conflicts(io, states) + scanner_accepts = states.scanner_accepts_table + return unless scanner_accepts + return unless scanner_accepts.unresolved_conflicts? + + io << "PSLR Unresolved Scanner Conflicts\n\n" + scanner_accepts.conflicts.each do |conflict| + io << " State #{conflict.parser_state_id || 'fallback'}, scanner state #{conflict.scanner_state_id}\n" + io << " witness: #{conflict.witness.inspect}\n" if conflict.witness + io << " shorter matches: #{conflict.shorter_tokens.join(', ')}\n" unless conflict.shorter_tokens.empty? + io << " current matches: #{conflict.current_tokens.join(', ')}\n" + end + io << "\n" + end + + # @rbs (IO io, Lrama::States states) -> void + def report_useless_lex_prec(io, states) + return unless states.scanner_accepts_table + + useless = states.lex_prec.useless_rules + return if useless.empty? + + io << "PSLR Useless %lex-prec Rules\n\n" + useless.each do |rule| + operator = LengthPrecedences.operator_label(rule.operator) + io << " #{rule.left_name} #{operator} #{rule.right_name} (line #{rule.lineno})\n" + end + io << "\n" + end + + # @rbs (IO io, Lrama::States states) -> void + def report_tie_candidates(io, states) + candidates = states.lexical_tie_candidates + return if candidates.nil? || candidates.empty? + + io << "PSLR Lexical Tie Candidates\n\n" + candidates.each do |left, right| + io << " #{left} #{right}\n" + end + io << "\n" + end # @rbs (Numeric?) -> String def format_ratio(value) diff --git a/lib/lrama/scanner_fsa.rb b/lib/lrama/scanner_fsa.rb index 1ed327534..32e0559a5 100644 --- a/lib/lrama/scanner_fsa.rb +++ b/lib/lrama/scanner_fsa.rb @@ -68,17 +68,18 @@ def acc_ss(state_id) end # Simulate the FSA on input string starting from initial state - # Returns all accepting states reached during the scan + # Returns all accepting states reached during the scan. + # The walk is byte-oriented to match the generated C runtime. # @rbs (String input) -> Array[{state: State, position: Integer, token: Grammar::TokenPattern}] def scan(input) results = [] current_state_id = 0 - input.each_char.with_index do |char, index| + input.each_byte.with_index do |byte, index| current_state = @states[current_state_id] break unless current_state - next_state_id = current_state.transitions[char] + next_state_id = current_state.transitions[byte.chr] break unless next_state_id current_state_id = next_state_id @@ -216,6 +217,7 @@ def to_ary def build_nfa nfa_states = [] nfa_counter = [0] + @pattern_references = {} # Create NFA start state nfa_start = create_nfa_state(nfa_counter, nfa_states) @@ -235,6 +237,10 @@ def build_nfa # Mark end state as accepting end_state.accepting_token = token_pattern + + # {NAME} may only reference patterns that are already defined, so + # register after a successful compile (no self/forward references). + @pattern_references[token_pattern.name] = token_pattern.regex_pattern end nfa_states @@ -248,8 +254,11 @@ def create_nfa_state(counter, states) state end - ASCII_CHARS = (0..127).map(&:chr).freeze #: Array[String] - ANY_CHARS = (ASCII_CHARS - ["\n"]).freeze #: Array[String] + # The input alphabet is bytes (0-255): keywords and operators are + # ASCII, and byte-oriented classes let multi-byte UTF-8 sequences + # pass through negated classes and dot unmodified. + BYTE_CHARS = (0..255).map(&:chr).freeze #: Array[String] + ANY_CHARS = (BYTE_CHARS - ["\n"]).freeze #: Array[String] DIGIT_CHARS = ("0".."9").to_a.freeze #: Array[String] WORD_CHARS = (("a".."z").to_a + ("A".."Z").to_a + DIGIT_CHARS + ["_"]).freeze #: Array[String] WHITESPACE_CHARS = [" ", "\t", "\n", "\r", "\f", "\v"].freeze #: Array[String] @@ -329,6 +338,10 @@ def compile_sequence(pattern, pos, counter, states, stop_char) frag, i = compile_expression(pattern, i + 1, counter, states, ")") fragments << frag next + when '{' + frag, i = compile_pattern_reference(pattern, i, counter, states) + fragments << frag + next when ')' raise PatternError, "unmatched close group at offset #{i}" when '.' @@ -354,6 +367,31 @@ def empty_sequence_message(stop_char) stop_char ? "empty groups are not allowed" : "empty patterns are not allowed" end + # Compile a {NAME} reference by inlining the body of an already + # defined %token-pattern (paper Fig 3.2c/3.2d idiom). Self and + # forward references are rejected because @pattern_references only + # contains patterns compiled before the current one. + # @rbs (String pattern, Integer offset, Array[Integer] counter, Array[NFAState] states) -> [Fragment, Integer] + def compile_pattern_reference(pattern, offset, counter, states) + close = pattern.index("}", offset) + raise PatternError, "unclosed pattern reference at offset #{offset}" unless close + + name = pattern[offset + 1...close] + unless name&.match?(/\A[a-zA-Z_][a-zA-Z0-9_]*\z/) + raise PatternError, "invalid pattern reference {#{name}} at offset #{offset} (escape a literal brace as \\{)" + end + + referenced = (@pattern_references || {})[name] + unless referenced + raise PatternError, "undefined or forward pattern reference {#{name}} (references must name an earlier %token-pattern)" + end + + fragment, consumed = compile_expression(referenced, 0, counter, states) + raise PatternError, "unexpected trailing input in referenced pattern {#{name}}" if consumed < referenced.length + + [fragment, close + 1] + end + # @rbs (String pattern, Integer offset, Array[Integer] counter, Array[NFAState] states) -> [Fragment, Integer] def compile_escape(pattern, offset, counter, states) raise PatternError, "dangling escape at offset #{offset}" if offset + 1 >= pattern.length @@ -441,7 +479,7 @@ def expand_char_class(char_class) end if negated - chars = ASCII_CHARS - chars + chars = BYTE_CHARS - chars end chars.uniq diff --git a/lib/lrama/states.rb b/lib/lrama/states.rb index a4491a9ae..9aa675a33 100644 --- a/lib/lrama/states.rb +++ b/lib/lrama/states.rb @@ -333,6 +333,13 @@ def compute_la_sources_for_conflicted_states end end + # Public accessor for reporting: acc(sp) with tie expansion and + # layout injection, as used by the scanner_accepts construction. + # @rbs (State state) -> Set[String] + def pslr_acceptable_tokens(state) + acceptable_tokens_for_pslr(state) + end + private # @rbs (Grammar::Symbol accessing_symbol, Array[State::Item] kernels, Hash[Array[State::Item], State] states_created) -> [State, bool] @@ -991,9 +998,12 @@ def compute_state(state, transition, next_state) def compatible_split_state?(state, filtered_lookaheads, pslr_lookaheads = nil) pslr_lookaheads ||= filtered_lookaheads - return false unless state.is_compatible?(filtered_lookaheads) + if @pslr_split_enabled && @grammar.pslr_canonical_tables? + return false unless canonical_lookaheads_match?(state, pslr_lookaheads) + else + return false unless state.is_compatible?(filtered_lookaheads) + end return true unless @pslr_split_enabled && @scanner_fsa - return true unless state.lookaheads_recomputed pslr_compatible_successors?(state, state.item_lookahead_set, pslr_lookaheads) end diff --git a/spec/lrama/grammar_spec.rb b/spec/lrama/grammar_spec.rb index 7a86972bd..49f8bb539 100644 --- a/spec/lrama/grammar_spec.rb +++ b/spec/lrama/grammar_spec.rb @@ -283,6 +283,37 @@ .to raise_error(RuntimeError, '%define pslr.max-state-ratio must be greater than or equal to 1.0, got "0.5".') end end + + context 'when pslr.tables has an unknown value' do + before do + grammar.define = { + 'lr.type' => 'pslr', + 'pslr.tables' => 'lalr' + } + end + + it 'raises an error' do + expect { grammar.validate! } + .to raise_error(RuntimeError, '%define pslr.tables must be "ielr" or "canonical-lr", got "lalr".') + end + end + + context 'when a layout token appears in a grammar rule' do + it 'raises an error' do + y = <<~GRAMMAR + %define lr.type pslr + %token-pattern ID /[a-z]+/ + %token-pattern YYLAYOUT_WS /[ ]+/ + %% + program: ID YYLAYOUT_WS ID + GRAMMAR + grammar = Lrama::Parser.new(y, "layout_in_rule.y").parse + grammar.prepare + + expect { grammar.validate! } + .to raise_error(RuntimeError, /layout token YYLAYOUT_WS must not appear in a grammar rule/) + end + end end describe "#finalize_lexical_ties!" do diff --git a/spec/lrama/integration_spec.rb b/spec/lrama/integration_spec.rb index 987dd981a..e498f86e0 100644 --- a/spec/lrama/integration_spec.rb +++ b/spec/lrama/integration_spec.rb @@ -445,6 +445,52 @@ def compile_pure_parser expect(status.success?).to be false end + it "computes canonical LR(1) tables when pslr.tables is canonical-lr" do + base_source = <<~GRAMMAR + %token-pattern LT />/ + %token-pattern RANGLE />/ + %token-pattern ID /[a-z]+/ + %lex-no-tie RANGLE RSHIFT + + %% + + program + : template_expr + | shift_expr + ; + + template_expr + : LT shared RANGLE + ; + + shift_expr + : START shared RSHIFT ID + ; + + shared + : MARK + ; + GRAMMAR + + states_by_tables = ["ielr", "canonical-lr"].map do |tables| + source = "%define lr.type pslr\n%define pslr.tables #{tables}\n" + base_source + grammar = Lrama::Parser.new(source, "integration/pslr_tables_#{tables}.y").parse + grammar.prepare + grammar.validate! + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + states + end + + ielr_states, canonical_states = states_by_tables + expect(canonical_states.states_count).to be >= ielr_states.states_count + expect(canonical_states.scanner_accepts_table).not_to be_nil + end + it "rejects pure mode when a terminal has no token pattern" do grammar_text = <<~GRAMMAR %define lr.type pslr diff --git a/spec/lrama/reporter/pslr_spec.rb b/spec/lrama/reporter/pslr_spec.rb new file mode 100644 index 000000000..0736481e1 --- /dev/null +++ b/spec/lrama/reporter/pslr_spec.rb @@ -0,0 +1,55 @@ +# frozen_string_literal: true + +require "stringio" + +RSpec.describe Lrama::Reporter::Pslr do + def build_states(source) + grammar = Lrama::Parser.new(source, "reporter_pslr.y").parse + grammar.prepare + grammar.validate! + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + states + end + + let(:source) do + <<~GRAMMAR + %define lr.type pslr + %token-pattern RSHIFT />>/ + %token-pattern RANGLE />/ + %token-pattern USELESS_A /a/ + %token-pattern USELESS_B /b/ + %lex-prec RANGLE -s RSHIFT + %lex-prec USELESS_A -~ USELESS_B + %% + program: RSHIFT | RANGLE + GRAMMAR + end + + it "reports summary, accept sets, scanner accepts rows and useless rules" do + states = build_states(source) + io = StringIO.new + described_class.new(pslr: true).report(io, states) + output = io.string + + expect(output).to include("PSLR Summary") + expect(output).to include("PSLR Acceptable Tokens") + expect(output).to include("PSLR Scanner Accepts") + expect(output).to include("Fallback:") + expect(output).to include("PSLR Useless %lex-prec Rules") + expect(output).to include("USELESS_A -~ USELESS_B") + end + + it "reports nothing for non-PSLR grammars" do + grammar = Lrama::Parser.new("%token NUM\n%%\nprogram: NUM\n", "plain.y").parse + grammar.prepare + grammar.validate! + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + io = StringIO.new + described_class.new(pslr: true).report(io, states) + + expect(io.string).to eq("") + end +end diff --git a/spec/lrama/scanner_fsa_spec.rb b/spec/lrama/scanner_fsa_spec.rb index 9912945ee..fb45aa7df 100644 --- a/spec/lrama/scanner_fsa_spec.rb +++ b/spec/lrama/scanner_fsa_spec.rb @@ -204,6 +204,48 @@ def token_pattern(name, regex, lineno: 1, order: 0) end end + describe "{NAME} pattern references" do + it "inlines the body of an earlier pattern" do + com_start = token_pattern("COM_START", "\\/\\*[^*]*", order: 0) + com = token_pattern("COM", "{COM_START}\\*\\/", order: 1) + fsa = Lrama::ScannerFSA.new([com_start, com]) + + names = fsa.scan("/*abc*/").map { |result| result[:token].name } + expect(names).to include("COM") + end + + it "rejects undefined and forward references" do + expect { Lrama::ScannerFSA.new([token_pattern("BAD", "{MISSING}x", lineno: 3)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /BAD at line 3.*undefined or forward pattern reference \{MISSING\}/m) + end + + it "rejects self references" do + expect { Lrama::ScannerFSA.new([token_pattern("SELF", "{SELF}x", lineno: 4)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /SELF at line 4.*undefined or forward pattern reference \{SELF\}/m) + end + + it "still matches escaped literal braces" do + brace = token_pattern("LBRACE", "\\{") + expect(Lrama::ScannerFSA.new([brace]).scan("{").map { |result| result[:token].name }).to include("LBRACE") + end + + it "rejects malformed references" do + expect { Lrama::ScannerFSA.new([token_pattern("BAD", "{1x}", lineno: 5)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /invalid pattern reference/) + end + end + + describe "byte-oriented classes" do + it "matches multi-byte UTF-8 sequences through negated classes" do + not_star = token_pattern("NOT_STAR", "[^*]+") + fsa = Lrama::ScannerFSA.new([not_star]) + + results = fsa.scan("あ") + expect(results.map { |result| result[:token].name }).to include("NOT_STAR") + expect(results.map { |result| result[:position] }).to include("あ".bytesize) + end + end + describe "#pairwise_conflict_pairs" do it "detects identity and length conflicts" do rangle = Lrama::Grammar::TokenPattern.new( From bed8566a4800f5afafc6cd6f06dd384ac45a49a3 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 22:40:10 +0900 Subject: [PATCH 13/24] pslr: regenerate RBS signatures and fix operator annotations Annotate %lex-prec operator constants and attributes as ::Symbol so they do not resolve to Lrama::Grammar::Symbol inside the Grammar namespace, and regenerate the rbs-inline signatures for the new pairwise resolution, LAC, pure-mode and reporting code. steep check is clean. --- lib/lrama/grammar.rb | 4 +- lib/lrama/grammar/lex_prec.rb | 38 +++++++-------- lib/lrama/state/scanner_accepts.rb | 2 +- sig/generated/lrama/grammar.rbs | 8 ++-- sig/generated/lrama/grammar/lex_prec.rbs | 48 +++++++++---------- .../lrama/pslr/pairwise_resolution.rbs | 42 ++++++++++++++++ sig/generated/lrama/reporter/pslr.rbs | 18 +++++++ sig/generated/lrama/scanner_fsa.rbs | 15 +++++- sig/generated/lrama/state/scanner_accepts.rbs | 32 +++++++++---- sig/generated/lrama/states.rbs | 12 +++++ sig/generated/lrama/warnings/parse_lac.rbs | 13 +++++ .../lrama/warnings/pslr_coverage.rbs | 17 +++++++ 12 files changed, 187 insertions(+), 62 deletions(-) create mode 100644 sig/generated/lrama/pslr/pairwise_resolution.rbs create mode 100644 sig/generated/lrama/warnings/parse_lac.rbs create mode 100644 sig/generated/lrama/warnings/pslr_coverage.rbs diff --git a/lib/lrama/grammar.rb b/lib/lrama/grammar.rb index 9efcbdc72..342939b7c 100644 --- a/lib/lrama/grammar.rb +++ b/lib/lrama/grammar.rb @@ -474,7 +474,7 @@ def add_symbol_set(name:, symbols:) # Add lex-prec rules from %lex-prec directive. # Stores as raw declaration for delayed expansion after implicit literal synthesis. - # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Grammar::LexPrec::Declaration + # @rbs (left_token: Lexer::Token::Base, operator: ::Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Grammar::LexPrec::Declaration def add_lex_prec_rule(left_token:, operator:, right_token:, lineno:) # Register terminals so they are known to the symbol resolver canonical_lexical_operand(left_token) unless left_token.s_value == "yyall" || @symbol_sets.key?(left_token.s_value) @@ -628,7 +628,7 @@ def synthesize_implicit_literal_token_patterns! # Validate that identity-component operators are not applied to self-pairs. # Self-pair is allowed only for length-only operators (-~ and -s). - # @rbs (Lexer::Token::Base left, Lexer::Token::Base right, Symbol operator, Integer lineno) -> void + # @rbs (Lexer::Token::Base left, Lexer::Token::Base right, ::Symbol operator, Integer lineno) -> void def validate_lex_prec_self_pair!(left, right, operator, lineno) return unless left.s_value == right.s_value diff --git a/lib/lrama/grammar/lex_prec.rb b/lib/lrama/grammar/lex_prec.rb index 22c787356..1d0e8c872 100644 --- a/lib/lrama/grammar/lex_prec.rb +++ b/lib/lrama/grammar/lex_prec.rb @@ -14,20 +14,20 @@ class Grammar # void + # @rbs (left_operand: Lexer::Token::Base, operator: ::Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> void def initialize(left_operand:, operator:, right_operand:, lineno:) @left_operand = left_operand @operator = operator @@ -72,11 +72,11 @@ def initialize(left_operand:, operator:, right_operand:, lineno:) class Rule attr_reader :left_token #: Lexer::Token::Base - attr_reader :operator #: Symbol + attr_reader :operator #: ::Symbol attr_reader :right_token #: Lexer::Token::Base attr_reader :lineno #: Integer - # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> void + # @rbs (left_token: Lexer::Token::Base, operator: ::Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> void def initialize(left_token:, operator:, right_token:, lineno:) @left_token = left_token @operator = operator @@ -119,7 +119,7 @@ def useless_rules end # Store a raw declaration for delayed expansion. - # @rbs (left_operand: Lexer::Token::Base, operator: Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> Declaration + # @rbs (left_operand: Lexer::Token::Base, operator: ::Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> Declaration def add_declaration(left_operand:, operator:, right_operand:, lineno:) decl = Declaration.new( left_operand: left_operand, @@ -131,7 +131,7 @@ def add_declaration(left_operand:, operator:, right_operand:, lineno:) decl end - # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Rule + # @rbs (left_token: Lexer::Token::Base, operator: ::Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Rule def add_rule(left_token:, operator:, right_token:, lineno:) rule = Rule.new( left_token: left_token, @@ -187,7 +187,7 @@ def right_token_length_winner(token1, token2) private - # @rbs (String token1, String token2, Array[Symbol] operators) -> bool + # @rbs (String token1, String token2, Array[::Symbol] operators) -> bool def pair_rule?(token1, token2, operators) @rules.any? do |rule| operators.include?(rule.operator) && diff --git a/lib/lrama/state/scanner_accepts.rb b/lib/lrama/state/scanner_accepts.rb index 0595ed38d..97a75646b 100644 --- a/lib/lrama/state/scanner_accepts.rb +++ b/lib/lrama/state/scanner_accepts.rb @@ -229,7 +229,7 @@ class CompleteProfileComputer attr_reader :table #: Hash[Integer, Grammar::TokenPattern] attr_reader :conflicts #: Array[Conflict] - # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void + # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer], ?track_rule_usage: bool) -> void def initialize(scanner_fsa, lex_prec, length_prec, acceptable_tokens, parser_state_id = nil, fallback: false, token_order: {}, track_rule_usage: false) @scanner_fsa = scanner_fsa @resolver = ProfileResolver.new(lex_prec, length_prec, fallback: fallback, token_order: token_order, track_rule_usage: track_rule_usage) diff --git a/sig/generated/lrama/grammar.rbs b/sig/generated/lrama/grammar.rbs index 45df0d986..9b0f51491 100644 --- a/sig/generated/lrama/grammar.rbs +++ b/sig/generated/lrama/grammar.rbs @@ -331,8 +331,8 @@ module Lrama # Add lex-prec rules from %lex-prec directive. # Stores as raw declaration for delayed expansion after implicit literal synthesis. - # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Grammar::LexPrec::Declaration - def add_lex_prec_rule: (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Grammar::LexPrec::Declaration + # @rbs (left_token: Lexer::Token::Base, operator: ::Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Grammar::LexPrec::Declaration + def add_lex_prec_rule: (left_token: Lexer::Token::Base, operator: ::Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Grammar::LexPrec::Declaration # Finalize lexical declarations after implicit literal synthesis. # Expands yyall and symbol-set operands using the post-synthesis token universe. @@ -377,8 +377,8 @@ module Lrama # Validate that identity-component operators are not applied to self-pairs. # Self-pair is allowed only for length-only operators (-~ and -s). - # @rbs (Lexer::Token::Base left, Lexer::Token::Base right, Symbol operator, Integer lineno) -> void - def validate_lex_prec_self_pair!: (Lexer::Token::Base left, Lexer::Token::Base right, Symbol operator, Integer lineno) -> void + # @rbs (Lexer::Token::Base left, Lexer::Token::Base right, ::Symbol operator, Integer lineno) -> void + def validate_lex_prec_self_pair!: (Lexer::Token::Base left, Lexer::Token::Base right, ::Symbol operator, Integer lineno) -> void # @rbs (Grammar::Symbol term) -> String? def implicit_literal_regex_pattern: (Grammar::Symbol term) -> String? diff --git a/sig/generated/lrama/grammar/lex_prec.rbs b/sig/generated/lrama/grammar/lex_prec.rbs index b6e6c5e21..c88e30410 100644 --- a/sig/generated/lrama/grammar/lex_prec.rbs +++ b/sig/generated/lrama/grammar/lex_prec.rbs @@ -13,56 +13,56 @@ module Lrama # void - def initialize: (left_operand: Lexer::Token::Base, operator: Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> void + # @rbs (left_operand: Lexer::Token::Base, operator: ::Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> void + def initialize: (left_operand: Lexer::Token::Base, operator: ::Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> void end class Rule attr_reader left_token: Lexer::Token::Base - attr_reader operator: Symbol + attr_reader operator: ::Symbol attr_reader right_token: Lexer::Token::Base attr_reader lineno: Integer - # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> void - def initialize: (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> void + # @rbs (left_token: Lexer::Token::Base, operator: ::Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> void + def initialize: (left_token: Lexer::Token::Base, operator: ::Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> void # @rbs () -> String def left_name: () -> String @@ -89,11 +89,11 @@ module Lrama def useless_rules: () -> Array[Rule] # Store a raw declaration for delayed expansion. - # @rbs (left_operand: Lexer::Token::Base, operator: Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> Declaration - def add_declaration: (left_operand: Lexer::Token::Base, operator: Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> Declaration + # @rbs (left_operand: Lexer::Token::Base, operator: ::Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> Declaration + def add_declaration: (left_operand: Lexer::Token::Base, operator: ::Symbol, right_operand: Lexer::Token::Base, lineno: Integer) -> Declaration - # @rbs (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Rule - def add_rule: (left_token: Lexer::Token::Base, operator: Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Rule + # @rbs (left_token: Lexer::Token::Base, operator: ::Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Rule + def add_rule: (left_token: Lexer::Token::Base, operator: ::Symbol, right_token: Lexer::Token::Base, lineno: Integer) -> Rule # True when winner explicitly wins an identity conflict against loser. # The relation is intentionally not transitive. @@ -114,8 +114,8 @@ module Lrama private - # @rbs (String token1, String token2, Array[Symbol] operators) -> bool - def pair_rule?: (String token1, String token2, Array[Symbol] operators) -> bool + # @rbs (String token1, String token2, Array[::Symbol] operators) -> bool + def pair_rule?: (String token1, String token2, Array[::Symbol] operators) -> bool end end end diff --git a/sig/generated/lrama/pslr/pairwise_resolution.rbs b/sig/generated/lrama/pslr/pairwise_resolution.rbs new file mode 100644 index 000000000..ccdaba302 --- /dev/null +++ b/sig/generated/lrama/pslr/pairwise_resolution.rbs @@ -0,0 +1,42 @@ +# Generated from lib/lrama/pslr/pairwise_resolution.rb with RBS::Inline + +module Lrama + module Pslr + # Pair-based PSLR state compatibility (paper section 3.4.3). + # + # The scanner FSA is scanned once to find every token pair that can be + # in an identity or length scanner conflict. Two acceptable-token sets + # are then compatible when no conflict pair distinguishes them: + # + # * both sets contain the same subset of the pair (the pseudo-scanner + # resolves the conflict identically, or leaves it identically + # unresolved -- unresolved/unresolved states merge), or + # * one set contains neither token of the pair (its match set for + # inputs manifesting the conflict is empty for this pair). + # + # Reducing the check to pairs is the precomputation the paper + # recommends for phase 3: the per-pair verdict no longer depends on + # the rest of the accept set, so state splitting does not have to + # re-run the profile resolver for every candidate merge. Layout + # tokens are members of every accept set, so pairs won by layout can + # never distinguish two states (the split-stable layout optimization + # of section 3.6 falls out of the presence test). + class PairwiseResolution + attr_reader conflict_pairs: Set[[ String, String ]] + + # @rbs (ScannerFSA scanner_fsa) -> void + def initialize: (ScannerFSA scanner_fsa) -> void + + # @rbs (Set[String] left_acc, Set[String] right_acc) -> bool + def compatible_accept_sets?: (Set[String] left_acc, Set[String] right_acc) -> bool + + private + + # @rbs ([String, String] pair, Set[String] left_acc, Set[String] right_acc) -> bool + def pair_compatible?: ([ String, String ] pair, Set[String] left_acc, Set[String] right_acc) -> bool + + # @rbs ([String, String] pair, Set[String] acc) -> Integer + def presence: ([ String, String ] pair, Set[String] acc) -> Integer + end + end +end diff --git a/sig/generated/lrama/reporter/pslr.rbs b/sig/generated/lrama/reporter/pslr.rbs index c9de08058..874f2e2ca 100644 --- a/sig/generated/lrama/reporter/pslr.rbs +++ b/sig/generated/lrama/reporter/pslr.rbs @@ -11,6 +11,24 @@ module Lrama private + # @rbs (IO io, Lrama::States states) -> void + def report_summary: (IO io, Lrama::States states) -> void + + # @rbs (IO io, Lrama::States states) -> void + def report_acceptable_tokens: (IO io, Lrama::States states) -> void + + # @rbs (IO io, Lrama::States states) -> void + def report_scanner_accepts: (IO io, Lrama::States states) -> void + + # @rbs (IO io, Lrama::States states) -> void + def report_unresolved_conflicts: (IO io, Lrama::States states) -> void + + # @rbs (IO io, Lrama::States states) -> void + def report_useless_lex_prec: (IO io, Lrama::States states) -> void + + # @rbs (IO io, Lrama::States states) -> void + def report_tie_candidates: (IO io, Lrama::States states) -> void + # @rbs (Numeric?) -> String def format_ratio: (Numeric?) -> String end diff --git a/sig/generated/lrama/scanner_fsa.rbs b/sig/generated/lrama/scanner_fsa.rbs index 7397a65d3..fd4e23c2f 100644 --- a/sig/generated/lrama/scanner_fsa.rbs +++ b/sig/generated/lrama/scanner_fsa.rbs @@ -46,7 +46,8 @@ module Lrama def acc_ss: (Integer state_id) -> Array[Grammar::TokenPattern] # Simulate the FSA on input string starting from initial state - # Returns all accepting states reached during the scan + # Returns all accepting states reached during the scan. + # The walk is byte-oriented to match the generated C runtime. # @rbs (String input) -> Array[{state: State, position: Integer, token: Grammar::TokenPattern}] def scan: (String input) -> Array[{ state: State, position: Integer, token: Grammar::TokenPattern }] @@ -113,7 +114,10 @@ module Lrama # @rbs (Array[Integer] counter, Array[NFAState] states) -> NFAState def create_nfa_state: (Array[Integer] counter, Array[NFAState] states) -> NFAState - ASCII_CHARS: Array[String] + # The input alphabet is bytes (0-255): keywords and operators are + # ASCII, and byte-oriented classes let multi-byte UTF-8 sequences + # pass through negated classes and dot unmodified. + BYTE_CHARS: Array[String] ANY_CHARS: Array[String] @@ -141,6 +145,13 @@ module Lrama # @rbs (String? stop_char) -> String def empty_sequence_message: (String? stop_char) -> String + # Compile a {NAME} reference by inlining the body of an already + # defined %token-pattern (paper Fig 3.2c/3.2d idiom). Self and + # forward references are rejected because @pattern_references only + # contains patterns compiled before the current one. + # @rbs (String pattern, Integer offset, Array[Integer] counter, Array[NFAState] states) -> [Fragment, Integer] + def compile_pattern_reference: (String pattern, Integer offset, Array[Integer] counter, Array[NFAState] states) -> [ Fragment, Integer ] + # @rbs (String pattern, Integer offset, Array[Integer] counter, Array[NFAState] states) -> [Fragment, Integer] def compile_escape: (String pattern, Integer offset, Array[Integer] counter, Array[NFAState] states) -> [ Fragment, Integer ] diff --git a/sig/generated/lrama/state/scanner_accepts.rbs b/sig/generated/lrama/state/scanner_accepts.rbs index 39ce04a98..efd756efa 100644 --- a/sig/generated/lrama/state/scanner_accepts.rbs +++ b/sig/generated/lrama/state/scanner_accepts.rbs @@ -33,8 +33,10 @@ module Lrama attr_reader current_tokens: Array[String] - # @rbs (parser_state_id: Integer?, scanner_state_id: Integer, shorter_tokens: Array[String], selected_shorter_token: String?, current_tokens: Array[String]) -> void - def initialize: (parser_state_id: Integer?, scanner_state_id: Integer, shorter_tokens: Array[String], selected_shorter_token: String?, current_tokens: Array[String]) -> void + attr_reader witness: String? + + # @rbs (parser_state_id: Integer?, scanner_state_id: Integer, shorter_tokens: Array[String], selected_shorter_token: String?, current_tokens: Array[String], ?witness: String?) -> void + def initialize: (parser_state_id: Integer?, scanner_state_id: Integer, shorter_tokens: Array[String], selected_shorter_token: String?, current_tokens: Array[String], ?witness: String?) -> void end class ProfileOutcome @@ -64,8 +66,8 @@ module Lrama end class ProfileResolver - # @rbs (Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void - def initialize: (Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void + # @rbs (Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?fallback: bool, ?token_order: Hash[String, Integer], ?track_rule_usage: bool) -> void + def initialize: (Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?fallback: bool, ?token_order: Hash[String, Integer], ?track_rule_usage: bool) -> void # @rbs (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome def resolve: (Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> ProfileOutcome @@ -90,6 +92,16 @@ module Lrama # @rbs (String candidate, Set[String] current_tokens) -> bool def fallback_identity_winner?: (String candidate, Set[String] current_tokens) -> bool + # Mark the %lex-prec rules that made the profile decision as used. + # Only normal-row scanner_accepts construction tracks usage: + # the fallback row spans the whole token universe and exploratory + # resolutions (state compatibility probes) must not mark rules. + # @rbs (String selected_shorter_token, Set[String] current_tokens) -> void + def mark_shorter_win_rules_used: (String selected_shorter_token, Set[String] current_tokens) -> void + + # @rbs (String winner, Set[String] shorter_tokens, Set[String] current_tokens) -> void + def mark_longer_win_rules_used: (String winner, Set[String] shorter_tokens, Set[String] current_tokens) -> void + # @rbs (String candidate, String other) -> bool def token_order_precedes?: (String candidate, String other) -> bool @@ -102,19 +114,19 @@ module Lrama attr_reader conflicts: Array[Conflict] - # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void - def initialize: (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer]) -> void + # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer], ?track_rule_usage: bool) -> void + def initialize: (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer], ?track_rule_usage: bool) -> void # @rbs () -> void def compute: () -> void private - # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void - def visit_transitions: (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited, String path) -> void + def visit_transitions: (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited, String path) -> void - # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void - def visit_state: (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited) -> void + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited, String path) -> void + def visit_state: (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited, String path) -> void # @rbs (ScannerFSA::State fsa_state) -> Set[String] def current_acceptable_tokens: (ScannerFSA::State fsa_state) -> Set[String] diff --git a/sig/generated/lrama/states.rbs b/sig/generated/lrama/states.rbs index 725d37ed4..81836ac74 100644 --- a/sig/generated/lrama/states.rbs +++ b/sig/generated/lrama/states.rbs @@ -126,6 +126,11 @@ module Lrama def compute_la_sources_for_conflicted_states: () -> untyped + # Public accessor for reporting: acc(sp) with tie expansion and + # layout injection, as used by the scanner_accepts construction. + # @rbs (State state) -> Set[String] + def pslr_acceptable_tokens: (State state) -> Set[String] + private # @rbs (Grammar::Symbol accessing_symbol, Array[State::Item] kernels, Hash[Array[State::Item], State] states_created) -> [State, bool] @@ -259,6 +264,8 @@ module Lrama # @rbs (State state, ?State::lookahead_set filtered_lookaheads) -> Array[[Integer, String?]] def pslr_state_signature: (State state, ?State::lookahead_set filtered_lookaheads) -> Array[[ Integer, String? ]] + # Pair-based PSLR compatibility (Def 3.4.3, reduced to token pairs as + # recommended by section 3.4.3 for splitting performance). # @rbs (Set[String] left_acc, Set[String] right_acc) -> bool def pslr_compatible_accept_sets?: (Set[String] left_acc, Set[String] right_acc) -> bool @@ -319,6 +326,11 @@ module Lrama # @rbs (Logger logger) -> void def validate_pslr_scanner_conflicts!: (Logger logger) -> void + # Pure mode owns lexical analysis completely, so every terminal must + # be producible by the pseudo-scanner. + # @rbs (Logger logger) -> void + def validate_pslr_pure_coverage!: (Logger logger) -> void + # @rbs (State::ScannerAccepts::Conflict conflict) -> String def pslr_scanner_conflict_message: (State::ScannerAccepts::Conflict conflict) -> String diff --git a/sig/generated/lrama/warnings/parse_lac.rbs b/sig/generated/lrama/warnings/parse_lac.rbs new file mode 100644 index 000000000..35a8785a4 --- /dev/null +++ b/sig/generated/lrama/warnings/parse_lac.rbs @@ -0,0 +1,13 @@ +# Generated from lib/lrama/warnings/parse_lac.rb with RBS::Inline + +module Lrama + class Warnings + class ParseLac + # @rbs (Logger logger, bool warnings) -> void + def initialize: (Logger logger, bool warnings) -> void + + # @rbs (Lrama::Grammar grammar) -> void + def warn: (Lrama::Grammar grammar) -> void + end + end +end diff --git a/sig/generated/lrama/warnings/pslr_coverage.rbs b/sig/generated/lrama/warnings/pslr_coverage.rbs new file mode 100644 index 000000000..c487f6b08 --- /dev/null +++ b/sig/generated/lrama/warnings/pslr_coverage.rbs @@ -0,0 +1,17 @@ +# Generated from lib/lrama/warnings/pslr_coverage.rb with RBS::Inline + +module Lrama + class Warnings + class PslrCoverage + # @rbs (Logger logger, bool warnings) -> void + def initialize: (Logger logger, bool warnings) -> void + + # Bridge mode allows partial coverage: terminals without a + # %token-pattern must keep coming from the user lexer. List them so + # the boundary between generated and hand-written scanning is + # explicit. + # @rbs (Lrama::Grammar grammar) -> void + def warn: (Lrama::Grammar grammar) -> void + end + end +end From 43eb053f9b2de8e410e212686158124098ce2e7e Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 22:41:45 +0900 Subject: [PATCH 14/24] docs: update NEWS for the completed PSLR(1) feature set Document token actions, pure and bridge operating modes, the length-delimited scan API, {NAME} pattern references, byte-oriented classes, configurable LAC, canonical-lr table debugging, conflict witnesses, useless-rule reporting and the extended --report=pslr output. --- NEWS.md | 54 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 37 insertions(+), 17 deletions(-) diff --git a/NEWS.md b/NEWS.md index 8a1a52ae6..caeca88ed 100644 --- a/NEWS.md +++ b/NEWS.md @@ -49,13 +49,20 @@ This adds the following PSLR-related grammar directives and integration points: - `%define lr.type pslr` enables PSLR parser generation - `%token-pattern` declares token candidates and their regular expressions for PSLR-aware lexical disambiguation +- `%token-action` attaches user code to matched token patterns; `yytext`, `yyleng`, `yylval`, and the accumulated + layout text are available in the action body - `%lex-prec` declares explicit lexical precedence for overlapping token patterns - `%symbol-set` declares reusable sets of terminal tokens for PSLR lexical declarations - `%lex-tie` expands parser-state acceptable-token sets for tied terminals - `%lex-no-tie` records an explicit no-tie decision for terminals with overlapping token patterns - `YYLAYOUT*` token patterns are recognized in every parser state and discarded by PSLR-aware lexers +- `%define api.pslr.lexer generated` enables pure mode: the generated parser owns lexical analysis completely +- `%define api.pslr.state-member` names the parser-state field to be shared with the lexer when using the generated helper macros (bridge mode) +- `%define parse.lac` controls lookahead correction (`full` by default for PSLR parsers, available to LALR/IELR parsers too) +- `%define pslr.tables canonical-lr` switches state splitting to canonical LR(1) compatibility for debugging merged conflict reports - `%define pslr.max-states` and `%define pslr.max-state-ratio` are Lrama-specific safety guards for state growth -- `%define api.pslr.state-member` names the parser-state field to be shared with the lexer when using the generated helper macros +- `--report=pslr` renders split metrics, per-state acceptable-token sets, scanner-accepts rows, unresolved-conflict + witnesses, useless `%lex-prec` rules, and lexical tie candidates Typical usage looks like this: @@ -156,25 +163,38 @@ use the subset accepted by the current state plus tied tokens and layout tokens. generated scanner universe so error handling can still identify and consume a token when the current parser state has no normal scanner decision. -`%token-pattern` currently uses an ASCII byte-oriented regular-expression subset for PSLR pseudo scanning. +`%token-pattern` currently uses a byte-oriented regular-expression subset for PSLR pseudo scanning. Supported constructs are literals, escaped literals such as `\/`, `\*`, `\+`, `\?`, `\(`, `\)`, `\[`, `\]`, and `\\`, grouping with `(...)`, alternation with `|`, repetition operators `*`, `+`, `?`, character classes with escapes such as `[\]]`, `[\\]`, and `[\n\t\r]`, ranges such as `[a-z]`, negated classes such as `[^*]`, common -escapes such as `\n`, `\t`, and `\r`, and `.`. The `.` operator matches ASCII bytes except newline; negated -character classes range over ASCII bytes. Unicode properties and full Ruby/Onigmo regexp syntax are not supported. -Unsupported or malformed constructs are rejected during generation rather than silently reinterpreted. Nullable -token patterns such as `//`, `/()/`, `/a*/`, `/a?/`, and `/a|/` are generation errors because PSLR token lexemes -must be non-empty. - -When the parser and lexer share a context through `%parse-param` / `%lex-param`, the generated header also -provides helpers such as `YYPSLR_PSEUDO_SCAN(...)`, so the lexer can choose a token based on the current parser -state. The paper-compatible scanning path needs the lexer to pass the unconsumed input prefix, not only an -already-decided token fragment, so legacy external lexer bridges may still be limited by the text they provide. - -PSLR parsers enable a lightweight LAC check in the generated parser so syntax errors caused by LR state merging, -default reductions, or `%nonassoc` error actions are detected before user semantic actions are run for the bad -lookahead. PSLR support is still experimental. Scoped lexical declarations, lexical nonterminals, and `%lex` -are not implemented yet. If you find any bugs, please report them. +escapes such as `\n`, `\t`, and `\r`, `.`, and `{NAME}` references that inline the body of an earlier +`%token-pattern` (self and forward references are rejected; write a literal brace as `\{`). The `.` operator +matches any byte except newline; negated character classes range over all bytes (0-255), so multi-byte UTF-8 +sequences pass through negated classes and `.` unmodified. Unicode properties and full Ruby/Onigmo regexp syntax +are not supported. Unsupported or malformed constructs are rejected during generation rather than silently +reinterpreted. Nullable token patterns such as `//`, `/()/`, `/a*/`, `/a?/`, and `/a|/` are generation errors +because PSLR token lexemes must be non-empty. + +Two operating modes are supported. In pure mode (`%define api.pslr.lexer generated`), the generated parser owns +lexical analysis: `yylex` is generated, layout tokens are skipped with their text accumulated, `%token-action` +bodies build semantic values from `yytext`/`yyleng`, and the caller hands the input to the parser with +`yypslr_set_input(input, len)` before `yyparse`. Pure mode requires a `%token-pattern` for every terminal. +In bridge mode (`%define api.pslr.state-member`), an existing hand-written lexer consults the pseudo-scanner +through helper macros such as `YYPSLR_PSEUDO_SCAN(Context, Input, InputLen, MatchLength)`; terminals without a +token pattern stay owned by the user lexer and are reported as a warning. The scan API is length-delimited +(`input` plus `input_len`) so inputs containing NUL bytes are handled correctly, and the scan result reports +`from_fallback` when the token came from the syntax-error fallback row. The paper-compatible scanning path needs +the lexer to pass the unconsumed input prefix, not only an already-decided token fragment, so legacy external +lexer bridges may still be limited by the text they provide. + +Unresolved pseudo-scanner conflict reports include a witness: an example input that reaches the conflicting +scanner profile. `%lex-prec` rules that never participate in a normal-row resolution are reported as useless. + +PSLR parsers enable LAC (lookahead correction, `%define parse.lac full`) by default so syntax errors caused by +LR state merging, default reductions, or `%nonassoc` error actions are detected before user semantic actions are +run for the bad lookahead, and expected-token lists in error messages are computed by exploratory parses. LAC can +also be enabled independently for LALR/IELR parsers. PSLR support is still experimental. Scoped lexical +declarations, lexical nonterminals, and `%lex` are not implemented yet. If you find any bugs, please report them. ## Lrama 0.7.1 (2025-12-24) From 8eefb44c73765e01b589b96852c96b84581860b5 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 8 Jul 2026 22:57:18 +0900 Subject: [PATCH 15/24] ci: fix Ruby 2.5 compatibility and vendored-gem ASCII check Array#filter_map is Ruby 2.7+, so the PSLR report renderer now uses map + compact; the test suite must keep passing on Ruby 2.5 because lrama is executed by BASERUBY when building CRuby. The US-ASCII source check scanned vendor/bundle, where rbs 4.0.3 ships a C file containing a UTF-8 comment, failing the job for every pull request. Exclude vendored gems: they are not sources of this repository. --- lib/lrama/reporter/pslr.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/lrama/reporter/pslr.rb b/lib/lrama/reporter/pslr.rb index ccbf3015a..289b5307c 100644 --- a/lib/lrama/reporter/pslr.rb +++ b/lib/lrama/reporter/pslr.rb @@ -63,19 +63,19 @@ def report_scanner_accepts(io, states) io << "PSLR Scanner Accepts\n\n" states.states.each do |state| - cells = accepting_states.filter_map do |fsa_state| + cells = accepting_states.map {|fsa_state| token = scanner_accepts[state.id, fsa_state.id] "ss#{fsa_state.id}=>#{token.name}" if token - end + }.compact next if cells.empty? io << " State #{state.id}: #{cells.join(' ')}\n" end - fallback_cells = accepting_states.filter_map do |fsa_state| + fallback_cells = accepting_states.map {|fsa_state| token = scanner_accepts.fallback_table[fsa_state.id] "ss#{fsa_state.id}=>#{token.name}" if token - end + }.compact io << " Fallback: #{fallback_cells.join(' ')}\n" unless fallback_cells.empty? io << "\n" end From 0b688d5e228a6fc94721bc6952b20bc01267eb4c Mon Sep 17 00:00:00 2001 From: ydah Date: Fri, 4 Sep 2026 17:04:47 +0900 Subject: [PATCH 16/24] pslr: resolve scanner profiles consistently --- lib/lrama/pslr/pairwise_resolution.rb | 75 -------- lib/lrama/state/scanner_accepts.rb | 60 ++++--- lib/lrama/states.rb | 12 +- .../lrama/pslr/pairwise_resolution.rbs | 42 ----- sig/generated/lrama/state/scanner_accepts.rbs | 13 +- sig/generated/lrama/states.rbs | 3 +- spec/lrama/pslr/pairwise_resolution_spec.rb | 49 ------ spec/lrama/state/scanner_accepts_spec.rb | 166 +++++++++++++++--- spec/lrama/states_spec.rb | 14 ++ 9 files changed, 212 insertions(+), 222 deletions(-) delete mode 100644 lib/lrama/pslr/pairwise_resolution.rb delete mode 100644 sig/generated/lrama/pslr/pairwise_resolution.rbs delete mode 100644 spec/lrama/pslr/pairwise_resolution_spec.rb diff --git a/lib/lrama/pslr/pairwise_resolution.rb b/lib/lrama/pslr/pairwise_resolution.rb deleted file mode 100644 index c7102ff96..000000000 --- a/lib/lrama/pslr/pairwise_resolution.rb +++ /dev/null @@ -1,75 +0,0 @@ -# rbs_inline: enabled -# frozen_string_literal: true - -require "set" - -module Lrama - module Pslr - # Pair-based PSLR state compatibility (paper section 3.4.3). - # - # The scanner FSA is scanned once to find every token pair that can be - # in an identity or length scanner conflict. Two acceptable-token sets - # are then compatible when no conflict pair distinguishes them: - # - # * both sets contain the same subset of the pair (the pseudo-scanner - # resolves the conflict identically, or leaves it identically - # unresolved -- unresolved/unresolved states merge), or - # * one set contains neither token of the pair (its match set for - # inputs manifesting the conflict is empty for this pair). - # - # Reducing the check to pairs is the precomputation the paper - # recommends for phase 3: the per-pair verdict no longer depends on - # the rest of the accept set, so state splitting does not have to - # re-run the profile resolver for every candidate merge. Layout - # tokens are members of every accept set, so pairs won by layout can - # never distinguish two states (the split-stable layout optimization - # of section 3.6 falls out of the presence test). - class PairwiseResolution - attr_reader :conflict_pairs #: Set[[String, String]] - - # @rbs (ScannerFSA scanner_fsa) -> void - def initialize(scanner_fsa) - @conflict_pairs = scanner_fsa.pairwise_conflict_pairs - pairs_by_token = Hash.new {|h, k| h[k] = [] } #: Hash[String, Array[[String, String]]] - @pairs_by_token = @conflict_pairs.each_with_object(pairs_by_token) do |pair, hash| - hash[pair[0]] << pair - hash[pair[1]] << pair - end - end - - # @rbs (Set[String] left_acc, Set[String] right_acc) -> bool - def compatible_accept_sets?(left_acc, right_acc) - return true if left_acc == right_acc - - # Only conflict pairs touching the symmetric difference can - # distinguish the two accept sets. - diff = (left_acc - right_acc) | (right_acc - left_acc) - return true if diff.empty? - - checked = Set.new #: Set[[String, String]] - diff.all? do |token| - @pairs_by_token[token].all? do |pair| - next true unless checked.add?(pair) - - pair_compatible?(pair, left_acc, right_acc) - end - end - end - - private - - # @rbs ([String, String] pair, Set[String] left_acc, Set[String] right_acc) -> bool - def pair_compatible?(pair, left_acc, right_acc) - left_presence = presence(pair, left_acc) - right_presence = presence(pair, right_acc) - - left_presence == right_presence || left_presence == 0 || right_presence == 0 - end - - # @rbs ([String, String] pair, Set[String] acc) -> Integer - def presence(pair, acc) - (acc.include?(pair[0]) ? 1 : 0) | (acc.include?(pair[1]) ? 2 : 0) - end - end - end -end diff --git a/lib/lrama/state/scanner_accepts.rb b/lib/lrama/state/scanner_accepts.rb index 97a75646b..860000b5c 100644 --- a/lib/lrama/state/scanner_accepts.rb +++ b/lib/lrama/state/scanner_accepts.rb @@ -22,8 +22,6 @@ class State # and otherwise-unresolved identity conflicts are resolved by token # declaration order. # - # When %lex-scope declarations are present, each parser state may use - # a merged set of global + scope-active lexical precedence rules. class ScannerAccepts class Conflict attr_reader :parser_state_id #: Integer? @@ -53,11 +51,12 @@ class ProfileOutcome attr_reader :token_name #: String? attr_reader :conflict #: Conflict? - # @rbs (kind: Symbol, ?token_name: String?, ?conflict: Conflict?) -> void - def initialize(kind:, token_name: nil, conflict: nil) + # @rbs (kind: Symbol, ?token_name: String?, ?conflict: Conflict?, ?current_match: bool) -> void + def initialize(kind:, token_name: nil, conflict: nil, current_match: false) @kind = kind @token_name = token_name @conflict = conflict + @current_match = current_match end # @rbs () -> bool @@ -74,6 +73,11 @@ def resolved? def unresolved? @kind == UNRESOLVED end + + # @rbs () -> bool + def current_match? + @current_match + end end class ProfileResolver @@ -118,7 +122,7 @@ def resolve_normal(shorter_tokens, selected_shorter_token, current_tokens) if winners.size == 1 winner = winners.first #: String mark_longer_win_rules_used(winner, shorter_tokens, current_tokens) - return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: winner) + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: winner, current_match: true) end ProfileOutcome.new(kind: ProfileOutcome::UNRESOLVED) @@ -141,12 +145,16 @@ def resolve_fallback(shorter_tokens, selected_shorter_token, current_tokens) shorter_tokens.all? {|shorter| @length_prec.fallback_precedes?(shorter, candidate) } end - return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: explicit_winners.first) if explicit_winners.size == 1 + if explicit_winners.size == 1 + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: explicit_winners.first, current_match: true) + end declaration_order_winner = current_tokens.sort_by {|token| token_order_key(token) }.find do |candidate| shorter_tokens.all? {|shorter| @length_prec.fallback_precedes?(shorter, candidate) } end - return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: declaration_order_winner) if declaration_order_winner + if declaration_order_winner + return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: declaration_order_winner, current_match: true) + end return ProfileOutcome.new(kind: ProfileOutcome::RESOLVED, token_name: selected_shorter_token) if selected_shorter_token @@ -237,6 +245,7 @@ def initialize(scanner_fsa, lex_prec, length_prec, acceptable_tokens, parser_sta @parser_state_id = parser_state_id @table = {} @conflicts = [] + @reported_conflict_profiles = Set.new token_patterns_by_name = {} #: Hash[String, Grammar::TokenPattern] @token_patterns_by_name = scanner_fsa.token_patterns.each_with_object(token_patterns_by_name) do |token_pattern, hash| hash[token_pattern.name] ||= token_pattern @@ -274,31 +283,17 @@ def visit_state(fsa_state_id, shorter_tokens, selected_shorter_token, visited, p result = @resolver.resolve(shorter_tokens, selected_shorter_token, current_tokens) if result.resolved? - if result.token_name && current_tokens.include?(result.token_name) + if result.current_match? && result.token_name token_pattern = token_pattern_for(result.token_name) existing = @table[fsa_state_id] if existing && existing.name != token_pattern.name - @conflicts << Conflict.new( - parser_state_id: @parser_state_id, - scanner_state_id: fsa_state_id, - shorter_tokens: shorter_tokens.to_a.sort, - selected_shorter_token: existing.name, - current_tokens: current_tokens.to_a.sort, - witness: path - ) + report_conflict(fsa_state_id, shorter_tokens, selected_shorter_token, current_tokens, path) else @table[fsa_state_id] = token_pattern end end elsif result.unresolved? - @conflicts << Conflict.new( - parser_state_id: @parser_state_id, - scanner_state_id: fsa_state_id, - shorter_tokens: shorter_tokens.to_a.sort, - selected_shorter_token: selected_shorter_token, - current_tokens: current_tokens.to_a.sort, - witness: path - ) + report_conflict(fsa_state_id, shorter_tokens, selected_shorter_token, current_tokens, path) end next_shorter_tokens = shorter_tokens | current_tokens @@ -318,6 +313,23 @@ def token_pattern_for(token_name) @token_patterns_by_name.fetch(token_name) end + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens, String path) -> void + def report_conflict(fsa_state_id, shorter_tokens, selected_shorter_token, current_tokens, path) + sorted_shorter_tokens = shorter_tokens.to_a.sort + sorted_current_tokens = current_tokens.to_a.sort + profile = [sorted_shorter_tokens, selected_shorter_token, sorted_current_tokens] + return unless @reported_conflict_profiles.add?(profile) + + @conflicts << Conflict.new( + parser_state_id: @parser_state_id, + scanner_state_id: fsa_state_id, + shorter_tokens: sorted_shorter_tokens, + selected_shorter_token: selected_shorter_token, + current_tokens: sorted_current_tokens, + witness: path + ) + end + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> [Integer, Array[String], String?, Array[String]] def profile_key(fsa_state_id, shorter_tokens, selected_shorter_token, current_tokens) [fsa_state_id, shorter_tokens.to_a.sort, selected_shorter_token, current_tokens.to_a.sort] diff --git a/lib/lrama/states.rb b/lib/lrama/states.rb index 9aa675a33..02c31a9d3 100644 --- a/lib/lrama/states.rb +++ b/lib/lrama/states.rb @@ -4,7 +4,6 @@ require "forwardable" require "set" require_relative "lexer_context_classifier" -require_relative "pslr/pairwise_resolution" require_relative "tracer/duration" require_relative "state/item" @@ -1072,14 +1071,17 @@ def pslr_state_signature(state, filtered_lookaheads = nil) signature end - # Pair-based PSLR compatibility (Def 3.4.3, reduced to token pairs as - # recommended by section 3.4.3 for splitting performance). + # PSLR compatibility based on complete pseudo-scanner conflict profiles. # @rbs (Set[String] left_acc, Set[String] right_acc) -> bool def pslr_compatible_accept_sets?(left_acc, right_acc) return true unless @scanner_fsa - @pslr_pairwise_resolution ||= Pslr::PairwiseResolution.new(@scanner_fsa) - @pslr_pairwise_resolution.compatible_accept_sets?(left_acc, right_acc) + @pslr_compatibility_checker ||= State::ScannerAccepts::CompatibilityChecker.new( + @scanner_fsa, + lex_prec, + @length_precedences + ) + @pslr_compatibility_checker.compatible?(left_acc, right_acc) end # @rbs (State state, ?State::lookahead_set filtered_lookaheads, ?expand_ties: bool, ?include_layout: bool) -> Set[String] diff --git a/sig/generated/lrama/pslr/pairwise_resolution.rbs b/sig/generated/lrama/pslr/pairwise_resolution.rbs deleted file mode 100644 index ccdaba302..000000000 --- a/sig/generated/lrama/pslr/pairwise_resolution.rbs +++ /dev/null @@ -1,42 +0,0 @@ -# Generated from lib/lrama/pslr/pairwise_resolution.rb with RBS::Inline - -module Lrama - module Pslr - # Pair-based PSLR state compatibility (paper section 3.4.3). - # - # The scanner FSA is scanned once to find every token pair that can be - # in an identity or length scanner conflict. Two acceptable-token sets - # are then compatible when no conflict pair distinguishes them: - # - # * both sets contain the same subset of the pair (the pseudo-scanner - # resolves the conflict identically, or leaves it identically - # unresolved -- unresolved/unresolved states merge), or - # * one set contains neither token of the pair (its match set for - # inputs manifesting the conflict is empty for this pair). - # - # Reducing the check to pairs is the precomputation the paper - # recommends for phase 3: the per-pair verdict no longer depends on - # the rest of the accept set, so state splitting does not have to - # re-run the profile resolver for every candidate merge. Layout - # tokens are members of every accept set, so pairs won by layout can - # never distinguish two states (the split-stable layout optimization - # of section 3.6 falls out of the presence test). - class PairwiseResolution - attr_reader conflict_pairs: Set[[ String, String ]] - - # @rbs (ScannerFSA scanner_fsa) -> void - def initialize: (ScannerFSA scanner_fsa) -> void - - # @rbs (Set[String] left_acc, Set[String] right_acc) -> bool - def compatible_accept_sets?: (Set[String] left_acc, Set[String] right_acc) -> bool - - private - - # @rbs ([String, String] pair, Set[String] left_acc, Set[String] right_acc) -> bool - def pair_compatible?: ([ String, String ] pair, Set[String] left_acc, Set[String] right_acc) -> bool - - # @rbs ([String, String] pair, Set[String] acc) -> Integer - def presence: ([ String, String ] pair, Set[String] acc) -> Integer - end - end -end diff --git a/sig/generated/lrama/state/scanner_accepts.rbs b/sig/generated/lrama/state/scanner_accepts.rbs index efd756efa..443c4ed90 100644 --- a/sig/generated/lrama/state/scanner_accepts.rbs +++ b/sig/generated/lrama/state/scanner_accepts.rbs @@ -18,9 +18,6 @@ module Lrama # length defaults are handled by LengthPrecedences#fallback_precedes?, # and otherwise-unresolved identity conflicts are resolved by token # declaration order. - # - # When %lex-scope declarations are present, each parser state may use - # a merged set of global + scope-active lexical precedence rules. class ScannerAccepts class Conflict attr_reader parser_state_id: Integer? @@ -52,8 +49,8 @@ module Lrama attr_reader conflict: Conflict? - # @rbs (kind: Symbol, ?token_name: String?, ?conflict: Conflict?) -> void - def initialize: (kind: Symbol, ?token_name: String?, ?conflict: Conflict?) -> void + # @rbs (kind: Symbol, ?token_name: String?, ?conflict: Conflict?, ?current_match: bool) -> void + def initialize: (kind: Symbol, ?token_name: String?, ?conflict: Conflict?, ?current_match: bool) -> void # @rbs () -> bool def empty?: () -> bool @@ -63,6 +60,9 @@ module Lrama # @rbs () -> bool def unresolved?: () -> bool + + # @rbs () -> bool + def current_match?: () -> bool end class ProfileResolver @@ -134,6 +134,9 @@ module Lrama # @rbs (String token_name) -> Grammar::TokenPattern def token_pattern_for: (String token_name) -> Grammar::TokenPattern + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens, String path) -> void + def report_conflict: (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens, String path) -> void + # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> [Integer, Array[String], String?, Array[String]] def profile_key: (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[String] current_tokens) -> [ Integer, Array[String], String?, Array[String] ] end diff --git a/sig/generated/lrama/states.rbs b/sig/generated/lrama/states.rbs index 81836ac74..a2a6bb01c 100644 --- a/sig/generated/lrama/states.rbs +++ b/sig/generated/lrama/states.rbs @@ -264,8 +264,7 @@ module Lrama # @rbs (State state, ?State::lookahead_set filtered_lookaheads) -> Array[[Integer, String?]] def pslr_state_signature: (State state, ?State::lookahead_set filtered_lookaheads) -> Array[[ Integer, String? ]] - # Pair-based PSLR compatibility (Def 3.4.3, reduced to token pairs as - # recommended by section 3.4.3 for splitting performance). + # PSLR compatibility based on complete pseudo-scanner conflict profiles. # @rbs (Set[String] left_acc, Set[String] right_acc) -> bool def pslr_compatible_accept_sets?: (Set[String] left_acc, Set[String] right_acc) -> bool diff --git a/spec/lrama/pslr/pairwise_resolution_spec.rb b/spec/lrama/pslr/pairwise_resolution_spec.rb deleted file mode 100644 index 7ce6f3c8a..000000000 --- a/spec/lrama/pslr/pairwise_resolution_spec.rb +++ /dev/null @@ -1,49 +0,0 @@ -# frozen_string_literal: true - -RSpec.describe Lrama::Pslr::PairwiseResolution do - def token_pattern(name, regex, order) - Lrama::Grammar::TokenPattern.new( - id: Lrama::Lexer::Token::Ident.new(s_value: name), - pattern: Lrama::Lexer::Token::Regex.new(s_value: "/#{regex}/"), - lineno: 1, - definition_order: order - ) - end - - let(:rangle) { token_pattern("RANGLE", ">", 0) } - let(:rshift) { token_pattern("RSHIFT", ">>", 1) } - let(:identifier) { token_pattern("ID", "[a-z]+", 2) } - let(:keyword) { token_pattern("IF", "if", 3) } - let(:layout) { token_pattern("YYLAYOUT_WS", "[ ]+", 4) } - let(:scanner_fsa) { Lrama::ScannerFSA.new([rangle, rshift, identifier, keyword, layout]) } - let(:pairwise) { described_class.new(scanner_fsa) } - - it "treats identical accept sets as compatible" do - acc = Set["RANGLE", "RSHIFT"] - expect(pairwise.compatible_accept_sets?(acc, acc.dup)).to be true - end - - it "splits states that pick different tokens of a conflict pair" do - expect(pairwise.compatible_accept_sets?(Set["RANGLE"], Set["RSHIFT"])).to be false - end - - it "splits a resolved state from a state seeing the full conflict" do - expect(pairwise.compatible_accept_sets?(Set["ID"], Set["ID", "IF"])).to be false - end - - it "treats states as compatible when one side has no match for the pair" do - expect(pairwise.compatible_accept_sets?(Set["RANGLE"], Set["ID"])).to be true - end - - it "ignores tokens without scanner conflicts" do - expect(pairwise.compatible_accept_sets?(Set["RANGLE", "ID"], Set["RANGLE"])).to be true - end - - it "never splits on layout tokens because they are in every accept set" do - left = Set["RANGLE", "YYLAYOUT_WS"] - right = Set["RANGLE", "RSHIFT", "YYLAYOUT_WS"] - - expect(pairwise.compatible_accept_sets?(left, right)).to be false - expect(pairwise.compatible_accept_sets?(Set["ID", "YYLAYOUT_WS"], Set["YYLAYOUT_WS", "ID"])).to be true - end -end diff --git a/spec/lrama/state/scanner_accepts_spec.rb b/spec/lrama/state/scanner_accepts_spec.rb index 43bff5942..2a3953b79 100644 --- a/spec/lrama/state/scanner_accepts_spec.rb +++ b/spec/lrama/state/scanner_accepts_spec.rb @@ -169,6 +169,55 @@ def parser_state(id, token_names) expect(outcome).to be_resolved expect(outcome.token_name).to eq("ID") + expect(outcome).to be_current_match + end + + it "writes a same-token autolength winner to scanner_accepts" do + id = token_pattern("ID", "a+", 0) + scanner_fsa = Lrama::ScannerFSA.new([id]) + lex_prec = Lrama::Grammar::LexPrec.new + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, ["ID"])], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + symbols: [] + ) + + scanner_accepts.build + + accepting = scanner_fsa.states.find {|state| state.accepting_tokens.map(&:name) == ["ID"] } + expect(scanner_accepts[0, accepting.id].name).to eq("ID") + end + + it "does not report a conflict when a shorter-match winner revisits a current accepting state" do + x = token_pattern("X", "x", 0) + y = token_pattern("Y", "y", 1) + states = 4.times.map {|id| Lrama::ScannerFSA::State.new(id) } + states[0].add_transition("a", 1) + states[0].add_transition("b", 2) + states[1].add_accepting_token(x) + states[1].add_transition("c", 3) + states[2].add_accepting_token(y) + states[2].add_transition("c", 3) + states[3].add_accepting_token(x) + states[3].add_accepting_token(y) + scanner_fsa = instance_double(Lrama::ScannerFSA, states: states, token_patterns: [x, y]) + lex_prec = Lrama::Grammar::LexPrec.new + lex_prec.add_rule(left_token: ident("X"), operator: Lrama::Grammar::LexPrec::SHORTEST, right_token: ident("X"), lineno: 1) + lex_prec.add_rule(left_token: ident("X"), operator: Lrama::Grammar::LexPrec::SHORTEST, right_token: ident("Y"), lineno: 2) + lex_prec.add_rule(left_token: ident("X"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("Y"), lineno: 3) + computer = Lrama::State::ScannerAccepts::CompleteProfileComputer.new( + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + Set["X", "Y"] + ) + + computer.compute + + expect(computer.table.fetch(3).name).to eq("Y") + expect(computer.conflicts).to be_empty end it "uses declaration order only in fallback mode" do @@ -255,19 +304,79 @@ def parser_state(id, token_names) expect(scanner_accepts.fallback_table.fetch(accepting.id).name).to eq("A") end - it "keeps normal parser-state rows strict for explicit identity cycles" do + [ + { + figure: "3.3", + patterns: { "A" => "a", "B" => "a", "C" => "a" }, + rules: [ + ["A", Lrama::Grammar::LexPrec::IDENTITY_RIGHT, "B"], + ["B", Lrama::Grammar::LexPrec::IDENTITY_RIGHT, "C"], + ["C", Lrama::Grammar::LexPrec::IDENTITY_RIGHT, "A"] + ], + profile: [[], nil, ["A", "B", "C"]], + witness: "a" + }, + { + figure: "3.4", + patterns: { "A" => "a", "B" => "ab", "C" => "abc" }, + rules: [ + ["A", Lrama::Grammar::LexPrec::LONGEST, "B"], + ["B", Lrama::Grammar::LexPrec::LONGEST, "C"], + ["C", Lrama::Grammar::LexPrec::TOKEN_RIGHT_LENGTH, "A"] + ], + profile: [["A", "B"], "B", ["C"]], + witness: "abc" + }, + { + figure: "3.5", + patterns: { "A" => "a|abc", "B" => "ab" }, + rules: [["A", Lrama::Grammar::LexPrec::SHORTEST, "B"]], + profile: [["A", "B"], "A", ["A"]], + witness: "abc" + } + ].each do |test_case| + it "keeps dissertation Figure #{test_case[:figure]} unresolved" do + tokens = test_case[:patterns].each_with_index.map do |(name, regex), order| + token_pattern(name, regex, order) + end + scanner_fsa = Lrama::ScannerFSA.new(tokens) + lex_prec = Lrama::Grammar::LexPrec.new + test_case[:rules].each_with_index do |(left, operator, right), index| + lex_prec.add_rule(left_token: ident(left), operator: operator, right_token: ident(right), lineno: index + 1) + end + scanner_accepts = Lrama::State::ScannerAccepts.new( + [parser_state(0, test_case[:patterns].keys)], + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec), + symbols: [] + ) + + scanner_accepts.build + + expect(scanner_accepts.unresolved_conflicts?).to be true + expect(scanner_accepts.conflicts).to include( + an_object_having_attributes( + shorter_tokens: test_case[:profile][0], + selected_shorter_token: test_case[:profile][1], + current_tokens: test_case[:profile][2], + witness: test_case[:witness] + ) + ) + end + end + end + + describe "conflict witnesses" do + it "attaches an example input to unresolved conflicts" do tokens = [ - token_pattern("A", "a", 0), - token_pattern("B", "a", 1), - token_pattern("C", "a", 2) + token_pattern("A", "ab", 0), + token_pattern("B", "ab", 1) ] scanner_fsa = Lrama::ScannerFSA.new(tokens) lex_prec = Lrama::Grammar::LexPrec.new - lex_prec.add_rule(left_token: ident("A"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("B"), lineno: 1) - lex_prec.add_rule(left_token: ident("B"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("C"), lineno: 2) - lex_prec.add_rule(left_token: ident("C"), operator: Lrama::Grammar::LexPrec::IDENTITY_RIGHT, right_token: ident("A"), lineno: 3) scanner_accepts = Lrama::State::ScannerAccepts.new( - [parser_state(0, ["A", "B", "C"])], + [parser_state(0, ["A", "B"])], scanner_fsa, lex_prec, Lrama::LengthPrecedences.new(lex_prec), @@ -276,17 +385,14 @@ def parser_state(id, token_names) scanner_accepts.build - accepting = scanner_fsa.states.find {|state| state.accepting_tokens.map(&:name).sort == ["A", "B", "C"] } - expect(scanner_accepts[0, accepting.id]).to be_nil - expect(scanner_accepts.unresolved_conflicts?).to be true + witnesses = scanner_accepts.conflicts.map(&:witness) + expect(witnesses).to include("ab") end - end - describe "conflict witnesses" do - it "attaches an example input to unresolved conflicts" do + it "reports duplicate scanner states with the same profile once using the first witness" do tokens = [ - token_pattern("A", "ab", 0), - token_pattern("B", "ab", 1) + token_pattern("A", "a|b", 0), + token_pattern("B", "a|b", 1) ] scanner_fsa = Lrama::ScannerFSA.new(tokens) lex_prec = Lrama::Grammar::LexPrec.new @@ -294,13 +400,14 @@ def parser_state(id, token_names) [parser_state(0, ["A", "B"])], scanner_fsa, lex_prec, - Lrama::LengthPrecedences.new(lex_prec) + Lrama::LengthPrecedences.new(lex_prec), + symbols: [] ) scanner_accepts.build - witnesses = scanner_accepts.conflicts.map(&:witness) - expect(witnesses).to include("ab") + expect(scanner_accepts.conflicts.size).to eq(1) + expect(scanner_accepts.conflicts.first.witness).to eq("a") end end @@ -320,7 +427,8 @@ def parser_state(id, token_names) [parser_state(0, ["A", "B", "X", "Y"])], scanner_fsa, lex_prec, - Lrama::LengthPrecedences.new(lex_prec) + Lrama::LengthPrecedences.new(lex_prec), + symbols: [] ) scanner_accepts.build @@ -369,6 +477,24 @@ def parser_state(id, token_names) expect(checker.compatible?(Set["A", "B"], Set["A", "B"])).to be true end + + it "uses lexical precedence when comparing accept sets" do + expect(checker.compatible?(Set["RANGLE"], Set["RANGLE", "RSHIFT"])).to be false + + lex_prec.add_rule( + left_token: ident("RSHIFT"), + operator: Lrama::Grammar::LexPrec::TOKEN_RIGHT, + right_token: ident("RANGLE"), + lineno: 1 + ) + precedence_checker = described_class.new( + scanner_fsa, + lex_prec, + Lrama::LengthPrecedences.new(lex_prec) + ) + + expect(precedence_checker.compatible?(Set["RANGLE"], Set["RANGLE", "RSHIFT"])).to be true + end end describe "lexical ties" do diff --git a/spec/lrama/states_spec.rb b/spec/lrama/states_spec.rb index 7d2df3237..a2d0dd3e3 100644 --- a/spec/lrama/states_spec.rb +++ b/spec/lrama/states_spec.rb @@ -3964,6 +3964,20 @@ class : keyword_class tSTRING keyword_end %prec tPLUS expect(states.send(:compatible_split_state?, mock_state, filtered_lookaheads)).to be false end + it "uses lexical precedence when comparing PSLR accept sets" do + grammar.lex_prec.add_rule( + left_token: grammar.find_symbol_by_s_value!("RSHIFT").id, + operator: Lrama::Grammar::LexPrec::TOKEN_RIGHT, + right_token: grammar.find_symbol_by_s_value!("RANGLE").id, + lineno: 1 + ) + states.instance_variable_set(:@length_precedences, Lrama::LengthPrecedences.new(grammar.lex_prec)) + + expect( + states.send(:pslr_compatible_accept_sets?, Set["RANGLE"], Set["RANGLE", "RSHIFT"]) + ).to be true + end + it "detects unresolved PSLR inadequacies per transition" do propagated = { kernel_item => grammar.find_symbol_by_s_value!("RANGLE").number_bitmap } matching_state = instance_double(Lrama::State, id: 8) From 818b647aa221ffc28288bef3ee515b56903148cf Mon Sep 17 00:00:00 2001 From: ydah Date: Fri, 4 Sep 2026 17:04:56 +0900 Subject: [PATCH 17/24] pslr: harden generated parser runtime --- lib/lrama/output.rb | 36 ++++++++++++++--------- spec/lrama/integration_spec.rb | 26 +++++++++++++---- spec/lrama/output_spec.rb | 52 ++++++++++++++++++++++++++++++++-- template/bison/yacc.c | 46 +++++++++++++++++++++--------- 4 files changed, 124 insertions(+), 36 deletions(-) diff --git a/lib/lrama/output.rb b/lib/lrama/output.rb index fb6dc3864..372e3d74a 100644 --- a/lib/lrama/output.rb +++ b/lib/lrama/output.rb @@ -414,9 +414,7 @@ def pslr_scanner_enabled? def pslr_function_declarations return "" unless pslr_enabled? - declarations = [<<~C_CODE] - int yy_state_accepts_token (int yystate, int yychar); - C_CODE + declarations = [] if pslr_scanner_enabled? declarations << <<~C_CODE @@ -754,12 +752,12 @@ def pslr_lac_function yy_state_t *yylac_top; if (!yylac_base) - return 1; + return YYENOMEM; if (YYMAXDEPTH < yylac_len) { YYFREE (yylac_base); - return 1; + return YYENOMEM; } YYCOPY (yylac_base, yyss, yylac_len); @@ -820,7 +818,7 @@ def pslr_lac_function if (yylac_base + YYMAXDEPTH - 1 <= yylac_top) { YYFREE (yylac_base); - return 1; + return YYENOMEM; } *++yylac_top = YY_CAST (yy_state_t, yystate); @@ -1033,15 +1031,18 @@ def pslr_layout_declarations yypslr_layout_length = 0; } - static void + static int yypslr_layout_append (const char *text, int length) { - if (yypslr_layout_length + length < YYPSLR_LAYOUT_BUFFER_SIZE) - { - memcpy (yypslr_layout_buffer + yypslr_layout_length, text, length); - yypslr_layout_length += length; - yypslr_layout_buffer[yypslr_layout_length] = '\\0'; - } + if (length < 0 + || (size_t) length >= (size_t) YYPSLR_LAYOUT_BUFFER_SIZE + - (size_t) yypslr_layout_length) + return 0; + + memcpy (yypslr_layout_buffer + yypslr_layout_length, text, (size_t) length); + yypslr_layout_length += length; + yypslr_layout_buffer[yypslr_layout_length] = '\\0'; + return 1; } # define YYPSLR_LAYOUT_TEXT yypslr_layout_buffer @@ -1131,7 +1132,14 @@ def pslr_layout_scan_function if (result->is_layout) { - YYPSLR_LAYOUT_APPEND (*input, result->length); + if (!YYPSLR_LAYOUT_APPEND (*input, result->length)) + { + result->token = YYUNDEF; + result->is_layout = 0; + result->is_character_token = 0; + result->from_fallback = 0; + return result->token; + } #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, result->length, yylvalp);" : ""} *input += result->length; *input_len -= (size_t)result->length; diff --git a/spec/lrama/integration_spec.rb b/spec/lrama/integration_spec.rb index e498f86e0..1d1144523 100644 --- a/spec/lrama/integration_spec.rb +++ b/spec/lrama/integration_spec.rb @@ -414,17 +414,20 @@ def generate_object(grammar_file_path, c_path, obj_path, command_args: []) end describe "PSLR pure mode (api.pslr.lexer generated)" do - def compile_pure_parser + def compile_pure_parser(layout_buffer_size: nil) tmpdir = Dir.tmpdir grammar_file_path = fixture_path("integration/pslr_pure.y") - c_path = tmpdir + "/pslr_pure#{file_extension}" + suffix = layout_buffer_size ? "_layout_#{layout_buffer_size}" : "" + c_path = tmpdir + "/pslr_pure#{suffix}#{file_extension}" h_path = tmpdir + "/pslr_pure.h" - obj_path = tmpdir + "/pslr_pure" + obj_path = tmpdir + "/pslr_pure#{suffix}" + cache_key = "pslr_pure#{suffix}" - unless IntegrationHelper.compiled_parsers["pslr_pure"] && File.exist?(obj_path) + unless IntegrationHelper.compiled_parsers[cache_key] && File.exist?(obj_path) Lrama::Command.new(%W[-H#{h_path} -o#{c_path} #{grammar_file_path}]).run - exec_command("#{compiler} -Wall -O0 -g -I#{tmpdir} #{c_path} -o #{obj_path}") - IntegrationHelper.compiled_parsers["pslr_pure"] = true + buffer_define = layout_buffer_size ? "-DYYPSLR_LAYOUT_BUFFER_SIZE=#{layout_buffer_size}" : "" + exec_command("#{compiler} -Wall -O0 -g -I#{tmpdir} #{buffer_define} #{c_path} -o #{obj_path}") + IntegrationHelper.compiled_parsers[cache_key] = true end obj_path @@ -445,6 +448,17 @@ def compile_pure_parser expect(status.success?).to be false end + it "fails instead of discarding layout that exceeds the layout buffer" do + obj_path = compile_pure_parser(layout_buffer_size: 4) + + out, _err, status = Open3.capture3(obj_path, " 1") + expect(status.success?).to be true + expect(out).to eq("=> 1\n") + + _out, _err, status = Open3.capture3(obj_path, " 1") + expect(status.success?).to be false + end + it "computes canonical LR(1) tables when pslr.tables is canonical-lr" do base_source = <<~GRAMMAR %token-pattern LT /= (size_t) YYPSLR_LAYOUT_BUFFER_SIZE") + expect(result).not_to include("yypslr_layout_length + length") + end + end + + describe "#pslr_layout_scan_function" do + it "returns an undefined token while preserving the matched length when layout does not fit" do + result = pslr_output.pslr_layout_scan_function + + expect(result).to include("if (!YYPSLR_LAYOUT_APPEND") + expect(result).to include("result->token = YYUNDEF;") + expect(result).not_to include("result->length = 0;") + expect(result).to include("result->is_layout = 0;") end end @@ -559,7 +589,9 @@ describe "#pslr_function_declarations" do it "declares the PSLR helper entry points" do result = pslr_output.pslr_function_declarations - expect(result).to include("int yy_state_accepts_token") + expect(result).not_to include("yy_state_accepts_token") + expect(result).not_to include("yy_state_eventually_accepts_token") + expect(result).not_to include("yy_state_deep_accepts_token") expect(result).to include("int yy_pseudo_scan") expect(result).to include("YYPSLR_PSEUDO_SCAN_STATE") expect(result).to include("YYPSLR_PSEUDO_SCAN") @@ -676,7 +708,23 @@ expect(rendered).to include("yy_scanner_fallback_accepts") expect(rendered).to include("yy_token_pattern_is_layout") expect(rendered).to include("yy_lac_check_") - expect(rendered_header).to include("int yy_state_accepts_token") + expect(rendered.index("enum { YYENOMEM = -2 };")).to be < rendered.index("yy_lac_check_") + expect(rendered.scan("if (yylac_status == YYENOMEM)").size).to eq(3) + expect(rendered).to include("static int\nyy_state_accepts_token") + expect(rendered).to include("static int\nyy_state_eventually_accepts_token") + expect(rendered).to include("static int\nyy_state_deep_accepts_token") + expect(rendered.scan("YY_ATTRIBUTE_UNUSED\nstatic int\nyy_state_").size).to eq(3) + expect(rendered).to include("const yy_state_t *stack_base") + expect(rendered).to include("const yy_state_t *stack_top") + expect(rendered).to include("const yy_state_t *target") + expect(rendered).to match( + /if \(total_depth > stack_top - stack_base\).*target = stack_top - total_depth;/m + ) + expect(rendered).not_to include("yy_state_t_compat") + expect(rendered).not_to include("const void *stack_") + expect(rendered_header).not_to include("yy_state_accepts_token") + expect(rendered_header).not_to include("yy_state_eventually_accepts_token") + expect(rendered_header).not_to include("yy_state_deep_accepts_token") expect(rendered_header).to include("int yy_pseudo_scan") expect(rendered_header).to include("yypslr_scan_result") expect(rendered_header).to include("YYSETSTATE_CONTEXT(CurrentState)") diff --git a/template/bison/yacc.c b/template/bison/yacc.c index 153d07e02..33d870f88 100644 --- a/template/bison/yacc.c +++ b/template/bison/yacc.c @@ -607,7 +607,9 @@ static const <%= output.int_type_for(output.context.yyr2) %> yyr2[] = #endif <%- end -%> -int +<%- if output.pslr_enabled? -%> +YY_ATTRIBUTE_UNUSED +static int yy_state_accepts_token (int yystate, int yychar) { yysymbol_kind_t yytoken = YYTRANSLATE (yychar); @@ -636,7 +638,8 @@ yy_state_accepts_token (int yystate, int yychar) * Returns 1 if the token would be accepted in the current state or in a * state reachable via a chain of empty default reductions; 0 otherwise. */ -int +YY_ATTRIBUTE_UNUSED +static int yy_state_eventually_accepts_token (int yystate, int yychar) { yysymbol_kind_t yytoken = YYTRANSLATE (yychar); @@ -700,14 +703,13 @@ yy_state_eventually_accepts_token (int yystate, int yychar) * stack_base and stack_top point to the parser's state stack (yy_state_t). * Returns 1 if the token is reachable; 0 otherwise. */ -int +YY_ATTRIBUTE_UNUSED +static int yy_state_deep_accepts_token (int yystate, int yychar, - const void *stack_base_v, const void *stack_top_v) + const yy_state_t *stack_base, + const yy_state_t *stack_top) { - typedef short yy_state_t_compat; yysymbol_kind_t yytoken = YYTRANSLATE (yychar); - const yy_state_t_compat *stack_base = (const yy_state_t_compat *)stack_base_v; - const yy_state_t_compat *stack_top = (const yy_state_t_compat *)stack_top_v; int visited[64]; int visited_count = 0; int stack_consumed = 0; /* how many stack items we've "popped" */ @@ -767,11 +769,12 @@ yy_state_deep_accepts_token (int yystate, int yychar, { /* Non-empty reduction: need to look at the stack. */ int total_depth = stack_consumed + rhs_len; - const yy_state_t_compat *target = stack_top - total_depth; + const yy_state_t *target; - if (target < stack_base) + if (total_depth > stack_top - stack_base) return 0; /* Stack too shallow. */ + target = stack_top - total_depth; uncovered_state = (int)*target; lhs = yyr1[rule] - YYNTOKENS; goto_state = yypgoto[lhs] + uncovered_state; @@ -789,6 +792,7 @@ yy_state_deep_accepts_token (int yystate, int yychar, } } } +<%- end -%> enum { YYENOMEM = -2 }; @@ -1092,10 +1096,14 @@ yypcontext_expected_tokens (const yypcontext_t *yyctx, int yycount = 0; <%- if output.lac_enabled? -%> int yyx; + int yylac_status; for (yyx = 0; yyx < YYNTOKENS; ++yyx) if (yyx != YYSYMBOL_YYerror - && yy_lac_check_ (yyctx->yyss, yyctx->yyssp, YY_CAST (yysymbol_kind_t, yyx))) + && (yylac_status = yy_lac_check_ (yyctx->yyss, yyctx->yyssp, + YY_CAST (yysymbol_kind_t, yyx)))) { + if (yylac_status == YYENOMEM) + return YYENOMEM; if (!yyarg) ++yycount; else if (yycount == yyargn) @@ -1929,8 +1937,13 @@ YYLTYPE yylloc = yyloc_default; YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc<%= output.user_args %>); } - if (!yy_lac_check_ (yyss, yyssp, yytoken)) - goto yyerrlab; + { + int yylac_status = yy_lac_check_ (yyss, yyssp, yytoken); + if (yylac_status == YYENOMEM) + YYNOMEM; + if (!yylac_status) + goto yyerrlab; + } goto yydefault; } @@ -2004,8 +2017,13 @@ YYLTYPE yylloc = yyloc_default; } <%- if output.lac_enabled? -%> - if (!yy_lac_check_ (yyss, yyssp, yytoken)) - goto yyerrlab; + { + int yylac_status = yy_lac_check_ (yyss, yyssp, yytoken); + if (yylac_status == YYENOMEM) + YYNOMEM; + if (!yylac_status) + goto yyerrlab; + } <%- end -%> /* If the proper action on seeing token YYTOKEN is to reduce or to From 55d3aaa121fdc37bb72a06cb270dc6e8325ef3d0 Mon Sep 17 00:00:00 2001 From: ydah Date: Fri, 4 Sep 2026 17:05:03 +0900 Subject: [PATCH 18/24] pslr: isolate context split lookaheads --- spec/lrama/states_spec.rb | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/spec/lrama/states_spec.rb b/spec/lrama/states_spec.rb index a2d0dd3e3..6eebc1c25 100644 --- a/spec/lrama/states_spec.rb +++ b/spec/lrama/states_spec.rb @@ -3939,6 +3939,20 @@ class : keyword_class tSTRING keyword_end %prec tPLUS states.instance_variable_set(:@pslr_split_enabled, true) end + it "retains the original lookaheads when a context split changes" do + states.compute + original = states.states.first + kernel = original.kernels.first + rshift = grammar.find_symbol_by_s_value!("RSHIFT").number_bitmap + rangle = grammar.find_symbol_by_s_value!("RANGLE").number_bitmap + original.item_lookahead_set = { kernel => rshift } + + split = states.send(:copy_split_state, original) + split.item_lookahead_set[kernel] = rangle + + expect(original.item_lookahead_set[kernel]).to eq(rshift) + end + before do allow(mock_state).to receive(:acceptable_pslr_reduce_lookahead) { |_reduce, lookaheads| lookaheads.fetch(kernel_item) } end From 2fbf4042ef1c846e7b7c2b2ac700e47e20482b91 Mon Sep 17 00:00:00 2001 From: ydah Date: Fri, 4 Sep 2026 17:05:10 +0900 Subject: [PATCH 19/24] pslr: make per-state report details opt-in --- NEWS.md | 4 ++-- lib/lrama/reporter/pslr.rb | 11 +++++++---- sig/generated/lrama/reporter/pslr.rbs | 4 ++-- spec/lrama/reporter/pslr_spec.rb | 16 +++++++++++++--- 4 files changed, 24 insertions(+), 11 deletions(-) diff --git a/NEWS.md b/NEWS.md index caeca88ed..63310aa68 100644 --- a/NEWS.md +++ b/NEWS.md @@ -61,8 +61,8 @@ This adds the following PSLR-related grammar directives and integration points: - `%define parse.lac` controls lookahead correction (`full` by default for PSLR parsers, available to LALR/IELR parsers too) - `%define pslr.tables canonical-lr` switches state splitting to canonical LR(1) compatibility for debugging merged conflict reports - `%define pslr.max-states` and `%define pslr.max-state-ratio` are Lrama-specific safety guards for state growth -- `--report=pslr` renders split metrics, per-state acceptable-token sets, scanner-accepts rows, unresolved-conflict - witnesses, useless `%lex-prec` rules, and lexical tie candidates +- `--report=pslr` renders split metrics, unresolved-conflict witnesses, useless `%lex-prec` rules, and lexical tie + candidates; adding `states` (`--report=pslr,states`) also renders per-state acceptable-token sets and scanner-accepts rows Typical usage looks like this: diff --git a/lib/lrama/reporter/pslr.rb b/lib/lrama/reporter/pslr.rb index 289b5307c..411585d55 100644 --- a/lib/lrama/reporter/pslr.rb +++ b/lib/lrama/reporter/pslr.rb @@ -4,9 +4,10 @@ module Lrama class Reporter class Pslr - # @rbs (?pslr: bool, **bool _) -> void - def initialize(pslr: false, **_) + # @rbs (?pslr: bool, ?states: bool, **bool _) -> void + def initialize(pslr: false, states: false, **_) @pslr = pslr + @states = states end # @rbs (IO io, Lrama::States states) -> void @@ -15,8 +16,10 @@ def report(io, states) return unless states.pslr_defined? report_summary(io, states) - report_acceptable_tokens(io, states) - report_scanner_accepts(io, states) + if @states + report_acceptable_tokens(io, states) + report_scanner_accepts(io, states) + end report_unresolved_conflicts(io, states) report_useless_lex_prec(io, states) report_tie_candidates(io, states) diff --git a/sig/generated/lrama/reporter/pslr.rbs b/sig/generated/lrama/reporter/pslr.rbs index 874f2e2ca..1cbf21c30 100644 --- a/sig/generated/lrama/reporter/pslr.rbs +++ b/sig/generated/lrama/reporter/pslr.rbs @@ -3,8 +3,8 @@ module Lrama class Reporter class Pslr - # @rbs (?pslr: bool, **bool _) -> void - def initialize: (?pslr: bool, **bool _) -> void + # @rbs (?pslr: bool, ?states: bool, **bool _) -> void + def initialize: (?pslr: bool, ?states: bool, **bool _) -> void # @rbs (IO io, Lrama::States states) -> void def report: (IO io, Lrama::States states) -> void diff --git a/spec/lrama/reporter/pslr_spec.rb b/spec/lrama/reporter/pslr_spec.rb index 0736481e1..7cbe4c3c3 100644 --- a/spec/lrama/reporter/pslr_spec.rb +++ b/spec/lrama/reporter/pslr_spec.rb @@ -27,18 +27,28 @@ def build_states(source) GRAMMAR end - it "reports summary, accept sets, scanner accepts rows and useless rules" do + it "reports summary and diagnostics without per-state details" do states = build_states(source) io = StringIO.new described_class.new(pslr: true).report(io, states) output = io.string expect(output).to include("PSLR Summary") + expect(output).to include("PSLR Useless %lex-prec Rules") + expect(output).to include("USELESS_A -~ USELESS_B") + expect(output).not_to include("PSLR Acceptable Tokens") + expect(output).not_to include("PSLR Scanner Accepts") + end + + it "reports per-state details when states are requested" do + states = build_states(source) + io = StringIO.new + described_class.new(pslr: true, states: true).report(io, states) + output = io.string + expect(output).to include("PSLR Acceptable Tokens") expect(output).to include("PSLR Scanner Accepts") expect(output).to include("Fallback:") - expect(output).to include("PSLR Useless %lex-prec Rules") - expect(output).to include("USELESS_A -~ USELESS_B") end it "reports nothing for non-PSLR grammars" do From 9644de82c3d5200b63bab36203b691b54a51ca4c Mon Sep 17 00:00:00 2001 From: ydah Date: Thu, 15 Oct 2026 10:52:22 +0900 Subject: [PATCH 20/24] pslr: fix state merging, declarations, and generated runtime --- lib/lrama/command.rb | 2 +- lib/lrama/grammar.rb | 3 + lib/lrama/lexer.rb | 2 +- lib/lrama/output.rb | 112 ++++++--- lib/lrama/scanner_fsa.rb | 1 + lib/lrama/state.rb | 2 +- lib/lrama/states.rb | 1 + spec/lrama/generated_runtime_spec.rb | 257 ++++++++++++++++++++ spec/lrama/grammar/symbols/resolver_spec.rb | 30 +++ spec/lrama/grammar_spec.rb | 118 +++++++++ spec/lrama/lexer_spec.rb | 13 + spec/lrama/output_spec.rb | 2 +- spec/lrama/parser_spec.rb | 47 ++++ spec/lrama/pslr_downstream_runtime_spec.rb | 116 +++++++++ spec/lrama/scanner_fsa_spec.rb | 15 ++ spec/lrama/states_spec.rb | 28 ++- template/bison/yacc.c | 8 +- 17 files changed, 720 insertions(+), 37 deletions(-) create mode 100644 spec/lrama/generated_runtime_spec.rb create mode 100644 spec/lrama/pslr_downstream_runtime_spec.rb diff --git a/lib/lrama/command.rb b/lib/lrama/command.rb index b9cab61b3..6c93a84fc 100644 --- a/lib/lrama/command.rb +++ b/lib/lrama/command.rb @@ -32,8 +32,8 @@ def execute_command_workflow text = read_input grammar = build_grammar(text) states, context = compute_status(grammar) - states.validate!(@logger) render_reports(states) if @options.report_file + states.validate!(@logger) @tracer.trace(grammar) render_diagram(grammar) render_output(context, grammar) diff --git a/lib/lrama/grammar.rb b/lib/lrama/grammar.rb index 342939b7c..05dc02410 100644 --- a/lib/lrama/grammar.rb +++ b/lib/lrama/grammar.rb @@ -546,6 +546,9 @@ def add_lexer_context(name:, symbols:) end unless ctx = @lexer_contexts[name] + # Generated C stores context flags in an unsigned long long. + raise "%lexer-context supports at most 64 distinct contexts" if @lexer_context_counter >= 64 + ctx = Grammar::LexerContext.new(name: name, index: @lexer_context_counter) @lexer_context_counter += 1 @lexer_contexts[name] = ctx diff --git a/lib/lrama/lexer.rb b/lib/lrama/lexer.rb index 290374d64..0cf7158d1 100644 --- a/lib/lrama/lexer.rb +++ b/lib/lrama/lexer.rb @@ -292,7 +292,7 @@ def scan_regex_token in_char_class = false elsif char == "/" && !in_char_class return Lrama::Lexer::Token::Regex.new( - s_value: @scanner.string[start_pos...@scanner.pos], + s_value: @scanner.string.byteslice(start_pos...@scanner.pos), location: location ) elsif char == "\n" diff --git a/lib/lrama/output.rb b/lib/lrama/output.rb index 372e3d74a..a62e5be48 100644 --- a/lib/lrama/output.rb +++ b/lib/lrama/output.rb @@ -402,7 +402,7 @@ def lac_enabled? # Pure mode: the generated parser owns lexical analysis # (%define api.pslr.lexer generated). def pslr_pure_mode? - pslr_enabled? && @grammar.pslr_lexer_generated? && pslr_scanner_enabled? + pslr_enabled? && @grammar.pslr_lexer_generated? end # Check if PSLR scanner tables are available. @@ -414,12 +414,10 @@ def pslr_scanner_enabled? def pslr_function_declarations return "" unless pslr_enabled? - declarations = [] + declarations = ["#include "] if pslr_scanner_enabled? declarations << <<~C_CODE - #include - #ifndef YYPSLR_SCAN_RESULT_DEFINED # define YYPSLR_SCAN_RESULT_DEFINED typedef struct yypslr_scan_result { @@ -844,7 +842,7 @@ def pseudo_scan_function * input_len: Number of remaining input bytes * result: Output parameter for the match * - * Returns: Selected parser token ID. YYEOF when input_len is zero. + * Returns: Selected parser token ID. #{eof_symbol.id.s_value} when input_len is zero. * If neither the parser-state row nor the fallback row matches, * returns YYUNDEF and consumes one byte (character-token handling); * from_fallback is set for both cases because a syntax error is @@ -875,7 +873,7 @@ def pseudo_scan_function } if (input_len == 0) { - result->token = YYEOF; + result->token = #{eof_symbol.id.s_value}; return result->token; } @@ -964,7 +962,7 @@ def lexer_context_defines_code lines = [] lines << "/* Lexer context constants — generated from %lexer-context directives */" classifier.contexts.each do |lc| - lines << "#define YY_CTX_%-8s 0x%02x" % [lc.name, lc.bitmask] + lines << "#define YY_CTX_%-8s 0x%02xULL" % [lc.name, lc.bitmask] end lines.join("\n") end @@ -980,20 +978,20 @@ def lexer_context_table_code lines << "/* Lexer Context Classification Table */" lines << "/* Maps parser state -> lexer context flags */" lines << "" - lines << "static const unsigned char yy_lexer_context[] = {" + lines << "static const unsigned long long yy_lexer_context[] = {" table.each_with_index do |ctx, idx| ctx_name = LexerContextClassifier.context_name(ctx, lexer_contexts) comma = idx < table.size - 1 ? "," : "" - lines << " /* state #{idx} */ #{ctx}#{comma} /* #{ctx_name} */" + lines << " /* state #{idx} */ #{ctx}ULL#{comma} /* #{ctx_name} */" end lines << "};" lines << "" lines << "int" - lines << "yy_lexer_context_is(int yystate, int ctx_mask) {" + lines << "yy_lexer_context_is(int yystate, unsigned long long ctx_mask) {" lines << " if (yystate < 0 || yystate >= #{table.size}) return 0;" - lines << " return yy_lexer_context[yystate] & ctx_mask;" + lines << " return (yy_lexer_context[yystate] & ctx_mask) != 0;" lines << "}" lines.join("\n") @@ -1006,13 +1004,15 @@ def pslr_token_actions_enabled? # Generate layout accumulation declarations def pslr_layout_declarations - return "" unless pslr_scanner_enabled? + return "" unless pslr_scanner_enabled? || pslr_pure_mode? <<~C_CODE #ifndef YYPSLR_LAYOUT_DEFINED # define YYPSLR_LAYOUT_DEFINED + #include + typedef struct yypslr_layout { const char *text; int length; @@ -1106,7 +1106,7 @@ def pslr_layout_scan_function * Layout tokens are accumulated in the layout buffer; * non-layout tokens are returned to the caller with the * accumulated layout available via YYPSLR_LAYOUT_TEXT. - * The YYEOF token action (if any) runs before returning YYEOF so + * The #{eof_symbol.id.s_value} token action (if any) runs before returning #{eof_symbol.id.s_value} so * trailing layout can be recovered (paper section 3.6). */ int @@ -1124,7 +1124,7 @@ def pslr_layout_scan_function if (token == YYEMPTY) return token; - if (token == YYEOF) + if (token == #{eof_symbol.id.s_value}) { #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, 0, yylvalp);" : ""} return token; @@ -1163,15 +1163,73 @@ def pslr_generated_lexer_function params << "YYLTYPE *yyllocp" if @grammar.locations params << lex_param unless lex_param.empty? unused = [] - unused << " YY_USE (yyllocp);" if @grammar.locations unused << " YY_USE (#{lex_param_name});" unless lex_param.empty? + location_declarations = location_reset = location_start = location_end = "" + if @grammar.locations + location_declarations = <<~C_CODE + static const char *yypslr_location_cursor = 0; + static int yypslr_line = 1; + static int yypslr_column = 1; + + static void + yypslr_update_location (void) + { + while (yypslr_location_cursor != yypslr_input_cursor) + { + if (*yypslr_location_cursor++ == '\\n') + { + yypslr_line++; + yypslr_column = 1; + } + else + yypslr_column++; + } + } + C_CODE + location_reset = <<~C_CODE + yypslr_location_cursor = input; + yypslr_line = yypslr_column = 1; + C_CODE + location_start = <<~C_CODE + yypslr_update_location (); + yyllocp->first_line = yypslr_line; + yyllocp->first_column = yypslr_column; + C_CODE + location_end = <<~C_CODE + yypslr_update_location (); + yyllocp->last_line = yypslr_line; + yyllocp->last_column = yypslr_column; + C_CODE + end + + scan = if pslr_scanner_enabled? + <<~C_CODE + yypslr_scan_result yypslr_result; + yypslr_token = yypslr_scan_with_layout (yypslr_parser_state, + &yypslr_input_cursor, + &yypslr_input_remain, + yylvalp, + &yypslr_result); + yypslr_length = yypslr_result.length; + C_CODE + else + <<~C_CODE + YY_USE (yylvalp); + YYPSLR_LAYOUT_CLEAR (); + yypslr_token = yypslr_input_remain ? YYUNDEF : #{eof_symbol.id.s_value}; + yypslr_length = yypslr_input_remain ? 1 : 0; + #{pslr_token_actions_enabled? ? " if (yypslr_token == #{eof_symbol.id.s_value})\n YYPSLR_TOKEN_ACTION (yypslr_token, yypslr_input_cursor, 0, yylvalp);" : ""} + C_CODE + end + <<~C_CODE /* Pure-mode PSLR lexer: generated, owns the input cursor. */ static const char *yypslr_input_cursor = 0; static size_t yypslr_input_remain = 0; static int yypslr_parser_state = 0; + #{location_declarations} void yypslr_set_input (const char *input, size_t input_len) @@ -1179,6 +1237,7 @@ def pslr_generated_lexer_function yypslr_input_cursor = input; yypslr_input_remain = input_len; yypslr_parser_state = 0; + #{location_reset} } #define YYPSLR_SET_PARSER_STATE(State) (yypslr_parser_state = (State)) @@ -1186,21 +1245,18 @@ def pslr_generated_lexer_function static int yylex (#{params.join(", ")}) { - yypslr_scan_result yypslr_result; int yypslr_token; + int yypslr_length; #{unused.join("\n")} - yypslr_token = yypslr_scan_with_layout (yypslr_parser_state, - &yypslr_input_cursor, - &yypslr_input_remain, - yylvalp, - &yypslr_result); - - if (yypslr_token == YYEMPTY || yypslr_token == YYEOF) - return yypslr_token; - - yypslr_input_cursor += yypslr_result.length; - yypslr_input_remain -= (size_t) yypslr_result.length; + #{scan} + #{location_start} + if (yypslr_token != YYEMPTY && yypslr_token != #{eof_symbol.id.s_value}) + { + yypslr_input_cursor += yypslr_length; + yypslr_input_remain -= (size_t) yypslr_length; + } + #{location_end} return yypslr_token; } C_CODE @@ -1208,7 +1264,7 @@ def pslr_generated_lexer_function # Generate all PSLR C code def pslr_tables_and_functions - return "" unless pslr_scanner_enabled? + return "" unless pslr_scanner_enabled? || pslr_pure_mode? parts = [ "/* PSLR(1) Scanner Tables and Functions */", diff --git a/lib/lrama/scanner_fsa.rb b/lib/lrama/scanner_fsa.rb index 32e0559a5..6cfee6f48 100644 --- a/lib/lrama/scanner_fsa.rb +++ b/lib/lrama/scanner_fsa.rb @@ -270,6 +270,7 @@ def create_nfa_state(counter, states) # @rbs (String pattern, Array[Integer] counter, Array[NFAState] states) -> [NFAState, NFAState] def compile_regex(pattern, counter, states) raise PatternError, "empty patterns are not allowed" if pattern.empty? + raise PatternError, "non-ASCII characters are not supported in byte-oriented patterns" unless pattern.ascii_only? fragment, pos = compile_expression(pattern, 0, counter, states) raise PatternError, "unexpected trailing input at offset #{pos}" if pos < pattern.length diff --git a/lib/lrama/state.rb b/lib/lrama/state.rb index 1591a12d3..ba497849c 100644 --- a/lib/lrama/state.rb +++ b/lib/lrama/state.rb @@ -387,7 +387,7 @@ def propagate_lookaheads(next_state, lookaheads = nil, filter: true) kernel = kernels.find {|k| k.predecessor_item_of?(next_kernel) } (lookaheads || item_lookahead_set).fetch(kernel) else - goto_follow_set(next_kernel.lhs) + goto_follow_set(next_kernel.lhs, lookaheads) end sets[next_kernel] = mask ? lookahead_sets & mask : lookahead_sets diff --git a/lib/lrama/states.rb b/lib/lrama/states.rb index 02c31a9d3..3709d565c 100644 --- a/lib/lrama/states.rb +++ b/lib/lrama/states.rb @@ -1003,6 +1003,7 @@ def compatible_split_state?(state, filtered_lookaheads, pslr_lookaheads = nil) return false unless state.is_compatible?(filtered_lookaheads) end return true unless @pslr_split_enabled && @scanner_fsa + return true unless state.lookaheads_recomputed pslr_compatible_successors?(state, state.item_lookahead_set, pslr_lookaheads) end diff --git a/spec/lrama/generated_runtime_spec.rb b/spec/lrama/generated_runtime_spec.rb new file mode 100644 index 000000000..6b191ff97 --- /dev/null +++ b/spec/lrama/generated_runtime_spec.rb @@ -0,0 +1,257 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "generated runtime" do + def with_parser(source, flags: []) + Dir.mktmpdir("lrama-runtime") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + executable = File.join(dir, "parser") + File.write(grammar, <<~GRAMMAR + source) + %code provides { + static int yyerror(YYLTYPE *loc, const char *message) + { + (void)loc; + (void)message; + return 0; + } + } + GRAMMAR + Lrama::Command.new(["-o", output, grammar]).run + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", *flags, output, "-o", executable) + expect(status.success?).to be(true), err + yield executable + end + end + + it "compiles PSLR scanning without user-provided string declarations or layout tokens" do + with_parser(<<~GRAMMAR) do |parser| + %define lr.type pslr + %define api.pslr.lexer generated + %token-pattern A /a/ + %% + start: A; + %% + int main(void) { yypslr_set_input("a", 1); return yyparse(); } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + + ["lalr", "pslr"].each do |type| + it "uses heap storage for LAC with #{type} and an alloca parser stack" do + lexer = type == "pslr" ? "%define api.pslr.lexer generated" : <<~GRAMMAR + %code provides { + static int yylex(YYSTYPE *value) + { + static int read = 0; + (void)value; + return read++ ? YYEOF : A; + } + } + GRAMMAR + with_parser(<<~GRAMMAR, flags: ["-DYYSTACK_USE_ALLOCA=1"]) do |parser| + %code provides { #include } + %define lr.type #{type} + %define parse.lac full + #{lexer} + %token-pattern A /a/ + %% + start: A; + %% + int main(void) { + #{type == "pslr" ? 'yypslr_set_input("a", 1);' : ""} + return yyparse(); + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + + [false, true].each do |custom_copy| + it "supports yyoverflow with #{type} LAC#{custom_copy ? ' and a custom YYCOPY' : ''}" do + lexer = type == "pslr" ? "%define api.pslr.lexer generated" : <<~GRAMMAR + %define parse.lac full + %code provides { + static int yylex(YYSTYPE *value) + { + static int read = 0; + (void)value; + return read++ ? YYEOF : A; + } + } + GRAMMAR + copy = custom_copy ? <<~GRAMMAR : "" + #include + static int copy_count = 0; + #define YYCOPY(Dst, Src, Count) (copy_count++, memcpy((Dst), (Src), (Count) * sizeof(*(Src)))) + GRAMMAR + with_parser(<<~GRAMMAR) do |parser| + %code provides { + #define yyoverflow(Message, States, StatesSize, Values, ValuesSize, Locations, LocationsSize, StackSize) ((void)0) + #{copy} + } + %define lr.type #{type} + #{lexer} + %token-pattern A /a/ + %% + start: A; + %% + int main(void) { + #{type == "pslr" ? 'yypslr_set_input("a", 1);' : ""} + if (yyparse()) return 1; + return #{custom_copy ? 'copy_count == 0' : '0'}; + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + end + end + + it "tracks token, layout and EOF locations and resets them when input is replaced" do + with_parser(<<~'GRAMMAR') do |parser| + %code provides { + #include + #include + } + %define lr.type pslr + %define api.pslr.lexer generated + %locations + %token-pattern A /a+/ + %token-pattern YYLAYOUT_WS /[ \t\r\n]+/ + %% + start: A A { + printf("%d:%d-%d:%d %d:%d-%d:%d\n", + @1.first_line, @1.first_column, @1.last_line, @1.last_column, + @2.first_line, @2.first_column, @2.last_line, @2.last_column); + }; + %% + int main(void) { + YYSTYPE value = 0; + YYLTYPE location; + yypslr_set_input(" \naa\n a \n", 9); + if (yyparse()) return 1; + if (yylex(&value, &location) != YYEOF) return 2; + printf("EOF %d:%d-%d:%d\n", location.first_line, location.first_column, + location.last_line, location.last_column); + yypslr_set_input("a aa", 4); + return yyparse(); + } + GRAMMAR + out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + expect(out).to eq("2:1-2:3 3:2-3:3\nEOF 4:1-4:1\n1:1-1:2 1:3-1:5\n") + end + end + + it "preserves the ninth and sixty-fourth lexer context flags" do + declarations = (0...64).map { |i| "%lexer-context C#{i} A" }.join("\n") + with_parser(<<~GRAMMAR) do |parser| + %code provides { #include } + %define lr.type pslr + %define api.pslr.lexer generated + %token-pattern A /a/ + #{declarations} + %% + start: A; + %% + int main(void) { + int state; + int found = 0; + for (state = 0; state < YYNSTATES; state++) { + if (yy_lexer_context_is(state, YY_CTX_C8) && yy_lexer_context_is(state, YY_CTX_C63)) + found = 1; + } + if (!found || yy_lexer_context_is(-1, YY_CTX_C63) + || yy_lexer_context_is(YYNSTATES, YY_CTX_C63)) return 1; + yypslr_set_input("a", 1); + return yyparse(); + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + + it "generates an EOF lexer with locations for an empty token universe and consumes unexpected bytes" do + with_parser(<<~GRAMMAR) do |parser| + %define lr.type pslr + %define api.pslr.lexer generated + %locations + %% + start: %empty; + %% + int main(void) { + YYSTYPE value = 0; + YYLTYPE location; + yypslr_set_input("", 0); + if (yyparse()) return 1; + yypslr_set_input("x", 1); + if (!yyparse()) return 2; + yypslr_set_input("x", 1); + if (yylex(&value, &location) != YYUNDEF) return 3; + if (location.first_column != 1 || location.last_column != 2) return 4; + if (yylex(&value, &location) != YYEOF) return 5; + if (location.first_column != 2 || location.last_column != 2) return 6; + yypslr_set_input("", 0); + return yyparse(); + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + + it "runs the EOF token action without token patterns or locations" do + with_parser(<<~GRAMMAR) do |parser| + %code provides { static int eof_count = 0; } + %define lr.type pslr + %define api.pslr.lexer generated + %token-action YYEOF { eof_count++; } + %% + start: %empty; + %% + int main(void) { + yypslr_set_input(0, 0); + if (yyparse() || eof_count != 1) return 1; + yypslr_set_input("", 0); + return yyparse() || eof_count != 2; + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + + [false, true].each do |scanner| + it "uses a renamed EOF token and its action #{scanner ? 'with scanner and layout' : 'without token patterns'}" do + patterns = scanner ? "%token-pattern A /a/\n%token-pattern YYLAYOUT_WS / +/" : "" + with_parser(<<~GRAMMAR) do |parser| + %code provides { static int eof_count = 0; static int trailing_layout = 0; } + %define lr.type pslr + %define api.pslr.lexer generated + %token EOI 0 + %token-action EOI { eof_count++; trailing_layout = YYPSLR_LAYOUT_LENGTH; } + #{patterns} + %% + start: #{scanner ? 'A' : '%empty'}; + %% + int main(void) { + yypslr_set_input("#{scanner ? 'a ' : ''}", #{scanner ? 3 : 0}); + return yyparse() || eof_count != 1 || trailing_layout != #{scanner ? 2 : 0}; + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + end +end diff --git a/spec/lrama/grammar/symbols/resolver_spec.rb b/spec/lrama/grammar/symbols/resolver_spec.rb index ac24ffaeb..0a7f2da78 100644 --- a/spec/lrama/grammar/symbols/resolver_spec.rb +++ b/spec/lrama/grammar/symbols/resolver_spec.rb @@ -64,6 +64,36 @@ expect(term1).to eq(term2) end + [nil, 300].each do |token_id| + it "preserves omitted attributes when redeclaring a term with token_id #{token_id.inspect}" do + tag = Lrama::Lexer::Token::Tag.new(s_value: "") + term = resolver.add_term(id: symbol_id("NUM"), alias_name: '"number"', tag: tag, token_id: 300) + + redeclared = resolver.add_term(id: symbol_id("NUM"), token_id: token_id, replace: true) + + expect(redeclared).to equal(term) + expect(redeclared.alias_name).to eq('"number"') + expect(redeclared.tag).to eq(tag) + expect(redeclared.token_id).to eq(300) + end + end + + [nil, 256].each do |token_id| + it "preserves the canonical identifier when redeclaring an alias with token_id #{token_id.inspect}" do + id = symbol_id("YYerror") + tag = Lrama::Lexer::Token::Tag.new(s_value: "") + term = resolver.add_term(id: id, alias_name: "error", tag: tag, token_id: 256) + + redeclared = resolver.add_term(id: symbol_id("error"), token_id: token_id, replace: true) + + expect(redeclared).to equal(term) + expect(redeclared.id).to eq(id) + expect(redeclared.alias_name).to eq("error") + expect(redeclared.tag).to eq(tag) + expect(redeclared.token_id).to eq(256) + end + end + [false, true].each do |replace| it "rejects a duplicate token code without changing the original term with replace=#{replace}" do original = resolver.add_term(id: symbol_id("A"), token_id: 300) diff --git a/spec/lrama/grammar_spec.rb b/spec/lrama/grammar_spec.rb index 49f8bb539..fc66d1c6e 100644 --- a/spec/lrama/grammar_spec.rb +++ b/spec/lrama/grammar_spec.rb @@ -21,6 +21,30 @@ end end + describe '#add_lexer_context' do + before do + 64.times { |index| grammar.add_lexer_context(name: "CTX#{index}", symbols: []) } + end + + it 'supports all 64 context bits' do + expect(grammar.lexer_contexts.fetch("CTX63").bitmask).to eq(1 << 63) + end + + it 'rejects a context that exceeds the generated mask capacity' do + expect { grammar.add_lexer_context(name: "OVERFLOW", symbols: []) } + .to raise_error("%lexer-context supports at most 64 distinct contexts") + expect(grammar.lexer_contexts.size).to eq(64) + end + + it 'allows an existing context to be extended at capacity' do + symbol = Lrama::Lexer::Token::Ident.new(s_value: "NUM") + context = grammar.add_lexer_context(name: "CTX63", symbols: [symbol]) + + expect(context.symbols).to eq([symbol]) + expect(grammar.lexer_contexts.size).to eq(64) + end + end + describe '#validate!' do let(:grammar_file) { Lrama::Lexer::GrammarFile.new('parse.y', '') } @@ -316,6 +340,62 @@ end end + describe "#finalize_lexical_declarations!" do + it "resolves quoted aliases to canonical token ids" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "lex_prec_alias.y").parse + %token-pattern ID /[a-z]+/ "identifier" + %token-pattern IF /if/ "if" + %lex-prec "identifier" <~ "if" + %% + start: ID | IF ; + GRAMMAR + grammar.prepare + grammar.validate! + + grammar.finalize_lexical_declarations! + + expect(grammar.lex_prec.rules.map {|rule| [rule.left_name, rule.right_name] }).to eq([["ID", "IF"]]) + expect(grammar.lex_prec.identity_precedes?("IF", "ID")).to be true + expect(grammar.lex_prec.longest_pair?("ID", "IF")).to be true + end + + it "resolves aliases in symbol sets and keeps literal terminals" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "symbol_set_alias.y").parse + %token-pattern ID /[a-z]+/ + %token-pattern IF /if/ "if" + %symbol-set keywords "if" ';' + %lex-prec ID <~ keywords + %% + start: ID | IF | ';' ; + GRAMMAR + grammar.prepare + grammar.validate! + + grammar.finalize_lexical_declarations! + + expect(grammar.symbol_sets.fetch("keywords").map(&:s_value)).to eq(["IF", "';'"]) + expect(grammar.lex_prec.rules.map {|rule| [rule.left_name, rule.right_name] }).to eq([["ID", "IF"], ["ID", "';'"]]) + end + + it "expands yyall after later token patterns and implicit literals are registered" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "lex_prec_yyall.y").parse + %lex-prec yyall -~ yyall + %token-pattern IF /if/ "if" + %% + start: IF ';' ; + GRAMMAR + grammar.prepare + grammar.validate! + grammar.synthesize_implicit_literal_token_patterns! + + grammar.finalize_lexical_declarations! + + expect(grammar.lex_prec.rules.map {|rule| [rule.left_name, rule.right_name] }).to contain_exactly( + ["IF", "IF"], ["IF", "';'"], ["';'", "IF"], ["';'", "';'"] + ) + end + end + describe "#finalize_lexical_ties!" do def build_pslr_grammar(source) grammar = Lrama::Parser.new(source, "lex_tie.y").parse @@ -339,6 +419,44 @@ def build_pslr_grammar(source) expect(grammar.lex_tie.tied?("A", "B")).to be true end + ["lex-tie", "lex-no-tie"].each do |directive| + ['"if"', "keywords"].each do |operand| + it "resolves #{directive} aliases in #{operand}" do + grammar = build_pslr_grammar(<<~GRAMMAR) + %define lr.type pslr + %token-pattern ID /[a-z]+/ "identifier" + %token-pattern IF /if/ "if" + %symbol-set keywords "if" + %#{directive} "identifier" #{operand} + %% + start: ID | IF ; + GRAMMAR + + expect(grammar.lex_tie.declarations.first.groups.map(&:names)).to eq([["ID"], ["IF"]]) + grammar.finalize_lexical_ties!(Lrama::ScannerFSA.new(grammar.token_patterns)) + + expect(grammar.lex_tie.tied?("ID", "IF")).to eq(directive == "lex-tie") + expect(grammar.lex_tie.no_tie?("ID", "IF")).to eq(directive == "lex-no-tie") + end + end + + it "expands #{directive} yyall after implicit literal synthesis" do + grammar = build_pslr_grammar(<<~GRAMMAR) + %define lr.type pslr + %#{directive} yyall yyall + %token-pattern PLUSPLUS /\\+\\+/ + %% + start: PLUSPLUS | '+' ; + GRAMMAR + grammar.synthesize_implicit_literal_token_patterns! + + grammar.finalize_lexical_ties!(Lrama::ScannerFSA.new(grammar.token_patterns)) + + expect(grammar.lex_tie.tied?("PLUSPLUS", "'+'")).to eq(directive == "lex-tie") + expect(grammar.lex_tie.no_tie?("PLUSPLUS", "'+'")).to eq(directive == "lex-no-tie") + end + end + it "limits set-set ties to scanner-conflicting pairs" do grammar = build_pslr_grammar(<<~GRAMMAR) %define lr.type pslr diff --git a/spec/lrama/lexer_spec.rb b/spec/lrama/lexer_spec.rb index 0c041208e..ce72f2d35 100644 --- a/spec/lrama/lexer_spec.rb +++ b/spec/lrama/lexer_spec.rb @@ -536,6 +536,19 @@ MSG end + it 'preserves regex text after a multibyte comment' do + text = "/* 日本語 */\n%token-pattern ID /[a-z]+/\n%%" + grammar_file = Lrama::Lexer::GrammarFile.new("multibyte.y", text) + lexer = Lrama::Lexer.new(grammar_file) + 2.times { lexer.next_token } + + type, token = lexer.next_token + + expect(type).to eq(:REGEX) + expect(token.s_value).to eq('/[a-z]+/') + expect(token.pattern).to eq('[a-z]+') + end + [%q('\''), %q('\"'), %q('\a'), %q('\?'), %q('\1'), %q('\12'), %q('\101'), %q('\x41')].each do |literal| it "lexes the escaped character literal #{literal.inspect}" do grammar_file = Lrama::Lexer::GrammarFile.new("character.y", "#{literal} NEXT") diff --git a/spec/lrama/output_spec.rb b/spec/lrama/output_spec.rb index 6c7942405..79b489259 100644 --- a/spec/lrama/output_spec.rb +++ b/spec/lrama/output_spec.rb @@ -400,7 +400,7 @@ let(:mock_grammar) do instance_double( Lrama::Grammar, - eof_symbol: nil, + eof_symbol: instance_double(Lrama::Grammar::Symbol, id: Lrama::Lexer::Token::Ident.new(s_value: "YYEOF")), error_symbol: nil, undef_symbol: nil, accept_symbol: nil, diff --git a/spec/lrama/parser_spec.rb b/spec/lrama/parser_spec.rb index 0b384cbb2..5ad5aaef6 100644 --- a/spec/lrama/parser_spec.rb +++ b/spec/lrama/parser_spec.rb @@ -5250,6 +5250,53 @@ class : keyword_class tSTRING keyword_end expect(token_pattern.tag.s_value).to eq("") end + [ + "%token A", + "%left A", + "%lex-prec A -~ A", + "%lex-tie A B", + "%lex-no-tie A B", + "%symbol-set letters A", + '%token A 300 "old letter"' + ].each do |declaration| + it "applies token pattern tags and aliases after #{declaration}" do + y = <<~GRAMMAR + %union { int val; int old; } + #{declaration} + %token-pattern A /a/ "letter" + %% + start: "letter" { use($1); } ; + GRAMMAR + grammar = Lrama::Parser.new(y, "token_pattern_attributes.y").parse + grammar.prepare + grammar.validate! + + rule = grammar.rules.last + expect(rule.translated_code(grammar)).to eq(" use((yyvsp[0].val)); ") + expect(rule.rhs.first.id.s_value).to eq("A") + expect(rule.rhs.first.alias_name).to eq('"letter"') + end + end + + it "preserves token attributes omitted by a token pattern declaration" do + y = <<~GRAMMAR + %union { int val; } + %token A 300 "letter" + %token-pattern A /a/ + %% + start: "letter" { use($1); } ; + GRAMMAR + grammar = Lrama::Parser.new(y, "token_pattern_attributes.y").parse + grammar.prepare + grammar.validate! + + rule = grammar.rules.last + expect(rule.translated_code(grammar)).to eq(" use((yyvsp[0].val)); ") + expect(rule.rhs.first.id.s_value).to eq("A") + expect(rule.rhs.first.alias_name).to eq('"letter"') + expect(rule.rhs.first.token_id).to eq(300) + end + it "parses escaped slashes inside token patterns" do y = <<~GRAMMAR %token-pattern SLASH /\\// diff --git a/spec/lrama/pslr_downstream_runtime_spec.rb b/spec/lrama/pslr_downstream_runtime_spec.rb new file mode 100644 index 000000000..32a33cbe3 --- /dev/null +++ b/spec/lrama/pslr_downstream_runtime_spec.rb @@ -0,0 +1,116 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "PSLR downstream scanner compatibility" do + include PslrFamilyHelper + + it "uses the initial state's nullable prefix to select the scanner token" do + grammar = build_grammar(<<~GRAMMAR, "initial_nullable_prefix.y") + %define lr.type pslr + %token-pattern IF /if/ + %token-pattern ID /[a-z]+/ + %lex-prec ID <~ IF + %% + start: optional ID; + optional: %empty; + GRAMMAR + _ielr_states, pslr_states = compute_ielr_and_pslr(grammar) + scanner = pslr_states.scanner_fsa + accepting_state = "if".each_char.reduce(scanner.initial_state) do |state, char| + scanner.states.fetch(state.transitions.fetch(char)) + end + + expect(pslr_states.scanner_accepts_table[0, accepting_state.id]&.name).to eq("ID") + end + + it "merges compatible contexts and propagates late lookaheads through every successor" do + grammar = build_grammar(<<~GRAMMAR, "compatible_successors.y") + %define lr.type pslr + %token-pattern P /p/ + %token-pattern Q /q/ + %token-pattern R /r/ + %token-pattern X /x/ + %token-pattern Y /y/ + %token-pattern Z /z/ + %token-pattern A /a/ + %token-pattern B /b/ + %% + start: P shared A | Q R shared B; + shared: X Y | X Z; + GRAMMAR + ielr_states, pslr_states = compute_ielr_and_pslr(grammar) + + expect(pslr_states.states_count).to eq(ielr_states.states_count) + %w[Y Z].each do |suffix| + reductions = pslr_states.states.select do |state| + state.reduces.any? { |reduce| reduce.rule.display_name == "shared -> X #{suffix}" } + end + expect(reductions.size).to eq(1) + expect(acceptable_tokens(pslr_states, reductions.first)).to contain_exactly("A", "B") + end + end + + { + "two shifts" => ["shared: X Y;", "x y"], + "four shifts" => ["shared: X Y X Y;", "x y x y"], + "right recursion" => ["shared: X shared | Y;", "x x y"], + "left recursion" => ["shared: shared X | Y;", "y x x"], + "nullable recursion" => ["shared: X optional Y; optional: %empty | X optional;", "x x x y"], + "nullable tail" => ["shared: X optional; optional: %empty;", "x"], + "recursive nullable tail" => ["shared: X optional; optional: %empty | Y optional;", "x y y"] + }.each do |label, (rules, shared_input)| + it "preserves keyword and identifier contexts through #{label}" do + Dir.mktmpdir("lrama-downstream") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + executable = File.join(dir, "parser") + File.write(grammar, <<~GRAMMAR) + %code provides { + #include + static int yyerror(YYLTYPE *loc, const char *message) + { + (void)loc; + (void)message; + return 0; + } + } + %define lr.type pslr + %define api.pslr.lexer generated + %token-pattern P /p/ + %token-pattern Q /q/ + %token-pattern X /x/ + %token-pattern Y /y/ + %token-pattern IF /if/ + %token-pattern ID /[a-z]+/ + %token-pattern YYLAYOUT_WS /[ ]+/ + %lex-prec ID <~ IF + %lex-prec ID <~ X + %lex-prec ID <~ Y + %% + start: P shared IF | Q shared ID; + #{rules} + %% + int main(int argc, char **argv) { + if (argc != 2) return 2; + yypslr_set_input(argv[1], (int)strlen(argv[1])); + return yyparse(); + } + GRAMMAR + Lrama::Command.new(["-o", output, grammar]).run + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", output, "-o", executable) + expect(status.success?).to be(true), err + + ["q #{shared_input} if", "p #{shared_input} if", "q #{shared_input} name"].each do |input| + _out, err, status = Open3.capture3(executable, input) + expect(status.success?).to be(true), "rejected #{input.inspect}: #{err}" + end + _out, _err, status = Open3.capture3(executable, "p #{shared_input} name") + expect(status.exitstatus).to eq(1) + end + end + end +end diff --git a/spec/lrama/scanner_fsa_spec.rb b/spec/lrama/scanner_fsa_spec.rb index fb45aa7df..3242c93cd 100644 --- a/spec/lrama/scanner_fsa_spec.rb +++ b/spec/lrama/scanner_fsa_spec.rb @@ -161,9 +161,24 @@ def token_pattern(name, regex, lineno: 1, order: 0) expect(fsa.scan("a\nb").map { |result| result[:token].name }).to include("NOT_STAR") expect(fsa.scan("*")).to be_empty end + + it "matches multibyte input as bytes through dot and negated classes" do + [".+", "[^*]+"].each do |pattern| + fsa = Lrama::ScannerFSA.new([token_pattern("BYTES", pattern)]) + + expect(fsa.scan("éλ").last[:position]).to eq("éλ".bytesize) + end + end end describe "pattern validation" do + ["é", "λ", "[é]", "[^λ]", "[a-λ]"].each do |pattern| + it "rejects non-ASCII pattern #{pattern.inspect} before building transitions" do + expect { Lrama::ScannerFSA.new([token_pattern("NON_ASCII", pattern, lineno: 12)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /NON_ASCII at line 12.*non-ASCII characters are not supported/m) + end + end + it "rejects empty token patterns" do expect { Lrama::ScannerFSA.new([token_pattern("EMPTY", "", lineno: 42)]) } .to raise_error(Lrama::ScannerFSA::PatternError, /EMPTY at line 42.*empty patterns/m) diff --git a/spec/lrama/states_spec.rb b/spec/lrama/states_spec.rb index 6eebc1c25..be175a183 100644 --- a/spec/lrama/states_spec.rb +++ b/spec/lrama/states_spec.rb @@ -627,6 +627,30 @@ class go to state 5 end end + describe '#compute_follow_kernel_items' do + it "maps each kernel to whether the goto inherits its lookaheads" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "follow_kernel_items.y").parse + %token P X Y + %% + start: first | second; + first: P shared X; + second: P shared; + shared: Y; + GRAMMAR + grammar.prepare + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.send(:compute_predecessors) + states.send(:compute_follow_kernel_items) + state = states.states.find { |candidate| candidate.accessing_symbol.name == "P" } + goto = state.nterm_transitions.find { |transition| transition.next_sym.name == "shared" } + first = state.kernels.find { |kernel| kernel.lhs.name == "first" } + second = state.kernels.find { |kernel| kernel.lhs.name == "second" } + + expect(state.follow_kernel_items[goto]).to eq({ first => false, second => true }.compare_by_identity) + end + end + describe '#reads_relation' do it do path = "states/reads_relation.y" @@ -3980,9 +4004,9 @@ class : keyword_class tSTRING keyword_end %prec tPLUS it "uses lexical precedence when comparing PSLR accept sets" do grammar.lex_prec.add_rule( - left_token: grammar.find_symbol_by_s_value!("RSHIFT").id, + left_token: Lrama::Lexer::Token::Ident.new(s_value: "RSHIFT"), operator: Lrama::Grammar::LexPrec::TOKEN_RIGHT, - right_token: grammar.find_symbol_by_s_value!("RANGLE").id, + right_token: Lrama::Lexer::Token::Ident.new(s_value: "RANGLE"), lineno: 1 ) states.instance_variable_set(:@length_precedences, Lrama::LengthPrecedences.new(grammar.lex_prec)) diff --git a/template/bison/yacc.c b/template/bison/yacc.c index 33d870f88..2885e4961 100644 --- a/template/bison/yacc.c +++ b/template/bison/yacc.c @@ -361,6 +361,9 @@ typedef int yy_state_fast_t; # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif +# endif + + /* LAC and error recovery need heap allocation even with alloca stacks. */ # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) @@ -381,7 +384,6 @@ void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif -# endif #endif /* 1 */ #if (! defined yyoverflow \ @@ -427,7 +429,7 @@ union yyalloc #endif -#if defined YYCOPY_NEEDED && YYCOPY_NEEDED +#if (defined YYCOPY_NEEDED && YYCOPY_NEEDED) || <%= output.lac_enabled? ? 1 : 0 %> /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY @@ -445,7 +447,7 @@ union yyalloc while (0) # endif # endif -#endif /* !YYCOPY_NEEDED */ +#endif /* YYCOPY_NEEDED or LAC */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL <%= output.yyfinal %> From e378ca3e9aba0b6160474b315869c89d39846840 Mon Sep 17 00:00:00 2001 From: ydah Date: Wed, 21 Oct 2026 09:38:22 +0900 Subject: [PATCH 21/24] pslr: fix scanner, recovery, and declaration regressions Preserve fallback profiles and lexer declarations, repair pending reductions with LAC, and initialize unreachable-state lookaheads. Reject unsupported regexes, grow layout storage, and avoid quadratic LAC and scanner work. Validated with 785 specs, 84 C++ runtime specs, Steep, and targeted sanitizer and differential checks. --- lib/lrama/grammar/lex_tie.rb | 2 +- lib/lrama/output.rb | 300 ++++++++++++------ lib/lrama/reporter/pslr.rb | 23 +- lib/lrama/scanner_fsa.rb | 7 + lib/lrama/state/scanner_accepts.rb | 34 +- lib/lrama/states.rb | 10 +- sig/generated/lrama/state/scanner_accepts.rbs | 8 + spec/lrama/error_symbol_runtime_spec.rb | 47 +++ spec/lrama/fallback_profiles_runtime_spec.rb | 65 ++++ spec/lrama/generated_runtime_spec.rb | 29 +- spec/lrama/grammar_spec.rb | 55 ++++ spec/lrama/integration_spec.rb | 7 +- spec/lrama/lac_runtime_spec.rb | 206 ++++++++++++ spec/lrama/layout_runtime_spec.rb | 140 ++++++++ spec/lrama/lexer_context_classifier_spec.rb | 21 ++ spec/lrama/lexer_context_runtime_spec.rb | 78 +++++ spec/lrama/lexer_params_runtime_spec.rb | 124 ++++++++ spec/lrama/output_spec.rb | 21 +- spec/lrama/pslr_split_state_runtime_spec.rb | 72 +++++ .../repair_default_reduction_runtime_spec.rb | 78 +++++ spec/lrama/repair_replay_runtime_spec.rb | 80 +++++ spec/lrama/reporter/pslr_spec.rb | 21 ++ spec/lrama/scanner_fsa_spec.rb | 79 +++++ .../lrama/scanner_termination_runtime_spec.rb | 106 +++++++ spec/lrama/state/scanner_accepts_spec.rb | 32 ++ template/bison/_yacc.h | 5 + template/bison/yacc.c | 118 ++++--- 27 files changed, 1598 insertions(+), 170 deletions(-) create mode 100644 spec/lrama/error_symbol_runtime_spec.rb create mode 100644 spec/lrama/fallback_profiles_runtime_spec.rb create mode 100644 spec/lrama/lac_runtime_spec.rb create mode 100644 spec/lrama/layout_runtime_spec.rb create mode 100644 spec/lrama/lexer_context_runtime_spec.rb create mode 100644 spec/lrama/lexer_params_runtime_spec.rb create mode 100644 spec/lrama/pslr_split_state_runtime_spec.rb create mode 100644 spec/lrama/repair_default_reduction_runtime_spec.rb create mode 100644 spec/lrama/repair_replay_runtime_spec.rb create mode 100644 spec/lrama/scanner_termination_runtime_spec.rb diff --git a/lib/lrama/grammar/lex_tie.rb b/lib/lrama/grammar/lex_tie.rb index b4d89557c..9ddff2cff 100644 --- a/lib/lrama/grammar/lex_tie.rb +++ b/lib/lrama/grammar/lex_tie.rb @@ -194,7 +194,7 @@ def rebuild_relations(token_names, decisions) end @ties = Hash.new { |h, k| h[k] = Set.new([k]) } - groups = token_names.group_by {|name| root(parents, name) } + groups = parents.keys.group_by {|name| root(parents, name) } groups.each_value do |names| tied = names.to_set names.each {|name| @ties[name] = tied.dup } diff --git a/lib/lrama/output.rb b/lib/lrama/output.rb index a62e5be48..2aa8809dd 100644 --- a/lib/lrama/output.rb +++ b/lib/lrama/output.rb @@ -452,13 +452,13 @@ def pslr_function_declarations # define YYPSLR_TOKEN_IS_LAYOUT(Token) yy_pslr_token_is_layout ((Token)) #endif - int yypslr_scan_with_layout (int parser_state, const char **input, - size_t *input_len, YYSTYPE *yylvalp, - yypslr_scan_result *result); + int yypslr_scan_with_layout (int yyparser_state, const char **yyinput, + size_t *yyinput_len, YYSTYPE *yylvalp, + yypslr_scan_result *yyresult#{lex_param.empty? ? "" : ", #{lex_param}"}); #ifndef YYPSLR_SCAN_WITH_LAYOUT - # define YYPSLR_SCAN_WITH_LAYOUT(ParserState, InputPtr, InputLenPtr, LvalPtr, Result) \\ - yypslr_scan_with_layout ((ParserState), (InputPtr), (InputLenPtr), (LvalPtr), (Result)) + # define YYPSLR_SCAN_WITH_LAYOUT(yyParserState, yyInputPtr, yyInputLenPtr, yyLvalPtr, yyResult) \\ + yypslr_scan_with_layout ((yyParserState), (yyInputPtr), (yyInputLenPtr), (yyLvalPtr), (yyResult)#{lex_param.empty? ? "" : ", #{lex_param_name}"}) #endif C_CODE end @@ -673,18 +673,100 @@ def scanner_accepts_table_code lines << "};" lines << "" - lines << "static const int yy_scanner_fallback_accepts[YY_NUM_ACCEPTING_STATES] = {" - fallback_row = pslr_accepting_states.map do |fsa_state| - token = scanner_accepts.fallback_table[fsa_state.id] - token ? token_pattern_indexes.fetch(token) : -1 + lines << "#define YY_NUM_FALLBACK_PROFILES #{scanner_accepts.fallback_profiles.size}" + lines << "static const int yy_scanner_fallback_accepts[YY_NUM_FALLBACK_PROFILES][YY_NUM_ACCEPTING_STATES] = {" + scanner_accepts.fallback_profiles.each do |profile| + row = pslr_accepting_states.map do |fsa_state| + transition = profile[fsa_state.id] + token = transition && transition.last + token ? token_pattern_indexes.fetch(token) : -1 + end + lines << " {#{row.join(', ')}}," + end + lines << "};" + lines << "static const int yy_scanner_fallback_next[YY_NUM_FALLBACK_PROFILES][YY_NUM_ACCEPTING_STATES] = {" + scanner_accepts.fallback_profiles.each do |profile| + row = pslr_accepting_states.map do |fsa_state| + transition = profile[fsa_state.id] + transition ? transition.first : -1 + end + lines << " {#{row.join(', ')}}," end - lines << " #{fallback_row.join(', ')}" lines << "};" + lines << scanner_continuation_table_code + end + + lines.join("\n") + end + + def scanner_continuation_table_code + scanner_fsa = @context.states.scanner_fsa + scanner_accepts = @context.states.scanner_accepts_table + patterns = @context.states.token_patterns + accepting_states = pslr_accepting_states + relations = scanner_fsa.states.map {|state| [state.id, state.transitions.values.uniq] }.to_h + accepting_bits = scanner_fsa.states.map {|state| [state.id, 0] }.to_h + accepting_states.each_with_index {|state, index| accepting_bits[state.id] = 1 << index } + reachable = Digraph.new(relations.keys, relations, accepting_bits).compute + future = scanner_fsa.states.map do |state| + relations.fetch(state.id).inject(0) {|bits, target| bits | reachable.fetch(target) } + end + + # Rows share a profile when the same future accepting states can replace the winner. + profiles = {} + normal_profiles = @context.states.states.map do |parser_state| + [nil, *patterns].map do |winner| + mask = 0 + accepting_states.each_with_index do |state, index| + token = scanner_accepts[parser_state.id, state.id] + if token && (!winner || @context.states.length_precedences.normal_precedes?(winner.name, token.name)) + mask |= 1 << index + end + end + profiles[mask] ||= profiles.size + end end + lines = ["/* Continue only while a future match can replace the selected token. */"] + lines << "static const int yy_scanner_normal_profile[YY_NUM_PARSER_STATES][YY_NUM_TOKEN_PATTERNS + 1] = {" + normal_profiles.each {|row| lines << " {#{row.join(', ')}}," } + lines << "};" + lines << "static const unsigned char yy_scanner_continue[#{profiles.size}][YY_SCANNER_NUM_STATES] = {" + profiles.each_key do |mask| + lines << " {#{future.map {|bits| (bits & mask).zero? ? 0 : 1 }.join(', ')}}," + end + lines << "};" + lines << "static const unsigned char yy_scanner_fallback_continue[YY_NUM_FALLBACK_PROFILES][YY_SCANNER_NUM_STATES] = {" + scanner_fallback_continuations.each {|row| lines << " {#{row.join(', ')}}," } + lines << "};" lines.join("\n") end + def scanner_fallback_continuations + scanner_fsa = @context.states.scanner_fsa + profiles = @context.states.scanner_accepts_table.fallback_profiles + initial = [0, 0] + nodes = [initial] + visited = Set.new(nodes) + relations = {} + updates = {} + nodes.each do |node| + profile_id, state_id = node + updates[node] = 0 + relations[node] = scanner_fsa.states[state_id].transitions.values.uniq.map do |target_id| + transition = profiles[profile_id][target_id] + updates[node] = 1 if transition && transition.last + target = [transition ? transition.first : profile_id, target_id] + nodes << target if visited.add?(target) + target + end + end + reachable_updates = Digraph.new(nodes, relations, updates).compute + profiles.each_index.map do |profile_id| + scanner_fsa.states.map {|state| reachable_updates.fetch([profile_id, state.id], 0) } + end + end + # Generate length_precedences table as C code def length_precedences_table_code return "" unless pslr_scanner_enabled? @@ -704,17 +786,6 @@ def length_precedences_table_code num_tokens, :normal_precedes? ) - - lines << "" - lines << "/* yy_pslr_fallback_length_precedes keeps explicit PSLR length" - lines << " precedence and otherwise uses traditional longest-match fallback. */" - lines << "" - - lines << length_precedence_matrix_code( - "yy_pslr_fallback_length_precedes", - num_tokens, - :fallback_precedes? - ) end lines.join("\n") @@ -744,26 +815,18 @@ def pslr_lac_function static int yy_lac_check_ (yy_state_t *yyss, yy_state_t *yyssp, yysymbol_kind_t yytoken) { - YYPTRDIFF_T yylac_len = yyssp - yyss + 1; - yy_state_t *yylac_base = YY_CAST (yy_state_t *, - YYMALLOC (YY_CAST (YYSIZE_T, YYMAXDEPTH * YYSIZEOF (yy_state_t)))); - yy_state_t *yylac_top; + yy_state_t yylac_states[YYINITDEPTH]; + yy_state_t *yylac_base = yylac_states; + YYPTRDIFF_T yylac_size = YYINITDEPTH; + YYPTRDIFF_T yylac_len = 0; + int yylac_status = 0; - if (!yylac_base) + if (YYMAXDEPTH < yyssp - yyss + 1) return YYENOMEM; - if (YYMAXDEPTH < yylac_len) - { - YYFREE (yylac_base); - return YYENOMEM; - } - - YYCOPY (yylac_base, yyss, yylac_len); - yylac_top = yylac_base + yylac_len - 1; - for (;;) { - int yystate = *yylac_top; + int yystate = yylac_len ? yylac_base[yylac_len - 1] : *yyssp; int yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) @@ -774,53 +837,71 @@ def pslr_lac_function yyn = yytable[yyn]; if (0 < yyn) { - YYFREE (yylac_base); - return 1; + yylac_status = 1; + break; } if (yytable_value_is_error (yyn)) - { - YYFREE (yylac_base); - return 0; - } + break; yyn = -yyn; } else { yyn = yydefact[yystate]; if (yyn == 0) - { - YYFREE (yylac_base); - return 0; - } + break; } } else { yyn = yydefact[yystate]; if (yyn == 0) - { - YYFREE (yylac_base); - return 0; - } + break; } - yylac_top -= yyr2[yyn]; + /* Keep the parser's stack read-only; only speculative states need storage. */ + if (yylac_len < yyr2[yyn]) + { + yyssp -= yyr2[yyn] - yylac_len; + yylac_len = 0; + } + else + yylac_len -= yyr2[yyn]; { const int yylhs = yyr1[yyn] - YYNTOKENS; - const int yyi = yypgoto[yylhs] + *yylac_top; - yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yylac_top + const int yytop = yylac_len ? yylac_base[yylac_len - 1] : *yyssp; + const int yyi = yypgoto[yylhs] + yytop; + yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == yytop ? yytable[yyi] : yydefgoto[yylhs]); } - if (yylac_base + YYMAXDEPTH - 1 <= yylac_top) + if (YYMAXDEPTH <= yyssp - yyss + 1 + yylac_len) { - YYFREE (yylac_base); - return YYENOMEM; + yylac_status = YYENOMEM; + break; + } + if (yylac_len == yylac_size) + { + yy_state_t *yylac_new; + yylac_size = yylac_size <= YYMAXDEPTH / 2 ? 2 * yylac_size : YYMAXDEPTH; + yylac_new = YY_CAST (yy_state_t *, + YYMALLOC (YY_CAST (YYSIZE_T, yylac_size * YYSIZEOF (yy_state_t)))); + if (!yylac_new) + { + yylac_status = YYENOMEM; + break; + } + YYCOPY (yylac_new, yylac_base, yylac_len); + if (yylac_base != yylac_states) + YYFREE (yylac_base); + yylac_base = yylac_new; } - *++yylac_top = YY_CAST (yy_state_t, yystate); + yylac_base[yylac_len++] = YY_CAST (yy_state_t, yystate); } + if (yylac_base != yylac_states) + YYFREE (yylac_base); + return yylac_status; } C_CODE end @@ -856,6 +937,7 @@ def pseudo_scan_function int pbest = YY_PSLR_EMPTY_PATTERN; int fallback_ibest = 0; int fallback_pbest = YY_PSLR_EMPTY_PATTERN; + int fallback_profile = 0; size_t i = 0; if (result == NULL) { @@ -900,15 +982,18 @@ def pseudo_scan_function } } - pattern_index = yy_scanner_fallback_accepts[sa]; + pattern_index = yy_scanner_fallback_accepts[fallback_profile][sa]; + fallback_profile = yy_scanner_fallback_next[fallback_profile][sa]; if (pattern_index != YY_PSLR_EMPTY_PATTERN) { - if (fallback_pbest == YY_PSLR_EMPTY_PATTERN || - yy_pslr_fallback_length_precedes[fallback_pbest][pattern_index]) { - fallback_pbest = pattern_index; - fallback_ibest = (int)i; - } + fallback_pbest = pattern_index; + fallback_ibest = (int)i; } } + + if (!yy_scanner_continue[yy_scanner_normal_profile[parser_state][pbest + 1]][ss] && + (pbest != YY_PSLR_EMPTY_PATTERN || !yy_scanner_fallback_continue[fallback_profile][ss])) { + break; + } } if (pbest != YY_PSLR_EMPTY_PATTERN) { @@ -1011,6 +1096,7 @@ def pslr_layout_declarations #ifndef YYPSLR_LAYOUT_DEFINED # define YYPSLR_LAYOUT_DEFINED + #include #include typedef struct yypslr_layout { @@ -1022,23 +1108,48 @@ def pslr_layout_declarations # define YYPSLR_LAYOUT_BUFFER_SIZE 4096 # endif - static char yypslr_layout_buffer[YYPSLR_LAYOUT_BUFFER_SIZE]; + static char yypslr_layout_initial[YYPSLR_LAYOUT_BUFFER_SIZE]; + static char *yypslr_layout_buffer = yypslr_layout_initial; + static size_t yypslr_layout_capacity = sizeof yypslr_layout_initial; static int yypslr_layout_length = 0; static void yypslr_layout_clear (void) { + if (yypslr_layout_buffer != yypslr_layout_initial) + YYFREE (yypslr_layout_buffer); + yypslr_layout_buffer = yypslr_layout_initial; + yypslr_layout_capacity = sizeof yypslr_layout_initial; yypslr_layout_length = 0; + yypslr_layout_buffer[0] = '\\0'; } static int yypslr_layout_append (const char *text, int length) { - if (length < 0 - || (size_t) length >= (size_t) YYPSLR_LAYOUT_BUFFER_SIZE - - (size_t) yypslr_layout_length) + size_t required; + if (length < 0 || length > INT_MAX - yypslr_layout_length) return 0; + required = (size_t) yypslr_layout_length + (size_t) length + 1; + if (required > (size_t) YYSIZE_MAXIMUM) + return 0; + if (required > yypslr_layout_capacity) + { + size_t capacity = yypslr_layout_capacity; + char *buffer; + while (capacity < required) + capacity = capacity > (size_t) YYSIZE_MAXIMUM / 2 ? required : capacity * 2; + buffer = YY_CAST (char *, YYMALLOC (capacity)); + if (!buffer) + return 0; + memcpy (buffer, yypslr_layout_buffer, (size_t) yypslr_layout_length); + if (yypslr_layout_buffer != yypslr_layout_initial) + YYFREE (yypslr_layout_buffer); + yypslr_layout_buffer = buffer; + yypslr_layout_capacity = capacity; + } + memcpy (yypslr_layout_buffer + yypslr_layout_length, text, (size_t) length); yypslr_layout_length += length; yypslr_layout_buffer[yypslr_layout_length] = '\\0'; @@ -1068,16 +1179,17 @@ def pslr_token_action_function lines << "" lines << "#define yylval (*yylvalp)" lines << "static void" - lines << "yypslr_token_action (int token, const char *yytext, int yyleng, YYSTYPE *yylvalp)" + lines << "yypslr_token_action (int yytoken, const char *yytext, int yyleng, YYSTYPE *yylvalp#{lex_param.empty? ? "" : ", #{lex_param}"})" lines << "{" lines << " YY_USE (yytext);" lines << " YY_USE (yyleng);" lines << " YY_USE (yylvalp);" + lines << " YY_USE (#{lex_param_name});" unless lex_param.empty? @grammar.token_actions.each_with_index do |action, idx| token_id = @context.states.find_symbol_by_s_value!(action.token_name).token_id keyword = idx == 0 ? "if" : "else if" - lines << " #{keyword} (token == #{token_id})" + lines << " #{keyword} (yytoken == #{token_id})" lines << " {" lines << "#line #{action.lineno} \"#{@grammar_file_path}\"" lines << " {#{action.code.s_value}}" @@ -1088,8 +1200,8 @@ def pslr_token_action_function lines << "}" lines << "#undef yylval" lines << "" - lines << "#define YYPSLR_TOKEN_ACTION(Token, Text, Len, LvalPtr) \\" - lines << " yypslr_token_action ((Token), (Text), (Len), (LvalPtr))" + lines << "#define YYPSLR_TOKEN_ACTION(yyToken, yyText, yyLen, yyLvalPtr) \\" + lines << " yypslr_token_action ((yyToken), (yyText), (yyLen), (yyLvalPtr)#{lex_param.empty? ? "" : ", #{lex_param_name}"})" lines.join("\n") end @@ -1110,44 +1222,45 @@ def pslr_layout_scan_function * trailing layout can be recovered (paper section 3.6). */ int - yypslr_scan_with_layout (int parser_state, const char **input, - size_t *input_len, YYSTYPE *yylvalp, - yypslr_scan_result *result) + yypslr_scan_with_layout (int yyparser_state, const char **yyinput, + size_t *yyinput_len, YYSTYPE *yylvalp, + yypslr_scan_result *yyresult#{lex_param.empty? ? "" : ", #{lex_param}"}) { YYPSLR_LAYOUT_CLEAR (); YY_USE (yylvalp); + #{lex_param.empty? ? "" : " YY_USE (#{lex_param_name});"} for (;;) { - int token = yy_pseudo_scan_result (parser_state, *input, *input_len, result); + int yytoken = yy_pseudo_scan_result (yyparser_state, *yyinput, *yyinput_len, yyresult); - if (token == YYEMPTY) - return token; + if (yytoken == YYEMPTY) + return yytoken; - if (token == #{eof_symbol.id.s_value}) + if (yytoken == #{eof_symbol.id.s_value}) { - #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, 0, yylvalp);" : ""} - return token; + #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (yytoken, *yyinput, 0, yylvalp);" : ""} + return yytoken; } - if (result->is_layout) + if (yyresult->is_layout) { - if (!YYPSLR_LAYOUT_APPEND (*input, result->length)) + if (!YYPSLR_LAYOUT_APPEND (*yyinput, yyresult->length)) { - result->token = YYUNDEF; - result->is_layout = 0; - result->is_character_token = 0; - result->from_fallback = 0; - return result->token; + yyresult->token = YYUNDEF; + yyresult->is_layout = 0; + yyresult->is_character_token = 0; + yyresult->from_fallback = 0; + return yyresult->token; } - #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, result->length, yylvalp);" : ""} - *input += result->length; - *input_len -= (size_t)result->length; + #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (yytoken, *yyinput, yyresult->length, yylvalp);" : ""} + *yyinput += yyresult->length; + *yyinput_len -= (size_t)yyresult->length; continue; } - #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (token, *input, result->length, yylvalp);" : ""} - return token; + #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (yytoken, *yyinput, yyresult->length, yylvalp);" : ""} + return yytoken; } } C_CODE @@ -1210,7 +1323,7 @@ def pslr_generated_lexer_function &yypslr_input_cursor, &yypslr_input_remain, yylvalp, - &yypslr_result); + &yypslr_result#{lex_param.empty? ? "" : ", #{lex_param_name}"}); yypslr_length = yypslr_result.length; C_CODE else @@ -1234,6 +1347,7 @@ def pslr_generated_lexer_function void yypslr_set_input (const char *input, size_t input_len) { + YYPSLR_LAYOUT_CLEAR (); yypslr_input_cursor = input; yypslr_input_remain = input_len; yypslr_parser_state = 0; diff --git a/lib/lrama/reporter/pslr.rb b/lib/lrama/reporter/pslr.rb index 411585d55..3be401e49 100644 --- a/lib/lrama/reporter/pslr.rb +++ b/lib/lrama/reporter/pslr.rb @@ -75,11 +75,24 @@ def report_scanner_accepts(io, states) io << " State #{state.id}: #{cells.join(' ')}\n" end - fallback_cells = accepting_states.map {|fsa_state| - token = scanner_accepts.fallback_table[fsa_state.id] - "ss#{fsa_state.id}=>#{token.name}" if token - }.compact - io << " Fallback: #{fallback_cells.join(' ')}\n" unless fallback_cells.empty? + path_dependent = scanner_accepts.fallback_profiles.any? do |profile| + profile.any? { |state_id, (_, token)| token && token != scanner_accepts.fallback_table[state_id] } + end + if path_dependent + io << " Fallback: starts in profile 0\n" + scanner_accepts.fallback_profiles.each_with_index do |profile, id| + cells = profile.map do |state_id, (next_id, token)| + "ss#{state_id}=>#{token ? token.name : 'keep'} (profile #{next_id})" + end + io << " profile #{id}: #{cells.join(' ')}\n" + end + else + fallback_cells = accepting_states.map {|fsa_state| + token = scanner_accepts.fallback_table[fsa_state.id] + "ss#{fsa_state.id}=>#{token.name}" if token + }.compact + io << " Fallback: #{fallback_cells.join(' ')}\n" unless fallback_cells.empty? + end io << "\n" end diff --git a/lib/lrama/scanner_fsa.rb b/lib/lrama/scanner_fsa.rb index 6cfee6f48..9471bda54 100644 --- a/lib/lrama/scanner_fsa.rb +++ b/lib/lrama/scanner_fsa.rb @@ -225,6 +225,8 @@ def build_nfa @token_patterns.each do |token_pattern| # Build NFA fragment for this pattern begin + raise PatternError, "duplicate pattern definition" if @pattern_references.key?(token_pattern.name) + start_state, end_state = compile_regex(token_pattern.regex_pattern, nfa_counter, nfa_states) rescue PatternError => e raise PatternError, @@ -332,6 +334,9 @@ def compile_sequence(pattern, pos, counter, states, stop_char) if fragments.empty? raise PatternError, "quantifier #{char} without preceding element at offset #{i}" end + if QUANTIFIERS.include?(pattern[i + 1]) + raise PatternError, "consecutive quantifiers are not supported at offset #{i + 1}" + end fragments << apply_quantifier(fragments.pop, char, counter, states) when '|' break @@ -350,6 +355,8 @@ def compile_sequence(pattern, pos, counter, states, stop_char) fragments << frag when ']' raise PatternError, "unmatched character class close at offset #{i}" + when '^', '$' + raise PatternError, "anchors are not supported at offset #{i}" else frag = compile_literal(char, counter, states) fragments << frag diff --git a/lib/lrama/state/scanner_accepts.rb b/lib/lrama/state/scanner_accepts.rb index 860000b5c..024a24c09 100644 --- a/lib/lrama/state/scanner_accepts.rb +++ b/lib/lrama/state/scanner_accepts.rb @@ -21,6 +21,7 @@ class State # length defaults are handled by LengthPrecedences#fallback_precedes?, # and otherwise-unresolved identity conflicts are resolved by token # declaration order. + # Fallback profile transitions retain the matching history when winners differ. # class ScannerAccepts class Conflict @@ -236,6 +237,7 @@ def token_order_key(token) class CompleteProfileComputer attr_reader :table #: Hash[Integer, Grammar::TokenPattern] attr_reader :conflicts #: Array[Conflict] + attr_reader :fallback_profiles #: Array[Hash[Integer, [Integer, Grammar::TokenPattern?]]] # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer], ?track_rule_usage: bool) -> void def initialize(scanner_fsa, lex_prec, length_prec, acceptable_tokens, parser_state_id = nil, fallback: false, token_order: {}, track_rule_usage: false) @@ -243,8 +245,12 @@ def initialize(scanner_fsa, lex_prec, length_prec, acceptable_tokens, parser_sta @resolver = ProfileResolver.new(lex_prec, length_prec, fallback: fallback, token_order: token_order, track_rule_usage: track_rule_usage) @acceptable_tokens = acceptable_tokens @parser_state_id = parser_state_id + @fallback = fallback @table = {} @conflicts = [] + @fallback_profiles = [] + @fallback_profile_ids = {} #: Hash[[Array[String], String?], Integer] + fallback_profile_id(Set.new, nil) if fallback @reported_conflict_profiles = Set.new token_patterns_by_name = {} #: Hash[String, Grammar::TokenPattern] @token_patterns_by_name = scanner_fsa.token_patterns.each_with_object(token_patterns_by_name) do |token_pattern, hash| @@ -298,9 +304,25 @@ def visit_state(fsa_state_id, shorter_tokens, selected_shorter_token, visited, p next_shorter_tokens = shorter_tokens | current_tokens next_selected = result.resolved? ? result.token_name : nil + if @fallback && !current_tokens.empty? + profile_id = fallback_profile_id(shorter_tokens, selected_shorter_token) + next_profile_id = fallback_profile_id(next_shorter_tokens, next_selected) + token = result.current_match? && result.token_name ? token_pattern_for(result.token_name) : nil + @fallback_profiles[profile_id][fsa_state_id] = [next_profile_id, token] + end visit_transitions(fsa_state_id, next_shorter_tokens, next_selected, visited, path) end + # @rbs (Set[String] shorter_tokens, String? selected_shorter_token) -> Integer + def fallback_profile_id(shorter_tokens, selected_shorter_token) + key = [shorter_tokens.to_a.sort, selected_shorter_token] #: [Array[String], String?] + @fallback_profile_ids.fetch(key) do + id = @fallback_profiles.size + @fallback_profiles << {} + @fallback_profile_ids[key] = id + end + end + # @rbs (ScannerFSA::State fsa_state) -> Set[String] def current_acceptable_tokens(fsa_state) fsa_state.accepting_tokens.each_with_object(Set.new) do |token_pattern, tokens| @@ -420,6 +442,7 @@ def outcomes_compatible?(left, right) attr_reader :table #: Hash[[Integer, Integer], Grammar::TokenPattern?] attr_reader :fallback_table #: Hash[Integer, Grammar::TokenPattern] + attr_reader :fallback_profiles #: Array[Hash[Integer, [Integer, Grammar::TokenPattern?]]] attr_reader :conflicts #: Array[Conflict] # @rbs (Array[State] parser_states, ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?Grammar::LexTie? lex_tie, symbols: Array[Grammar::Symbol], ?layout_token_names: Set[String]) -> void @@ -433,6 +456,7 @@ def initialize(parser_states, scanner_fsa, lex_prec, length_prec, lex_tie = nil, @layout_token_names = layout_token_names.to_set @table = {} @fallback_table = {} + @fallback_profiles = [] @conflicts = [] end @@ -505,8 +529,16 @@ def compute_fallback_row token_order: token_order ) computer.compute + @fallback_profiles = computer.fallback_profiles - computer.table.each do |scanner_state_id, token_pattern| + # Only history-independent winners belong in the flat diagnostic row. + @scanner_fsa.states.each do |state| + tokens = @fallback_profiles.map do |profile| + profile[state.id] + end.compact.map(&:last).uniq + next unless tokens.size == 1 && (token_pattern = tokens.first) + + scanner_state_id = state.id @fallback_table[scanner_state_id] = token_pattern @table[[FALLBACK_ROW_ID, scanner_state_id]] = token_pattern end diff --git a/lib/lrama/states.rb b/lib/lrama/states.rb index 3709d565c..9083d1d42 100644 --- a/lib/lrama/states.rb +++ b/lib/lrama/states.rb @@ -293,7 +293,7 @@ def lexer_context_enabled? def compute_la_sources_for_conflicted_states reflexive = {} - reachable_parser_states.each do |state| + @states.each do |state| state.nterm_transitions.each do |goto| reflexive[goto] = [goto] end @@ -552,11 +552,15 @@ def compute_la end @states.each do |state| + needs_look_ahead = !(state.reduces.count == 1 && state.term_transitions.count == 0) + if needs_look_ahead + # Splitting can leave reductions without any lookback paths. + state.reduces.each { |reduce| reduce.look_ahead = [] } + end + lookback_relation_on_state = @lookback_relation[state.id] next unless lookback_relation_on_state - needs_look_ahead = !(state.reduces.count == 1 && state.term_transitions.count == 0) - lookback_relation_on_state.each do |rule_id, ary| look_ahead = 0 diff --git a/sig/generated/lrama/state/scanner_accepts.rbs b/sig/generated/lrama/state/scanner_accepts.rbs index 443c4ed90..50ea57bf1 100644 --- a/sig/generated/lrama/state/scanner_accepts.rbs +++ b/sig/generated/lrama/state/scanner_accepts.rbs @@ -18,6 +18,7 @@ module Lrama # length defaults are handled by LengthPrecedences#fallback_precedes?, # and otherwise-unresolved identity conflicts are resolved by token # declaration order. + # Fallback profile transitions retain the matching history when winners differ. class ScannerAccepts class Conflict attr_reader parser_state_id: Integer? @@ -114,6 +115,8 @@ module Lrama attr_reader conflicts: Array[Conflict] + attr_reader fallback_profiles: Array[Hash[Integer, [ Integer, Grammar::TokenPattern? ]]] + # @rbs (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer], ?track_rule_usage: bool) -> void def initialize: (ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, Set[String] acceptable_tokens, ?Integer? parser_state_id, ?fallback: bool, ?token_order: Hash[String, Integer], ?track_rule_usage: bool) -> void @@ -128,6 +131,9 @@ module Lrama # @rbs (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited, String path) -> void def visit_state: (Integer fsa_state_id, Set[String] shorter_tokens, String? selected_shorter_token, Set[untyped] visited, String path) -> void + # @rbs (Set[String] shorter_tokens, String? selected_shorter_token) -> Integer + def fallback_profile_id: (Set[String] shorter_tokens, String? selected_shorter_token) -> Integer + # @rbs (ScannerFSA::State fsa_state) -> Set[String] def current_acceptable_tokens: (ScannerFSA::State fsa_state) -> Set[String] @@ -169,6 +175,8 @@ module Lrama attr_reader fallback_table: Hash[Integer, Grammar::TokenPattern] + attr_reader fallback_profiles: Array[Hash[Integer, [ Integer, Grammar::TokenPattern? ]]] + attr_reader conflicts: Array[Conflict] # @rbs (Array[State] parser_states, ScannerFSA scanner_fsa, Grammar::LexPrec lex_prec, LengthPrecedences length_prec, ?Grammar::LexTie? lex_tie, symbols: Array[Grammar::Symbol], ?layout_token_names: Set[String]) -> void diff --git a/spec/lrama/error_symbol_runtime_spec.rb b/spec/lrama/error_symbol_runtime_spec.rb new file mode 100644 index 000000000..f0c05d21b --- /dev/null +++ b/spec/lrama/error_symbol_runtime_spec.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "declared error symbol runtime" do + [false, true].each do |typed| + it "compiles and recovers with a #{typed ? 'typed' : 'plain'} error token declaration" do + Dir.mktmpdir("lrama-error-symbol") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + executable = File.join(dir, "parser") + File.write(grammar, <<~GRAMMAR) + #{typed ? '%union { int value; }' : ''} + %token #{typed ? '' : ''} error + %token A + %code provides { + static int yyerror(YYLTYPE *loc, const char *message) + { + (void)loc; + (void)message; + return 0; + } + static int yylex(YYSTYPE *value) + { + static int index = 0; + static int tokens[] = { YYUNDEF, A, YYEOF }; + (void)value; + return tokens[index++]; + } + } + %% + start: error A { #{typed ? '$1 = 7;' : ''} yyerrok; }; + %% + int main(void) { return yyparse(); } + GRAMMAR + Lrama::Command.new(["-o", output, grammar]).run + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", output, "-o", executable) + expect(status.success?).to be(true), err + _out, err, status = Open3.capture3(executable) + expect(status.success?).to be(true), err + end + end + end +end diff --git a/spec/lrama/fallback_profiles_runtime_spec.rb b/spec/lrama/fallback_profiles_runtime_spec.rb new file mode 100644 index 000000000..9bad828f6 --- /dev/null +++ b/spec/lrama/fallback_profiles_runtime_spec.rb @@ -0,0 +1,65 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "generated fallback scanner profiles" do + it "resolves fallback precedence from the matches on the actual input path" do + Dir.mktmpdir("lrama-fallback") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + executable = File.join(dir, "parser") + File.write(grammar, <<~'GRAMMAR') + %code provides { + #include + #include + static int yyerror(YYLTYPE *loc, const char *message) { + (void)loc; (void)message; return 0; + } + } + %define lr.type pslr + %define api.pslr.lexer generated + %token-pattern A /aa/ + %token-pattern B /a+b/ + %token-pattern C /a+b/ + %token-pattern SHORT /d/ + %token-pattern LONG /d+/ + %token-pattern REPEAT /f+/ + %token-pattern SELF /e+/ + %lex-prec C << A + %lex-prec B <- C + %lex-prec A -~ B + %lex-prec SHORT -s LONG + %lex-prec SELF -s SELF + %% + start: 'x' A | 'y' B | 'z' C | 'u' SHORT | 'v' LONG | 'w' REPEAT | 't' SELF; + %% + int main(void) { + const char *inputs[] = {"ab", "aab", "aaaaab", "aaaaa", "dddddd", "ffffff", "eeeeee"}; + const int expected[] = {C, B, B, A, SHORT, REPEAT, SELF}; + const int lengths[] = {2, 3, 6, 2, 1, 6, 1}; + int i; + for (i = 0; i < 7; i++) { + yypslr_scan_result result; + int token = yy_pseudo_scan_result(0, inputs[i], strlen(inputs[i]), &result); + if (token != expected[i] || result.length != lengths[i] || !result.from_fallback) { + printf("%s: token %d (expected %d), length %d\n", inputs[i], token, expected[i], result.length); + return 1; + } + } + yypslr_set_input("yab", 3); + if (yyparse()) return 2; + yypslr_set_input("zaab", 4); + return yyparse(); + } + GRAMMAR + Lrama::Command.new(["-o", output, grammar]).run + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", output, "-o", executable) + expect(status.success?).to be(true), err + out, err, status = Open3.capture3(executable) + expect(status.success?).to be(true), out + err + end + end +end diff --git a/spec/lrama/generated_runtime_spec.rb b/spec/lrama/generated_runtime_spec.rb index 6b191ff97..d392a8ba6 100644 --- a/spec/lrama/generated_runtime_spec.rb +++ b/spec/lrama/generated_runtime_spec.rb @@ -106,7 +106,7 @@ def with_parser(source, flags: []) int main(void) { #{type == "pslr" ? 'yypslr_set_input("a", 1);' : ""} if (yyparse()) return 1; - return #{custom_copy ? 'copy_count == 0' : '0'}; + return #{custom_copy ? 'copy_count != 0' : '0'}; } GRAMMAR _out, err, status = Open3.capture3(parser) @@ -181,6 +181,33 @@ def with_parser(source, flags: []) end end + it "clears layout text for adjacent tokens and EOF and after replacing input" do + with_parser(<<~'GRAMMAR') do |parser| + %code provides { #include } + %define lr.type pslr + %define api.pslr.lexer generated + %token-pattern A /a/ + %token-pattern B /b/ + %token-pattern YYLAYOUT_WS / +/ + %token-action A { printf("A %d:[%s]\n", YYPSLR_LAYOUT_LENGTH, YYPSLR_LAYOUT_TEXT); } + %token-action B { printf("B %d:[%s]\n", YYPSLR_LAYOUT_LENGTH, YYPSLR_LAYOUT_TEXT); } + %token-action YYEOF { printf("EOF %d:[%s]\n", YYPSLR_LAYOUT_LENGTH, YYPSLR_LAYOUT_TEXT); } + %% + start: A B; + %% + int main(void) { + yypslr_set_input(" ab", 3); + if (yyparse()) return 1; + yypslr_set_input("a b ", 4); + return yyparse(); + } + GRAMMAR + out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + expect(out).to eq("A 1:[ ]\nB 0:[]\nEOF 0:[]\nA 0:[]\nB 1:[ ]\nEOF 1:[ ]\n") + end + end + it "generates an EOF lexer with locations for an empty token universe and consumes unexpected bytes" do with_parser(<<~GRAMMAR) do |parser| %define lr.type pslr diff --git a/spec/lrama/grammar_spec.rb b/spec/lrama/grammar_spec.rb index fc66d1c6e..c5b5af35f 100644 --- a/spec/lrama/grammar_spec.rb +++ b/spec/lrama/grammar_spec.rb @@ -419,6 +419,61 @@ def build_pslr_grammar(source) expect(grammar.lex_tie.tied?("A", "B")).to be true end + it "preserves transitive ties through terminals without scanner patterns" do + grammar = build_pslr_grammar(<<~GRAMMAR) + %define lr.type pslr + %token ID NAME + %token-pattern IF /if/ + %lex-tie ID NAME + %lex-tie NAME IF + %lex-no-tie yyall yyall + %% + start: ID | NAME | IF ; + GRAMMAR + + grammar.finalize_lexical_ties!(Lrama::ScannerFSA.new(grammar.token_patterns)) + + %w[ID NAME IF].each do |name| + expect(grammar.lex_tie.tied_names(name)).to contain_exactly("ID", "NAME", "IF") + end + end + + it "rejects no-ties conflicting with transitive ties through external terminals" do + grammar = build_pslr_grammar(<<~GRAMMAR) + %define lr.type pslr + %token ID NAME + %token-pattern IF /if/ + %lex-tie ID NAME + %lex-tie NAME IF + %lex-no-tie ID IF + %% + start: ID | NAME | IF ; + GRAMMAR + + expect do + grammar.finalize_lexical_ties!(Lrama::ScannerFSA.new(grammar.token_patterns)) + end.to raise_error(RuntimeError, /%lex-no-tie ID IF conflicts/) + end + + it "includes patterns tied to external terminals in normal scanner rows" do + grammar = build_pslr_grammar(<<~GRAMMAR) + %define lr.type pslr + %token ID + %token-pattern IF /if/ + %token-pattern OTHER /[a-z]+/ + %lex-tie ID IF + %lex-prec OTHER <~ IF + %% + start: ID | OTHER ; + GRAMMAR + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + + accepting = states.scanner_fsa.states.find { |state| state.accepting_tokens.any? { |token| token.name == "IF" } } + expect(states.scanner_accepts_table[0, accepting.id].name).to eq("IF") + end + ["lex-tie", "lex-no-tie"].each do |directive| ['"if"', "keywords"].each do |operand| it "resolves #{directive} aliases in #{operand}" do diff --git a/spec/lrama/integration_spec.rb b/spec/lrama/integration_spec.rb index 1d1144523..94fe9916a 100644 --- a/spec/lrama/integration_spec.rb +++ b/spec/lrama/integration_spec.rb @@ -448,15 +448,16 @@ def compile_pure_parser(layout_buffer_size: nil) expect(status.success?).to be false end - it "fails instead of discarding layout that exceeds the layout buffer" do + it "grows the initial layout buffer to retain longer layout" do obj_path = compile_pure_parser(layout_buffer_size: 4) out, _err, status = Open3.capture3(obj_path, " 1") expect(status.success?).to be true expect(out).to eq("=> 1\n") - _out, _err, status = Open3.capture3(obj_path, " 1") - expect(status.success?).to be false + out, _err, status = Open3.capture3(obj_path, " 1") + expect(status.success?).to be true + expect(out).to eq("=> 1\n") end it "computes canonical LR(1) tables when pslr.tables is canonical-lr" do diff --git a/spec/lrama/lac_runtime_spec.rb b/spec/lrama/lac_runtime_spec.rb new file mode 100644 index 000000000..10c6ae667 --- /dev/null +++ b/spec/lrama/lac_runtime_spec.rb @@ -0,0 +1,206 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "LAC runtime" do + def with_lac_parser(source, instrument: false, flags: []) + Dir.mktmpdir("lrama-lac") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + executable = File.join(dir, "parser") + File.write(grammar, <<~GRAMMAR + source) + %define parse.lac full + %code provides { + static int yyerror(YYLTYPE *loc, const char *message) + { (void)loc; (void)message; return 0; } + } + GRAMMAR + Lrama::Command.new(["-o", output, grammar]).run + if instrument + code = File.read(output) + expect(code.sub!(/(yy_lac_check_ \([^\n]*\)\n\{)/, "\\1\n if (yytoken == YYSYMBOL_YYEOF) eof_checks++;")).not_to be_nil + File.write(output, code) + end + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", *flags, output, "-o", executable) + expect(status.success?).to be(true), err + yield executable + end + end + + it "does not copy the parser stack or repeatedly validate unchanged lookahead" do + with_lac_parser(<<~'GRAMMAR', instrument: true) do |parser| + %code provides { + #include + #include + #include + #define YYINITDEPTH 2048 + static long copied_states = 0, allocations = 0, eof_checks = 0; + #define YYCOPY(Dst, Src, Count) (copied_states += (Count), memcpy((Dst), (Src), (Count) * sizeof(*(Src)))) + #define YYMALLOC(Size) (allocations++, malloc(Size)) + static int remaining; + } + %token A + %code provides { + static int yylex(YYSTYPE *value) + { (void)value; return remaining-- > 0 ? A : YYEOF; } + } + %% + start: list; + list: %empty | A list; + %% + int main(void) { + int lengths[] = {256, 1024}; + int i; + for (i = 0; i < 2; i++) { + copied_states = allocations = eof_checks = 0; + remaining = lengths[i]; + if (yyparse()) return 1; + printf("%ld %ld %ld\n", copied_states, allocations, eof_checks); + } + return 0; + } + GRAMMAR + out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + expect(out).to eq("0 0 1\n0 0 1\n") + end + end + + it "revalidates lookahead changed by a semantic action before further reductions" do + with_lac_parser(<<~'GRAMMAR') do |parser| + %code provides { static int reduced = 0; } + %token A B C + %code provides { + static int yylex(YYSTYPE *value) { + static int tokens[] = {A, B, YYEOF}; + static int i = 0; + (void)value; + return tokens[i++]; + } + } + %% + start: mid B; + mid: prefix { reduced++; }; + prefix: A { yychar = C; }; + %% + int main(void) { return yyparse() == 1 && reduced == 0 ? 0 : 1; } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + + it "revalidates a new lookahead after yyclearin even when its token kind is unchanged" do + with_lac_parser(<<~'GRAMMAR', instrument: true) do |parser| + %code provides { static int eof_checks = 0; } + %token A + %code provides { + static int yylex(YYSTYPE *value) { + static int i = 0; + (void)value; + return i++ ? YYEOF : A; + } + } + %% + start: n; + n: A { yyclearin; }; + %% + int main(void) { return yyparse() || eof_checks != 2; } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + + it "revalidates YYBACKUP after it changes the stack while keeping the same lookahead kind" do + with_lac_parser(<<~'GRAMMAR', instrument: true) do |parser| + %code provides { static int eof_checks = 0, backed_up = 0, reduced = 0; } + %token A + %code provides { + static int yylex(YYSTYPE *value) { + static int i = 0; + (void)value; + return i++ ? YYEOF : A; + } + } + %% + start: n; + n: A { + if (!backed_up) { + backed_up = 1; + yyclearin; + YYBACKUP(YYEOF, 0); + } + reduced++; + } + | %empty { reduced++; }; + %% + int main(void) { return yyparse() || !backed_up || reduced != 1 || eof_checks != 2; } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + + it "grows speculative storage without changing the parser stack and reports allocation failure" do + with_lac_parser(<<~'GRAMMAR', flags: ["-DYYINITDEPTH=2"]) do |parser| + %code provides { + #include + #include + static int allocations = 0, releases = 0, copies = 0, fail = 0, reduced = 0; + #define YYMALLOC(Size) (fail ? 0 : (allocations++, malloc(Size))) + #define YYFREE(Ptr) (releases++, free(Ptr)) + #define YYCOPY(Dst, Src, Count) (copies++, memcpy((Dst), (Src), (Count) * sizeof(*(Src)))) + } + %token A + %code provides { + static int yylex(YYSTYPE *value) { + static int i = 0; + (void)value; + return i++ ? YYEOF : A; + } + } + %% + start: n n n n n A; + n: %empty { reduced++; }; + %% + int main(void) { + yy_state_t stack[] = {0}; + if (yy_lac_check_(stack, stack, YYSYMBOL_A) != 1) return 1; + if (!allocations || !copies || allocations != releases || stack[0] || reduced) return 2; + fail = 1; + if (yy_lac_check_(stack, stack, YYSYMBOL_A) != YYENOMEM) return 3; + if (stack[0] || reduced) return 4; + fail = 0; + if (yyparse() || reduced != 5) return 5; + return 0; + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + + it "respects YYMAXDEPTH when empty reductions grow the speculative stack" do + with_lac_parser(<<~'GRAMMAR', flags: ["-DYYMAXDEPTH=4"]) do |parser| + %token A + %code provides { + static int yylex(YYSTYPE *value) { (void)value; return YYEOF; } + } + %% + start: n n n n n A; + n: %empty; + %% + int main(void) { + yy_state_t stack[] = {0}; + return yy_lac_check_(stack, stack, YYSYMBOL_A) == YYENOMEM && stack[0] == 0 ? 0 : 1; + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end +end diff --git a/spec/lrama/layout_runtime_spec.rb b/spec/lrama/layout_runtime_spec.rb new file mode 100644 index 000000000..1b9c8cb13 --- /dev/null +++ b/spec/lrama/layout_runtime_spec.rb @@ -0,0 +1,140 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "PSLR layout storage" do + def with_parser(source) + Dir.mktmpdir("lrama-layout") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + executable = File.join(dir, "parser") + File.write(grammar, <<~GRAMMAR + source) + %define lr.type pslr + %define api.pslr.lexer generated + %code provides { + #include + #include + static int yyerror(YYLTYPE *loc, const char *message) + { (void)loc; (void)message; return 0; } + } + GRAMMAR + Lrama::Command.new(["-o", output, grammar]).run + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", output, "-o", executable) + expect(status.success?).to be(true), err + yield executable + end + end + + [false, true].each do |actions| + it "accepts layout beyond the initial buffer #{actions ? 'with' : 'without'} token actions" do + with_parser(<<~GRAMMAR) do |parser| + %define parse.lac none + %code provides { + #define YYSTACK_USE_ALLOCA 1 + static int expected; + static int invalid_layout; + } + %token-pattern A /a/ + %token-pattern YYLAYOUT_WS / +/ + %token-pattern YYLAYOUT_COMMENT /!+/ + #{actions ? <<~ACTIONS : ''} + %token-action A { + if (YYPSLR_LAYOUT_LENGTH != expected + || strlen(YYPSLR_LAYOUT_TEXT) != (size_t)expected) + invalid_layout = 1; + } + %token-action YYEOF { + if (YYPSLR_LAYOUT_LENGTH || YYPSLR_LAYOUT_TEXT[0]) invalid_layout = 1; + } + ACTIONS + %% + start: A; + %% + int main(int argc, char **argv) { + if (argc != 2) return 1; + expected = (int)strlen(argv[1]) - 1; + yypslr_set_input(argv[1], strlen(argv[1])); + if (yyparse() || invalid_layout) return 2; + expected = 0; + yypslr_set_input("a", 1); + return yyparse() || invalid_layout; + } + GRAMMAR + [" " * 4095, " " * 4096, " " * 32768, " !" * 8192].each do |layout| + _out, err, status = Open3.capture3(parser, layout + "a") + expect(status.success?).to be(true), "#{layout.bytesize} bytes: exit #{status.exitstatus}: #{err}" + end + end + end + end + + it "preserves long trailing layout for the EOF action and clears it when input is replaced" do + with_parser(<<~GRAMMAR) do |parser| + %code provides { static int trailing_length; } + %token-pattern A /a/ + %token-pattern YYLAYOUT_WS / +/ + %token-action YYEOF { + trailing_length = YYPSLR_LAYOUT_LENGTH; + if (strlen(YYPSLR_LAYOUT_TEXT) != (size_t)trailing_length) abort(); + } + %% + start: A; + %% + int main(void) { + char input[8194]; + input[0] = 'a'; + memset(input + 1, ' ', 8192); + input[8193] = 0; + yypslr_set_input(input, 8193); + if (yyparse() || trailing_length != 8192) return 1; + yypslr_set_input("a", 1); + if (YYPSLR_LAYOUT_LENGTH || YYPSLR_LAYOUT_TEXT[0]) return 2; + return yyparse() || trailing_length; + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), "exit #{status.exitstatus}: #{err}" + end + end + + it "preserves accumulated text on allocation failure and releases grown storage on clear" do + with_parser(<<~GRAMMAR) do |parser| + %define parse.lac none + %code provides { + #include + #define YYPSLR_LAYOUT_BUFFER_SIZE 4 + static int fail_allocation; + static int allocations; + static int releases; + #define YYMALLOC(Size) (fail_allocation ? 0 : (allocations++, malloc(Size))) + #define YYFREE(Ptr) (releases++, free(Ptr)) + } + %token-pattern A /a/ + %token-pattern YYLAYOUT_WS / +/ + %% + start: A; + %% + int main(void) { + if (!YYPSLR_LAYOUT_APPEND(" ", 2)) return 1; + if (YYPSLR_LAYOUT_APPEND("", -1) || YYPSLR_LAYOUT_APPEND("", INT_MAX)) return 2; + fail_allocation = 1; + if (YYPSLR_LAYOUT_APPEND("!!!", 3)) return 3; + if (YYPSLR_LAYOUT_LENGTH != 2 || strcmp(YYPSLR_LAYOUT_TEXT, " ")) return 4; + fail_allocation = 0; + if (!YYPSLR_LAYOUT_APPEND("!!!", 3)) return 5; + if (YYPSLR_LAYOUT_LENGTH != 5 || strcmp(YYPSLR_LAYOUT_TEXT, " !!!")) return 6; + YYPSLR_LAYOUT_CLEAR(); + if (allocations != 1 || releases != 1 || YYPSLR_LAYOUT_TEXT[0]) return 7; + fail_allocation = 1; + yypslr_set_input(" a", 5); + return yyparse() != 1; + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), "exit #{status.exitstatus}: #{err}" + end + end +end diff --git a/spec/lrama/lexer_context_classifier_spec.rb b/spec/lrama/lexer_context_classifier_spec.rb index 0ad703ca1..c69d40d05 100644 --- a/spec/lrama/lexer_context_classifier_spec.rb +++ b/spec/lrama/lexer_context_classifier_spec.rb @@ -136,6 +136,27 @@ def build_classifier_with_contexts end describe "#classify with grammar-defined contexts" do + [false, true].each do |context_first| + it "resolves context aliases declared #{context_first ? 'before' : 'after'} their tokens" do + context = '%lexer-context END "a"' + grammar = build_grammar(<<~GRAMMAR, "lexer_context/alias.y") + %define lr.type pslr + #{context if context_first} + %token A "a" B + #{context unless context_first} + %lexer-context ALSO_END A + %% + start: A B; + GRAMMAR + states = Lrama::States.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + states.compute + states.compute_pslr + + target = states.states.first.term_transitions.find { |shift| shift.next_sym.id.s_value == "A" }.to_state + expect(target.lexer_context).to eq(3) + end + end + context "with %lexer-context directives" do let(:grammar) do build_grammar(<<~GRAMMAR, "lexer_context/basic.y") diff --git a/spec/lrama/lexer_context_runtime_spec.rb b/spec/lrama/lexer_context_runtime_spec.rb new file mode 100644 index 000000000..d797055c6 --- /dev/null +++ b/spec/lrama/lexer_context_runtime_spec.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "external lexer contexts" do + [false, true].product([:identifier, :alias_before, :alias_after]).each do |patterns, operand| + it "exports #{operand} context declarations to a separate lexer #{patterns ? 'with' : 'without'} scanner patterns" do + Dir.mktmpdir("lrama-lexer-context") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + lexer = File.join(dir, cpp ? "lexer.cpp" : "lexer.c") + executable = File.join(dir, "parser") + File.write(grammar, <<~GRAMMAR) + %define lr.type pslr + %define api.pslr.state-member current_state + %parse-param {struct parse_params *p} + %lex-param {struct parse_params *p} + %code requires { + struct parse_params { int current_state; int reads; }; + } + %code provides { + int yylex(YYSTYPE *value, struct parse_params *p); + int yyerror(YYLTYPE *loc, struct parse_params *p, const char *message); + } + #{'%lexer-context BEG "a"' if operand == :alias_before} + %token A "a" B + #{patterns ? "%token-pattern A /a/\n%token-pattern B /b/" : ''} + #{operand == :identifier ? '%lexer-context BEG A' : '%lexer-context BEG "a"' unless operand == :alias_before} + %lexer-context END B + #{(2...64).map { |i| "%lexer-context C#{i} A" }.join("\n")} + %% + start: A B; + %% + int yyerror(YYLTYPE *loc, struct parse_params *p, const char *message) + { + (void)loc; (void)p; (void)message; + return 0; + } + GRAMMAR + File.write(lexer, <<~C_CODE) + #include "parser.h" + #include "parser.h" + + int yylex(YYSTYPE *value, struct parse_params *p) + { + (void)value; + switch (p->reads++) { + case 0: return A; + case 1: + if (!yy_lexer_context_is(p->current_state, YY_CTX_BEG) + || !yy_lexer_context_is(p->current_state, YY_CTX_C63) + || yy_lexer_context_is(p->current_state, YY_CTX_END)) + return YYUNDEF; + return B; + default: return YYEOF; + } + } + + int main(void) + { + struct parse_params params = { 0, 0 }; + if (yy_lexer_context_is(-1, YY_CTX_BEG)) return 1; + if (yyparse(¶ms)) return 2; + return params.reads != 3; + } + C_CODE + Lrama::Command.new(["-d", "-o", output, grammar]).run + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", output, lexer, "-o", executable) + expect(status.success?).to be(true), err + _out, err, status = Open3.capture3(executable) + expect(status.success?).to be(true), err + end + end + end +end diff --git a/spec/lrama/lexer_params_runtime_spec.rb b/spec/lrama/lexer_params_runtime_spec.rb new file mode 100644 index 000000000..523e1c06b --- /dev/null +++ b/spec/lrama/lexer_params_runtime_spec.rb @@ -0,0 +1,124 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "PSLR lexer parameter runtime" do + def run_parser(source, lexer: nil) + Dir.mktmpdir("lrama-lexer-params") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + executable = File.join(dir, "parser") + File.write(grammar, source) + Lrama::Command.new(["-d", "-o", output, grammar]).run + sources = [output] + if lexer + lexer_path = File.join(dir, cpp ? "lexer.cpp" : "lexer.c") + File.write(lexer_path, lexer) + sources << lexer_path + end + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", *sources, "-o", executable) + expect(status.success?).to be(true), err + _out, err, status = Open3.capture3(executable) + expect(status.success?).to be(true), "exit #{status.exitstatus}: #{err}" + end + end + + %w[counter token input result parser_state input_len Token].product([false, true]).each do |parameter, locations| + it "passes lexer parameter #{parameter} to token, layout and EOF actions #{locations ? 'with' : 'without'} locations" do + run_parser(<<~GRAMMAR) + %define lr.type pslr + %define api.pslr.lexer generated + #{locations ? '%locations' : ''} + %lex-param {int *#{parameter}} + %parse-param {int *#{parameter}} + %code provides { + static int yyerror(YYLTYPE *loc, int *counter, const char *message) + { (void)loc; (void)counter; (void)message; return 0; } + } + %token-pattern A /a/ + %token-pattern YYLAYOUT_WS / +/ + %token-action A { yylval = ++*#{parameter}; } + %token-action YYLAYOUT_WS { ++*#{parameter}; } + %token-action YYEOF { ++*#{parameter}; } + %% + start: A { if ($1 != 2) YYABORT; }; + %% + int main(void) { + int counter = 0; + yypslr_set_input(" a ", 3); + return yyparse(&counter) || counter != 4; + } + GRAMMAR + end + end + + it "passes a lexer parameter to the EOF action without scanner patterns" do + run_parser(<<~GRAMMAR) + %define lr.type pslr + %define api.pslr.lexer generated + %lex-param {int *counter} + %parse-param {int *counter} + %code provides { + static int yyerror(YYLTYPE *loc, int *counter, const char *message) + { (void)loc; (void)counter; (void)message; return 0; } + } + %token-action YYEOF { ++*counter; } + %% + start: %empty; + %% + int main(void) { + int counter = 0; + yypslr_set_input("", 0); + return yyparse(&counter) || counter != 1; + } + GRAMMAR + end + + it "forwards a separately compiled bridge lexer's parameter through the layout macro" do + lexer = <<~C_CODE + #include "parser.h" + + int yylex(YYSTYPE *value, struct lexer_state *Result) { + yypslr_scan_result result; + int token = YYPSLR_SCAN_WITH_LAYOUT(Result->current_state, &Result->input, &Result->remaining, value, &result); + if (token != YYEOF && token != YYEMPTY) { + Result->input += result.length; + Result->remaining -= result.length; + } + return token; + } + C_CODE + run_parser(<<~GRAMMAR, lexer: lexer) + %define lr.type pslr + %define api.pslr.state-member current_state + %lex-param {struct lexer_state *Result} + %parse-param {struct lexer_state *Result} + %code requires { + #include + struct lexer_state { int current_state; int counter; const char *input; size_t remaining; }; + } + %code provides { + int yylex(YYSTYPE *value, struct lexer_state *p); + int yyerror(YYLTYPE *loc, struct lexer_state *p, const char *message); + } + %token-pattern A /a/ + %token-pattern YYLAYOUT_WS / +/ + %token-action A { yylval = ++Result->counter; } + %token-action YYLAYOUT_WS { ++Result->counter; } + %token-action YYEOF { ++Result->counter; } + %% + start: A { if ($1 != 2) YYABORT; }; + %% + int yyerror(YYLTYPE *loc, struct lexer_state *p, const char *message) + { (void)loc; (void)p; (void)message; return 0; } + + int main(void) { + struct lexer_state state = { 0, 0, " a ", 3 }; + return yyparse(&state) || state.counter != 4; + } + GRAMMAR + end +end diff --git a/spec/lrama/output_spec.rb b/spec/lrama/output_spec.rb index 79b489259..b6ddc3c18 100644 --- a/spec/lrama/output_spec.rb +++ b/spec/lrama/output_spec.rb @@ -470,7 +470,7 @@ expect(result).to include("parser_state") expect(result).to include("match_length") expect(result).to include("yy_token_pattern_to_token_id") - expect(result).to include("yy_pslr_fallback_length_precedes") + expect(result).to include("yy_scanner_fallback_next[fallback_profile][sa]") expect(result).to include("result->token = YYEOF") end @@ -512,28 +512,29 @@ expect(result).to include("yy_lac_check_") expect(result).to include("yydefact") - expect(result.scan("return YYENOMEM;").size).to eq(3) + expect(result).to include("YYENOMEM") end end describe "#pslr_layout_declarations" do - it "reports layout buffer overflow without signed addition" do + it "checks layout length before growing the buffer" do result = pslr_output.pslr_layout_declarations expect(result).to include("static int\nyypslr_layout_append") - expect(result).to include("(size_t) length >= (size_t) YYPSLR_LAYOUT_BUFFER_SIZE") + expect(result).to include("length > INT_MAX - yypslr_layout_length") + expect(result).to include("YYMALLOC (capacity)") expect(result).not_to include("yypslr_layout_length + length") end end describe "#pslr_layout_scan_function" do - it "returns an undefined token while preserving the matched length when layout does not fit" do + it "returns an undefined token while preserving the matched length when layout allocation fails" do result = pslr_output.pslr_layout_scan_function expect(result).to include("if (!YYPSLR_LAYOUT_APPEND") - expect(result).to include("result->token = YYUNDEF;") - expect(result).not_to include("result->length = 0;") - expect(result).to include("result->is_layout = 0;") + expect(result).to include("yyresult->token = YYUNDEF;") + expect(result).not_to include("yyresult->length = 0;") + expect(result).to include("yyresult->is_layout = 0;") end end @@ -609,7 +610,6 @@ it "generates length precedences table" do result = pslr_output.length_precedences_table_code expect(result).to include("yy_pslr_length_precedes") - expect(result).to include("yy_pslr_fallback_length_precedes") expect(result).to include("old_token") end @@ -631,7 +631,6 @@ result = pslr_output.length_precedences_table_code expect(result).to include("static const int yy_pslr_length_precedes[2][2] = {\n /* A */ {1, 0},") - expect(result).to include("static const int yy_pslr_fallback_length_precedes[2][2] = {\n /* A */ {1, 1},") end end @@ -709,7 +708,7 @@ expect(rendered).to include("yy_token_pattern_is_layout") expect(rendered).to include("yy_lac_check_") expect(rendered.index("enum { YYENOMEM = -2 };")).to be < rendered.index("yy_lac_check_") - expect(rendered.scan("if (yylac_status == YYENOMEM)").size).to eq(3) + expect(rendered.scan("if (yylac_status == YYENOMEM)").size).to eq(2) expect(rendered).to include("static int\nyy_state_accepts_token") expect(rendered).to include("static int\nyy_state_eventually_accepts_token") expect(rendered).to include("static int\nyy_state_deep_accepts_token") diff --git a/spec/lrama/pslr_split_state_runtime_spec.rb b/spec/lrama/pslr_split_state_runtime_spec.rb new file mode 100644 index 000000000..36e989244 --- /dev/null +++ b/spec/lrama/pslr_split_state_runtime_spec.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "PSLR output with unreachable split states" do + { + "partially populated reduction lookaheads" => { + patterns: "%token-pattern A /a/\n%token-pattern C /c/", + rules: "start: y; x: A A y | A x y; y: %empty | C x x | A;", + valid: ["", "a"], + invalid: ["aa", "c"] + }, + "unreachable lookahead-source transitions" => { + patterns: "%token-pattern A /a/\n%token-pattern B /b/\n%token-pattern C /c/", + rules: "start: C x y; x: A | B y; y: A x B | A B x;", + valid: ["caaab", "caaba", "cbaabaab"], + invalid: ["", "caab"] + } + }.each do |label, example| + [nil, "states", "pslr"].each do |report| + it "generates and runs #{label} with #{report || 'no'} report" do + Dir.mktmpdir("lrama-split-state") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + report_file = File.join(dir, "parser.output") + executable = File.join(dir, "parser") + File.write(grammar, <<~GRAMMAR) + %code provides { + #include + static int yyerror(YYLTYPE *loc, const char *message) + { + (void)loc; + (void)message; + return 0; + } + } + %define lr.type pslr + %define api.pslr.lexer generated + #{example.fetch(:patterns)} + %% + #{example.fetch(:rules)} + %% + int main(int argc, char **argv) { + if (argc != 2) return 2; + yypslr_set_input(argv[1], (int)strlen(argv[1])); + return yyparse(); + } + GRAMMAR + options = ["-o", output, grammar] + options += ["--report=#{report}", "--report-file=#{report_file}"] if report + Lrama::Command.new(options).run + if report + expect(File.read(report_file)).to include(report == "states" ? "State 0" : "PSLR Summary") + end + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", output, "-o", executable) + expect(status.success?).to be(true), err + example.fetch(:valid).each do |input| + _out, err, status = Open3.capture3(executable, input) + expect(status.exitstatus).to eq(0), "rejected #{input.inspect}: #{err}" + end + example.fetch(:invalid).each do |input| + _out, err, status = Open3.capture3(executable, input) + expect(status.exitstatus).to eq(1), "accepted #{input.inspect}: #{err}" + end + end + end + end + end +end diff --git a/spec/lrama/repair_default_reduction_runtime_spec.rb b/spec/lrama/repair_default_reduction_runtime_spec.rb new file mode 100644 index 000000000..1a56b67c5 --- /dev/null +++ b/spec/lrama/repair_default_reduction_runtime_spec.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "repair searches through default reductions" do + rules = { + "one reduction" => ["a: A { actions++; $$ = $1; };", 1], + "chained reductions" => ["a: b { actions++; $$ = $1; }; b: c { actions++; $$ = $1; }; c: A { actions++; $$ = $1; };", 3], + "nullable reductions" => ["a: A empty { actions++; $$ = $1 + $2; }; empty: %empty { actions++; $$ = 0; };", 2], + "nullable reductions requiring stack growth" => ["a: A #{(['empty'] * 110).join(' ')} { actions++; $$ = $1; }; empty: %empty { actions++; $$ = 0; };", 111] + } + + [["lalr", "full"], ["pslr", nil], ["lalr", "none"]].each do |type, lac| + rules.each do |description, (productions, action_count)| + it "inserts a missing token after #{description} with #{type} LAC #{lac || 'default'}" do + Dir.mktmpdir("lrama-repair-default-reduction") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + executable = File.join(dir, "parser") + File.write(grammar, <<~GRAMMAR) + %define lr.type #{type} + #{lac ? "%define parse.lac #{lac}" : ""} + %locations + %union { int value; } + %token-pattern A /a/ + %token-pattern B /b/ + %type a #{description == "chained reductions" ? "b c" : ""} #{productions.include?("empty:") ? "empty" : ""} + %error-token { + $$ = 29; + @$.first_line = @$.last_line = 3; + @$.first_column = 4; + @$.last_column = 5; + } B + %code provides { + static int reads = 0; + static int errors = 0; + static int actions = 0; + static int accepted = 0; + static int yyerror(YYLTYPE *location, const char *message) { + (void)location; + (void)message; + errors++; + return 0; + } + static int yylex(YYSTYPE *value, YYLTYPE *location) { + value->value = 17; + location->first_line = location->last_line = 1; + location->first_column = 1; + location->last_column = 2; + return reads++ ? YYEOF : A; + } + } + %% + start: a B { + if ($1 != 17 || $2 != 29 || actions != #{action_count}) YYABORT; + if (@1.first_line != 1 || @1.first_column != 1) YYABORT; + if (@2.first_line != 3 || @2.first_column != 4 || @2.last_line != 3 || @2.last_column != 5) YYABORT; + accepted++; + }; + #{productions} + %% + int main(void) { + return yyparse() || accepted != 1 || errors != 1 || reads != 2; + } + GRAMMAR + Lrama::Command.new(["-e", "-o", output, grammar]).run + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", output, "-o", executable) + expect(status.success?).to be(true), "#{status}: #{err}" + _out, err, status = Open3.capture3(executable) + expect(status.success?).to be(true), "#{status}: #{err}" + end + end + end + end +end diff --git a/spec/lrama/repair_replay_runtime_spec.rb b/spec/lrama/repair_replay_runtime_spec.rb new file mode 100644 index 000000000..59779b291 --- /dev/null +++ b/spec/lrama/repair_replay_runtime_spec.rb @@ -0,0 +1,80 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "repair token replay" do + [["lalr", "full"], ["pslr", nil], ["lalr", "none"]].each do |type, lac| + [false, true].each do |multiple| + it "replays #{multiple ? 'multiple repairs' : 'a repair'} and the saved lookahead with #{type} LAC #{lac || 'default'}" do + Dir.mktmpdir("lrama-repair-replay") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + executable = File.join(dir, "parser") + File.write(grammar, <<~GRAMMAR) + %define lr.type #{type} + #{lac ? "%define parse.lac #{lac}" : ""} + %locations + %union { int value; } + %token-pattern A /a/ + %token-pattern N /n/ + %token-pattern B /b/ + #{multiple ? "%token-pattern M /m/" : ""} + %type n #{multiple ? "m" : ""} + %error-token { + $$ = 22; + @$.first_line = @$.last_line = 3; + @$.first_column = 4; + @$.last_column = 5; + } N + #{multiple ? "%error-token { $$ = 44; @$.first_line = @$.last_line = 4; @$.first_column = 5; @$.last_column = 6; } M" : ""} + %code provides { + static int reads = 0; + static int errors = 0; + static int accepted = 0; + static int yyerror(YYLTYPE *location, const char *message) { + (void)location; + (void)message; + errors++; + return 0; + } + static int yylex(YYSTYPE *value, YYLTYPE *location) { + const int tokens[] = { A, B, YYEOF }; + const int values[] = { 11, 33, 0 }; + int index = reads < 3 ? reads : 2; + value->value = values[index]; + location->first_line = location->last_line = index ? 5 : 1; + location->first_column = index ? 6 : 2; + location->last_column = index ? 7 : 3; + reads++; + return tokens[index]; + } + } + %% + start: A n #{multiple ? "m" : ""} B { + if ($1 != 11 || $2 != 22 || $#{multiple ? 4 : 3} != 33) YYABORT; + if (@2.first_line != 3 || @2.first_column != 4 || @2.last_line != 3 || @2.last_column != 5) YYABORT; + if (@#{multiple ? 4 : 3}.first_line != 5 || @#{multiple ? 4 : 3}.first_column != 6 + || @#{multiple ? 4 : 3}.last_line != 5 || @#{multiple ? 4 : 3}.last_column != 7) YYABORT; + #{multiple ? "if ($3 != 44 || @3.first_line != 4 || @3.first_column != 5 || @3.last_line != 4 || @3.last_column != 6) YYABORT;" : ""} + accepted++; + }; + n: N; + #{multiple ? "m: M;" : ""} + %% + int main(void) { + return yyparse() || accepted != 1 || errors != 1 || reads != 3; + } + GRAMMAR + Lrama::Command.new(["-e", "-o", output, grammar]).run + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", output, "-o", executable) + expect(status.success?).to be(true), "#{status}: #{err}" + _out, err, status = Open3.capture3(executable) + expect(status.success?).to be(true), "#{status}: #{err}" + end + end + end + end +end diff --git a/spec/lrama/reporter/pslr_spec.rb b/spec/lrama/reporter/pslr_spec.rb index 7cbe4c3c3..c78271372 100644 --- a/spec/lrama/reporter/pslr_spec.rb +++ b/spec/lrama/reporter/pslr_spec.rb @@ -62,4 +62,25 @@ def build_states(source) expect(io.string).to eq("") end + + it "reports path-dependent fallback choices without a universal winner" do + states = build_states(<<~GRAMMAR) + %define lr.type pslr + %token-pattern A /aa/ + %token-pattern B /a+b/ + %token-pattern C /a+b/ + %lex-prec C << A + %lex-prec B <- C + %lex-prec A -~ B + %% + start: 'x' A | 'y' B | 'z' C; + GRAMMAR + io = StringIO.new + described_class.new(pslr: true, states: true).report(io, states) + fallback = io.string.split(" Fallback:").last + accepting = states.scanner_fsa.scan("ab").last[:state].id + + expect(fallback).to include("profile 0") + expect(fallback).to include("ss#{accepting}=>B", "ss#{accepting}=>C") + end end diff --git a/spec/lrama/scanner_fsa_spec.rb b/spec/lrama/scanner_fsa_spec.rb index 3242c93cd..a02d69454 100644 --- a/spec/lrama/scanner_fsa_spec.rb +++ b/spec/lrama/scanner_fsa_spec.rb @@ -169,9 +169,44 @@ def token_pattern(name, regex, lineno: 1, order: 0) expect(fsa.scan("éλ").last[:position]).to eq("éλ".bytesize) end end + + it "quantifies escaped literals, classes, and groups independently" do + { + "a\\?+" => "a???", + "a[?]+" => "a???", + "a(b+)?" => "abbb", + "ab*c+" => "abbccc" + }.each do |pattern, input| + fsa = Lrama::ScannerFSA.new([token_pattern("VALID", pattern)]) + + expect(fsa.scan(input).last[:position]).to eq(input.bytesize) + end + end + + it "matches escaped anchor characters and preserves character class syntax" do + { "\\^foo\\$" => "^foo$", "[$^]+" => "$^^$", "[^a]+" => "^$" }.each do |pattern, input| + fsa = Lrama::ScannerFSA.new([token_pattern("LITERAL", pattern)]) + + expect(fsa.scan(input).last[:position]).to eq(input.bytesize) + end + end end describe "pattern validation" do + ["^foo", "foo$", "^foo$", "f^oo", "fo$o", "(foo|^bar)", "(foo$)bar"].each do |pattern| + it "rejects unsupported anchors in #{pattern.inspect}" do + expect { Lrama::ScannerFSA.new([token_pattern("ANCHORED", pattern, lineno: 14)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /ANCHORED at line 14.*anchors are not supported.*offset/m) + end + end + + ["ab*?", "ab+?", "ab??", "ab**", "ab*+", "ab++", "ab+*", "ab?*", "ab?+", "a(b+?)"].each do |pattern| + it "rejects consecutive quantifiers in #{pattern.inspect}" do + expect { Lrama::ScannerFSA.new([token_pattern("BAD_REPEAT", pattern, lineno: 13)]) } + .to raise_error(Lrama::ScannerFSA::PatternError, /BAD_REPEAT at line 13.*consecutive quantifiers.*offset/m) + end + end + ["é", "λ", "[é]", "[^λ]", "[a-λ]"].each do |pattern| it "rejects non-ASCII pattern #{pattern.inspect} before building transitions" do expect { Lrama::ScannerFSA.new([token_pattern("NON_ASCII", pattern, lineno: 12)]) } @@ -220,6 +255,50 @@ def token_pattern(name, regex, lineno: 1, order: 0) end describe "{NAME} pattern references" do + ["a", "b", "{A}b"].each do |pattern| + it "rejects redefining A with /#{pattern}/ before expanding further references" do + patterns = [ + token_pattern("A", "a", order: 0), + token_pattern("A", pattern, lineno: 9, order: 1), + token_pattern("B", "{A}", lineno: 10, order: 2) + ] + + expect { Lrama::ScannerFSA.new(patterns) } + .to raise_error(Lrama::ScannerFSA::PatternError, /A at line 9.*duplicate pattern definition/m) + end + end + + it "rejects redefinitions that introduce indirect recursive references" do + patterns = [ + token_pattern("A", "a", order: 0), + token_pattern("B", "{A}b", order: 1), + token_pattern("A", "{B}c", lineno: 8, order: 2), + token_pattern("C", "{A}", order: 3) + ] + + expect { Lrama::ScannerFSA.new(patterns) } + .to raise_error(Lrama::ScannerFSA::PatternError, /A at line 8.*duplicate pattern definition/m) + end + + it "expands distinct patterns through multiple earlier references" do + patterns = [ + token_pattern("A", "a", order: 0), + token_pattern("B", "{A}b", order: 1), + token_pattern("C", "{B}{A}c", order: 2) + ] + + expect(Lrama::ScannerFSA.new(patterns).scan("abac").last) + .to include(token: patterns.last, position: 4) + end + + it "quantifies a reference to a quantified pattern" do + ref = token_pattern("REF", "b+", order: 0) + repeated = token_pattern("REPEATED", "a{REF}+", order: 1) + fsa = Lrama::ScannerFSA.new([ref, repeated]) + + expect(fsa.scan("abbb").last).to include(token: repeated, position: 4) + end + it "inlines the body of an earlier pattern" do com_start = token_pattern("COM_START", "\\/\\*[^*]*", order: 0) com = token_pattern("COM", "{COM_START}\\*\\/", order: 1) diff --git a/spec/lrama/scanner_termination_runtime_spec.rb b/spec/lrama/scanner_termination_runtime_spec.rb new file mode 100644 index 000000000..b74155c59 --- /dev/null +++ b/spec/lrama/scanner_termination_runtime_spec.rb @@ -0,0 +1,106 @@ +# frozen_string_literal: true + +require "open3" +require "tmpdir" + +RSpec.describe "generated scanner termination" do + def with_scanner(source) + Dir.mktmpdir("lrama-scanner-termination") do |dir| + compiler = ENV.fetch("COMPILER", "cc") + cpp = compiler.include?("++") + grammar = File.join(dir, "parser.y") + output = File.join(dir, cpp ? "parser.cpp" : "parser.c") + executable = File.join(dir, "parser") + File.write(grammar, <<~GRAMMAR + source) + %code provides { + #include + #include + static size_t scanner_steps; + static int yyerror(YYLTYPE *loc, const char *message) { + (void)loc; (void)message; return 0; + } + } + %define lr.type pslr + %define api.pslr.lexer generated + GRAMMAR + Lrama::Command.new(["-o", output, grammar]).run + source = File.read(output) + expect(source).to include("int next_ss = yy_scanner_transition[ss][c];") + source.sub!("int next_ss = yy_scanner_transition[ss][c];", "int next_ss = (scanner_steps++, yy_scanner_transition[ss][c]);") + File.write(output, source) + _out, err, status = Open3.capture3(compiler, cpp ? "-std=c++11" : "-std=c99", "-Werror", output, "-o", executable) + expect(status.success?).to be(true), err + out, err, status = Open3.capture3(executable) + expect(status.success?).to be(true), out + err + yield out if block_given? + end + end + + it "takes one scanner transition per shortest token in normal and fallback rows" do + with_scanner(<<~'GRAMMAR') do |out| + %token-pattern A /a+/ + %lex-prec A -s A + %% + start: %empty | start A; + %% + int main(void) { + char input[8192]; + size_t lengths[] = {4096, 8192}; + size_t i, j; + memset(input, 'a', sizeof input); + for (i = 0; i < 2; i++) { + scanner_steps = 0; + yypslr_set_input(input, lengths[i]); + if (yyparse()) return 1; + printf("%lu ", (unsigned long)scanner_steps); + scanner_steps = 0; + for (j = 0; j < lengths[i]; j++) { + yypslr_scan_result result; + if (yy_pseudo_scan_result(YYFINAL, input + j, lengths[i] - j, &result) != A + || result.length != 1 || !result.from_fallback) return 2; + } + printf("%lu\n", (unsigned long)scanner_steps); + } + return 0; + } + GRAMMAR + expect(out).to eq("4096 4096\n8192 8192\n") + end + end + + it "keeps scanning for reachable replacements and normal matches after fallback wins" do + with_scanner(<<~'GRAMMAR') + %token-pattern A /a+/ + %token-pattern LONG /a+b/ + %token-pattern REPEAT /c+/ + %lex-prec A -s A + %lex-prec A -~ LONG + %% + start: LONG | 'x' A | 'y' choice | REPEAT; + choice: A | LONG; + %% + int main(void) { + yypslr_scan_result result; + int state, checked = 0; + if (yy_pseudo_scan_result(0, "aaab", 4, &result) != LONG + || result.length != 4 || result.from_fallback) return 1; + if (yy_pseudo_scan_result(0, "ccc", 3, &result) != REPEAT + || result.length != 3 || result.from_fallback) return 2; + if (yy_pseudo_scan_result(YYFINAL, "aaab", 4, &result) != LONG + || result.length != 4 || !result.from_fallback) return 3; + for (state = 0; state < YYNSTATES; state++) { + if (yy_pseudo_scan_result(state, "a", 1, &result) == A && !result.from_fallback + && yy_pseudo_scan_result(state, "ab", 2, &result) == A) { + scanner_steps = 0; + if (yy_pseudo_scan_result(state, "aaaab", 5, &result) != A + || result.length != 1 || result.from_fallback || scanner_steps != 1) return 4; + checked = 1; + } + } + if (!checked) return 5; + yypslr_set_input("yaaab", 5); + return yyparse(); + } + GRAMMAR + end +end diff --git a/spec/lrama/state/scanner_accepts_spec.rb b/spec/lrama/state/scanner_accepts_spec.rb index 2a3953b79..a1f915048 100644 --- a/spec/lrama/state/scanner_accepts_spec.rb +++ b/spec/lrama/state/scanner_accepts_spec.rb @@ -304,6 +304,38 @@ def parser_state(id, token_names) expect(scanner_accepts.fallback_table.fetch(accepting.id).name).to eq("A") end + it "preserves fallback winners for paths with different shorter matches" do + tokens = [token_pattern("A", "aa", 0), token_pattern("B", "a+b", 1), token_pattern("C", "a+b", 2)] + scanner_fsa = Lrama::ScannerFSA.new(tokens) + lex_prec = Lrama::Grammar::LexPrec.new + [["C", Lrama::Grammar::LexPrec::TOKEN_RIGHT, "A"], + ["B", Lrama::Grammar::LexPrec::IDENTITY_RIGHT, "C"], + ["A", Lrama::Grammar::LexPrec::LONGEST, "B"]].each do |left, operator, right| + lex_prec.add_rule(left_token: ident(left), operator: operator, right_token: ident(right), lineno: 1) + end + scanner_accepts = Lrama::State::ScannerAccepts.new( + tokens.each_with_index.map { |token, index| parser_state(index, [token.name]) }, + scanner_fsa, lex_prec, Lrama::LengthPrecedences.new(lex_prec) + ) + scanner_accepts.build + + { "ab" => "C", "aab" => "B", "aaaaab" => "B" }.each do |input, expected| + profile = 0 + selected = nil + scanner_fsa.scan(input).group_by { |match| match[:position] }.each_value do |matches| + state_id = matches.first[:state].id + profile, token = scanner_accepts.fallback_profiles.fetch(profile).fetch(state_id) + selected = token.name if token + end + expect(selected).to eq(expected) + end + accepting = scanner_fsa.scan("ab").last[:state].id + expect(scanner_accepts.fallback_table).not_to have_key(accepting) + expect(scanner_accepts[1, accepting].name).to eq("B") + expect(scanner_accepts[2, accepting].name).to eq("C") + expect(scanner_accepts).not_to be_unresolved_conflicts + end + [ { figure: "3.3", diff --git a/template/bison/_yacc.h b/template/bison/_yacc.h index 7cf4b6b21..818c56c3a 100644 --- a/template/bison/_yacc.h +++ b/template/bison/_yacc.h @@ -75,6 +75,11 @@ int yyparse (<%= output.parse_param %>); <%= output.pslr_function_declarations %> <%- end -%> +<%- if output.lexer_context_enabled? -%> +<%= output.lexer_context_defines_code %> +int yy_lexer_context_is (int yystate, unsigned long long ctx_mask); +<%- end -%> + <%= output.percent_code("provides") %> <%-# b4_cpp_guard_close([b4_spec_mapped_header_file]) -%> diff --git a/template/bison/yacc.c b/template/bison/yacc.c index 2885e4961..fce2628ca 100644 --- a/template/bison/yacc.c +++ b/template/bison/yacc.c @@ -799,7 +799,7 @@ yy_state_deep_accepts_token (int yystate, int yychar, enum { YYENOMEM = -2 }; #define yyerrok (yyerrstatus = 0) -#define yyclearin (yychar = YYEMPTY) +#define yyclearin (yychar = YYEMPTY<%= output.lac_enabled? ? ", yylac_token = YYEMPTY" : "" %>) #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab @@ -813,6 +813,9 @@ enum { YYENOMEM = -2 }; do \ if (yychar == YYEMPTY) \ { \ +<%- if output.lac_enabled? -%> + yylac_token = YYEMPTY; \ +<%- end -%> yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ @@ -1539,7 +1542,24 @@ yy_process_repairs(yy_repairs *reps, yysymbol_kind_t token) goto yyrecover_backup; yyrecover_newstate: - // TODO: check reps->stack_length + if (reps->state - reps->states + 1 == reps->stack_length) + { + YYPTRDIFF_T used = reps->stack_length; + YYPTRDIFF_T capacity = used * 2; + yy_state_t *states; + if (YYMAXDEPTH <= used) + return 0; + if (YYMAXDEPTH < capacity) + capacity = YYMAXDEPTH; + states = (yy_state_t *) YYMALLOC (sizeof (yy_state_t) * capacity); + if (!states) + return 0; + YYCOPY (states, reps->states, used); + YYFREE (reps->states); + reps->states = states; + reps->state = states + used - 1; + reps->stack_length = capacity; + } reps->state += 1; *reps->state = (yy_state_t) yystate; @@ -1580,6 +1600,8 @@ yy_process_repairs(yy_repairs *reps, yysymbol_kind_t token) yyrecover_reduce: yylen = yyr2[yyn]; + if (reps->state - reps->states < yylen) + goto yyrecover_errlab; /* YYPOPSTACK */ reps->state -= yylen; yylen = 0; @@ -1608,20 +1630,24 @@ yyrecover(yy_state_t *yyss, yy_state_t *yyssp, int yychar<%= output.user_formals yy_repairs *head = (yy_repairs *) YYMALLOC (sizeof (yy_repairs)); yy_repairs *current = head; yy_repairs *tail = head; - YYPTRDIFF_T stack_length = yyssp - yyss + 1; + YYPTRDIFF_T used = yyssp - yyss + 1; + YYPTRDIFF_T stack_length = used * 2 > 100 ? used * 2 : 100; head->id = count; head->next = 0; head->stack_length = stack_length; head->states = (yy_state_t *) YYMALLOC (sizeof (yy_state_t) * (stack_length)); head->state = head->states + (yyssp - yyss); - YYCOPY (head->states, yyss, stack_length); + YYCOPY (head->states, yyss, used); head->repair_length = 0; head->prev_repair = 0; - stack_length = (stack_length * 2 > 100) ? (stack_length * 2) : 100; count++; + /* LAC can detect an error before the parser performs default reductions. */ + if (!yy_process_repairs (head, YYSYMBOL_YYEMPTY)) + goto done; + while (current) { int yystate = *current->state; @@ -1643,8 +1669,8 @@ yyrecover(yy_state_t *yyss, yy_state_t *yyssp, int yychar<%= output.user_formals yy_repairs *reps = (yy_repairs *) YYMALLOC (sizeof (yy_repairs)); reps->id = count; reps->next = 0; - reps->stack_length = stack_length; - reps->states = (yy_state_t *) YYMALLOC (sizeof (yy_state_t) * (stack_length)); + reps->stack_length = current->stack_length; + reps->states = (yy_state_t *) YYMALLOC (sizeof (yy_state_t) * reps->stack_length); reps->state = reps->states + (current->state - current->states); YYCOPY (reps->states, current->states, current->state - current->states + 1); reps->repair_length = current->repair_length + 1; @@ -1655,6 +1681,7 @@ yyrecover(yy_state_t *yyss, yy_state_t *yyssp, int yychar<%= output.user_formals /* Process PDA assuming next token is yyx */ if (! yy_process_repairs (reps, (yysymbol_kind_t)yyx)) { + YYFREE (reps->states); YYFREE (reps); continue; } @@ -1765,6 +1792,10 @@ YYLTYPE yylloc = yyloc_default; int yyresult; /* Lookahead symbol kind. */ yysymbol_kind_t yytoken = YYSYMBOL_YYEMPTY; +<%- if output.lac_enabled? -%> + /* A successful LAC check remains valid through ordinary reductions. */ + int yylac_token = YYEMPTY; +<%- end -%> /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; @@ -1912,49 +1943,19 @@ YYLTYPE yylloc = yyloc_default; /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; <%- if output.lac_enabled? -%> - if (yypact_value_is_default (yyn) && yydefact[yystate] != 0) - { - if (yychar == YYEMPTY) - { - YYDPRINTF ((stderr, "Reading a token\n")); - yychar = yylex <%= output.yylex_formals %>; - } - - if (yychar <= <%= output.eof_symbol.id.s_value %>) - { - yychar = <%= output.eof_symbol.id.s_value %>; - yytoken = <%= output.eof_symbol.enum_name %>; - YYDPRINTF ((stderr, "Now at end of input.\n")); - } - else if (yychar == <%= output.error_symbol.id.s_value %>) - { - yychar = <%= output.undef_symbol.id.s_value %>; - yytoken = <%= output.error_symbol.enum_name %>; - yyerror_range[1] = yylloc; - goto yyerrlab1; - } - else - { - yytoken = YYTRANSLATE (yychar); - YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc<%= output.user_args %>); - } - - { - int yylac_status = yy_lac_check_ (yyss, yyssp, yytoken); - if (yylac_status == YYENOMEM) - YYNOMEM; - if (!yylac_status) - goto yyerrlab; - } - - goto yydefault; - } -<%- end -%> + /* Default reductions also need lookahead from the repair queue for LAC. */ + if (yypact_value_is_default (yyn) && yydefact[yystate] == 0) +<%- else -%> if (yypact_value_is_default (yyn)) +<%- end -%> goto yydefault; /* Not known => get a lookahead token if don't already have one. */ +<%- if output.lac_enabled? -%> + if (yychar == YYEMPTY) + yylac_token = YYEMPTY; +<%- end -%> <%- if output.error_recovery -%> if (YYERROR_RECOVERY_ENABLED(<%= output.parse_param_name %>)) { @@ -2019,13 +2020,17 @@ YYLTYPE yylloc = yyloc_default; } <%- if output.lac_enabled? -%> - { - int yylac_status = yy_lac_check_ (yyss, yyssp, yytoken); - if (yylac_status == YYENOMEM) - YYNOMEM; - if (!yylac_status) - goto yyerrlab; - } + if (yylac_token != yychar) + { + int yylac_status = yy_lac_check_ (yyss, yyssp, yytoken); + if (yylac_status == YYENOMEM) + YYNOMEM; + if (!yylac_status) + goto yyerrlab; + yylac_token = yychar; + } + if (yypact_value_is_default (yyn)) + goto yydefault; <%- end -%> /* If the proper action on seeing token YYTOKEN is to reduce or to @@ -2058,6 +2063,9 @@ YYLTYPE yylloc = yyloc_default; /* Discard the shifted token. */ yychar = YYEMPTY; +<%- if output.lac_enabled? -%> + yylac_token = YYEMPTY; +<%- end -%> goto yynewstate; @@ -2137,6 +2145,9 @@ YYLTYPE yylloc = yyloc_default; | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: +<%- if output.lac_enabled? -%> + yylac_token = YYEMPTY; +<%- end -%> /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYSYMBOL_YYEMPTY : YYTRANSLATE (yychar); @@ -2226,6 +2237,9 @@ YYLTYPE yylloc = yyloc_default; | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: +<%- if output.lac_enabled? -%> + yylac_token = YYEMPTY; +<%- end -%> <%- if output.error_recovery -%> if (YYERROR_RECOVERY_ENABLED(<%= output.parse_param_name %>)) { From 6774061c5d380c38e8742aa6a05a2e4d41f0c7d1 Mon Sep 17 00:00:00 2001 From: ydah Date: Sat, 21 Nov 2026 18:41:47 +0900 Subject: [PATCH 22/24] pslr: preserve scanner and runtime fixes from the master merge --- NEWS.md | 22 +- lib/lrama/grammar/lex_tie.rb | 6 +- lib/lrama/grammar/lexer_context.rb | 4 +- lib/lrama/lexer_context_classifier.rb | 2 +- lib/lrama/output.rb | 243 +++++++----------- sig/generated/lrama/grammar/lexer_context.rbs | 6 +- spec/lrama/generated_runtime_spec.rb | 207 +++++++++++++-- spec/lrama/grammar_spec.rb | 25 ++ spec/lrama/integration_spec.rb | 2 +- spec/lrama/lac_runtime_spec.rb | 33 ++- spec/lrama/lexer_context_classifier_spec.rb | 22 +- spec/lrama/lexer_params_runtime_spec.rb | 20 +- spec/lrama/output_spec.rb | 15 +- spec/lrama/parser_spec.rb | 34 ++- spec/lrama/pslr_state_construction_spec.rb | 115 +++++++++ spec/lrama/scanner_fsa_spec.rb | 2 +- .../lrama/scanner_termination_runtime_spec.rb | 42 +++ spec/lrama/state/scanner_accepts_spec.rb | 3 +- spec/lrama/state_spec.rb | 2 +- template/bison/_pslr_scanner.c | 160 ++++++++++++ template/bison/yacc.c | 21 +- 21 files changed, 759 insertions(+), 227 deletions(-) create mode 100644 spec/lrama/pslr_state_construction_spec.rb create mode 100644 template/bison/_pslr_scanner.c diff --git a/NEWS.md b/NEWS.md index 63310aa68..f02e751cf 100644 --- a/NEWS.md +++ b/NEWS.md @@ -178,11 +178,16 @@ because PSLR token lexemes must be non-empty. Two operating modes are supported. In pure mode (`%define api.pslr.lexer generated`), the generated parser owns lexical analysis: `yylex` is generated, layout tokens are skipped with their text accumulated, `%token-action` bodies build semantic values from `yytext`/`yyleng`, and the caller hands the input to the parser with -`yypslr_set_input(input, len)` before `yyparse`. Pure mode requires a `%token-pattern` for every terminal. -In bridge mode (`%define api.pslr.state-member`), an existing hand-written lexer consults the pseudo-scanner +`yypslr_set_input(input, len)` before `yyparse`. Set the input on the thread that will parse it. A nested +`yyparse` call uses its own input cursor, source location, and layout buffer. Pure mode requires a +`%token-pattern` for every terminal. +In bridge mode, `%define api.pslr.state-member` names the field in the first parser parameter that stores the +current parser state. An existing hand-written lexer consults the pseudo-scanner through helper macros such as `YYPSLR_PSEUDO_SCAN(Context, Input, InputLen, MatchLength)`; terminals without a token pattern stay owned by the user lexer and are reported as a warning. The scan API is length-delimited -(`input` plus `input_len`) so inputs containing NUL bytes are handled correctly, and the scan result reports +(`input` plus `input_len`) so inputs containing NUL bytes are handled correctly. A single lexeme must fit in +the `int` match length. The scanner reports `YYUNDEF` for a longer match and caps source line and column +numbers at `INT_MAX`. The scan result reports `from_fallback` when the token came from the syntax-error fallback row. The paper-compatible scanning path needs the lexer to pass the unconsumed input prefix, not only an already-decided token fragment, so legacy external lexer bridges may still be limited by the text they provide. @@ -190,11 +195,12 @@ lexer bridges may still be limited by the text they provide. Unresolved pseudo-scanner conflict reports include a witness: an example input that reaches the conflicting scanner profile. `%lex-prec` rules that never participate in a normal-row resolution are reported as useless. -PSLR parsers enable LAC (lookahead correction, `%define parse.lac full`) by default so syntax errors caused by -LR state merging, default reductions, or `%nonassoc` error actions are detected before user semantic actions are -run for the bad lookahead, and expected-token lists in error messages are computed by exploratory parses. LAC can -also be enabled independently for LALR/IELR parsers. PSLR support is still experimental. Scoped lexical -declarations, lexical nonterminals, and `%lex` are not implemented yet. If you find any bugs, please report them. +PSLR parsers enable LAC (lookahead correction, `%define parse.lac full`) by default. Once the parser reads a +lookahead token, it checks whether it can shift that token before running further semantic actions. States with +an unconditional default reduction can still run their action before the next lexer call. LAC also computes +expected-token lists in error messages and can be enabled for LALR/IELR parsers. PSLR support is still +experimental. Scoped lexical declarations, lexical nonterminals, and `%lex` are not implemented yet. If you +find any bugs, please report them. ## Lrama 0.7.1 (2025-12-24) diff --git a/lib/lrama/grammar/lex_tie.rb b/lib/lrama/grammar/lex_tie.rb index 9ddff2cff..a767850cb 100644 --- a/lib/lrama/grammar/lex_tie.rb +++ b/lib/lrama/grammar/lex_tie.rb @@ -53,7 +53,7 @@ def initialize(kind:, specificity:, lineno:) # @rbs () -> void def initialize - @ties = Hash.new { |h, k| h[k] = Set.new([k]) } + @ties = {} @no_ties = Set.new @declarations = [] end @@ -99,7 +99,7 @@ def finalize!(token_names, conflict_pairs) # @rbs (String name) -> Set[String] def tied_names(name) - @ties[name].dup + @ties[name]&.dup || Set[name] end # @rbs (String left, String right) -> bool @@ -193,7 +193,7 @@ def rebuild_relations(token_names, decisions) tie_specificities[pair] = decision.specificity end - @ties = Hash.new { |h, k| h[k] = Set.new([k]) } + @ties = {} groups = parents.keys.group_by {|name| root(parents, name) } groups.each_value do |names| tied = names.to_set diff --git a/lib/lrama/grammar/lexer_context.rb b/lib/lrama/grammar/lexer_context.rb index e779899f4..245f887e7 100644 --- a/lib/lrama/grammar/lexer_context.rb +++ b/lib/lrama/grammar/lexer_context.rb @@ -12,7 +12,7 @@ class Grammar class LexerContext attr_reader :name #: String attr_reader :index #: Integer - attr_reader :symbols #: Array[Lexer::Token::Ident] + attr_reader :symbols #: Array[Lexer::Token::Base] # @rbs (name: String, index: Integer) -> void def initialize(name:, index:) @@ -28,7 +28,7 @@ def bitmask end # Add symbols that belong to this context. - # @rbs (Array[Lexer::Token::Ident] syms) -> void + # @rbs (Array[Lexer::Token::Base] syms) -> void def add_symbols(syms) syms.each do |sym| @symbols << sym diff --git a/lib/lrama/lexer_context_classifier.rb b/lib/lrama/lexer_context_classifier.rb index e61c990a1..ce9126561 100644 --- a/lib/lrama/lexer_context_classifier.rb +++ b/lib/lrama/lexer_context_classifier.rb @@ -55,7 +55,7 @@ def infer_item_context(item) # # @rbs (Grammar::Symbol sym) -> Integer def classify_symbol_context(sym) - name = sym.id.s_value + name = sym.name # Also try without surrounding quotes for single-char tokens bare = name.gsub(/\A["']|["']\z/, "") diff --git a/lib/lrama/output.rb b/lib/lrama/output.rb index 2aa8809dd..367d0af4a 100644 --- a/lib/lrama/output.rb +++ b/lib/lrama/output.rb @@ -497,13 +497,14 @@ def pslr_function_declarations C_CODE end - if !parse_param_name.empty? + if (context_param = @grammar.parse_params.first) + context_name = extract_param_name(context_param) declarations << <<~C_CODE #ifndef YYSETSTATE_CONTEXT # define YYSETSTATE_CONTEXT(CurrentState) \\ do { \\ - if (#{parse_param_name} != 0) { \\ - YYGETSTATE_CONTEXT (#{parse_param_name}) = (CurrentState); \\ + if (#{context_name} != 0) { \\ + YYGETSTATE_CONTEXT (#{context_name}) = (CurrentState); \\ } \\ } while (0) #endif @@ -923,7 +924,7 @@ def pseudo_scan_function * input_len: Number of remaining input bytes * result: Output parameter for the match * - * Returns: Selected parser token ID. #{eof_symbol.id.s_value} when input_len is zero. + * Returns: Selected parser token ID. #{eof_symbol.name} when input_len is zero. * If neither the parser-state row nor the fallback row matches, * returns YYUNDEF and consumes one byte (character-token handling); * from_fallback is set for both cases because a syntax error is @@ -933,9 +934,9 @@ def pseudo_scan_function yy_pseudo_scan_result (int parser_state, const char *input, size_t input_len, yypslr_scan_result *result) { int ss = 0; /* FSA initial state */ - int ibest = 0; + size_t ibest = 0; int pbest = YY_PSLR_EMPTY_PATTERN; - int fallback_ibest = 0; + size_t fallback_ibest = 0; int fallback_pbest = YY_PSLR_EMPTY_PATTERN; int fallback_profile = 0; size_t i = 0; @@ -950,12 +951,12 @@ def pseudo_scan_function result->is_character_token = 0; result->from_fallback = 0; - if (parser_state < 0 || parser_state >= YY_NUM_PARSER_STATES || input == NULL) { + if (parser_state < 0 || parser_state >= YY_NUM_PARSER_STATES || (!input && input_len)) { return YYEMPTY; } if (input_len == 0) { - result->token = #{eof_symbol.id.s_value}; + result->token = #{eof_symbol.name}; return result->token; } @@ -978,7 +979,7 @@ def pseudo_scan_function if (pbest == YY_PSLR_EMPTY_PATTERN || yy_pslr_length_precedes[pbest][pattern_index]) { pbest = pattern_index; - ibest = (int)i; + ibest = i; } } @@ -986,7 +987,7 @@ def pseudo_scan_function fallback_profile = yy_scanner_fallback_next[fallback_profile][sa]; if (pattern_index != YY_PSLR_EMPTY_PATTERN) { fallback_pbest = pattern_index; - fallback_ibest = (int)i; + fallback_ibest = i; } } @@ -996,25 +997,21 @@ def pseudo_scan_function } } - if (pbest != YY_PSLR_EMPTY_PATTERN) { - result->token = yy_token_pattern_to_token_id[pbest]; - result->length = ibest; - result->is_layout = yy_token_pattern_is_layout[pbest]; - return result->token; - } - - if (fallback_pbest != YY_PSLR_EMPTY_PATTERN) { - result->token = yy_token_pattern_to_token_id[fallback_pbest]; - result->length = fallback_ibest; - result->is_layout = yy_token_pattern_is_layout[fallback_pbest]; + if (pbest == YY_PSLR_EMPTY_PATTERN) { + pbest = fallback_pbest; + ibest = fallback_ibest; result->from_fallback = 1; - return result->token; } - result->token = YYUNDEF; - result->length = 1; - result->is_character_token = 1; - result->from_fallback = 1; + if (pbest != YY_PSLR_EMPTY_PATTERN && ibest <= INT_MAX) { + result->token = yy_token_pattern_to_token_id[pbest]; + result->length = (int)ibest; + result->is_layout = yy_token_pattern_is_layout[pbest]; + } else { + result->token = YYUNDEF; + result->length = ibest > INT_MAX ? INT_MAX : 1; + result->is_character_token = pbest == YY_PSLR_EMPTY_PATTERN; + } return result->token; } @@ -1087,82 +1084,10 @@ def pslr_token_actions_enabled? pslr_enabled? && !@grammar.token_actions.empty? end - # Generate layout accumulation declarations def pslr_layout_declarations return "" unless pslr_scanner_enabled? || pslr_pure_mode? - <<~C_CODE - - #ifndef YYPSLR_LAYOUT_DEFINED - # define YYPSLR_LAYOUT_DEFINED - - #include - #include - - typedef struct yypslr_layout { - const char *text; - int length; - } yypslr_layout; - - # ifndef YYPSLR_LAYOUT_BUFFER_SIZE - # define YYPSLR_LAYOUT_BUFFER_SIZE 4096 - # endif - - static char yypslr_layout_initial[YYPSLR_LAYOUT_BUFFER_SIZE]; - static char *yypslr_layout_buffer = yypslr_layout_initial; - static size_t yypslr_layout_capacity = sizeof yypslr_layout_initial; - static int yypslr_layout_length = 0; - - static void - yypslr_layout_clear (void) - { - if (yypslr_layout_buffer != yypslr_layout_initial) - YYFREE (yypslr_layout_buffer); - yypslr_layout_buffer = yypslr_layout_initial; - yypslr_layout_capacity = sizeof yypslr_layout_initial; - yypslr_layout_length = 0; - yypslr_layout_buffer[0] = '\\0'; - } - - static int - yypslr_layout_append (const char *text, int length) - { - size_t required; - if (length < 0 || length > INT_MAX - yypslr_layout_length) - return 0; - - required = (size_t) yypslr_layout_length + (size_t) length + 1; - if (required > (size_t) YYSIZE_MAXIMUM) - return 0; - if (required > yypslr_layout_capacity) - { - size_t capacity = yypslr_layout_capacity; - char *buffer; - while (capacity < required) - capacity = capacity > (size_t) YYSIZE_MAXIMUM / 2 ? required : capacity * 2; - buffer = YY_CAST (char *, YYMALLOC (capacity)); - if (!buffer) - return 0; - memcpy (buffer, yypslr_layout_buffer, (size_t) yypslr_layout_length); - if (yypslr_layout_buffer != yypslr_layout_initial) - YYFREE (yypslr_layout_buffer); - yypslr_layout_buffer = buffer; - yypslr_layout_capacity = capacity; - } - - memcpy (yypslr_layout_buffer + yypslr_layout_length, text, (size_t) length); - yypslr_layout_length += length; - yypslr_layout_buffer[yypslr_layout_length] = '\\0'; - return 1; - } - - # define YYPSLR_LAYOUT_TEXT yypslr_layout_buffer - # define YYPSLR_LAYOUT_LENGTH yypslr_layout_length - # define YYPSLR_LAYOUT_CLEAR() yypslr_layout_clear () - # define YYPSLR_LAYOUT_APPEND(Text, Len) yypslr_layout_append ((Text), (Len)) - - #endif /* YYPSLR_LAYOUT_DEFINED */ - C_CODE + render_partial("bison/_pslr_scanner.c") end # Generate token action dispatch function. @@ -1184,7 +1109,7 @@ def pslr_token_action_function lines << " YY_USE (yytext);" lines << " YY_USE (yyleng);" lines << " YY_USE (yylvalp);" - lines << " YY_USE (#{lex_param_name});" unless lex_param.empty? + lines << lex_param_use @grammar.token_actions.each_with_index do |action, idx| token_id = @context.states.find_symbol_by_s_value!(action.token_name).token_id @@ -1218,7 +1143,7 @@ def pslr_layout_scan_function * Layout tokens are accumulated in the layout buffer; * non-layout tokens are returned to the caller with the * accumulated layout available via YYPSLR_LAYOUT_TEXT. - * The #{eof_symbol.id.s_value} token action (if any) runs before returning #{eof_symbol.id.s_value} so + * The #{eof_symbol.name} token action (if any) runs before returning #{eof_symbol.name} so * trailing layout can be recovered (paper section 3.6). */ int @@ -1228,7 +1153,7 @@ def pslr_layout_scan_function { YYPSLR_LAYOUT_CLEAR (); YY_USE (yylvalp); - #{lex_param.empty? ? "" : " YY_USE (#{lex_param_name});"} + #{lex_param_use} for (;;) { @@ -1237,12 +1162,6 @@ def pslr_layout_scan_function if (yytoken == YYEMPTY) return yytoken; - if (yytoken == #{eof_symbol.id.s_value}) - { - #{pslr_token_actions_enabled? ? " YYPSLR_TOKEN_ACTION (yytoken, *yyinput, 0, yylvalp);" : ""} - return yytoken; - } - if (yyresult->is_layout) { if (!YYPSLR_LAYOUT_APPEND (*yyinput, yyresult->length)) @@ -1272,56 +1191,54 @@ def pslr_layout_scan_function def pslr_generated_lexer_function return "" unless pslr_pure_mode? + args = ["yylvalp"] + args << "yyllocp" if @grammar.locations + args << lex_param_name unless lex_param.empty? params = ["YYSTYPE *yylvalp"] params << "YYLTYPE *yyllocp" if @grammar.locations params << lex_param unless lex_param.empty? - unused = [] - unused << " YY_USE (#{lex_param_name});" unless lex_param.empty? location_declarations = location_reset = location_start = location_end = "" if @grammar.locations location_declarations = <<~C_CODE - static const char *yypslr_location_cursor = 0; - static int yypslr_line = 1; - static int yypslr_column = 1; - static void - yypslr_update_location (void) + yypslr_update_location (yypslr_scanner *yypslr_lexer) { - while (yypslr_location_cursor != yypslr_input_cursor) + while (yypslr_lexer->input.location_cursor != yypslr_lexer->input.cursor) { - if (*yypslr_location_cursor++ == '\\n') + if (*yypslr_lexer->input.location_cursor++ == '\\n') { - yypslr_line++; - yypslr_column = 1; + if (yypslr_lexer->input.line < INT_MAX - 1) + yypslr_lexer->input.line++; + yypslr_lexer->input.column = 0; } - else - yypslr_column++; + else if (yypslr_lexer->input.column < INT_MAX - 1) + yypslr_lexer->input.column++; } } C_CODE location_reset = <<~C_CODE - yypslr_location_cursor = input; - yypslr_line = yypslr_column = 1; + yypslr_lexer->input.location_cursor = input; + yypslr_lexer->input.line = yypslr_lexer->input.column = 0; C_CODE location_start = <<~C_CODE - yypslr_update_location (); - yyllocp->first_line = yypslr_line; - yyllocp->first_column = yypslr_column; + yypslr_update_location (yypslr_lexer); + yyllocp->first_line = yypslr_lexer->input.line + 1; + yyllocp->first_column = yypslr_lexer->input.column + 1; C_CODE location_end = <<~C_CODE - yypslr_update_location (); - yyllocp->last_line = yypslr_line; - yyllocp->last_column = yypslr_column; + yypslr_update_location (yypslr_lexer); + yyllocp->last_line = yypslr_lexer->input.line + 1; + yyllocp->last_column = yypslr_lexer->input.column + 1; C_CODE end scan = if pslr_scanner_enabled? <<~C_CODE yypslr_scan_result yypslr_result; - yypslr_token = yypslr_scan_with_layout (yypslr_parser_state, - &yypslr_input_cursor, - &yypslr_input_remain, + yypslr_token = yypslr_scan_with_layout (yypslr_lexer->input.parser_state, + &yypslr_lexer->input.cursor, + &yypslr_lexer->input.remaining, yylvalp, &yypslr_result#{lex_param.empty? ? "" : ", #{lex_param_name}"}); yypslr_length = yypslr_result.length; @@ -1330,49 +1247,75 @@ def pslr_generated_lexer_function <<~C_CODE YY_USE (yylvalp); YYPSLR_LAYOUT_CLEAR (); - yypslr_token = yypslr_input_remain ? YYUNDEF : #{eof_symbol.id.s_value}; - yypslr_length = yypslr_input_remain ? 1 : 0; - #{pslr_token_actions_enabled? ? " if (yypslr_token == #{eof_symbol.id.s_value})\n YYPSLR_TOKEN_ACTION (yypslr_token, yypslr_input_cursor, 0, yylvalp);" : ""} + yypslr_token = yypslr_lexer->input.remaining ? YYUNDEF : #{eof_symbol.name}; + yypslr_length = yypslr_lexer->input.remaining ? 1 : 0; + #{pslr_token_actions_enabled? ? " if (yypslr_token == #{eof_symbol.name})\n YYPSLR_TOKEN_ACTION (yypslr_token, yypslr_lexer->input.cursor, 0, yylvalp);" : ""} C_CODE end <<~C_CODE /* Pure-mode PSLR lexer: generated, owns the input cursor. */ - static const char *yypslr_input_cursor = 0; - static size_t yypslr_input_remain = 0; - static int yypslr_parser_state = 0; #{location_declarations} void yypslr_set_input (const char *input, size_t input_len) { - YYPSLR_LAYOUT_CLEAR (); - yypslr_input_cursor = input; - yypslr_input_remain = input_len; - yypslr_parser_state = 0; + yypslr_scanner *yypslr_lexer = &yypslr_pending; + yypslr_layout_clear (yypslr_lexer); + yypslr_lexer->input.cursor = input; + yypslr_lexer->input.remaining = input_len; + yypslr_lexer->input.parser_state = 0; + yypslr_has_input = 1; #{location_reset} } - #define YYPSLR_SET_PARSER_STATE(State) (yypslr_parser_state = (State)) + #define YYPSLR_SET_PARSER_STATE(State) (yypslr_current ()->input.parser_state = (State)) static int - yylex (#{params.join(", ")}) + yypslr_read_token (#{params.join(", ")}) { + yypslr_scanner *yypslr_lexer = yypslr_current (); int yypslr_token; int yypslr_length; - #{unused.join("\n")} + #{lex_param_use} + if (yypslr_has_input) + { + int state = yypslr_lexer->input.parser_state; + yypslr_take_input (yypslr_lexer); + yypslr_lexer->input.parser_state = state; + } #{scan} #{location_start} - if (yypslr_token != YYEMPTY && yypslr_token != #{eof_symbol.id.s_value}) + if (yypslr_length > 0) { - yypslr_input_cursor += yypslr_length; - yypslr_input_remain -= (size_t) yypslr_length; + yypslr_lexer->input.cursor += yypslr_length; + yypslr_lexer->input.remaining -= (size_t) yypslr_length; } #{location_end} return yypslr_token; } + + /* A standalone lexer call may itself invoke yyparse in a token action. */ + static int + yypslr_read_standalone (#{params.join(", ")}) + { + yypslr_scope yypslr_call; + int yypslr_token; + yypslr_enter (&yypslr_call); + yypslr_token = yypslr_read_token (#{args.join(", ")}); + YYPSLR_LEAVE (yypslr_call); + return yypslr_token; + } + + static int + yylex (#{params.join(", ")}) + { + if (yypslr_active) + return yypslr_read_token (#{args.join(", ")}); + return yypslr_read_standalone (#{args.join(", ")}); + } C_CODE end @@ -1402,6 +1345,10 @@ def pslr_tables_and_functions private + def lex_param_use + @grammar.lex_params.map { |param| " YY_USE (#{extract_param_name(param)});" }.join("\n") + end + def include_header_path(output_file_path, header_file_path) if File.identical?(File.dirname(output_file_path), File.dirname(header_file_path)) File.basename(header_file_path) diff --git a/sig/generated/lrama/grammar/lexer_context.rbs b/sig/generated/lrama/grammar/lexer_context.rbs index 436576d98..292ce3690 100644 --- a/sig/generated/lrama/grammar/lexer_context.rbs +++ b/sig/generated/lrama/grammar/lexer_context.rbs @@ -13,7 +13,7 @@ module Lrama attr_reader index: Integer - attr_reader symbols: Array[Lexer::Token::Ident] + attr_reader symbols: Array[Lexer::Token::Base] # @rbs (name: String, index: Integer) -> void def initialize: (name: String, index: Integer) -> void @@ -23,8 +23,8 @@ module Lrama def bitmask: () -> Integer # Add symbols that belong to this context. - # @rbs (Array[Lexer::Token::Ident] syms) -> void - def add_symbols: (Array[Lexer::Token::Ident] syms) -> void + # @rbs (Array[Lexer::Token::Base] syms) -> void + def add_symbols: (Array[Lexer::Token::Base] syms) -> void end end end diff --git a/spec/lrama/generated_runtime_spec.rb b/spec/lrama/generated_runtime_spec.rb index d392a8ba6..36ccfbdef 100644 --- a/spec/lrama/generated_runtime_spec.rb +++ b/spec/lrama/generated_runtime_spec.rb @@ -28,6 +28,29 @@ def with_parser(source, flags: []) end end + %w[ielr canonical-lr].each do |tables| + it "selects the end token after a nonassociative expression with #{tables} tables" do + with_parser(<<~GRAMMAR) do |parser| + %define lr.type pslr + %define pslr.tables #{tables} + %define api.pslr.lexer generated + %token-pattern A /a/ + %token-pattern OP /o/ + %token-pattern END /o/ + %lex-prec END <- OP + %nonassoc OP + %% + start: expr END; + expr: A | expr OP expr; + %% + int main(void) { yypslr_set_input("aoao", 4); return yyparse(); } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.exitstatus).to eq(0), err + end + end + end + it "compiles PSLR scanning without user-provided string declarations or layout tokens" do with_parser(<<~GRAMMAR) do |parser| %define lr.type pslr @@ -43,6 +66,120 @@ def with_parser(source, flags: []) end end + it "preserves the outer scanner across nested parses from token and grammar actions" do + with_parser(<<~'GRAMMAR') do |parser| + %define lr.type pslr + %define api.pslr.lexer generated + %define api.pure full + %locations + %code provides { + #include + #define YYPSLR_LAYOUT_BUFFER_SIZE 2 + } + %token-pattern A /a/ + %token-pattern B /b/ + %token-pattern YYLAYOUT_WS /[ \n]+/ + %token-action A { + int length = YYPSLR_LAYOUT_LENGTH; + const char *layout = length == 2 ? " " : "\n "; + yypslr_set_input(" b", 4); + if (yyparse() || YYPSLR_LAYOUT_LENGTH != length + || strcmp(YYPSLR_LAYOUT_TEXT, layout)) exit(2); + } + %% + start: prefix A { + if (@2.first_line != 2 || @2.first_column != 3 || @2.last_column != 4) YYABORT; + } | B; + prefix: A { + yypslr_set_input("b", 1); + if (yyparse() || @1.first_line != 1 || @1.first_column != 3) YYABORT; + }; + %% + int main(void) { + YYSTYPE value; + YYLTYPE loc; + yypslr_set_input(" a\n a", 7); + if (yyparse()) return 3; + yypslr_set_input(" a", 3); + if (yylex(&value, &loc) != A || loc.first_column != 3 || loc.last_column != 4) return 4; + return yylex(&value, &loc) != YYEOF; + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), "exit #{status.exitstatus}: #{err}" + end + end + + it "keeps scanner state independent while two threads are inside yyparse" do + skip "requires pthreads" if windows? + with_parser(<<~GRAMMAR, flags: ["-pthread"]) do |parser| + %define lr.type pslr + %define api.pslr.lexer generated + %define api.pure full + %parse-param {int expected} + %code provides { + #include + #define yyerror(Loc, Expected, Message) yyerror(Loc, Message) + static pthread_t thread; + static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + static pthread_cond_t changed = PTHREAD_COND_INITIALIZER; + static int phase; + static void enter_phase(int next_phase) { + pthread_mutex_lock(&mutex); + while (phase < next_phase - 1) pthread_cond_wait(&changed, &mutex); + phase = next_phase; + pthread_cond_broadcast(&changed); + pthread_mutex_unlock(&mutex); + } + } + %initial-action { + if (expected == B) { + enter_phase(1); + enter_phase(4); + } else { + enter_phase(3); + if (pthread_join(thread, 0)) YYABORT; + } + } + %token-pattern A /a/ + %token-pattern B /b/ + %% + start: A { if (expected != A) YYABORT; } | B { if (expected != B) YYABORT; }; + %% + static void *worker(void *result) { + yypslr_set_input("b", 1); + *(int *)result = yyparse(B); + return 0; + } + int main(void) { + int result; + yypslr_set_input("a", 1); + if (pthread_create(&thread, 0, worker, &result)) return 1; + enter_phase(2); + return yyparse(A) || result; + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), "exit #{status.exitstatus}: #{err}" + end + end + + it "allows an initial action to set the generated lexer's input" do + with_parser(<<~GRAMMAR) do |parser| + %define lr.type pslr + %define api.pslr.lexer generated + %initial-action { yypslr_set_input("a", 1); } + %token-pattern A /a/ + %% + start: A; + %% + int main(void) { return yyparse(); } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + ["lalr", "pslr"].each do |type| it "uses heap storage for LAC with #{type} and an alloca parser stack" do lexer = type == "pslr" ? "%define api.pslr.lexer generated" : <<~GRAMMAR @@ -237,28 +374,34 @@ def with_parser(source, flags: []) end end - it "runs the EOF token action without token patterns or locations" do - with_parser(<<~GRAMMAR) do |parser| - %code provides { static int eof_count = 0; } - %define lr.type pslr - %define api.pslr.lexer generated - %token-action YYEOF { eof_count++; } - %% - start: %empty; - %% - int main(void) { - yypslr_set_input(0, 0); - if (yyparse() || eof_count != 1) return 1; - yypslr_set_input("", 0); - return yyparse() || eof_count != 2; - } - GRAMMAR - _out, err, status = Open3.capture3(parser) - expect(status.success?).to be(true), err + [false, true].each do |scanner| + it "runs the EOF action for an empty input pointer #{scanner ? 'with' : 'without'} scanner tables" do + with_parser(<<~GRAMMAR) do |parser| + %code provides { static int eof_count = 0; } + %define lr.type pslr + %define api.pslr.lexer generated + #{'%token-pattern A /a/' if scanner} + %token-action YYEOF { eof_count++; } + %% + start: %empty; + %% + int main(void) { + #ifdef YYPSLR_ENABLED + yypslr_scan_result result; + if (yy_pseudo_scan_result(0, 0, 1, &result) != YYEMPTY + || yy_pseudo_scan_result(-1, 0, 0, &result) != YYEMPTY) return 2; + #endif + yypslr_set_input(0, 0); + if (yyparse() || eof_count != 1) return 1; + yypslr_set_input("", 0); + return yyparse() || eof_count != 2; + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end end - end - [false, true].each do |scanner| it "uses a renamed EOF token and its action #{scanner ? 'with scanner and layout' : 'without token patterns'}" do patterns = scanner ? "%token-pattern A /a/\n%token-pattern YYLAYOUT_WS / +/" : "" with_parser(<<~GRAMMAR) do |parser| @@ -281,4 +424,28 @@ def with_parser(source, flags: []) end end end + + it "consumes an explicit end marker before parsing the next record" do + with_parser(<<~'GRAMMAR') do |parser| + %define lr.type pslr + %define api.pslr.lexer generated + %code provides { + #include + } + %token END 0 + %token-pattern END /;/ + %token-pattern A /a/ + %token-action END { if (yyleng != 1) exit(3); } + %% + start: A; + %% + int main(void) { + yypslr_set_input("a;a;", 4); + return yyparse() || yyparse(); + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), "exit #{status.exitstatus}: #{err}" + end + end end diff --git a/spec/lrama/grammar_spec.rb b/spec/lrama/grammar_spec.rb index c5b5af35f..c74b9cb3e 100644 --- a/spec/lrama/grammar_spec.rb +++ b/spec/lrama/grammar_spec.rb @@ -340,6 +340,11 @@ end end + it "rejects lexer context names that cannot be used in generated C macros" do + expect { grammar.add_lexer_context(name: "in-string", symbols: []) } + .to raise_error(/%lexer-context.*C identifier/) + end + describe "#finalize_lexical_declarations!" do it "resolves quoted aliases to canonical token ids" do grammar = Lrama::Parser.new(<<~GRAMMAR, "lex_prec_alias.y").parse @@ -359,6 +364,26 @@ expect(grammar.lex_prec.longest_pair?("ID", "IF")).to be true end + it "resolves an alias first mentioned before its token pattern" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "forward_alias.y").parse + %symbol-set words "word" + %lex-prec words -~ "word" + %lex-tie "word" OTHER + %token-pattern OTHER /other/ + %token-pattern WORD /word/ "word" + %% + start: "word"; + GRAMMAR + grammar.prepare + grammar.validate! + grammar.finalize_lexical_declarations! + + expect(grammar.rules.last.rhs).to eq([grammar.find_symbol_by_s_value!("WORD")]) + expect(grammar.lex_prec.rules.map(&:left_name)).to eq(["WORD"]) + grammar.finalize_lexical_ties!(Lrama::ScannerFSA.new(grammar.token_patterns)) + expect(grammar.lex_tie.tied?("WORD", "OTHER")).to be true + end + it "resolves aliases in symbol sets and keeps literal terminals" do grammar = Lrama::Parser.new(<<~GRAMMAR, "symbol_set_alias.y").parse %token-pattern ID /[a-z]+/ diff --git a/spec/lrama/integration_spec.rb b/spec/lrama/integration_spec.rb index 94fe9916a..ee596f6b6 100644 --- a/spec/lrama/integration_spec.rb +++ b/spec/lrama/integration_spec.rb @@ -22,7 +22,7 @@ def compiler end def file_extension - ['cc', 'gcc', 'clang'].include?(ENV['COMPILER']) ? ".c" : ".cpp" + compiler.include?("++") ? ".cpp" : ".c" end def test_parser(parser_name, input, expected, expect_success: true, lrama_command_args: [], debug: false) diff --git a/spec/lrama/lac_runtime_spec.rb b/spec/lrama/lac_runtime_spec.rb index 10c6ae667..ea5b370a0 100644 --- a/spec/lrama/lac_runtime_spec.rb +++ b/spec/lrama/lac_runtime_spec.rb @@ -69,6 +69,32 @@ def with_lac_parser(source, instrument: false, flags: []) end end + it "runs a default reduction before asking the lexer for the next token" do + with_lac_parser(<<~'GRAMMAR') do |parser| + %token A B BAD + %code provides { + static int enabled; + static int yylex(YYSTYPE *value) { + static int reads; + (void)value; + switch (reads++) { + case 0: return A; + case 1: return enabled ? B : BAD; + default: return YYEOF; + } + } + } + %% + start: prefix B; + prefix: A { enabled = 1; }; + %% + int main(void) { return yyparse(); } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + it "revalidates lookahead changed by a semantic action before further reductions" do with_lac_parser(<<~'GRAMMAR') do |parser| %code provides { static int reduced = 0; } @@ -96,7 +122,7 @@ def with_lac_parser(source, instrument: false, flags: []) it "revalidates a new lookahead after yyclearin even when its token kind is unchanged" do with_lac_parser(<<~'GRAMMAR', instrument: true) do |parser| %code provides { static int eof_checks = 0; } - %token A + %token A B %code provides { static int yylex(YYSTYPE *value) { static int i = 0; @@ -106,7 +132,7 @@ def with_lac_parser(source, instrument: false, flags: []) } %% start: n; - n: A { yyclearin; }; + n: A { yyclearin; } | A B; %% int main(void) { return yyparse() || eof_checks != 2; } GRAMMAR @@ -118,7 +144,7 @@ def with_lac_parser(source, instrument: false, flags: []) it "revalidates YYBACKUP after it changes the stack while keeping the same lookahead kind" do with_lac_parser(<<~'GRAMMAR', instrument: true) do |parser| %code provides { static int eof_checks = 0, backed_up = 0, reduced = 0; } - %token A + %token A B %code provides { static int yylex(YYSTYPE *value) { static int i = 0; @@ -136,6 +162,7 @@ def with_lac_parser(source, instrument: false, flags: []) } reduced++; } + | A B | %empty { reduced++; }; %% int main(void) { return yyparse() || !backed_up || reduced != 1 || eof_checks != 2; } diff --git a/spec/lrama/lexer_context_classifier_spec.rb b/spec/lrama/lexer_context_classifier_spec.rb index c69d40d05..d25488b89 100644 --- a/spec/lrama/lexer_context_classifier_spec.rb +++ b/spec/lrama/lexer_context_classifier_spec.rb @@ -71,7 +71,7 @@ def build_classifier_with_contexts it "classifies operator-like terminals" do %w[tPLUS tMINUS].each do |name| - sym = double("symbol", id: double("id", s_value: name), term?: true) + sym = double("symbol", name: name, term?: true) ctx = classifier.classify_symbol_context(sym) # BEG = 1 << 0 = 0x01 expect(ctx).to eq(0x01), "Expected #{name} to be BEG" @@ -80,7 +80,7 @@ def build_classifier_with_contexts it "classifies identifier terminals as CMDARG" do %w[tIDENTIFIER tFID tCONSTANT].each do |name| - sym = double("symbol", id: double("id", s_value: name), term?: true) + sym = double("symbol", name: name, term?: true) ctx = classifier.classify_symbol_context(sym) # CMDARG = 1 << 1 = 0x02 expect(ctx).to eq(0x02), "Expected #{name} to be CMDARG" @@ -89,7 +89,7 @@ def build_classifier_with_contexts it "classifies literal terminals as END" do %w[tINTEGER tFLOAT tSTRING_END].each do |name| - sym = double("symbol", id: double("id", s_value: name), term?: true) + sym = double("symbol", name: name, term?: true) ctx = classifier.classify_symbol_context(sym) # END = 1 << 2 = 0x04 expect(ctx).to eq(0x04), "Expected #{name} to be END" @@ -97,7 +97,7 @@ def build_classifier_with_contexts end it "classifies keyword_def as ENDFN" do - sym = double("symbol", id: double("id", s_value: "keyword_def"), term?: true) + sym = double("symbol", name: "keyword_def", term?: true) ctx = classifier.classify_symbol_context(sym) # ENDFN = 1 << 3 = 0x08 expect(ctx).to eq(0x08) @@ -105,7 +105,7 @@ def build_classifier_with_contexts it "classifies dot tokens as DOT" do %w[tDOT tCOLON2 tANDDOT].each do |name| - sym = double("symbol", id: double("id", s_value: name), term?: true) + sym = double("symbol", name: name, term?: true) ctx = classifier.classify_symbol_context(sym) # DOT = 1 << 4 = 0x10 expect(ctx).to eq(0x10), "Expected #{name} to be DOT" @@ -114,7 +114,7 @@ def build_classifier_with_contexts it "classifies open brackets as BEG" do %w[tLPAREN tLBRACK tLBRACE].each do |name| - sym = double("symbol", id: double("id", s_value: name), term?: true) + sym = double("symbol", name: name, term?: true) ctx = classifier.classify_symbol_context(sym) expect(ctx).to eq(0x01), "Expected #{name} to be BEG" end @@ -122,14 +122,14 @@ def build_classifier_with_contexts it "classifies close brackets as END" do %w[tRPAREN tRBRACK tRBRACE].each do |name| - sym = double("symbol", id: double("id", s_value: name), term?: true) + sym = double("symbol", name: name, term?: true) ctx = classifier.classify_symbol_context(sym) expect(ctx).to eq(0x04), "Expected #{name} to be END" end end it "returns 0 for unknown symbols" do - sym = double("symbol", id: double("id", s_value: "unknown_token"), term?: true) + sym = double("symbol", name: "unknown_token", term?: true) ctx = classifier.classify_symbol_context(sym) expect(ctx).to eq(0) end @@ -152,7 +152,7 @@ def build_classifier_with_contexts states.compute states.compute_pslr - target = states.states.first.term_transitions.find { |shift| shift.next_sym.id.s_value == "A" }.to_state + target = states.states.first.term_transitions.find { |shift| shift.next_sym.name == "A" }.to_state expect(target.lexer_context).to eq(3) end end @@ -354,7 +354,7 @@ def build_classifier_with_contexts operator_target_states = [] states.states.each do |state| state.term_transitions.each do |shift| - name = shift.next_sym.id.s_value + name = shift.next_sym.name if name == "tPLUS" || name == "tSTAR" operator_target_states << shift.to_state end @@ -410,7 +410,7 @@ def build_classifier_with_contexts def_target = nil states.states.each do |state| state.term_transitions.each do |shift| - if shift.next_sym.id.s_value == "keyword_def" + if shift.next_sym.name == "keyword_def" def_target = shift.to_state end end diff --git a/spec/lrama/lexer_params_runtime_spec.rb b/spec/lrama/lexer_params_runtime_spec.rb index 523e1c06b..a84852c55 100644 --- a/spec/lrama/lexer_params_runtime_spec.rb +++ b/spec/lrama/lexer_params_runtime_spec.rb @@ -77,11 +77,11 @@ def run_parser(source, lexer: nil) GRAMMAR end - it "forwards a separately compiled bridge lexer's parameter through the layout macro" do + it "forwards a separately compiled bridge lexer's parameters through the layout macro" do lexer = <<~C_CODE #include "parser.h" - int yylex(YYSTYPE *value, struct lexer_state *Result) { + int yylex(YYSTYPE *value, struct lexer_state *Result, int *count) { yypslr_scan_result result; int token = YYPSLR_SCAN_WITH_LAYOUT(Result->current_state, &Result->input, &Result->remaining, value, &result); if (token != YYEOF && token != YYEMPTY) { @@ -94,30 +94,30 @@ def run_parser(source, lexer: nil) run_parser(<<~GRAMMAR, lexer: lexer) %define lr.type pslr %define api.pslr.state-member current_state - %lex-param {struct lexer_state *Result} - %parse-param {struct lexer_state *Result} + %param {struct lexer_state *Result} {int *count} %code requires { #include struct lexer_state { int current_state; int counter; const char *input; size_t remaining; }; } %code provides { - int yylex(YYSTYPE *value, struct lexer_state *p); - int yyerror(YYLTYPE *loc, struct lexer_state *p, const char *message); + int yylex(YYSTYPE *value, struct lexer_state *p, int *count); + int yyerror(YYLTYPE *loc, struct lexer_state *p, int *count, const char *message); } %token-pattern A /a/ %token-pattern YYLAYOUT_WS / +/ %token-action A { yylval = ++Result->counter; } %token-action YYLAYOUT_WS { ++Result->counter; } - %token-action YYEOF { ++Result->counter; } + %token-action YYEOF { ++*count; } %% start: A { if ($1 != 2) YYABORT; }; %% - int yyerror(YYLTYPE *loc, struct lexer_state *p, const char *message) - { (void)loc; (void)p; (void)message; return 0; } + int yyerror(YYLTYPE *loc, struct lexer_state *p, int *count, const char *message) + { (void)loc; (void)p; (void)count; (void)message; return 0; } int main(void) { struct lexer_state state = { 0, 0, " a ", 3 }; - return yyparse(&state) || state.counter != 4; + int count = 0; + return yyparse(&state, &count) || state.counter != 3 || count != 1; } GRAMMAR end diff --git a/spec/lrama/output_spec.rb b/spec/lrama/output_spec.rb index b6ddc3c18..aa15d455e 100644 --- a/spec/lrama/output_spec.rb +++ b/spec/lrama/output_spec.rb @@ -400,13 +400,13 @@ let(:mock_grammar) do instance_double( Lrama::Grammar, - eof_symbol: instance_double(Lrama::Grammar::Symbol, id: Lrama::Lexer::Token::Ident.new(s_value: "YYEOF")), + eof_symbol: instance_double(Lrama::Grammar::Symbol, name: "YYEOF"), error_symbol: nil, undef_symbol: nil, accept_symbol: nil, locations: false, - parse_param: "struct parse_params *p", - lex_param: "struct parse_params *p", + parse_params: ["struct parse_params *p"], + lex_params: ["struct parse_params *p"], pslr_defined?: true, pslr_state_member: "current_state", parse_lac_full?: true, @@ -480,11 +480,6 @@ expect(result).to include("while (i < input_len)") expect(result).not_to include("input[i] != '\\0'") end - - it "marks fallback-row and character-token matches with from_fallback" do - result = pslr_output.pseudo_scan_function - expect(result.scan("result->from_fallback = 1;").size).to eq(2) - end end describe "#pslr_tables_and_functions" do @@ -521,9 +516,9 @@ result = pslr_output.pslr_layout_declarations expect(result).to include("static int\nyypslr_layout_append") - expect(result).to include("length > INT_MAX - yypslr_layout_length") + expect(result).to include("length > INT_MAX - scanner->length") expect(result).to include("YYMALLOC (capacity)") - expect(result).not_to include("yypslr_layout_length + length") + expect(result).not_to include("scanner->length + length") end end diff --git a/spec/lrama/parser_spec.rb b/spec/lrama/parser_spec.rb index 5ad5aaef6..4db17a23a 100644 --- a/spec/lrama/parser_spec.rb +++ b/spec/lrama/parser_spec.rb @@ -5196,7 +5196,37 @@ class : keyword_class tSTRING keyword_end end describe "PSLR directives" do + it "evaluates lexical declarations on both sides of %% in source order" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "declarations.y").parse + %token A 300 "letter" + %token-pattern A /a/ B /b/ + %% + start: "letter" B; + %token-action A { a(); } B { b(); }; + %token-pattern C /c/; + GRAMMAR + + grammar.prepare + expect(grammar.token_patterns.map { |pattern| [pattern.name, pattern.tag.s_value] }).to eq([ + ["A", ""], ["B", ""], ["C", ""] + ]) + expect(grammar.find_symbol_by_s_value!("A").token_id).to eq(300) + expect(grammar.token_actions.map(&:token_name)).to eq(%w[A B]) + expect(grammar.nodes.map { |node| node.loc.first_line }).to eq([1, 2, 2, 4, 5, 5, 6]) + end + describe "%token-pattern" do + it "resumes lexing line comments after a declaration in the rules section" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "declarations.y").parse + %% + %token-pattern A /a/; + start: A // first rule + ; + GRAMMAR + grammar.prepare + expect(grammar.rules.last.rhs.map(&:name)).to eq(["A"]) + end + it "parses a single token pattern" do y = <<~GRAMMAR %token-pattern RSHIFT />>/ "right shift" @@ -5273,7 +5303,7 @@ class : keyword_class tSTRING keyword_end rule = grammar.rules.last expect(rule.translated_code(grammar)).to eq(" use((yyvsp[0].val)); ") - expect(rule.rhs.first.id.s_value).to eq("A") + expect(rule.rhs.first.name).to eq("A") expect(rule.rhs.first.alias_name).to eq('"letter"') end end @@ -5292,7 +5322,7 @@ class : keyword_class tSTRING keyword_end rule = grammar.rules.last expect(rule.translated_code(grammar)).to eq(" use((yyvsp[0].val)); ") - expect(rule.rhs.first.id.s_value).to eq("A") + expect(rule.rhs.first.name).to eq("A") expect(rule.rhs.first.alias_name).to eq('"letter"') expect(rule.rhs.first.token_id).to eq(300) end diff --git a/spec/lrama/pslr_state_construction_spec.rb b/spec/lrama/pslr_state_construction_spec.rb new file mode 100644 index 000000000..f5554a1e5 --- /dev/null +++ b/spec/lrama/pslr_state_construction_spec.rb @@ -0,0 +1,115 @@ +# frozen_string_literal: true + +RSpec.describe Lrama::States, "PSLR state construction" do + let(:source) do + <<~GRAMMAR + %define lr.type pslr + %token P Q Z X + %lexer-context BEG P + %lexer-context CMDARG Q + %% + start: P n | Q n; + n: Z X | Z n; + GRAMMAR + end + + def states_for(source, define = {}) + grammar = Lrama::Parser.new(source, "states/pslr.y", false, false, define).parse + grammar.prepare + grammar.validate! + described_class.new(grammar, Lrama::Tracer.new(Lrama::Logger.new)) + end + + def transition(states, from, symbol) + from.transitions_by_symbol_number.fetch(states.find_symbol_by_s_value!(symbol).number).to_state + end + + it "preserves both predecessor contexts through neutral shifts and cycles" do + states = states_for(source) + states.compute + states.compute_pslr + + start = states.states.first + %w[P Q].zip([1, 2]).each do |name, context| + state = transition(states, start, name) + %w[Z Z X].each do |neutral| + state = transition(states, state, neutral) + expect(states.lexer_context_table[state.id]).to eq(context) + end + end + end + + it "keeps predecessors consistent with the final context-specific transitions" do + states = states_for(source) + states.compute + states.compute_pslr + states.states.each do |target| + incoming = states.states.select { |s| s.transitions.any? { |t| t.to_state.equal?(target) } } + expect(target.predecessors.map(&:id)).to match_array(incoming.map(&:id)) + end + end + + it "uses an explicit context on a transition in preference to an inherited one" do + states = states_for(source.sub("%%", "%lexer-context END Z\n%%")) + states.compute + states.compute_pslr + targets = states.states.select { |s| s.accessing_symbol == states.find_symbol_by_s_value!("Z") } + expect(targets.map(&:lexer_context)).to eq([4]) + end + + [ + ["empty: %empty %prec HIGH; direct: A %prec OP;", true], + ["direct: A %prec OP; empty: %empty %prec HIGH;", false], + ].each do |rules, accepts_op| + it "matches the parse table when competing reductions appear as #{rules}" do + states = states_for(<<~GRAMMAR) + %define lr.type pslr + %token A OP X Y Z + %nonassoc OP + %precedence HIGH + %% + start: A empty OP X | direct OP Y | A OP Z; + #{rules} + GRAMMAR + states.compute + states.compute_pslr + state = states.states.find { |candidate| candidate.reduces.size == 2 } + expect(states.pslr_acceptable_tokens(state).include?("OP")).to be(accepts_op) + incoming = state.item_lookahead_set + tokens = Lrama::State::ScannerAccepts.acceptable_tokens(state, states.symbols, incoming) + expect(tokens.include?("OP")).to be(accepts_op) + end + end + + describe "state limits" do + before do + allow(Lrama::State).to receive(:new).and_call_original + end + + it "stops constructing LR(0) states at the absolute limit" do + states = states_for(source, "pslr.max-states" => "5") + expect(Lrama::State).not_to receive(:new).with(5, anything, anything) + expect { states.compute }.to raise_error(/PSLR state growth exceeded pslr.max-states=5/) + expect(states.states_count).to eq(5) + end + + it "checks the absolute limit before allocating a scanner-driven split" do + grammar = File.read(fixture_path("command/pslr_growth_limit.y")) + states = states_for(grammar, "pslr.max-states" => "15") + states.compute + expect(states.states_count).to eq(14) + expect(Lrama::State).not_to receive(:new).with(15, anything, anything) + expect { states.compute_pslr }.to raise_error(/PSLR state growth exceeded pslr.max-states=15/) + expect(states.states_count).to eq(15) + end + + it "checks the ratio before allocating a lexer-context split" do + states = states_for(source, "pslr.max-state-ratio" => "1.0") + states.compute + base = states.states_count + expect(Lrama::State).not_to receive(:new).with(base, anything, anything) + expect { states.compute_pslr }.to raise_error(/PSLR state growth exceeded pslr.max-state-ratio=1.0/) + expect(states.states_count).to eq(base) + end + end +end diff --git a/spec/lrama/scanner_fsa_spec.rb b/spec/lrama/scanner_fsa_spec.rb index a02d69454..bbe627a0d 100644 --- a/spec/lrama/scanner_fsa_spec.rb +++ b/spec/lrama/scanner_fsa_spec.rb @@ -193,7 +193,7 @@ def token_pattern(name, regex, lineno: 1, order: 0) end describe "pattern validation" do - ["^foo", "foo$", "^foo$", "f^oo", "fo$o", "(foo|^bar)", "(foo$)bar"].each do |pattern| + ["^foo", "foo$", "^foo$", "f^oo", "foo$bar", "(foo|^bar)", "(foo$)bar"].each do |pattern| it "rejects unsupported anchors in #{pattern.inspect}" do expect { Lrama::ScannerFSA.new([token_pattern("ANCHORED", pattern, lineno: 14)]) } .to raise_error(Lrama::ScannerFSA::PatternError, /ANCHORED at line 14.*anchors are not supported.*offset/m) diff --git a/spec/lrama/scanner_termination_runtime_spec.rb b/spec/lrama/scanner_termination_runtime_spec.rb index b74155c59..e7459be70 100644 --- a/spec/lrama/scanner_termination_runtime_spec.rb +++ b/spec/lrama/scanner_termination_runtime_spec.rb @@ -68,6 +68,48 @@ def with_scanner(source) end end + it "keeps match lengths and source locations representable as int" do + with_scanner(<<~'GRAMMAR') + %code provides { + #include + /* Exercise the length boundary with a small input. */ + #undef INT_MAX + #define INT_MAX 7 + } + %locations + %token-pattern A /a+/ + %token-pattern NL /\n/ + %% + start: A NL; + %% + int main(void) { + yypslr_scan_result result; + int states[] = {0, YYFINAL}; + for (int i = 0; i < 2; i++) { + if (yy_pseudo_scan_result(states[i], "aaaaaaa", 7, &result) != A || result.length != 7 + || result.from_fallback != i || result.is_character_token) + return 1; + if (yy_pseudo_scan_result(states[i], "aaaaaaaa", 8, &result) != YYUNDEF || result.length != 7 + || result.from_fallback != i || result.is_character_token) + return 2; + if (yy_pseudo_scan_result(states[i], "?", 1, &result) != YYUNDEF || result.length != 1 + || !result.from_fallback || !result.is_character_token) + return 3; + } + YYSTYPE value; + YYLTYPE location; + yypslr_set_input("aaaaaaa\n\n\n\n\n\n\na", 15); + if (yylex(&value, &location) != A || location.last_column != INT_MAX) return 4; + for (int i = 0; i < 7; i++) { + if (yylex(&value, &location) != NL) return 5; + } + if (yylex(&value, &location) != A || location.first_line != INT_MAX + || location.first_column != 1 || location.last_column != 2) return 6; + return 0; + } + GRAMMAR + end + it "keeps scanning for reachable replacements and normal matches after fallback wins" do with_scanner(<<~'GRAMMAR') %token-pattern A /a+/ diff --git a/spec/lrama/state/scanner_accepts_spec.rb b/spec/lrama/state/scanner_accepts_spec.rb index a1f915048..e8987ac15 100644 --- a/spec/lrama/state/scanner_accepts_spec.rb +++ b/spec/lrama/state/scanner_accepts_spec.rb @@ -315,7 +315,8 @@ def parser_state(id, token_names) end scanner_accepts = Lrama::State::ScannerAccepts.new( tokens.each_with_index.map { |token, index| parser_state(index, [token.name]) }, - scanner_fsa, lex_prec, Lrama::LengthPrecedences.new(lex_prec) + scanner_fsa, lex_prec, Lrama::LengthPrecedences.new(lex_prec), + symbols: [] ) scanner_accepts.build diff --git a/spec/lrama/state_spec.rb b/spec/lrama/state_spec.rb index a8120c469..8db2c48d8 100644 --- a/spec/lrama/state_spec.rb +++ b/spec/lrama/state_spec.rb @@ -438,7 +438,7 @@ def annotation(contributions, from: origin, on: token, with: actions) ]) lookaheads = token_bitmap | Lrama::Bitmap.from_integer(rule.rhs.last.number) predecessor.item_lookahead_set = { next_item => lookaheads | 1 } - allow(predecessor).to receive(:goto_follow_set).with(rule.lhs).and_return(lookaheads | 1) + allow(predecessor).to receive(:goto_follow_set).with(rule.lhs, nil).and_return(lookaheads | 1) expect(predecessor.propagate_lookaheads(successor)).to eq({ next_item => lookaheads, last_item => lookaheads, diff --git a/template/bison/_pslr_scanner.c b/template/bison/_pslr_scanner.c new file mode 100644 index 000000000..6ded353f7 --- /dev/null +++ b/template/bison/_pslr_scanner.c @@ -0,0 +1,160 @@ +#ifndef YYPSLR_LAYOUT_DEFINED +# define YYPSLR_LAYOUT_DEFINED + +#include +#include + +typedef struct yypslr_layout { + const char *text; + int length; +} yypslr_layout; + +# ifndef YYPSLR_LAYOUT_BUFFER_SIZE +# define YYPSLR_LAYOUT_BUFFER_SIZE 4096 +# endif + +# if defined __cplusplus && 201103L <= __cplusplus +# define YYPSLR_THREAD_LOCAL thread_local +# elif defined _MSC_VER +# define YYPSLR_THREAD_LOCAL __declspec(thread) +# elif defined __STDC_VERSION__ && 201112L <= __STDC_VERSION__ +# define YYPSLR_THREAD_LOCAL _Thread_local +# elif defined __GNUC__ || defined __clang__ +# define YYPSLR_THREAD_LOCAL __thread +# else +# error "PSLR requires thread-local storage" +# endif + +typedef struct yypslr_scanner { + char initial[YYPSLR_LAYOUT_BUFFER_SIZE]; + char *buffer; + size_t capacity; + int length; +<%- if output.pslr_pure_mode? -%> + struct { + const char *cursor; + size_t remaining; + int parser_state; +<%- if output.grammar.locations -%> + const char *location_cursor; + int line, column; +<%- end -%> + } input; +<%- end -%> +} yypslr_scanner; + +/* Outside yyparse, scanner helpers operate on the calling thread's input. */ +static YYPSLR_THREAD_LOCAL yypslr_scanner yypslr_pending; +static YYPSLR_THREAD_LOCAL yypslr_scanner *yypslr_active; + +<%- if output.pslr_pure_mode? -%> +static YYPSLR_THREAD_LOCAL int yypslr_has_input; + +static void +yypslr_take_input (yypslr_scanner *scanner) +{ + scanner->input = yypslr_pending.input; + memset (&yypslr_pending.input, 0, sizeof yypslr_pending.input); + yypslr_has_input = 0; +} +<%- end -%> + +static yypslr_scanner * +yypslr_current (void) +{ + return yypslr_active ? yypslr_active : &yypslr_pending; +} + +static char * +yypslr_layout_buffer (yypslr_scanner *scanner) +{ + return scanner->buffer ? scanner->buffer : scanner->initial; +} + +static void +yypslr_layout_clear (yypslr_scanner *scanner) +{ + if (scanner->buffer) + YYFREE (scanner->buffer); + scanner->buffer = 0; + scanner->capacity = 0; + scanner->length = 0; + scanner->initial[0] = '\0'; +} + +static int +yypslr_layout_append (const char *text, int length) +{ + yypslr_scanner *scanner = yypslr_current (); + char *text_buffer = yypslr_layout_buffer (scanner); + size_t capacity = scanner->buffer ? scanner->capacity : sizeof scanner->initial; + size_t required; + if (length < 0 || length > INT_MAX - scanner->length) + return 0; + + required = (size_t) scanner->length + (size_t) length + 1; + if (required > (size_t) YYSIZE_MAXIMUM) + return 0; + if (required > capacity) + { + char *buffer; + while (capacity < required) + capacity = capacity > (size_t) YYSIZE_MAXIMUM / 2 ? required : capacity * 2; + buffer = YY_CAST (char *, YYMALLOC (capacity)); + if (!buffer) + return 0; + memcpy (buffer, text_buffer, (size_t) scanner->length); + if (scanner->buffer) + YYFREE (scanner->buffer); + text_buffer = scanner->buffer = buffer; + scanner->capacity = capacity; + } + + memcpy (text_buffer + scanner->length, text, (size_t) length); + scanner->length += length; + text_buffer[scanner->length] = '\0'; + return 1; +} + +# define YYPSLR_LAYOUT_TEXT yypslr_layout_buffer (yypslr_current ()) +# define YYPSLR_LAYOUT_LENGTH (yypslr_current ()->length) +# define YYPSLR_LAYOUT_CLEAR() yypslr_layout_clear (yypslr_current ()) +# define YYPSLR_LAYOUT_APPEND(Text, Len) yypslr_layout_append ((Text), (Len)) + +static void +yypslr_leave (yypslr_scanner *outer) +{ +<%- if output.pslr_pure_mode? -%> + if (!outer && !yypslr_has_input) + yypslr_pending.input = yypslr_active->input; +<%- end -%> + YYPSLR_LAYOUT_CLEAR (); + yypslr_active = outer; +} + +typedef struct yypslr_scope { + yypslr_scanner frame; + yypslr_scanner *outer; +#ifdef __cplusplus + ~yypslr_scope () { yypslr_leave (outer); } +#endif +} yypslr_scope; + +static void +yypslr_enter (yypslr_scope *scope) +{ + memset (&scope->frame, 0, sizeof scope->frame); +<%- if output.pslr_pure_mode? -%> + yypslr_take_input (&scope->frame); +<%- end -%> + scope->outer = yypslr_active; + yypslr_active = &scope->frame; +} + +#ifdef __cplusplus +# define YYPSLR_LEAVE(Scope) ((void) 0) +#else +# define YYPSLR_LEAVE(Scope) yypslr_leave ((Scope).outer) +#endif + +#endif /* YYPSLR_LAYOUT_DEFINED */ diff --git a/template/bison/yacc.c b/template/bison/yacc.c index fce2628ca..39140c0c2 100644 --- a/template/bison/yacc.c +++ b/template/bison/yacc.c @@ -1730,8 +1730,26 @@ yyrecover(yy_state_t *yyss, yy_state_t *yyssp, int yychar<%= output.user_formals | yyparse. | `----------*/ +<%- if output.pslr_scanner_enabled? || output.pslr_pure_mode? -%> +static int yypslr_parse (<%= output.parse_param %>); + int yyparse (<%= output.parse_param %>) +{ + yypslr_scope yypslr_call; + int yypslr_result; + yypslr_enter (&yypslr_call); + yypslr_result = yypslr_parse (<%= output.parse_param_name %>); + YYPSLR_LEAVE (yypslr_call); + return yypslr_result; +} + +static int +yypslr_parse (<%= output.parse_param %>) +<%- else -%> +int +yyparse (<%= output.parse_param %>) +<%- end -%> { <%# b4_declare_scanner_communication_variables -%> /* Lookahead token kind. */ @@ -1943,8 +1961,7 @@ YYLTYPE yylloc = yyloc_default; /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; <%- if output.lac_enabled? -%> - /* Default reductions also need lookahead from the repair queue for LAC. */ - if (yypact_value_is_default (yyn) && yydefact[yystate] == 0) + if (yypact_value_is_default (yyn) && yychar == YYEMPTY) <%- else -%> if (yypact_value_is_default (yyn)) <%- end -%> From 93372fd1d91c8e8c005f46a81c892a93277a9169 Mon Sep 17 00:00:00 2001 From: ydah Date: Sat, 21 Nov 2026 22:13:39 +0900 Subject: [PATCH 23/24] pslr: fix scanner reachability and generated lexer regressions Build scanner rows from selected shifts and viable reductions. Preserve rows that semantic actions can reach when lookahead is unchecked. Distinguish quoted literals in lexer contexts, decode implicit string patterns, and require coverage for input terminals. Allow custom location types in generated lexers, keep CLI diagnostics on validation errors, and pass long layout test inputs through stdin on Windows. --- NEWS.md | 8 +- lib/lrama/command.rb | 2 +- lib/lrama/grammar.rb | 5 +- lib/lrama/grammar/symbol.rb | 73 ++++++------ lib/lrama/lexer_context_classifier.rb | 6 +- lib/lrama/output.rb | 21 +++- lib/lrama/states.rb | 131 +++++++++++++++------ sig/generated/lrama/grammar/symbol.rbs | 8 ++ sig/generated/lrama/states.rbs | 32 +++-- spec/lrama/command_spec.rb | 8 +- spec/lrama/generated_runtime_spec.rb | 37 ++++++ spec/lrama/grammar_spec.rb | 34 ++++++ spec/lrama/lac_runtime_spec.rb | 28 ++++- spec/lrama/layout_runtime_spec.rb | 12 +- spec/lrama/pslr_state_construction_spec.rb | 81 +++++++++++++ spec/lrama/states_spec.rb | 5 +- template/bison/yacc.c | 2 +- 17 files changed, 385 insertions(+), 108 deletions(-) diff --git a/NEWS.md b/NEWS.md index f02e751cf..2e7e8c3e5 100644 --- a/NEWS.md +++ b/NEWS.md @@ -179,8 +179,12 @@ Two operating modes are supported. In pure mode (`%define api.pslr.lexer generat lexical analysis: `yylex` is generated, layout tokens are skipped with their text accumulated, `%token-action` bodies build semantic values from `yytext`/`yyleng`, and the caller hands the input to the parser with `yypslr_set_input(input, len)` before `yyparse`. Set the input on the thread that will parse it. A nested -`yyparse` call uses its own input cursor, source location, and layout buffer. Pure mode requires a -`%token-pattern` for every terminal. +`yyparse` call uses its own input cursor, source location, and layout buffer. In pure mode, each input terminal +used on the right-hand side of a rule needs an explicit or implicit token pattern. A symbol used only in +`%prec` supplies precedence without adding a scanner rule. +With `%locations`, the generated lexer reports one-based lines and byte columns, with an exclusive end. +To populate a custom `YYLTYPE`, define `YYPSLR_SET_LOCATION(Loc, FirstLine, FirstColumn, LastLine, LastColumn)` +in `%code requires` and assign the coordinates to `Loc`. In bridge mode, `%define api.pslr.state-member` names the field in the first parser parameter that stores the current parser state. An existing hand-written lexer consults the pseudo-scanner through helper macros such as `YYPSLR_PSEUDO_SCAN(Context, Input, InputLen, MatchLength)`; terminals without a diff --git a/lib/lrama/command.rb b/lib/lrama/command.rb index 6c93a84fc..f739e5221 100644 --- a/lib/lrama/command.rb +++ b/lib/lrama/command.rb @@ -33,9 +33,9 @@ def execute_command_workflow grammar = build_grammar(text) states, context = compute_status(grammar) render_reports(states) if @options.report_file - states.validate!(@logger) @tracer.trace(grammar) render_diagram(grammar) + states.validate!(@logger) render_output(context, grammar) @warnings.warn(grammar, states) end diff --git a/lib/lrama/grammar.rb b/lib/lrama/grammar.rb index 05dc02410..4ecae6811 100644 --- a/lib/lrama/grammar.rb +++ b/lib/lrama/grammar.rb @@ -404,9 +404,10 @@ def pslr_canonical_tables? # @rbs () -> Array[String] def uncovered_pslr_terminals covered = @token_patterns.map(&:name).to_set + used = @rules.each_with_object(Set.new) { |rule, symbols| symbols.merge(rule.rhs) } terms.reject do |term| - term == eof_symbol || term == error_symbol || term == undef_symbol || + !used.include?(term) || term == eof_symbol || term == error_symbol || term == undef_symbol || covered.include?(term.name) end.map(&:name) end @@ -657,7 +658,7 @@ def implicit_literal_regex_pattern(term) when :char term.character_code.chr when :string - term.name[1..-2] + term.string_literal end return if !literal || literal.empty? || !literal.ascii_only? diff --git a/lib/lrama/grammar/symbol.rb b/lib/lrama/grammar/symbol.rb index fda4325c5..4f0c15cbc 100644 --- a/lib/lrama/grammar/symbol.rb +++ b/lib/lrama/grammar/symbol.rb @@ -110,39 +110,7 @@ def character? # @rbs () -> Integer def character_code - # Ignore ' on both sides. - code = - case name[1..-2] - when "\\a" - 7 - when "\\b" - 8 - when "\\f" - 12 - when "\\n" - 10 - when "\\r" - 13 - when "\\t" - 9 - when "\\v" - 11 - when "\\\"" - 34 - when "\\'" - 39 - when "\\?" - 63 - when "\\\\" - 92 - when /\A\\([0-7]{1,3})\z/ - Integer($1, 8) - when /\A\\[xuU]([0-9a-fA-F]+)\z/ - Integer($1, 16) - when /\A(.)\z/ - $1&.bytes&.first - end - + code = literal_character_code(name[1..-2].to_s) raise "Unknown Char s_value #{name}" unless code unless (1..255).cover?(code) @@ -152,6 +120,15 @@ def character_code code end + # @rbs () -> String? + def string_literal + name[1..-2].to_s.gsub(/\\(?:[0-7]{1,3}|x[0-9a-fA-F]+|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)/) do |escape| + code = literal_character_code(escape) + return unless code && code < 128 + code.chr + end + end + # @rbs () -> bool def eof_symbol? !!@eof_symbol @@ -236,6 +213,36 @@ def comment display_name end end + + private + + # @rbs (String spelling) -> Integer? + def literal_character_code(spelling) + case spelling + when "\\a" + 7 + when "\\b" + 8 + when "\\f" + 12 + when "\\n" + 10 + when "\\r" + 13 + when "\\t" + 9 + when "\\v" + 11 + when "\\\"", "\\'", "\\?", "\\\\" + spelling.getbyte(1) + when /\A\\([0-7]{1,3})\z/ + Integer($1, 8) + when /\A\\[xuU]([0-9a-fA-F]+)\z/ + Integer($1, 16) + when /\A.\z/ + spelling.getbyte(0) + end + end end end end diff --git a/lib/lrama/lexer_context_classifier.rb b/lib/lrama/lexer_context_classifier.rb index ce9126561..1225481b1 100644 --- a/lib/lrama/lexer_context_classifier.rb +++ b/lib/lrama/lexer_context_classifier.rb @@ -56,11 +56,7 @@ def infer_item_context(item) # @rbs (Grammar::Symbol sym) -> Integer def classify_symbol_context(sym) name = sym.name - # Also try without surrounding quotes for single-char tokens - bare = name.gsub(/\A["']|["']\z/, "") - - # Direct match - ctx = @symbol_to_context[name] || @symbol_to_context[bare] + ctx = @symbol_to_context[name] return ctx if ctx # Fallback: inherit context from parameterized rule expansion arguments diff --git a/lib/lrama/output.rb b/lib/lrama/output.rb index 367d0af4a..587acad7e 100644 --- a/lib/lrama/output.rb +++ b/lib/lrama/output.rb @@ -1201,6 +1201,16 @@ def pslr_generated_lexer_function location_declarations = location_reset = location_start = location_end = "" if @grammar.locations location_declarations = <<~C_CODE + #ifndef YYPSLR_SET_LOCATION + # define YYPSLR_SET_LOCATION(Loc, FirstLine, FirstColumn, LastLine, LastColumn) \\ + do { \\ + (Loc).first_line = (FirstLine); \\ + (Loc).first_column = (FirstColumn); \\ + (Loc).last_line = (LastLine); \\ + (Loc).last_column = (LastColumn); \\ + } while (0) + #endif + static void yypslr_update_location (yypslr_scanner *yypslr_lexer) { @@ -1223,13 +1233,15 @@ def pslr_generated_lexer_function C_CODE location_start = <<~C_CODE yypslr_update_location (yypslr_lexer); - yyllocp->first_line = yypslr_lexer->input.line + 1; - yyllocp->first_column = yypslr_lexer->input.column + 1; + yypslr_first_line = yypslr_lexer->input.line + 1; + yypslr_first_column = yypslr_lexer->input.column + 1; C_CODE location_end = <<~C_CODE yypslr_update_location (yypslr_lexer); - yyllocp->last_line = yypslr_lexer->input.line + 1; - yyllocp->last_column = yypslr_lexer->input.column + 1; + YYPSLR_SET_LOCATION (*yyllocp, yypslr_first_line, yypslr_first_column, + yypslr_lexer->input.line + 1, yypslr_lexer->input.column + 1); + YY_USE (yypslr_first_line); + YY_USE (yypslr_first_column); C_CODE end @@ -1278,6 +1290,7 @@ def pslr_generated_lexer_function yypslr_scanner *yypslr_lexer = yypslr_current (); int yypslr_token; int yypslr_length; + #{@grammar.locations ? " int yypslr_first_line, yypslr_first_column;" : ""} #{lex_param_use} if (yypslr_has_input) diff --git a/lib/lrama/states.rb b/lib/lrama/states.rb index 9083d1d42..7d40d3027 100644 --- a/lib/lrama/states.rb +++ b/lib/lrama/states.rb @@ -216,8 +216,11 @@ def compute_pslr # Phase 5 report_duration(:compute_conflicts) { compute_conflicts(:ielr) } report_duration(:compute_default_reduction) { compute_default_reduction } - report_duration(:build_scanner_accepts) { build_scanner_accepts } - report_duration(:handle_pslr_inadequacies) { handle_pslr_inadequacies } + if @scanner_fsa + transitions = reachable_parser_transitions + report_duration(:build_scanner_accepts) { build_scanner_accepts(transitions.keys) } + report_duration(:handle_pslr_inadequacies) { handle_pslr_inadequacies(transitions) } + end finalize_pslr_metrics end @@ -1172,14 +1175,14 @@ def build_length_precedences end # Build scanner_accepts table - # @rbs () -> void - def build_scanner_accepts + # @rbs (Array[State] parser_states) -> void + def build_scanner_accepts(parser_states) return unless @scanner_fsa - collect_lexical_tie_candidates + collect_lexical_tie_candidates(parser_states) @scanner_accepts_table = State::ScannerAccepts.new( - reachable_parser_states, + parser_states, @scanner_fsa, lex_prec, @length_precedences, @@ -1191,11 +1194,9 @@ def build_scanner_accepts # Handle PSLR inadequacies # Detects and splits states where pseudo-scanner behavior differs - # @rbs () -> void - def handle_pslr_inadequacies - return unless @scanner_fsa && @scanner_accepts_table - - @pslr_inadequacies = detect_pslr_inadequacies + # @rbs (Hash[State, Array[State::transition]] transitions) -> void + def handle_pslr_inadequacies(transitions) + @pslr_inadequacies = detect_pslr_inadequacies(transitions) return if @pslr_inadequacies.empty? @tracer.warn("Detected #{@pslr_inadequacies.size} unresolved PSLR inadequacies") if @tracer.respond_to?(:warn) @@ -1221,14 +1222,13 @@ def finalize_pslr_metrics end # Detect PSLR inadequacies in isocore groups - # @rbs () -> Array[State::PslrInadequacy] - def detect_pslr_inadequacies + # @rbs (Hash[State, Array[State::transition]] transitions) -> Array[State::PslrInadequacy] + def detect_pslr_inadequacies(transitions) inadequacies = [] - @states.each do |state| - state.transitions.each do |transition| + transitions.each do |state, outgoing| + outgoing.each do |transition| next_state = transition.to_state - next unless next_state propagating_lookaheads = state.propagate_lookaheads(next_state.lalr_isocore, filter: false) expected_acc = acceptable_tokens_for_pslr(next_state, propagating_lookaheads) @@ -1259,8 +1259,8 @@ def detect_pslr_inadequacies inadequacies end - # @rbs () -> void - def collect_lexical_tie_candidates + # @rbs (Array[State] parser_states) -> void + def collect_lexical_tie_candidates(parser_states) @lexical_tie_candidates = [] return unless @scanner_fsa @@ -1268,7 +1268,7 @@ def collect_lexical_tie_candidates return if pairs.empty? candidates = Set.new - reachable_parser_states.each do |state| + parser_states.each do |state| pre_tie_tokens = acceptable_tokens_for_pslr(state, nil, expand_ties: false, include_layout: false) pairs.each do |left, right| next unless pre_tie_tokens.include?(left) ^ pre_tie_tokens.include?(right) @@ -1282,26 +1282,89 @@ def collect_lexical_tie_candidates @lexical_tie_candidates = candidates.to_a.sort end - # @rbs () -> Array[State] - def reachable_parser_states - return [] if @states.empty? - - visited = Set.new - stack = [@states.first] - reachable = [] + # @rbs () -> Hash[State, Array[State::transition]] + def reachable_parser_transitions + gotos = reducible_gotos + stack = @states.take(1) + reachable = {} #: Hash[State, Array[State::transition]] until stack.empty? state = stack.pop - next if visited.include?(state.id) + next if reachable.key?(state) - visited << state.id - reachable << state - state.transitions.each do |transition| - stack << transition.to_state if transition.to_state + transitions = state.selected_term_transitions + state.nterm_transitions.select { |goto| gotos.include?(goto) } + reachable[state] = transitions + transitions.each { |transition| stack << transition.to_state } + end + + reachable.sort_by { |state, _| state.id }.to_h + end + + # A goto on A can run after the parser traverses an entire RHS of A + # from that goto's source and selects the matching reduction at its end. + # @rbs () -> Set[State::Action::Goto] + def reducible_gotos + pending = [] #: Array[[State::Action::Goto, Array[State::Action::Goto]]] + lac = @grammar.parse_lac_full? + all_terminals = (1 << terms.size) - 1 + @states.each do |state| + lookbacks = @lookback_relation[state.id] + next unless lookbacks + + selected_reduction_lookaheads(state).each do |rule, lookaheads| + next if lookaheads.zero? + # LAC checks a fetched token before reduction. Unconditional defaults + # can run before fetching it, and unchecked actions can clear it. + check_follow = lac && lookaheads != all_terminals + lookbacks.fetch(rule.id, []).each do |goto| + next if check_follow && (@follow_sets.fetch(goto) & lookaheads).zero? + + current = goto.from_state + required = [] #: Array[State::Action::Goto] + shifts_selected = rule.rhs.all? do |symbol| + step = current.transitions_by_symbol_number.fetch(symbol.number) + current = step.to_state + required << step if step.is_a?(State::Action::Goto) + !(step.is_a?(State::Action::Shift) && step.not_selected) + end + pending << [goto, required] if shifts_selected + end end end - reachable.sort_by(&:id) + viable = Set.new #: Set[State::Action::Goto] + waiting = {} #: Hash[State::Action::Goto, Array[[State::Action::Goto, Array[State::Action::Goto]]]] + until pending.empty? + goto, required = pending.pop + next if viable.include?(goto) + + required.pop while !required.empty? && viable.include?(required.last) + if (dependency = required.last) + (waiting[dependency] ||= []) << [goto, required] + else + viable << goto + pending.concat(waiting.delete(goto) || []) + end + end + viable + end + + # A selected shift or explicit error takes priority over reductions. + # Among competing reductions the parse table selects the earliest rule. + # @rbs (State state) -> Hash[Grammar::Rule, Bitmap::bitmap] + def selected_reduction_lookaheads(state) + selected = {} #: Hash[Grammar::Rule, Bitmap::bitmap] + used = Bitmap.from_array(state.selected_term_transitions.map { |shift| shift.next_sym.number }) + used |= Bitmap.from_array(state.pslr_error_tokens.map(&:number)) + state.reduces.sort_by { |reduce| reduce.rule.id }.each do |reduce| + lookaheads = Bitmap.from_array(reduce.selected_look_ahead.map(&:number)) + selected[reduce.rule] = lookaheads & ~used + used |= lookaheads + end + if (default = state.default_reduction_rule) + selected[default] |= ((1 << terms.size) - 1) & ~used + end + selected end # @rbs (Logger logger) -> void @@ -1329,8 +1392,6 @@ def validate_pslr_scanner_conflicts!(logger) exit false end - # Pure mode owns lexical analysis completely, so every terminal must - # be producible by the pseudo-scanner. # @rbs (Logger logger) -> void def validate_pslr_pure_coverage!(logger) return unless pslr_defined? @@ -1340,7 +1401,7 @@ def validate_pslr_pure_coverage!(logger) return if uncovered.empty? logger.error( - "api.pslr.lexer generated requires a %token-pattern for every terminal; " \ + "api.pslr.lexer generated requires a %token-pattern for every input terminal; " \ "missing: #{uncovered.join(', ')}" ) exit false diff --git a/sig/generated/lrama/grammar/symbol.rbs b/sig/generated/lrama/grammar/symbol.rbs index d08e7ff6c..5f68dc468 100644 --- a/sig/generated/lrama/grammar/symbol.rbs +++ b/sig/generated/lrama/grammar/symbol.rbs @@ -79,6 +79,9 @@ module Lrama # @rbs () -> Integer def character_code: () -> Integer + # @rbs () -> String? + def string_literal: () -> String? + # @rbs () -> bool def eof_symbol?: () -> bool @@ -114,6 +117,11 @@ module Lrama # # @rbs () -> String? def comment: () -> String? + + private + + # @rbs (String spelling) -> Integer? + def literal_character_code: (String spelling) -> Integer? end end end diff --git a/sig/generated/lrama/states.rbs b/sig/generated/lrama/states.rbs index a2a6bb01c..764c9930b 100644 --- a/sig/generated/lrama/states.rbs +++ b/sig/generated/lrama/states.rbs @@ -298,26 +298,36 @@ module Lrama def build_length_precedences: () -> void # Build scanner_accepts table - # @rbs () -> void - def build_scanner_accepts: () -> void + # @rbs (Array[State] parser_states) -> void + def build_scanner_accepts: (Array[State] parser_states) -> void # Handle PSLR inadequacies # Detects and splits states where pseudo-scanner behavior differs - # @rbs () -> void - def handle_pslr_inadequacies: () -> void + # @rbs (Hash[State, Array[State::transition]] transitions) -> void + def handle_pslr_inadequacies: (Hash[State, Array[State::transition]] transitions) -> void # @rbs () -> void def finalize_pslr_metrics: () -> void # Detect PSLR inadequacies in isocore groups - # @rbs () -> Array[State::PslrInadequacy] - def detect_pslr_inadequacies: () -> Array[State::PslrInadequacy] + # @rbs (Hash[State, Array[State::transition]] transitions) -> Array[State::PslrInadequacy] + def detect_pslr_inadequacies: (Hash[State, Array[State::transition]] transitions) -> Array[State::PslrInadequacy] - # @rbs () -> void - def collect_lexical_tie_candidates: () -> void + # @rbs (Array[State] parser_states) -> void + def collect_lexical_tie_candidates: (Array[State] parser_states) -> void + + # @rbs () -> Hash[State, Array[State::transition]] + def reachable_parser_transitions: () -> Hash[State, Array[State::transition]] + + # A goto on A can run after the parser traverses an entire RHS of A + # from that goto's source and selects the matching reduction at its end. + # @rbs () -> Set[State::Action::Goto] + def reducible_gotos: () -> Set[State::Action::Goto] - # @rbs () -> Array[State] - def reachable_parser_states: () -> Array[State] + # A selected shift or explicit error takes priority over reductions. + # Among competing reductions the parse table selects the earliest rule. + # @rbs (State state) -> Hash[Grammar::Rule, Bitmap::bitmap] + def selected_reduction_lookaheads: (State state) -> Hash[Grammar::Rule, Bitmap::bitmap] # @rbs (Logger logger) -> void def validate_pslr_inadequacies!: (Logger logger) -> void @@ -325,8 +335,6 @@ module Lrama # @rbs (Logger logger) -> void def validate_pslr_scanner_conflicts!: (Logger logger) -> void - # Pure mode owns lexical analysis completely, so every terminal must - # be producible by the pseudo-scanner. # @rbs (Logger logger) -> void def validate_pslr_pure_coverage!: (Logger logger) -> void diff --git a/spec/lrama/command_spec.rb b/spec/lrama/command_spec.rb index 6256b62a5..103c86d6f 100644 --- a/spec/lrama/command_spec.rb +++ b/spec/lrama/command_spec.rb @@ -251,6 +251,7 @@ context "when validation fails with requested reports" do let(:outfile) { File.join(Dir.tmpdir, "invalid-parser.c") } let(:report_file) { File.join(Dir.tmpdir, "invalid-parser.output") } + let(:diagram_file) { File.join(Dir.tmpdir, "invalid-parser.html") } before do allow(STDIN).to receive(:read).and_return(source) @@ -259,23 +260,26 @@ after do File.delete(outfile) if File.exist?(outfile) File.delete(report_file) if File.exist?(report_file) + File.delete(diagram_file) if File.exist?(diagram_file) end shared_examples "a diagnostic report without parser output" do - it "writes the requested report before aborting" do + it "writes the requested diagnostics before aborting" do command = Lrama::Command.new([ "--report=pslr,states", "--report-file=#{report_file}", + "--trace=rules", "--diagram=#{diagram_file}", "-o", outfile, "-", "invalid.y" ]) expect do expect { command.run }.to raise_error(SystemExit) - end.to output(error_message).to_stderr_from_any_process + end.to output(/start -> .*#{error_message}/m).to_stderr_from_any_process expect(File).to exist(report_file) expect(File.read(report_file)).to include(report_message, "State 0") + expect(File.read(diagram_file)).to include('
') expect(File).not_to exist(outfile) end end diff --git a/spec/lrama/generated_runtime_spec.rb b/spec/lrama/generated_runtime_spec.rb index 36ccfbdef..ee7900754 100644 --- a/spec/lrama/generated_runtime_spec.rb +++ b/spec/lrama/generated_runtime_spec.rb @@ -289,6 +289,43 @@ def with_parser(source, flags: []) end end + it "sets custom token and EOF locations in the generated lexer" do + with_parser(<<~'GRAMMAR', flags: ["-Wunused-but-set-variable"]) do |parser| + %define lr.type pslr + %define api.pslr.lexer generated + %locations + %code requires { + struct Location { + int line, column; + #ifdef __cplusplus + explicit Location() : line(0), column(0) {} + #endif + }; + #define YYLTYPE struct Location + #define YYLLOC_DEFAULT(Current, Rhs, N) ((Current) = (Rhs)[N]) + #define YYPSLR_SET_LOCATION(Loc, FL, FC, LL, LC) \ + do { (Loc).line = (LL); (Loc).column = (LC); } while (0) + } + %token-pattern A /aa\nb/ + %token-pattern YYLAYOUT_WS /[ \n]+/ + %% + start: A { + if (@1.line != 3 || @1.column != 2) YYABORT; + }; + %% + int main(void) { + YYSTYPE value = 0; + YYLTYPE loc; + yypslr_set_input("\n aa\nb ", 7); + if (yyparse() || yylex(&value, &loc) != YYEOF) return 1; + return loc.line != 3 || loc.column != 3; + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + it "preserves the ninth and sixty-fourth lexer context flags" do declarations = (0...64).map { |i| "%lexer-context C#{i} A" }.join("\n") with_parser(<<~GRAMMAR) do |parser| diff --git a/spec/lrama/grammar_spec.rb b/spec/lrama/grammar_spec.rb index c74b9cb3e..c2764e8f2 100644 --- a/spec/lrama/grammar_spec.rb +++ b/spec/lrama/grammar_spec.rb @@ -635,7 +635,41 @@ def build_pslr_grammar(source) end end + describe "#uncovered_pslr_terminals" do + it "requires patterns for input terminals and skips precedence-only symbols" do + grammar = Lrama::Parser.new(<<~GRAMMAR, "precedence_only.y").parse + %define lr.type pslr + %define api.pslr.lexer generated + %token-pattern NUM /[0-9]+/ + %precedence UMINUS + %precedence OP + %% + expr: NUM | '-' expr %prec UMINUS | expr OP expr; + GRAMMAR + grammar.prepare + grammar.synthesize_implicit_literal_token_patterns! + + expect(grammar.uncovered_pslr_terminals).to eq(["OP"]) + end + end + describe "#synthesize_implicit_literal_token_patterns!" do + it "matches the decoded bytes of a quoted string literal" do + grammar = Lrama::Parser.new(<<~'GRAMMAR', "implicit_string.y").parse + %define lr.type pslr + %symbol-set delimiters "\n\042\\\x2b\u002e" + %% + start: "\n\042\\\x2b\u002e"; + GRAMMAR + grammar.prepare + grammar.synthesize_implicit_literal_token_patterns! + + scanner = Lrama::ScannerFSA.new(grammar.token_patterns) + literal = grammar.rules.last.rhs.first.name + expect(scanner.scan("\n\"\\+.").map { |match| match[:token].name }).to eq([literal]) + expect(scanner.scan(literal[1..-2])).to be_empty + end + it "adds exact-match token patterns for character literal terminals" do grammar = Lrama::Parser.new(<<~GRAMMAR, "implicit_literal.y").parse %define lr.type pslr diff --git a/spec/lrama/lac_runtime_spec.rb b/spec/lrama/lac_runtime_spec.rb index ea5b370a0..9c928aabc 100644 --- a/spec/lrama/lac_runtime_spec.rb +++ b/spec/lrama/lac_runtime_spec.rb @@ -4,7 +4,7 @@ require "tmpdir" RSpec.describe "LAC runtime" do - def with_lac_parser(source, instrument: false, flags: []) + def with_lac_parser(source, instrument: false, flags: [], lac: "full") Dir.mktmpdir("lrama-lac") do |dir| compiler = ENV.fetch("COMPILER", "cc") cpp = compiler.include?("++") @@ -12,7 +12,7 @@ def with_lac_parser(source, instrument: false, flags: []) output = File.join(dir, cpp ? "parser.cpp" : "parser.c") executable = File.join(dir, "parser") File.write(grammar, <<~GRAMMAR + source) - %define parse.lac full + %define parse.lac #{lac} %code provides { static int yyerror(YYLTYPE *loc, const char *message) { (void)loc; (void)message; return 0; } @@ -95,6 +95,30 @@ def with_lac_parser(source, instrument: false, flags: []) end end + it "retains scanner rows when a later action clears unchecked lookahead" do + with_lac_parser(<<~GRAMMAR, lac: "none") do |parser| + %define lr.type pslr + %define api.pslr.lexer generated + %token-pattern X /x/ + %token-pattern T /t/ + %token-pattern B /a/ + %token-pattern A /a/ + %right T + %% + start: short clear T A | X T; + short: X %prec T; + clear: %empty { yyclearin; }; + %% + int main(void) { + yypslr_set_input("x?ta", 4); + return yyparse(); + } + GRAMMAR + _out, err, status = Open3.capture3(parser) + expect(status.success?).to be(true), err + end + end + it "revalidates lookahead changed by a semantic action before further reductions" do with_lac_parser(<<~'GRAMMAR') do |parser| %code provides { static int reduced = 0; } diff --git a/spec/lrama/layout_runtime_spec.rb b/spec/lrama/layout_runtime_spec.rb index 1b9c8cb13..011d444a4 100644 --- a/spec/lrama/layout_runtime_spec.rb +++ b/spec/lrama/layout_runtime_spec.rb @@ -33,6 +33,7 @@ def with_parser(source) with_parser(<<~GRAMMAR) do |parser| %define parse.lac none %code provides { + #include #define YYSTACK_USE_ALLOCA 1 static int expected; static int invalid_layout; @@ -53,10 +54,11 @@ def with_parser(source) %% start: A; %% - int main(int argc, char **argv) { - if (argc != 2) return 1; - expected = (int)strlen(argv[1]) - 1; - yypslr_set_input(argv[1], strlen(argv[1])); + int main(void) { + char input[32768 + 2]; + if (!fgets(input, sizeof(input), stdin)) return 1; + expected = (int)strlen(input) - 1; + yypslr_set_input(input, strlen(input)); if (yyparse() || invalid_layout) return 2; expected = 0; yypslr_set_input("a", 1); @@ -64,7 +66,7 @@ def with_parser(source) } GRAMMAR [" " * 4095, " " * 4096, " " * 32768, " !" * 8192].each do |layout| - _out, err, status = Open3.capture3(parser, layout + "a") + _out, err, status = Open3.capture3(parser, stdin_data: layout + "a") expect(status.success?).to be(true), "#{layout.bytesize} bytes: exit #{status.exitstatus}: #{err}" end end diff --git a/spec/lrama/pslr_state_construction_spec.rb b/spec/lrama/pslr_state_construction_spec.rb index f5554a1e5..4f368f07c 100644 --- a/spec/lrama/pslr_state_construction_spec.rb +++ b/spec/lrama/pslr_state_construction_spec.rb @@ -57,6 +57,87 @@ def transition(states, from, symbol) expect(targets.map(&:lexer_context)).to eq([4]) end + it "keeps a character literal distinct from a named token in lexer contexts" do + states = states_for(<<~GRAMMAR) + %define lr.type pslr + %token a Z + %lexer-context BEG Z + %lexer-context AFTER_WORD a + %% + start: a Z | 'a' Z; + GRAMMAR + states.compute + states.compute_pslr + + start = states.states.first + expect(transition(states, start, "a").lexer_context).to eq(2) + expect(transition(states, start, "'a'").lexer_context).to eq(1) + end + + it "ignores scanner conflicts reached only through a shift disabled by precedence" do + states = states_for(<<~GRAMMAR) + %define lr.type pslr + %token-pattern X /x/ + %token-pattern T /t/ + %token-pattern A /a/ + %token-pattern B /a/ + %left T + %% + start: short T | X T suffix; + short: X %prec T; + suffix: A | B; + GRAMMAR + states.compute + states.compute_pslr + + expect(states.scanner_accepts_table.conflicts).to be_empty + expect(states.pslr_inadequacies).to be_empty + end + + it "follows a goto only where its rule can reduce" do + states = states_for(<<~GRAMMAR) + %define lr.type pslr + %token-pattern X /x/ + %token-pattern Y /y/ + %token-pattern T /t/ + %token-pattern A /a/ + %token-pattern B /a/ + %left T + %% + start: short T | X prefix suffix | Y prefix A; + short: X %prec T; + prefix: nested; + nested: T; + suffix: A | B; + GRAMMAR + states.compute + states.compute_pslr + + expect(states.scanner_accepts_table.conflicts).to be_empty + after_y = transition(states, states.states.first, "Y") + after_prefix = transition(states, after_y, "prefix") + expect(states.scanner_accepts_table.table.keys.map(&:first)).to include(after_prefix.id) + end + + it "excludes gotos whose only lookahead selects a shift over the default reduction" do + states = states_for(<<~GRAMMAR) + %define lr.type pslr + %token-pattern X /x/ + %token-pattern T /t/ + %token-pattern A /a/ + %token-pattern B /a/ + %right T + %% + start: short T suffix | X T; + short: X %prec T; + suffix: A | B; + GRAMMAR + states.compute + states.compute_pslr + + expect(states.scanner_accepts_table.conflicts).to be_empty + end + [ ["empty: %empty %prec HIGH; direct: A %prec OP;", true], ["direct: A %prec OP; empty: %empty %prec HIGH;", false], diff --git a/spec/lrama/states_spec.rb b/spec/lrama/states_spec.rb index be175a183..bc7b71fc1 100644 --- a/spec/lrama/states_spec.rb +++ b/spec/lrama/states_spec.rb @@ -4028,7 +4028,6 @@ class : keyword_class tSTRING keyword_end %prec tPLUS from_state = instance_double( Lrama::State, id: 1, - transitions: [transition], propagate_lookaheads: propagated, ) @@ -4040,9 +4039,7 @@ class : keyword_class tSTRING keyword_end %prec tPLUS allow(states).to receive(:acceptable_tokens_for_pslr).with(next_state, propagated).and_return(Set["RANGLE"]) allow(states).to receive(:acceptable_tokens_for_pslr).with(next_state).and_return(Set["RSHIFT"]) allow(states).to receive(:acceptable_tokens_for_pslr).with(matching_state).and_return(Set["RANGLE"]) - states.instance_variable_set(:@states, [from_state]) - - inadequacies = states.send(:detect_pslr_inadequacies) + inadequacies = states.send(:detect_pslr_inadequacies, { from_state => [transition] }) expect(inadequacies.size).to eq(1) expect(inadequacies.first.details[:matching_state_id]).to eq(8) diff --git a/template/bison/yacc.c b/template/bison/yacc.c index 39140c0c2..696a3d161 100644 --- a/template/bison/yacc.c +++ b/template/bison/yacc.c @@ -1768,7 +1768,7 @@ YY_INITIAL_VALUE (static const YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Location data for the lookahead symbol. */ -static const YYLTYPE yyloc_default +static YYLTYPE yyloc_default # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL = { 1, 1, 1, 1 } # endif From 0512355b13a0a029979e0b29768aa08e11d756a6 Mon Sep 17 00:00:00 2001 From: ydah Date: Sat, 21 Nov 2026 22:23:37 +0900 Subject: [PATCH 24/24] Only emit parser stack cleanup when relocation is enabled With a nontrivial C++ location type, the state stack stays in its local array. Use the relocation guard for the final free so GCC can compile this configuration with -Werror=free-nonheap-object. --- template/bison/yacc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/template/bison/yacc.c b/template/bison/yacc.c index 696a3d161..2cb32940b 100644 --- a/template/bison/yacc.c +++ b/template/bison/yacc.c @@ -1924,7 +1924,6 @@ YYLTYPE yylloc = yyloc_default; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); -# undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } @@ -2374,9 +2373,10 @@ YYLTYPE yylloc = yyloc_default; YY_ACCESSING_SYMBOL (+*yyssp), yyvsp, yylsp<%= output.user_args %>); YYPOPSTACK (1); } -#ifndef yyoverflow +#if !defined yyoverflow && defined YYSTACK_RELOCATE if (yyss != yyssa) YYSTACK_FREE (yyss); +# undef YYSTACK_RELOCATE #endif if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg);