Module: Lich::Gemstone::Combat::Definitions::PatternGate

Defined in:
documented/gemstone/combat/defs/pattern_gate.rb

Overview

Builds cheap literal-substring pre-filters for pattern sets to optimize matching performance.

A union of literal fragments extracted from patterns costs ~7us per line on real game text, compared to ~0.5-1ms per non-matching line for full regex alternation unions. Gates are derived automatically at load time so new patterns get gating for free and per-line cost stays flat as def files grow.

See Also:

Constant Summary collapse

MIN_LITERAL =

Build a gate for a list of patterns. Returns [union_regex, always_scan] where union_regex matches iff some pattern's literal is present, and always_scan lists patterns whose literal was too short to be a useful gate (they must be tried on every line).

4

Class Method Summary collapse

Class Method Details

.build(patterns) ⇒ Array

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Builds a gate for a list of patterns by extracting their longest guaranteed-literal runs.

Patterns with literals of 4+ characters are added to case-sensitive or case-insensitive unions; shorter or non-existent literals go into an always_scan list that must be tried on every line. Returns the gate regex and the patterns that bypass it, allowing the caller to reject lines that match neither the gate nor any always_scan pattern without full pattern matching.

Parameters:

  • patterns (Array<Regexp>) —

    regex patterns to extract literals from

Returns:

  • (Array) —

    tuple of [union_regex, always_scan] where union_regex is nil when no 4+-char literals exist, and always_scan is a frozen Array of Regexp patterns



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'documented/gemstone/combat/defs/pattern_gate.rb', line 116

def build(patterns)
  literals = []
  folded = []
  always_scan = []
  patterns.each do |pattern|
    literal = longest_literal(pattern)
    if literal && literal.length >= MIN_LITERAL
      # A case-folded pattern's literal has to be matched the same
      # way, or the gate rejects lines the pattern itself matches
      # (/ZEPHYR chills/i against "zephyr chills ..."). Folded
      # literals go into their own case-insensitive union rather
      # than sending the whole pattern to always_scan, which would
      # put every def of a case-folded family back on full scan.
      (case_folded?(pattern) ? folded : literals) << literal
    else
      always_scan << pattern
    end
  end
  [union_of(literals, folded), always_scan.freeze]
end

.case_folded?(regex) ⇒ Boolean

True when regex matches without regard to case, whether that was set as an option (//i, Regexp::IGNORECASE) or written inline as a global (?i) -- the inline form rides in the source and leaves options untouched. A scoped (?i:...) is not global, and its group is stripped out of the literal anyway.

Returns:

  • (Boolean)


97
98
99
100
101
102
103
# File 'documented/gemstone/combat/defs/pattern_gate.rb', line 97

def case_folded?(regex)
  return true if (regex.options & Regexp::IGNORECASE) != 0

  # Flags may be followed by a `-` group turning others off, as in
  # (?i-m); `i` before the dash still folds the whole pattern.
  regex.source.match?(/\(\?[a-z]*i[a-z]*(?:-[a-z]*)?\)/)
end

.longest_literal(regex) ⇒ Object

Longest guaranteed-literal run in a regex source, or nil when no safe literal exists. Character classes, escapes and then entire parenthesized groups (innermost-out, so nesting works) are removed wholesale - text inside a group may be optional or one alternation branch, so it is never guaranteed. What survives is top-level text that every match must contain; the longest metachar-free fragment of it is the gate literal. A source with a top-level | is a pure alternation with no guaranteed text - returns nil (always scan).



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'documented/gemstone/combat/defs/pattern_gate.rb', line 70

def longest_literal(regex)
  source = regex.source.dup
  source.gsub!(/\\[A-Za-z]/, "\x00")        # escape sequences (\d, \w, \b...)
  source.gsub!(/\[[^\]]*\]/, "\x00")        # character classes
  # Remove groups innermost-first so nested groups collapse cleanly
  nil while source.gsub!(/\((?:\?(?:<[a-zA-Z_]+>|:|=|!))?[^()]*\)/, "\x00")
  return nil if source.include?('|') # top-level alternation
  fragments = source.split(/[\\(){}?*+.^$\x00]/)
  # A fragment followed by ? or * in the original is optional; the
  # split above already breaks on those metachars, but the char
  # BEFORE ? belongs to the fragment - trim it to stay conservative.
  longest = fragments.max_by(&:length).to_s
  longest = longest[0..-2] if source =~ /#{Regexp.escape(longest)}[?*]/
  longest.empty? ? nil : longest
end

.rejects?(gate, always_scan, line) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Determines whether a line can be safely rejected without full pattern scanning.

Returns true only when the gate regex (if present) does not match and all always_scan patterns also fail to match. If the gate times out, the timeout is treated as undecided (not a rejection) so the line proceeds to full scan where the timeout is reported. A non-empty always_scan list does NOT blanket-disable rejection; it only adds patterns that must be tried before rejecting.

