flagnetic 0.1.0 → 0.1.2

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,7 +26,9 @@ 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
@@ -31,42 +36,32 @@ module Flagnetic
31
36
  # Go's.
32
37
  # - A match searches anywhere in the string unless the pattern is
33
38
  # 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.
39
+ # one U+FFFD, as Go decodes it.
37
40
  module Regex
38
41
  # Error is a pattern outside RE2 syntax or outside RE2.
39
42
  class Error < StandardError; end
40
43
 
41
- MATCH_TIMEOUT = 0.1
42
-
43
44
  REPLACEMENT = [0xFFFD].pack("U")
44
45
  private_constant :REPLACEMENT
45
46
 
46
- TIMEOUT_ERROR = defined?(Regexp::TimeoutError) ? Regexp::TimeoutError : Class.new(StandardError)
47
- private_constant :TIMEOUT_ERROR
48
-
49
47
  # Pattern is a compiled matches pattern.
50
48
  class Pattern
51
- def initialize(regexp)
52
- @regexp = regexp
49
+ def initialize(program)
50
+ @program = program
53
51
  freeze
54
52
  end
55
53
 
56
54
  # match? reports whether s contains a match.
57
55
  def match?(str)
58
- @regexp.match?(str.valid_encoding? ? str : str.scrub { |bad| REPLACEMENT * bad.bytesize })
59
- rescue TIMEOUT_ERROR
60
- false
56
+ str = str.scrub { |bad| REPLACEMENT * bad.bytesize } unless str.valid_encoding?
57
+ Vm.search(@program, str.codepoints)
61
58
  end
62
59
  end
63
60
 
64
- # compile translates an RE2 pattern into a Pattern, raising Error when
65
- # it is not one this evaluator can match with RE2 semantics.
61
+ # compile parses an RE2 pattern into a Pattern, raising Error when it
62
+ # is not one this evaluator can match with RE2 semantics.
66
63
  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))
64
+ Pattern.new(Compiler.compile(Parser.new(pattern).parse))
70
65
  rescue RegexpError => e
71
66
  raise Error, e.message
72
67
  end
@@ -96,13 +91,36 @@ module Flagnetic
96
91
  "xdigit" => [[0x30, 0x39], [0x41, 0x46], [0x61, 0x66]]
97
92
  }.freeze
98
93
  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
94
+ # canonical_name is Go's canonical form of a \p name: the separators _,
95
+ # - and space dropped, the first remaining character upper-cased and the
96
+ # rest lower-cased, ASCII letters only.
97
+ def self.canonical_name(name)
98
+ out = +""
99
+ name.each_char do |c|
100
+ next if ["_", "-", " "].include?(c)
101
+
102
+ out << (out.empty? ? c.tr("a-z", "A-Z") : c.tr("A-Z", "a-z"))
103
+ end
104
+ out
105
+ end
101
106
 
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
107
+ # PROPERTIES maps what Go reads a \p name as, once canonical, to the
108
+ # name of the property in Ruby's engine and whether it is inverted:
109
+ # the category and script names, the long names of categories, and the
110
+ # three Go adds, Any, ASCII and Assigned (every code point but
111
+ # Unassigned).
112
+ PROPERTIES = begin
113
+ names = UnicodeTables::PROPERTY_NAMES.to_h { |n| [Regex.canonical_name(n), [n, false]] }
114
+ UnicodeTables::CATEGORY_ALIASES.each { |a, actual| names[Regex.canonical_name(a)] ||= [actual, false] }
115
+ names.merge!("Lc" => ["LC", false], "Any" => ["Any", false], "Ascii" => ["ASCII", false],
116
+ "Assigned" => ["Cn", true]).freeze
117
+ end
118
+ MAX_REPEAT = 1000
119
+ MAX_DEPTH = 1000
120
+ # Go's limit on the size of a compiled expression, in instructions.
121
+ MAX_SIZE = (128 << 20) / 40
122
+ NO_NEWLINE = [[0, 9], [0xB, MAX_RUNE]].freeze
123
+ ANYTHING = [[0, MAX_RUNE]].freeze
106
124
 
107
125
  FOLD = 1
108
126
  MULTILINE = 2
@@ -160,16 +178,12 @@ module Flagnetic
160
178
  normalize(out)
161
179
  end
162
180
 
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}]"
181
+ # property is the class of the code points with property name, or
182
+ # without it when negated, and, under (?i), those an orbit of simple
183
+ # case folding ties to one that has it. Go adds the same code points
184
+ # (its FoldCategory and FoldScript tables).
185
+ def property(name, negated, fold)
186
+ Property.new(name, negated, fold && name != "Any" ? fold_extra(name) : [])
173
187
  end
174
188
 
175
189
  # fold_extra lists the code points without property name that share
