flagnetic 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,20 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "unicode_tables"
4
+ require_relative "regex_vm"
4
5
 
5
6
  module Flagnetic
6
7
  # Eval is the evaluator; see flagnetic/eval.rb.
7
8
  module Eval
8
9
  # Regex compiles the pattern of a matches condition. Patterns are RE2
9
- # syntax, as the reference evaluator (Go's regexp) reads them. Ruby's
10
- # engine reads a different dialect: ^ and $ are line anchors, \s includes
10
+ # syntax, as the reference evaluator (Go's regexp) reads them. Ruby's own
11
+ # engine reads a different dialect (^ and $ are line anchors, \s includes
11
12
  # \v, (?m) means what RE2 calls (?s), (?i) folds ß to ss, lookarounds and
12
- # backreferences exist. So a pattern is never handed to Regexp as is: it
13
- # is parsed as RE2 and translated into an Onigmo expression that matches
14
- # exactly the same strings.
13
+ # backreferences exist) and backtracks, so a context value an end user
14
+ # chooses could make it burn CPU or, cut off by a time limit, answer
15
+ # differently from the server. So a pattern is never handed to Regexp: it
16
+ # is parsed as RE2, compiled to the program of a Pike VM and matched in
17
+ # time linear in the input.
15
18
  #
16
19
  # The policy:
17
20
  #
@@ -23,50 +26,52 @@ module Flagnetic
23
26
  # uses Go's simple folding orbits, not Ruby's.
24
27
  # - What RE2 rejects is rejected: lookarounds, backreferences, atomic
25
28
  # groups, possessive or nested repetition, \Z, \G, \h, \K, \R, \C,
26
- # comments, unknown escapes and flags. The condition is then
29
+ # comments, unknown escapes and flags, repeat counts above 1000 (also
30
+ # when nested repeats multiply past it), groups nested deeper than 1000
31
+ # and programs of more than Go's size limit. The condition is then
27
32
  # inconsistent_ruleset, as in every other evaluator.
28
33
  # - \p and \P under (?i) match the property's code points and every
29
34
  # code point sharing a folding orbit with one, as Go does; whether a
30
35
  # code point has the property is Ruby's Unicode data, the orbits are
31
36
  # Go's.
37
+ # - A string over 64 KiB is not matched: it is a non-match, not an error.
32
38
  # - A match searches anywhere in the string unless the pattern is
33
39
  # anchored. Every byte of invalid UTF-8 in the matched string reads as
34
- # one U+FFFD, as Go decodes it. On
35
- # Ruby 3.2 and later a match is cut off after MATCH_TIMEOUT seconds and
36
- # the condition is false; RE2 is linear time and never needs to.
40
+ # one U+FFFD, as Go decodes it.
37
41
  module Regex
38
42
  # Error is a pattern outside RE2 syntax or outside RE2.
39
43
  class Error < StandardError; end
40
44
 
41
- MATCH_TIMEOUT = 0.1
42
-
43
45
  REPLACEMENT = [0xFFFD].pack("U")
44
46
  private_constant :REPLACEMENT
45
47
 
46
- TIMEOUT_ERROR = defined?(Regexp::TimeoutError) ? Regexp::TimeoutError : Class.new(StandardError)
47
- private_constant :TIMEOUT_ERROR
48
+ # MAX_INPUT_BYTES is the longest string a pattern is matched against.
49
+ # The Pike VM's cost is the input times the program, and a context
50
+ # value is chosen by an end user, so a longer one is a non-match
51
+ # instead of a request that burns CPU.
52
+ MAX_INPUT_BYTES = 64 << 10
48
53
 
49
54
  # Pattern is a compiled matches pattern.
50
55
  class Pattern
51
- def initialize(regexp)
52
- @regexp = regexp
56
+ def initialize(program)
57
+ @program = program
53
58
  freeze
54
59
  end
55
60
 
56
- # match? reports whether s contains a match.
61
+ # match? reports whether s contains a match; a string over
62
+ # MAX_INPUT_BYTES contains none.
57
63
  def match?(str)
58
- @regexp.match?(str.valid_encoding? ? str : str.scrub { |bad| REPLACEMENT * bad.bytesize })
59
- rescue TIMEOUT_ERROR
60
- false
64
+ return false if str.bytesize > MAX_INPUT_BYTES
65
+
66
+ str = str.scrub { |bad| REPLACEMENT * bad.bytesize } unless str.valid_encoding?
67
+ Vm.search(@program, str.codepoints)
61
68
  end
62
69
  end
63
70
 
