flagnetic 0.1.1 → 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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1550286a0e18788c593c2adc2268f4fa8ecb823b7dd64654bec4ff01a4fc1155
4
- data.tar.gz: f5a48dc03a8524cb2aee5a3739e87392dc8ebb41a182eaf96a9383b3b4761125
3
+ metadata.gz: 66ef6f1803ef21cf2f595614c9069ef974f960baa799b915a3b5970663b452c6
4
+ data.tar.gz: 11a3bdeec65a65a0358de993947a99faa7fd919df52c0f416324877390e2d5f9
5
5
  SHA512:
6
- metadata.gz: 322119cf31f48bc9eaf88b4770830e8efc7dfdc09ab7ab77e6087f18f6504533725abb7cde9188bcfa25db6ec4af11f12c416c6b3a878cb364a8f4bbf3bee07a
7
- data.tar.gz: 27358c4b7f92b3fe6e6cbf80835e1742cceb6def862dbf9749799172ac68e3ba28cd48ad5f319b1c869956735f8d58f1ec5f6d038177497e139cf1a7bdabb656
6
+ metadata.gz: 3498e26e7391884ee01637ce99ecbb570b66555bafb8bb08d13916801a825af8798f8683678990ce8e6e0ed570f30ab1b81f92788c90fc929954e75051dca135
7
+ data.tar.gz: 3835e3a2ada5e2588ab4b9b11bcfd7fd552cae18cdf036b8b06ebe572e5dee3ebcd0e4a15e2a4f7f383c17aec185d69e1a53e29fe1f3014b780345cfbf792dff
data/README.md CHANGED
@@ -37,7 +37,7 @@ A change saved in Flagnetic, a kill switch included, reaches a client holding th
37
37
 
38
38
  ## Client
39
39
 
40
- `Flagnetic::Client` is the server-mode client. It downloads the ruleset with the server key, holds it in memory, follows every change through the change stream (polling while the stream is down) and evaluates locally, so a getter never waits on the network and never raises.
40
+ `Flagnetic::Client` is the server-mode client. It downloads the ruleset with the server key, holds it in memory, follows every change through the change stream (polling while the stream is down) and evaluates locally, so a getter never waits on the network and never raises. A stream is stable once it has delivered a heartbeat: one the server closes before that (a draining replica, a proxy that ends the stream early) is a failure like any other and the reconnect backs off, while the close of a stable stream waits 0 to 2 seconds.
41
41
 