@@ -185,23 +199,12 @@ module Flagnetic
185
199
  end
186
200
  end
187
201
  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
202
  end
200
203
 
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
204
+ # Parser is a recursive-descent parser of RE2 syntax into a Node tree.
205
+ # Groups are never captured: a condition only asks whether the pattern
206
+ # matches.
207
+ class Parser
205
208
  def initialize(pattern)
206
209
  pattern = pattern.dup.force_encoding(Encoding::UTF_8)
207
210
  raise Error, "invalid UTF-8" unless pattern.valid_encoding?
@@ -210,11 +213,12 @@ module Flagnetic
210
213
  @pos = 0
211
214
  end
212
215
 
213
- def translate
214
- out = body(0, top: true)
216
+ def parse
217
+ node = body(0, 0, top: true)
215
218
  raise Error, "unexpected )" unless eof?
219
+ raise Error, "expression too large" if node.size > MAX_SIZE
216
220
 
217
- out
221
+ node
218
222
  end
219
223
 
220
224
  private
@@ -235,79 +239,73 @@ module Flagnetic
235
239
  advance
236
240
  end
237
241
 
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
242
+ def cat(items) = items.size == 1 ? items[0] : Node.new(Node::CAT, subs: items)
261
243
 
262
- def repeat(quantifier)
263
- raise Error, "missing argument to repetition operator" if @operand.nil?
264
- raise Error, "invalid nested repetition operator" if @repeated
244
+ def alt(subs) = subs.size == 1 ? subs[0] : Node.new(Node::ALT, subs: subs)
265
245
 
266
- @source.insert(@operand, "(?:")
267
- @source << ")" << quantifier
268
- @repeated = true
269
- end
270
- end
246
+ def char(ranges) = Node.new(Node::CHAR, set: CharSet.new(ranges, [], false))
271
247
 
272
248
  # body parses alternatives up to an unmatched ) or the end. A flag
273
249
  # group without a body changes flags up to the end of the enclosing
274
250
  # group, across alternatives, as in RE2.
275
- def body(flags, top: false)
276
- seq = Sequence.new
251
+ def body(flags, depth, top: false)
252
+ alternatives = []
253
+ items = []
254
+ repeated = false
277
255
  until eof? || (peek == ")" && !top)
256
+ repeat = false
278
257
  case peek
279
258
  when ")" then raise Error, "unexpected )"
280
259
  when "|"
281
260
  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))
261
+ alternatives << cat(items)
262
+ items = []
263
+ when "*", "+", "?", "{" then repeat = repeat_or_literal(items, flags, repeated)
264
+ when "(" then flags = group(items, flags, depth)
265
+ when "\\" then escape(items, flags)
266
+ else items << plain_atom(flags)
287
267
  end
268
+ repeated = repeat
288
269
  end
289
- seq.source
270
+ alt([*alternatives, cat(items)])
290
271
  end
291
272
 
292
- def repeat_or_literal(seq, flags)
293
- quantifier = repetition
294
- return seq.repeat(quantifier) if quantifier
273
+ # repeat_or_literal applies a repetition to the last item, or reads a
274
+ # { that starts no well-formed repetition as a literal. It reports
275
+ # whether it repeated.
276
+ def repeat_or_literal(items, flags, repeated)
277
+ counts = repetition
278
+ if counts
279
+ repeat(items, *counts, repeated)
280
+ return true
281
+ end
295
282
 
296
283
  advance
297
- seq.operand(literal("{".ord, flags))
284
+ items << literal("{".ord, flags)
285
+ false
286
+ end
287
+
288
+ def repeat(items, lo, hi, counted, repeated)
289
+ raise Error, "invalid nested repetition operator" if repeated
290
+ raise Error, "missing argument to repetition operator" if items.empty?
291
+
292
+ node = Node.new(Node::REPEAT, subs: [items.pop], lo: lo, hi: hi, counted: counted)
293
+ raise Error, "invalid repeat count" if counted && (lo >= 2 || hi >= 2) && node.need > MAX_REPEAT
294
+ raise Error, "expression too large" if node.size > MAX_SIZE
295
+
296
+ items << node
298
297
  end
299
298
 
300
299
  # group reads a group or a flag group and returns the flags in force
301
300
  # after it.
302
- def group(seq, flags)
301
+ def group(items, flags, depth)
303
302
  advance
303
+ raise Error, "expression nests too deeply" if depth + 1 > MAX_DEPTH
304
+
304
305
  inner = group_flags(flags)
305
- if inner.is_a?(Array)
306
- seq.separate
307
- return inner.first
308
- end
306
+ return inner.first if inner.is_a?(Array)
309
307
 
310
- seq.operand("(?:#{body(inner)})")
308
+ items << body(inner, depth + 1)
311
309
  expect(")", "missing )")
312
310
  flags
313
311
  end