64
- # compile translates an RE2 pattern into a Pattern, raising Error when
65
- # it is not one this evaluator can match with RE2 semantics.
71
+ # compile parses an RE2 pattern into a Pattern, raising Error when it
72
+ # is not one this evaluator can match with RE2 semantics.
66
73
  def self.compile(pattern)
67
- source = Translator.new(pattern).translate
68
- options = Regexp.respond_to?(:timeout) ? { timeout: MATCH_TIMEOUT } : {}
69
- Pattern.new(Regexp.new(source, **options))
74
+ Pattern.new(Compiler.compile(Parser.new(pattern).parse))
70
75
  rescue RegexpError => e
71
76
  raise Error, e.message
72
77
  end
@@ -96,13 +101,36 @@ module Flagnetic
96
101
  "xdigit" => [[0x30, 0x39], [0x41, 0x46], [0x61, 0x66]]
97
102
  }.freeze
98
103
  SIMPLE_ESCAPES = { "a" => 0x07, "f" => 0x0C, "n" => 0x0A, "r" => 0x0D, "t" => 0x09, "v" => 0x0B }.freeze
99
- PROPERTY_NAMES = (["Any"] + UnicodeTables::PROPERTY_NAMES).to_h { |n| [n, true] }.freeze
100
- MAX_REPEAT = 1000
104
+ # canonical_name is Go's canonical form of a \p name: the separators _,
105
+ # - and space dropped, the first remaining character upper-cased and the
106
+ # rest lower-cased, ASCII letters only.
107
+ def self.canonical_name(name)
108
+ out = +""
109
+ name.each_char do |c|
110
+ next if ["_", "-", " "].include?(c)
111
+
112
+ out << (out.empty? ? c.tr("a-z", "A-Z") : c.tr("A-Z", "a-z"))
113
+ end
114
+ out
115
+ end
101
116
 
102
- W = "[0-9A-Za-z_]"
103
- WORD_BOUNDARY = "(?:(?<=#{W})(?!#{W})|(?<!#{W})(?=#{W}))".freeze
104
- NOT_WORD_BOUNDARY = "(?:(?<=#{W})(?=#{W})|(?<!#{W})(?!#{W}))".freeze
105
- private_constant :W
117
+ # PROPERTIES maps what Go reads a \p name as, once canonical, to the
118
+ # name of the property in Ruby's engine and whether it is inverted:
119
+ # the category and script names, the long names of categories, and the
120
+ # three Go adds, Any, ASCII and Assigned (every code point but
121
+ # Unassigned).
122
+ PROPERTIES = begin
123
+ names = UnicodeTables::PROPERTY_NAMES.to_h { |n| [Regex.canonical_name(n), [n, false]] }
124
+ UnicodeTables::CATEGORY_ALIASES.each { |a, actual| names[Regex.canonical_name(a)] ||= [actual, false] }
125
+ names.merge!("Lc" => ["LC", false], "Any" => ["Any", false], "Ascii" => ["ASCII", false],
126
+ "Assigned" => ["Cn", true]).freeze
127
+ end
128
+ MAX_REPEAT = 1000
129
+ MAX_DEPTH = 1000
130
+ # Go's limit on the size of a compiled expression, in instructions.
131
+ MAX_SIZE = (128 << 20) / 40
132
+ NO_NEWLINE = [[0, 9], [0xB, MAX_RUNE]].freeze
133
+ ANYTHING = [[0, MAX_RUNE]].freeze
106
134
 
107
135
  FOLD = 1
108
136
  MULTILINE = 2
@@ -160,16 +188,12 @@ module Flagnetic
160
188
  normalize(out)
161
189
  end
162
190
 
163
- # folded_property is a Onigmo class matching the code points with
164
- # property name, or without it when negated, and, under (?i), those
165
- # an orbit of simple case folding ties to one that has it. Go adds
166
- # the same code points (its FoldCategory and FoldScript tables).
167
- def folded_property(name, negated)
168
- extra = fold_extra(name)
169
- return "\\p{#{"^" if negated}#{name}}" if extra.empty?
170
-
171
- items = extra.map { |c| format("\\u{%x}", c) }.join
172
- negated ? "[\\p{^#{name}}&&[^#{items}]]" : "[\\p{#{name}}#{items}]"
191
+ # property is the class of the code points with property name, or
192
+ # without it when negated, and, under (?i), those an orbit of simple
193
+ # case folding ties to one that has it. Go adds the same code points
194
+ # (its FoldCategory and FoldScript tables).
195
+ def property(name, negated, fold)
196
+ Property.new(name, negated, fold && name != "Any" ? fold_extra(name) : [])
173
197
  end