Parameters:

  • gate (Regexp, nil) —

    the union regex of extracted literals, or nil if no gating exists

  • always_scan (Array<Regexp>) —

    patterns with too-short or missing literals that bypass the gate

  • line (String) —

    the text line to test

Returns:

  • (Boolean) —

    true if the line cannot possibly match any pattern in this table



203
204
205
206
207
208
209
210
211
212
213
214
# File 'documented/gemstone/combat/defs/pattern_gate.rb', line 203

def rejects?(gate, always_scan, line)
  # A timeout anywhere in the gate leaves the answer UNDECIDED, so
  # the line goes to the full scan rather than being rejected:
  # deciding not to scan would hide every def behind this gate.
  # That scan re-evaluates the same pattern under safe_match,
  # which is where it gets reported. Distinguishing a timeout from
  # an honest non-match is the whole point -- safe_match?'s false
  # cannot tell them apart, so the raise is caught here.
  return false if gate && timeout_tolerant_match?(gate, line) != false

  always_scan.all? { |rx| timeout_tolerant_match?(rx, line) == false }
end

.report_timeout(pattern) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Reports a regex timeout through Supplements if available.

Called when a pattern exceeds its evaluation budget during matching. The timeout is attributed to that single pattern only, not to facts already yielded or defs after it.

Parameters:

  • pattern (Regexp) —

    the pattern that timed out



187
188
189
# File 'documented/gemstone/combat/defs/pattern_gate.rb', line 187

def report_timeout(pattern)
  Supplements.report_match_timeout(pattern) if defined?(Supplements)
end

.safe_match(pattern, line) ⇒ MatchData?

Convenience: true when the line can't possibly match any pattern in this table, so the caller may skip the full scan. A line is only rejectable when BOTH the literal gate misses AND no ungated (always_scan) pattern matches. Any always_scan pattern that matches keeps the line in play; a non-empty always_scan does NOT blanket- disable rejection (that was the old bug - it reverted the whole table to full-scan the moment one short-literal pattern existed). A pattern that exceeds its evaluation budget must cost that one pattern and nothing else: not the facts a line already yielded, not the defs after it, and not the worker's remaining work. Both helpers skip the offending pattern for this line and report it once per source, through Supplements so the dedup set and its reset-on-reload are shared with the compile-time reports.

Returns:



164
165
166
167
168
169
# File 'documented/gemstone/combat/defs/pattern_gate.rb', line 164

def safe_match(pattern, line)
  pattern.match(line)
rescue Regexp::TimeoutError
  report_timeout(pattern)
  nil
end

.safe_match?(pattern, line) ⇒ Boolean

Returns false when the pattern timed out.

Returns:

  • (Boolean) —

    false when the pattern timed out



172
173
174
175
176
177
# File 'documented/gemstone/combat/defs/pattern_gate.rb', line 172

def safe_match?(pattern, line)
  pattern.match?(line)
rescue Regexp::TimeoutError
  report_timeout(pattern)
  false
end

.timeout_tolerant_match?(pattern, line) ⇒ Boolean?

Returns true/false as matched, nil on a timeout.

Returns:

  • (Boolean, nil) —

    true/false as matched, nil on a timeout



217
218
219
220
221
222
# File 'documented/gemstone/combat/defs/pattern_gate.rb', line 217

def timeout_tolerant_match?(pattern, line)
  pattern.match?(line)
rescue Regexp::TimeoutError
  report_timeout(pattern)
  nil
end

.union_of(literals, folded) ⇒ Object

One gate regex covering both unions, or nil when there are no literals at all.



139
140
141
142
143
144
145
146
147
# File 'documented/gemstone/combat/defs/pattern_gate.rb', line 139

def union_of(literals, folded)
  exact = literals.empty? ? nil : Regexp.union(literals.uniq)
  loose = folded.empty? ? nil : Regexp.new(Regexp.union(folded.uniq).source, Regexp::IGNORECASE)
  return nil unless exact || loose
  return exact.freeze unless loose
  return loose.freeze unless exact

  Regexp.union(exact, loose).freeze
end

.union_or_nil(patterns, label) ⇒ Regexp?

Regexp.union of patterns, or nil when they cannot be combined.

A pattern that is perfectly valid on its own can still be illegal inside a union: a numbered backreference beside a named capture raises RegexpError ("numbered backref/call is not allowed"). Since a supplement may contribute either, a union of user and shipped patterns is not guaranteed to compile, and the caller gets nil rather than an exception.

Parameters:

  • patterns (Array<Regexp>)
  • label (String) —

    named in the report when the union fails

Returns:

  • (Regexp, nil) —

    frozen



236
237
238
239
240
241
# File 'documented/gemstone/combat/defs/pattern_gate.rb', line 236

def union_or_nil(patterns, label)
  Regexp.union(patterns).freeze
rescue RegexpError => e
  Supplements.report_union_failure(label, e) if defined?(Supplements)
  nil
end