@@ -316,39 +314,36 @@ module Flagnetic
316
314
  c = advance
317
315
  case c
318
316
  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"
317
+ when "." then char(flags.anybits?(DOT_NL) ? ANYTHING : NO_NEWLINE)
318
+ when "^" then Node.new(Node::ASSERT, what: flags.anybits?(MULTILINE) ? Vm::BEGIN_LINE : Vm::BEGIN_TEXT)
319
+ when "$" then Node.new(Node::ASSERT, what: flags.anybits?(MULTILINE) ? Vm::END_LINE : Vm::END_TEXT)
322
320
  else literal(c.ord, flags)
323
321
  end
324
322
  end
325
323
 
326
324
  # 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.
325
+ # and a lazy ?, returning [lo, hi, counted] (hi -1 when unbounded). A
326
+ # { that does not start a well-formed repetition is a literal: it
327
+ # returns nil and consumes nothing. Laziness never changes whether a
328
+ # string matches.
330
329
  def repetition
331
330
  c = peek
332
- quantifier =
331
+ counts =
333
332
  if c == "{"
334
333
  counts = repeat_counts
335
334
  return nil unless counts
336
335
 
337
- min, max = counts
338
- invalid = min.negative? || min > MAX_REPEAT || max > MAX_REPEAT || (max >= 0 && min > max)
336
+ lo, hi = counts
337
+ invalid = lo.negative? || lo > MAX_REPEAT || hi > MAX_REPEAT || (hi >= 0 && lo > hi)
339
338
  raise Error, "invalid repeat count" if invalid
340
339
 
341
- if max == min
342
- "{#{min}}"
343
- else
344
- "{#{min},#{max.negative? ? "" : max}}"
345
- end
340
+ [lo, hi, true]
346
341
  else
347
342
  advance
348
- c
343
+ [c == "+" ? 1 : 0, c == "?" ? 1 : -1, false]
349
344
  end
350
345
  advance if peek == "?"
351
- quantifier
346
+ counts
352
347
  end
353
348
 
354
349
  # repeat_counts reads {n}, {n,} or {n,m} as [min, max] (max -1 when
@@ -426,11 +421,11 @@ module Flagnetic
426
421
  raise Error, "missing )"
427
422
  end
428
423
 
429
- # escape emits what follows a backslash; every character of
424
+ # escape adds what follows a backslash to items; every character of
430
425
  # \Q...\E is an operand of its own.
431
- def escape(seq, flags)
426
+ def escape(items, flags)
432
427
  atom = escape_atom(flags)
433
- atom.is_a?(Array) ? atom.each { |a| seq.operand(a) } : seq.operand(atom)
428
+ atom.is_a?(Array) ? items.concat(atom) : items << atom
434
429
  end
435
430
 
436
431
  # escape_atom translates what follows a backslash outside a class.
@@ -440,10 +435,10 @@ module Flagnetic
440
435
  raise Error, "trailing backslash" if eof?
441
436
 
442
437
  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
438
+ when "A" then advance && Node.new(Node::ASSERT, what: Vm::BEGIN_TEXT)
439
+ when "z" then advance && Node.new(Node::ASSERT, what: Vm::END_TEXT)
440
+ when "b" then advance && Node.new(Node::ASSERT, what: Vm::WORD_BOUNDARY)
441
+ when "B" then advance && Node.new(Node::ASSERT, what: Vm::NOT_WORD_BOUNDARY)
447
442
  when "Q" then advance && quoted_literals(flags)
448
443
  when "d", "s", "w", "D", "S", "W"
449
444
  ranges, props = perl_class(flags)
@@ -535,10 +530,9 @@ module Flagnetic
535
530
  negated = !negated
536
531
  name = name[1..]
537
532
  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"
533
+ name, inverted = PROPERTIES.fetch(Regex.canonical_name(name)) { raise Error, "invalid character class range" }
540
534
 
541
- [[], ["\\p{#{"^" if negated}#{name}}"]]
535
+ [[], [Sets.property(name, negated != inverted, flags.anybits?(FOLD))]]
542
536
  end
543
537
 
544
538
  # char_class reads a class after its [.
@@ -610,37 +604,15 @@ module Flagnetic
610
604
 
611
605
  def literal(code_point, flags)
612
606
  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
607
+ char(flags.anybits?(FOLD) ? Sets.fold(ranges) : ranges)
621
608
  end
622
609
 
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.
610
+ # set builds the class of a [...] or an escape.
625
611
  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
612
+ Node.new(Node::CHAR, set: CharSet.new(Sets.normalize(ranges), props, negated))
641
613
  end
642
614
  end
643
- private_constant :Translator, :Sets
615
+ private_constant :Parser, :Sets
644
616
  end
645
617
  private_constant :Regex, :UnicodeTables
646
618
  end