42
42
  ```ruby
43
43
  require "flagnetic"
@@ -62,7 +62,7 @@ A client key (`fn_cli_...`) is refused at construction with an `ArgumentError`.
62
62
  | `stream:` | `false` turns the change stream off; the ruleset is then polled every 30 s (default `true`). |
63
63
  | `poll_interval:` | Seconds between polls while the stream is up (default 300, at least 30). |
64
64
  | `request_timeout:` | Seconds per request (default 10). |
65
- | `store:` | Path of a file keeping the last good ruleset across restarts. It is read at construction and rewritten on every accepted ruleset. |
65
+ | `store:` | Path of a file keeping the last good ruleset across restarts. It is read at construction and rewritten on every accepted ruleset. The file is headed by a digest of the SDK key: one written under another key (another environment's, say) or under none is discarded with `store_failed`. |
66
66
  | `logger:` | A callable receiving `(level, event, fields)`, or a standard `Logger`. Default: warnings and errors to `$stderr`. |
67
67
  | `platform:` | The platform in the `User-Agent` (`flagnetic-ruby/<version> (<platform>)`) and the events envelope, and an exposure's `platform` when the context names none (default `"server"`). |
68
68
  | `app_version:` | The application's version, sent with every evaluation summary and as an exposure's `app_version` when the context names none. |
@@ -102,7 +102,7 @@ client.flush(timeout: 5)
102
102
  - **Evaluation summaries.** Every evaluation is counted per flag, variation and reason (`fallback` and `local_override` included, never a unit ID or a value) and sent every `summary_interval` as one or more `evaluation_summary` events of at most 1,000 rows, with the version of the ruleset held at the interval's end. A report that fails merges into the next one; one older than an hour is dropped.
103
103
  - **Exposures.** Evaluating records nothing on its own. `exposure` sends the experiment block of the latest evaluation of that flag for that context, or nothing when it carried none (`exposure_skipped` at debug says why). A flag with automatic exposure sends one as it is evaluated. A repeat for the same experiment, unit and variation is sent once per `flush_interval`.
104
104
  - **Aliases.** `alias` links the unit ID used before sign-up to the one after it; it changes no context.
105
- - **Delivery.** Events go gzipped to `POST /sdk/v1/events` in batches of at most 500, each with a UUIDv7 event ID kept across retries, so the server drops a resend as a duplicate. An evaluation summary that is still unanswered when its flush ends is merged into the next window and sent under new IDs. A 429, a 5xx or a network error is retried with backoff (evaluation summaries wait for `Retry-After`, capped at five minutes); a 401 or 403 logs `key_revoked` and keeps the events; an event the server rejects is logged as `queue_dropped` and never sent again. The queue holds 10,000 events and drops the oldest beyond that.
105
+ - **Delivery.** Events go gzipped to `POST /sdk/v1/events` in batches of at most 500, each with a UUIDv7 event ID kept across retries, so the server drops a resend as a duplicate. An evaluation summary that is still unanswered when its flush ends is merged into the next window and sent under new IDs. A 429, a 5xx or a network error is retried with backoff (evaluation summaries wait for `Retry-After`, capped at five minutes); a 401 or 403 logs `key_revoked` and keeps the events; an event the server rejects is logged as `queue_dropped` and never sent again. The queue holds 10,000 events and drops the oldest beyond that. A string that is not valid UTF-8 (a unit ID taken from a cookie, say) is sent with each invalid byte replaced by U+FFFD; an event that still cannot be encoded is dropped alone, logged as `queue_dropped` with cause `not_serialisable` and the class of the error as `fault`, and costs no other event.
106
106
  - `flush(timeout:)` sends what is queued and the current window and waits at most `timeout` seconds; `close(timeout:)` flushes first and then stops the background thread, both within the one `timeout`. A forked child starts with an empty queue and window.
107
107
 
108
108
  An offline client sends nothing: it hands every summary, exposure and alias to its `recorder`.
@@ -114,11 +114,12 @@ Log events have stable names (`Flagnetic::EVENTS`); alert on the name, never on
114
114
  | `ruleset_loaded` | info | `source` (`fetch`, `store`, `offline`), `ruleset_version`, `flags` |
115
115
  | `fetch_failed` | warn (error offline) | `cause`, `stage` (`source` offline) |
116
116
  | `sse_connected` | info | |
117
- | `sse_dropped` | info after a server close, warn otherwise | `cause` |
117
+ | `sse_dropped` | info after a server close of a stable stream, warn otherwise | `cause` |
118
118
  | `stage_changed` | info to `fresh`, warn otherwise | `from`, `to` |
119
119
  | `key_revoked` | error, once per source until it recovers | `status`, `source` (`fetch`, `stream`) |
120
120
  | `schema_unsupported` | error, once | `schema_version`, `supported` |
121
121
  | `rule_unsupported` | error, once per flag and ruleset version | `flag`, `constructs`, `ruleset_version` |
122
+ | `condition_invalid` | error, once per flag and ruleset version | `flag`, `conditions`, `ruleset_version` |
122
123
  | `override_set` | warn | `flag` |
123
124
  | `override_refused` | warn | `flag`, `reason` (`not_allowed`, `protected`), `environment` |
124
125
  | `local_overrides_allowed` | warn | |
@@ -131,10 +132,12 @@ Log events have stable names (`Flagnetic::EVENTS`); alert on the name, never on
131
132
  | `exposures_disabled` | warn | |
132
133
  | `ingest_failed` | warn | `kind`, `events`, `retry_in`, `status`, `error` |
133
134
  | `client_not_configured` | warn | `rails_env`: the Rails integration found no SDK key and base URL and serves built-in defaults |
134
- | `queue_dropped` | warn | `kind` (`exposure_or_alias`, `evaluation_summary`), `cause` (`queue_full`, `client_error`, `refused_by_the_platform`, `window_older_than_one_hour`) and what was dropped |
135
+ | `queue_dropped` | warn | `kind` (`exposure_or_alias`, `evaluation_summary`), `cause` (`queue_full`, `not_serialisable`, `client_error`, `refused_by_the_platform`, `window_older_than_one_hour`) and what was dropped (`fault` for `not_serialisable`) |
135
136
 
136
137
  A ruleset from a newer server may hold constructs this SDK does not know. The client logs `rule_unsupported` once per flag and ruleset version, and the flag serves its default with the error code `inconsistent_ruleset`.
137
138
 
139
+ A condition this SDK cannot evaluate although the server accepted it, such as a pattern its regular expression engine refuses, makes the flag serve its default with `inconsistent_ruleset` in this SDK only. The client logs `condition_invalid` once per flag and ruleset version when the ruleset loads, with the reason of each condition in `conditions`.
140
+
138
141
  ## Flagnetic.client
139
142
 
140
143
  `Flagnetic.client` is the process-wide client: assign one with `Flagnetic.client = ...`, or set `Flagnetic.client_builder` to a callable that builds it on first use, once. It raises `Flagnetic::NotConfigured` until either is set.
@@ -256,7 +259,7 @@ Every other flag evaluates normally. The fix is to upgrade the SDK.
256
259
 
257
260
  ## Regular expressions
258
261
 
259
- A `matches` condition is RE2 syntax with RE2 semantics, as Go's `regexp` reads it, and not the dialect of Ruby's own engine. A pattern is parsed as RE2 and translated, so `^` and `$` are not line anchors, `\s` is `[\t\n\f\r ]`, lookarounds and backreferences are refused and `(?i)` folds case by Go's rules, `\p{...}` included. A pattern RE2 refuses makes the condition `inconsistent_ruleset`. A match that takes longer than 0.1 s makes the condition false.
262
+ A `matches` condition is RE2 syntax with RE2 semantics, as Go's `regexp` reads it, and not the dialect of Ruby's own engine. A pattern is parsed as RE2 and matched by an engine of its own that runs in time linear in the input, so a context value can never make a match slow or cut it off. `^` and `$` are not line anchors, `\s` is `[\t\n\f\r ]`, lookarounds and backreferences are refused and `(?i)` folds case by Go's rules, `\p{...}` included. A pattern RE2 refuses makes the condition `inconsistent_ruleset`.
260
263
 
261
264
  The case folding orbits and property names come from Go's `unicode` package, and `lib/flagnetic/eval/unicode_tables.rb` is generated from it:
262
265
 
@@ -26,14 +26,15 @@ module Flagnetic
26
26
  include FallbackChain
27
27
 
28
28
  # Timing holds the delays and intervals of the background thread, in
29
- # seconds. Only poll_interval and request_timeout are public options;
30
- # the timing option exists for tests and is not part of the API.
29
+ # seconds, and the random source of the stream's waits (nil: Random.new).
30
+ # Only poll_interval and request_timeout are public options; the timing
31
+ # option exists for tests and is not part of the API.
31
32
  Timing = Struct.new(:request_timeout, :fetch_base, :fetch_cap, :unauthorized_cap, :stream_base, :stream_cap,
32
- :stream_stable, :close_jitter, :silence, :poll_connected, :poll_down, :event_retries,
33
- :exposure_flush, :summary_flush, keyword_init: true)
33
+ :worker_stable, :close_jitter, :silence, :poll_connected, :poll_down, :event_retries,
34
+ :exposure_flush, :summary_flush, :random, keyword_init: true)
34
35
  DEFAULT_TIMING = Timing.new(
35
36
  request_timeout: 10, fetch_base: 1, fetch_cap: 300, unauthorized_cap: 900, stream_base: 1, stream_cap: 30,
36
- stream_stable: 60, close_jitter: 2, silence: 45, poll_connected: 300, poll_down: 30, event_retries: [1, 2, 4],
37
+ worker_stable: 60, close_jitter: 2, silence: 45, poll_connected: 300, poll_down: 30, event_retries: [1, 2, 4],
37
38
  exposure_flush: 2, summary_flush: 60
38
39
  ).freeze
39
40
  MIN_POLL_INTERVAL = 30
@@ -51,6 +52,8 @@ module Flagnetic
51
52
  # call is ever made; the stage is fresh; reload re-reads the source.
52
53
  # - store: a file path holding the last good ruleset, loaded as
53
54
  # last_good at construction and rewritten on every accepted ruleset.
55
+ # The file belongs to the SDK key that wrote it: one written under
56
+ # another key, or under none, is discarded with store_failed.
54
57
  # - logger: a callable receiving (level, event, fields), or a Logger.
55
58
  # Default: warn and above to $stderr.
56
59
  # - stream: false disables the change stream; polling then runs every
@@ -299,6 +302,7 @@ module Flagnetic
299
302
  @overrides = {}.freeze
300
303
  @once = {}
301
304
  @unsupported_logged = {}
305
+ @invalid_logged = {}
302
306
  @pid = Process.pid
303
307
  @closed = false
304
308
  end
@@ -335,7 +339,7 @@ module Flagnetic
335
339
  @transport = Transport.new(sdk_key: sdk_key, base_url: base_url, platform: platform,
336
340
  timeout: @timing.request_timeout)
337
341
  build_reporters(@transport, nil)
338
- @store = store && FileStore.new(store)
342
+ @store = store && FileStore.new(store, sdk_key)
339
343
  load_store if @store
340
344
  @worker = Worker.new(self, @transport, @timing, stream: stream)
341
345
  end
@@ -23,7 +23,7 @@ module Flagnetic
23
23
  # constructs it holds.
24
24
  CompiledSegment = Struct.new(:conditions, :unsupported)
25
25
 
26
- attr_reader :flags, :segments, :unsupported
26
+ attr_reader :flags, :segments, :unsupported, :invalid
27
27
 
28
28
  def initialize(ruleset)
29
29
  # A unit type named as an attribute is a string attribute holding
@@ -34,15 +34,25 @@ module Flagnetic
34
34
  @segments = ruleset.segments.to_h { |s| [s.key, compiler.segment(s)] }.freeze
35
35
  @flags = {}
36
36
  @unsupported = {}
37
- ruleset.flags.each do |f|
38
- @flags[f.key] = compiler.flag(f)
39
- found = compiler.unsupported_in(f, @flags[f.key], @segments)
40
- @unsupported[f.key] = found.freeze unless found.empty?
41
- end
37
+ @invalid = {}
38
+ ruleset.flags.each { |f| index_flag(compiler, f) }
42
39
  @flags.freeze
43
40
  @unsupported.freeze
41
+ @invalid.freeze
44
42
  freeze
45
43
  end
44
+
45
+ private
46
+
47
+ # index_flag compiles a flag and records what it holds that this
48
+ # evaluator does not know or cannot evaluate.
49
+ def index_flag(compiler, flag)
50
+ @flags[flag.key] = compiler.flag(flag)
51
+ found = compiler.unsupported_in(flag, @flags[flag.key], @segments)
52
+ @unsupported[flag.key] = found.freeze unless found.empty?
53
+ broken = compiler.invalid_in(flag, @flags[flag.key], @segments)
54
+ @invalid[flag.key] = broken.freeze unless broken.empty?
55
+ end
46
56
  end
47
57
 
48
58
  # The condition kinds and serve kinds this evaluator knows.
@@ -90,8 +100,29 @@ module Flagnetic
90
100
  found
91
101
  end
92
102
 
103
+ # invalid_in lists why the conditions of a compiled flag, and of the
104
+ # segments its rules name, cannot be evaluated by this evaluator, in
105
+ # document order, each once, apart from those that hold a construct it
106
+ # does not know (unsupported_in reports those). A server accepts only
107
+ # patterns and values its own evaluator reads, so one this evaluator
108
+ # refuses is a difference between the two.
109
+ def invalid_in(flag, compiled, segments)
110
+ found = []
111
+ flag.rules.each_index do |i|
112
+ compiled.rules[i].each do |c|
113
+ add_invalid(found, c)
114
+ segments[c.segment]&.conditions&.each { |sc| add_invalid(found, sc) } unless c.segment.to_s.empty?
115
+ end
116
+ end
117
+ found
118
+ end
119
+
93
120
  private
94
121
 
122
+ def add_invalid(found, compiled)
123
+ found << compiled.error if compiled.error && !compiled.unsupported && !found.include?(compiled.error)
124
+ end
125
+
95
126
  # valid_experiment? reports whether an experiment serve holds what
96
127
  # assigning a unit to a variation relies on: an experiment key, a unit
97
128
  # type and both salts; a traffic allocation within 0 to 10000; and at
@@ -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