174
198
 
175
199
  # fold_extra lists the code points without property name that share
@@ -185,23 +209,12 @@ module Flagnetic
185
209
  end
186
210
  end
187
211
  end
188
-
189
- # without_surrogates drops code points no Ruby string can hold; no Go
190
- # string decodes to them either, so they never match.
191
- def without_surrogates(ranges)
192
- normalize(ranges).flat_map do |lo, hi|
193
- next [[lo, hi]] if hi < SURROGATES.begin || lo > SURROGATES.end
194
-
195
- [([lo, SURROGATES.begin - 1] if lo < SURROGATES.begin),
196
- ([SURROGATES.end + 1, hi] if hi > SURROGATES.end)].compact
197
- end
198
- end
199
212
  end
200
213
 
201
- # Translator is a recursive-descent parser of RE2 syntax that emits the
202
- # equivalent Onigmo source as it goes. Every group is emitted
203
- # non-capturing: a condition only asks whether the pattern matches.
204
- class Translator
214
+ # Parser is a recursive-descent parser of RE2 syntax into a Node tree.
215
+ # Groups are never captured: a condition only asks whether the pattern
216
+ # matches.
217
+ class Parser
205
218
  def initialize(pattern)
206
219
  pattern = pattern.dup.force_encoding(Encoding::UTF_8)
207
220
  raise Error, "invalid UTF-8" unless pattern.valid_encoding?
@@ -210,11 +223,12 @@ module Flagnetic
210
223
  @pos = 0
211
224
  end
212
225
 
213
- def translate
214
- out = body(0, top: true)
226
+ def parse
227
+ node = body(0, 0, top: true)
215
228
  raise Error, "unexpected )" unless eof?
229
+ raise Error, "expression too large" if node.size > MAX_SIZE
216
230
 
217
- out
231
+ node
218
232
  end
219
233
 
220
234
  private
@@ -235,79 +249,73 @@ module Flagnetic
235
249
  advance
236
250
  end
237
251
 
238
- # Sequence is the Onigmo source of one group body as it is emitted,
239
- # with where its last repeatable operand starts.
240
- class Sequence
241
- attr_reader :source
242
-
243
- def initialize
244
- @source = +""
245
- @operand = nil
246
- @repeated = false
247
- end
248
-
249
- def operand(src)
250
- @operand = @source.size
251
- @repeated = false
252
- @source << src
253
- end
254
-
255
- # separate ends the current operand: after | or a flag group a
256
- # repetition has no argument.
257
- def separate(src = "")
258
- @operand = nil
259
- @source << src
260
- end
252
+ def cat(items) = items.size == 1 ? items[0] : Node.new(Node::CAT, subs: items)
261
253
 
262
- def repeat(quantifier)
263
- raise Error, "missing argument to repetition operator" if @operand.nil?
264
- raise Error, "invalid nested repetition operator" if @repeated
254
+ def alt(subs) = subs.size == 1 ? subs[0] : Node.new(Node::ALT, subs: subs)
265
255
 
266
- @source.insert(@operand, "(?:")
267
- @source << ")" << quantifier
268
- @repeated = true
269
- end
270
- end
256
+ def char(ranges) = Node.new(Node::CHAR, set: CharSet.new(ranges, [], false))
271
257
 
272
258
  # body parses alternatives up to an unmatched ) or the end. A flag
273
259
  # group without a body changes flags up to the end of the enclosing
274
260
  # group, across alternatives, as in RE2.
275
- def body(flags, top: false)
276
- seq = Sequence.new
261
+ def body(flags, depth, top: false)
262
+ alternatives = []
263
+ items = []
264
+ repeated = false
277
265
  until eof? || (peek == ")" && !top)
266
+ repeat = false
278
267
  case peek
279
268
  when ")" then raise Error, "unexpected )"
280
269
  when "|"
281
270
  advance
282
- seq.separate("|")
283
- when "*", "+", "?", "{" then repeat_or_literal(seq, flags)
284
- when "(" then flags = group(seq, flags)
285
- when "\\" then escape(seq, flags)
286
- else seq.operand(plain_atom(flags))
271
+ alternatives << cat(items)
272
+ items = []
273
+ when "*", "+", "?", "{" then repeat = repeat_or_literal(items, flags, repeated)
274
+ when "(" then flags = group(items, flags, depth)
275
+ when "\\" then escape(items, flags)
276
+ else items << plain_atom(flags)
287
277
  end
278
+ repeated = repeat
288
279
  end
289
- seq.source
280
+ alt([*alternatives, cat(items)])
290
281
  end
291
282
 
292
- def repeat_or_literal(seq, flags)
293
- quantifier = repetition
294
- return seq.repeat(quantifier) if quantifier
283
+ # repeat_or_literal applies a repetition to the last item, or reads a
284
+ # { that starts no well-formed repetition as a literal. It reports
285
+ # whether it repeated.
286
+ def repeat_or_literal(items, flags, repeated)
287
+ counts = repetition
288
+ if counts
289
+ repeat(items, *counts, repeated)
290
+ return true
291
+ end
295
292
 
296
293
  advance
297
- seq.operand(literal("{".ord, flags))
294
+ items << literal("{".ord, flags)
295
+ false
296
+ end
297
+
298
+ def repeat(items, lo, hi, counted, repeated)
299
+ raise Error, "invalid nested repetition operator" if repeated
300
+ raise Error, "missing argument to repetition operator" if items.empty?
301
+
302
+ node = Node.new(Node::REPEAT, subs: [items.pop], lo: lo, hi: hi, counted: counted)
303
+ raise Error, "invalid repeat count" if counted && (lo >= 2 || hi >= 2) && node.need > MAX_REPEAT
304
+ raise Error, "expression too large" if node.size > MAX_SIZE
305
+
306
+ items << node
298
307
  end
299
308
 
300
309
  # group reads a group or a flag group and returns the flags in force
301
310
  # after it.
302
- def group(seq, flags)
311
+ def group(items, flags, depth)
303
312
  advance
313
+ raise Error, "expression nests too deeply" if depth + 1 > MAX_DEPTH
314
+
304
315
  inner = group_flags(flags)
305
- if inner.is_a?(Array)
306
- seq.separate
307
- return inner.first
308
- end
316
+ return inner.first if inner.is_a?(Array)
309
317
 
310
- seq.operand("(?:#{body(inner)})")
318
+ items << body(inner, depth + 1)
311
319
  expect(")", "missing )")
312
320
  flags
313
321
  end
@@ -316,39 +324,36 @@ module Flagnetic
316
324
  c = advance
317
325
  case c
318
326
  when "[" then char_class(flags)
319
- when "." then flags.anybits?(DOT_NL) ? "(?m:.)" : "[^\\n]"
320
- when "^" then flags.anybits?(MULTILINE) ? "(?:\\A|(?<=\\n))" : "\\A"
321
- when "$" then flags.anybits?(MULTILINE) ? "(?:\\z|(?=\\n))" : "\\z"
327
+ when "." then char(flags.anybits?(DOT_NL) ? ANYTHING : NO_NEWLINE)
328
+ when "^" then Node.new(Node::ASSERT, what: flags.anybits?(MULTILINE) ? Vm::BEGIN_LINE : Vm::BEGIN_TEXT)
329
+ when "$" then Node.new(Node::ASSERT, what: flags.anybits?(MULTILINE) ? Vm::END_LINE : Vm::END_TEXT)
322
330
  else literal(c.ord, flags)
323
331
  end
324
332
  end
325
333
 
326
334
  # repetition consumes *, +, ? or a well-formed {n}, {n,} or {n,m},
327
- # and a lazy ?, returning the Onigmo quantifier. A { that does not
328
- # start a well-formed repetition is a literal: it returns nil and
329
- # consumes nothing. Laziness never changes whether a string matches.
335
+ # and a lazy ?, returning [lo, hi, counted] (hi -1 when unbounded). A
336
+ # { that does not start a well-formed repetition is a literal: it
337
+ # returns nil and consumes nothing. Laziness never changes whether a
338
+ # string matches.
330
339
  def repetition
331
340
  c = peek
332
- quantifier =
341
+ counts =
333
342
  if c == "{"
334
343
  counts = repeat_counts
335
344
  return nil unless counts
336
345
 
337
- min, max = counts
338
- invalid = min.negative? || min > MAX_REPEAT || max > MAX_REPEAT || (max >= 0 && min > max)
346
+ lo, hi = counts
347
+ invalid = lo.negative? || lo > MAX_REPEAT || hi > MAX_REPEAT || (hi >= 0 && lo > hi)
339
348
  raise Error, "invalid repeat count" if invalid
340
349
 
341
- if max == min
342
- "{#{min}}"
343
- else
344
- "{#{min},#{max.negative? ? "" : max}}"
345
- end
350
+ [lo, hi, true]
346
351
  else
347
352
  advance
348
- c
353
+ [c == "+" ? 1 : 0, c == "?" ? 1 : -1, false]
349
354
  end
350
355
  advance if peek == "?"
351
- quantifier
356
+ counts
352
357
  end
353
358
 
354
359
  # repeat_counts reads {n}, {n,} or {n,m} as [min, max] (max -1 when
@@ -426,11 +431,11 @@ module Flagnetic
426
431
  raise Error, "missing )"
427
432
  end
428
433
 
429
- # escape emits what follows a backslash; every character of
434
+ # escape adds what follows a backslash to items; every character of
430
435
  # \Q...\E is an operand of its own.
431
- def escape(seq, flags)
436
+ def escape(items, flags)
432
437
  atom = escape_atom(flags)
433
- atom.is_a?(Array) ? atom.each { |a| seq.operand(a) } : seq.operand(atom)
438
+ atom.is_a?(Array) ? items.concat(atom) : items << atom
434
439
  end
435
440
 
436
441
  # escape_atom translates what follows a backslash outside a class.
@@ -440,10 +445,10 @@ module Flagnetic
440
445
  raise Error, "trailing backslash" if eof?
441
446
 
442
447
  case peek
443
- when "A" then advance && "\\A"
444
- when "z" then advance && "\\z"
445
- when "b" then advance && WORD_BOUNDARY
446
- when "B" then advance && NOT_WORD_BOUNDARY
448
+ when "A" then advance && Node.new(Node::ASSERT, what: Vm::BEGIN_TEXT)
449
+ when "z" then advance && Node.new(Node::ASSERT, what: Vm::END_TEXT)
450
+ when "b" then advance && Node.new(Node::ASSERT, what: Vm::WORD_BOUNDARY)
451
+ when "B" then advance && Node.new(Node::ASSERT, what: Vm::NOT_WORD_BOUNDARY)
447
452
  when "Q" then advance && quoted_literals(flags)
448
453
  when "d", "s", "w", "D", "S", "W"
449
454
  ranges, props = perl_class(flags)
@@ -535,10 +540,9 @@ module Flagnetic
535
540
  negated = !negated
536
541
  name = name[1..]
537
542
  end
538
- raise Error, "invalid character class range" unless PROPERTY_NAMES.key?(name)
539
- return [[], [Sets.folded_property(name, negated)]] if flags.anybits?(FOLD) && name != "Any"
543
+ name, inverted = PROPERTIES.fetch(Regex.canonical_name(name)) { raise Error, "invalid character class range" }
540
544
 
541
- [[], ["\\p{#{"^" if negated}#{name}}"]]
545
+ [[], [Sets.property(name, negated != inverted, flags.anybits?(FOLD))]]
542
546
  end
543
547
 
544
548
  # char_class reads a class after its [.
@@ -610,37 +614,15 @@ module Flagnetic
610
614
 
611
615
  def literal(code_point, flags)
612
616
  ranges = [[code_point, code_point]]
613
- ranges = Sets.fold(ranges) if flags.anybits?(FOLD)
614
- if ranges.size == 1 && ranges[0][0] == ranges[0][1] && !SURROGATES.cover?(code_point)
615
- rune(code_point)
616
- else
617
- set(
618
- ranges, [], negated: false
619
- )
620
- end
617
+ char(flags.anybits?(FOLD) ? Sets.fold(ranges) : ranges)
621
618
  end
622
619
 
623
- # set emits a class. Ruby cannot hold surrogates, so they are dropped
624
- # from both a set and its negation; neither matches them in RE2.
620
+ # set builds the class of a [...] or an escape.
625
621
  def set(ranges, props, negated:)
626
- ranges = Sets.without_surrogates(ranges)
627
- if ranges.empty? && props.empty?
628
- negated ? "(?m:.)" : "(?!)"
629
- else
630
- items = ranges.map { |lo, hi| lo == hi ? rune(lo) : "#{rune(lo)}-#{rune(hi)}" }
631
- "[#{"^" if negated}#{items.join}#{props.join}]"
632
- end
633
- end
634
-
635
- def rune(code_point)
636
- if code_point < 0x80 && code_point.chr.match?(/\A[0-9A-Za-z]\z/)
637
- code_point.chr
638
- else
639
- format("\\u{%x}", code_point)
640
- end
622
+ Node.new(Node::CHAR, set: CharSet.new(Sets.normalize(ranges), props, negated))
641
623
  end
642
624
  end
643
- private_constant :Translator, :Sets
625
+ private_constant :Parser, :Sets
644
626
  end
645
627
  private_constant :Regex, :UnicodeTables
646
628
  end