varar-core 0.8.1 → 0.9.0

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.
@@ -10,57 +10,62 @@ module Varar
10
10
 
11
11
  module Sentences
12
12
  ABBREVIATIONS = Set.new(['e.g.', 'i.e.', 'etc.', 'cf.', 'vs.']).freeze
13
+ TERMINATOR = /[\n.!?]/
14
+ QUOTE = /[`"]/
13
15
 
14
16
  module_function
15
17
 
18
+ # Jumps from one terminator to the next with a regexp search rather than
19
+ # visiting every character: the rules are the same, but planning a large
20
+ # project splits tens of thousands of blocks.
16
21
  def split_sentences(text)
17
- cp_to_u16 = build_cp_to_u16(text)
22
+ # An ASCII string's code points are its UTF-16 units.
23
+ cp_to_u16 = text.ascii_only? ? nil : build_cp_to_u16(text)
18
24
  n = text.length
19
25
  out = []
20
-
21
- # Mark no-split zones (backtick spans, double-quoted strings).
22
- skip = Array.new(n, false)
23
- j = 0
24
- while j < n
25
- c = text[j]
26
- if ['`', '"'].include?(c)
27
- close = text.index(c, j + 1)
28
- break if close.nil?
29
-
30
- (j..close).each { |k| skip[k] = true }
31
- j = close + 1
32
- next
33
- end
34
- j += 1
35
- end
26
+ zones = no_split_zones(text)
27
+ zone = 0
36
28
 
37
29
  i = 0
38
30
  segment_start = 0
39
31
  while i < n
40
- if skip[i]
32
+ i = text.index(TERMINATOR, i)
33
+ break if i.nil?
34
+
35
+ zone += 1 while zone < zones.length && zones[zone].end < i
36
+ if (zone < zones.length && zones[zone].cover?(i)) ||
37
+ (text[i] == '.' && inside_number_or_abbrev?(text, i))
41
38
  i += 1
42
39
  next
43
40
  end
44
- ch = text[i]
45
- if ["\n", '.', '!', '?'].include?(ch)
46
- if ch == '.' && inside_number_or_abbrev?(text, i)
47
- i += 1
48
- next
49
- end
50
- stop = i + 1
51
- push_segment(out, text, segment_start, stop, cp_to_u16)
52
- i = stop
53
- i += 1 while i < n && [' ', "\n"].include?(text[i])
54
- segment_start = i
55
- next
56
- end
57
- i += 1
41
+ stop = i + 1
42
+ push_segment(out, text, segment_start, stop, cp_to_u16)
43
+ i = stop
44
+ i += 1 while i < n && [' ', "\n"].include?(text[i])
45
+ segment_start = i
58
46
  end
59
47
 
60
48
  push_segment(out, text, segment_start, n, cp_to_u16)
61
49
  out
62
50
  end
63
51
 
52
+ # Backtick spans and double-quoted strings, as ascending inclusive
53
+ # ranges of code-point indexes: terminators inside them don't split. An
54
+ # opening mark with no closing one ends the search — nothing after it
55
+ # is protected.
56
+ def no_split_zones(text)
57
+ zones = []
58
+ j = 0
59
+ while (j = text.index(QUOTE, j))
60
+ close = text.index(text[j], j + 1)
61
+ break if close.nil?
62
+
63
+ zones << (j..close)
64
+ j = close + 1
65
+ end
66
+ zones
67
+ end
68
+
64
69
  # cp_to_u16[cp_i] is the UTF-16 offset of text[cp_i].
65
70
  def build_cp_to_u16(text)
66
71
  result = Array.new(text.length + 1, 0)
@@ -94,10 +99,12 @@ module Varar
94
99
 
95
100
  lead = raw.length - raw.lstrip.length
96
101
  trail = raw.length - raw.rstrip.length
102
+ start = start_cp + lead
103
+ stop = end_cp - trail
97
104
  out << Sentence.new(
98
105
  text: stripped,
99
- start_offset: cp_to_u16[start_cp + lead],
100
- end_offset: cp_to_u16[end_cp - trail]
106
+ start_offset: cp_to_u16 ? cp_to_u16[start] : start,
107
+ end_offset: cp_to_u16 ? cp_to_u16[stop] : stop
101
108
  )
102
109
  end
103
110
 
@@ -11,18 +11,117 @@ module Varar
11
11
  :end_line, :end_col
12
12
  )
13
13
 
14
+ # Where a source's lines start and where its astral characters sit, found
15
+ # in one pass so that every later position lookup is a binary search.
16
+ # Walking the source from its first character for each span made parsing
17
+ # quadratic in the length of the oath (varar-dev/varar#130).
18
+ #
19
+ # +line_starts+: the UTF-16 offset each line starts at; entry 0 is 0.
20
+ # +astral_cps+: the code-point index of each astral character, ascending.
21
+ # +astral_u16s+: the UTF-16 offset of each of those same characters.
22
+ SourceIndex = Data.define(:source, :line_starts, :astral_cps, :astral_u16s)
23
+
14
24
  # UTF-16 offset conversion. Ruby strings are code-point indexed, so the
15
25
  # whole core converts to/from UTF-16 code units here (the single riskiest
16
26
  # part of the port — mirrors Python's span.py). Reused by the matcher and
17
27
  # by hash.rb.
28
+ #
29
+ # Anything taking more than a handful of positions from the same source
30
+ # builds an +index+ once and uses the +_at+ functions; the others build a
31
+ # throwaway index per call and suit a short string or a one-off lookup.
18
32
  module Offsets
19
33
  module_function
20
34
 
21
- # UTF-16 code-unit length of a string (astral chars count as 2).
35
+ # UTF-16 code-unit length of a string (astral chars count as 2). Not
36
+ # `String#count` over the astral range: it expands the million-character
37
+ # range on every call, which costs tens of milliseconds.
22
38
  def utf16_len(str)
23
- n = 0
24
- str.each_char { |ch| n += ch.ord > 0xFFFF ? 2 : 1 }
25
- n
39
+ return str.length if str.ascii_only?
40
+
41
+ str.each_char.sum { |ch| ch.ord > 0xFFFF ? 2 : 1 }
42
+ end
43
+
44
+ def index(source)
45
+ return ascii_index(source) if source.ascii_only?
46
+
47
+ line_starts = [0]
48
+ astral_cps = []
49
+ astral_u16s = []
50
+ u16 = 0
51
+ source.each_char.with_index do |ch, cp|
52
+ if ch == "\n"
53
+ line_starts << (u16 + 1)
54
+ elsif ch.ord > 0xFFFF
55
+ astral_cps << cp
56
+ astral_u16s << u16
57
+ u16 += 1
58
+ end
59
+ u16 += 1
60
+ end
61
+ SourceIndex.new(source: source, line_starts: line_starts.freeze, astral_cps: astral_cps.freeze,
62
+ astral_u16s: astral_u16s.freeze)
63
+ end
64
+
65
+ # No astral characters, and every character is one UTF-16 unit, so the
66
+ # newlines can be found by a search instead of visiting each character.
67
+ def ascii_index(source)
68
+ line_starts = [0]
69
+ pos = source.index("\n")
70
+ while pos
71
+ line_starts << (pos + 1)
72
+ pos = source.index("\n", pos + 1)
73
+ end
74
+ SourceIndex.new(source: source, line_starts: line_starts.freeze, astral_cps: [].freeze,
75
+ astral_u16s: [].freeze)
76
+ end
77
+
78
+ # UTF-16 offset of the code-point index +cp_index+ (clamped to the
79
+ # source).
80
+ def utf16_offset_at(idx, cp_index)
81
+ cp = cp_index.clamp(0, idx.source.length)
82
+ cp + count_below(idx.astral_cps, cp)
83
+ end
84
+
85
+ # The code-point index at a UTF-16 offset. An offset between the two
86
+ # halves of a surrogate pair rounds up past the character; one beyond
87
+ # the end is the end.
88
+ def cp_index_at(idx, u16)
89
+ return 0 if u16 <= 0
90
+
91
+ before = count_below(idx.astral_u16s, u16)
92
+ cp = u16 - before
93
+ cp += 1 if before.positive? && idx.astral_u16s[before - 1] + 1 == u16
94
+ [cp, idx.source.length].min
95
+ end
96
+
97
+ # Slice the indexed source by UTF-16 offsets.
98
+ def slice_at(idx, start_u16, end_u16)
99
+ idx.source[cp_index_at(idx, start_u16)...cp_index_at(idx, end_u16)]
100
+ end
101
+
102
+ # 1-based [line, col] at a UTF-16 offset; col counts UTF-16 units and
103
+ # resets to 1 after each newline (mirrors span.ts's lineCol). Rounds to a
104
+ # character boundary first, as +cp_index_at+ does.
105
+ def line_col_at(idx, offset_u16)
106
+ u16 = utf16_offset_at(idx, cp_index_at(idx, offset_u16))
107
+ line = count_below(idx.line_starts, u16 + 1)
108
+ [line, u16 - idx.line_starts[line - 1] + 1]
109
+ end
110
+
111
+ # Build a Span from UTF-16 start/end offsets into the indexed source.
112
+ def span_at(idx, start_u16, end_u16)
113
+ start_line, start_col = line_col_at(idx, start_u16)
114
+ end_line, end_col = line_col_at(idx, end_u16)
115
+ Span.new(
116
+ start_offset: start_u16, end_offset: end_u16,
117
+ start_line: start_line, start_col: start_col,
118
+ end_line: end_line, end_col: end_col
119
+ )
120
+ end
121
+
122
+ # How many entries of the ascending +sorted+ are below +value+.
123
+ def count_below(sorted, value)
124
+ sorted.bsearch_index { |x| x >= value } || sorted.length
26
125
  end
27
126
 
28
127
  # UTF-16 offset of the code-point index `cp_index` in `source`.
@@ -31,53 +130,27 @@ module Varar
31
130
  end
32
131
 
33
132
  # Inverse of to_utf16_offset: the code-point index at a UTF-16 offset.
133
+ # An ASCII string's code points are its UTF-16 units (Ruby knows a
134
+ # string is ASCII without looking at it again), so it needs no index.
34
135
  def cp_index_for_utf16(source, u16)
35
- count = 0
36
- source.each_char.with_index do |ch, i|
37
- return i if count >= u16
136
+ return u16.clamp(0, source.length) if source.ascii_only?
38
137
 
39
- count += ch.ord > 0xFFFF ? 2 : 1
40
- end
41
- source.length
138
+ cp_index_at(index(source), u16)
42
139
  end
43
140
 
44
141
  # Slice `source` by UTF-16 offsets, returning the covered substring.
45
142
  def utf16_slice(source, start_u16, end_u16)
46
- a = cp_index_for_utf16(source, start_u16)
47
- b = cp_index_for_utf16(source, end_u16)
48
- source[a...b]
143
+ source[cp_index_for_utf16(source, start_u16)...cp_index_for_utf16(source, end_u16)]
49
144
  end
50
145
 
51
- # 1-based [line, col] at a UTF-16 offset; col counts UTF-16 units and
52
- # resets to 1 after each newline (mirrors span.ts's lineCol).
146
+ # 1-based [line, col] at a UTF-16 offset.
53
147
  def line_col(source, offset_u16)
54
- line = 1
55
- col = 1
56
- count = 0
57
- source.each_char do |ch|
58
- break if count >= offset_u16
59
-
60
- width = ch.ord > 0xFFFF ? 2 : 1
61
- if ch == "\n"
62
- line += 1
63
- col = 1
64
- else
65
- col += width
66
- end
67
- count += width
68
- end
69
- [line, col]
148
+ line_col_at(index(source), offset_u16)
70
149
  end
71
150
 
72
151
  # Build a Span from UTF-16 start/end offsets.
73
152
  def span_from_offsets(source, start_u16, end_u16)
74
- start_line, start_col = line_col(source, start_u16)
75
- end_line, end_col = line_col(source, end_u16)
76
- Span.new(
77
- start_offset: start_u16, end_offset: end_u16,
78
- start_line: start_line, start_col: start_col,
79
- end_line: end_line, end_col: end_col
80
- )
153
+ span_at(index(source), start_u16, end_u16)
81
154
  end
82
155
  end
83
156
  end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'cucumber/cucumber_expressions/ast'
4
+ require 'cucumber/cucumber_expressions/cucumber_expression_parser'
5
+
6
+ module Varar
7
+ module Core
8
+ # What the matcher needs from a step expression, derived once when the
9
+ # step is registered rather than once per sentence it is tried against.
10
+ #
11
+ # +pattern+: the expression's regexp without its `^…$` anchors, so it
12
+ # finds the expression anywhere in a sentence.
13
+ # +keywords+: words every sentence matching this expression must contain
14
+ # as whole words — see StepIndex.keywords_of. Empty when the expression
15
+ # guarantees none.
16
+ StepScan = Data.define(:pattern, :keywords)
17
+
18
+ # Which steps can possibly match a sentence, answered from the words in
19
+ # it. Without this every step's pattern runs against every sentence, and
20
+ # matching a project costs sentences × steps; with it, a sentence only pays
21
+ # for the steps that share a word with it (varar-dev/varar#130).
22
+ #
23
+ # It is an optimisation and nothing else: the candidates it returns are a
24
+ # superset of the steps that match, in registration order, so the matcher
25
+ # finds exactly the hits it would find by trying them all. Port of
26
+ # step-index.ts.
27
+ #
28
+ # +by_keyword+: step positions (indexes into the registry's steps), each
29
+ # filed under the one keyword of its expression that fewest other steps
30
+ # share. +unindexed+: steps whose expression guarantees no word — always
31
+ # candidates.
32
+ StepIndex = Data.define(:by_keyword, :unindexed) do
33
+ # Positions of the steps worth trying against +sentence+, in
34
+ # registration order — the order the matcher reports hits in, which
35
+ # decides how ties read in an ambiguity diagnostic.
36
+ def candidates(steps, sentence)
37
+ words = Set.new(sentence.scan(StepIndex::WORD))
38
+ found = unindexed.dup
39
+ words.each do |word|
40
+ by_keyword.fetch(word, []).each do |position|
41
+ # Filed under one keyword, but a match needs all of them.
42
+ found << position if steps[position].scan.keywords.all? { |k| words.include?(k) }
43
+ end
44
+ end
45
+ found.sort
46
+ end
47
+ end
48
+
49
+ class StepIndex
50
+ WORD = /[\p{L}\p{N}_]+/
51
+
52
+ class << self
53
+ def step_scan(expression, compiled)
54
+ # cucumber-expressions anchors its regexp (`^…$`); strip the anchors
55
+ # to scan for the expression inside a longer sentence.
56
+ regexp = compiled.regexp
57
+ source = regexp.source
58
+ source = source[1..] if source.start_with?('^')
59
+ source = source[0...-1] if source.end_with?('$')
60
+ StepScan.new(pattern: Regexp.new(source, regexp.options), keywords: keywords_of(expression).freeze)
61
+ end
62
+
63
+ # The words of an expression's literal text that any matching sentence
64
+ # must contain *as whole words*, so that looking a sentence's own words
65
+ # up finds the expression.
66
+ #
67
+ # Only top-level text counts: an optional `(s)` may be absent, an
68
+ # alternation `a/b` is one of several. And only a word with literal
69
+ # text on both sides of it: the neighbours are then part of every
70
+ # match, so the word is delimited in the sentence exactly as it is in
71
+ # the expression. A word at either end of a literal run touches a
72
+ # parameter, a group, or the edge of the match, and can be glued to
73
+ # more word characters there — `{int}kg` matches inside `5kg`, and
74
+ # `log in` matches inside `blog in`. Such an expression is still found,
75
+ # through another of its words or by being tried against every
76
+ # sentence.
77
+ def keywords_of(expression)
78
+ ast = Cucumber::CucumberExpressions::CucumberExpressionParser.new.parse(expression)
79
+ keywords = []
80
+ run = +''
81
+ flush = lambda do
82
+ run.scan(WORD) do
83
+ m = Regexp.last_match
84
+ interior = m.begin(0).positive? && m.end(0) < run.length
85
+ keywords << m[0] if interior && !keywords.include?(m[0])
86
+ end
87
+ run = +''
88
+ end
89
+ ast.nodes.each do |node|
90
+ # `text` is the literal as it must appear in a sentence (escapes
91
+ # resolved) — the same string the expression's regexp is built
92
+ # from.
93
+ if node.type == Cucumber::CucumberExpressions::NodeType::TEXT
94
+ run << node.text
95
+ else
96
+ flush.call
97
+ end
98
+ end
99
+ flush.call
100
+ keywords
101
+ end
102
+
103
+ def create(steps)
104
+ frequency = Hash.new(0)
105
+ steps.each { |step| step.scan.keywords.each { |k| frequency[k] += 1 } }
106
+ by_keyword = {}
107
+ unindexed = []
108
+ steps.each_with_index do |step, position|
109
+ # File the step under its rarest keyword (the first of them on a
110
+ # tie), so a common word like `the` does not make it a candidate
111
+ # for every sentence.
112
+ rarest = step.scan.keywords.min_by.with_index { |k, i| [frequency[k], i] }
113
+ if rarest.nil?
114
+ unindexed << position
115
+ else
116
+ (by_keyword[rarest] ||= []) << position
117
+ end
118
+ end
119
+ new(by_keyword: by_keyword.transform_values(&:freeze).freeze, unindexed: unindexed.freeze)
120
+ end
121
+ end
122
+ end
123
+ end
124
+ end
@@ -14,7 +14,7 @@ module Varar
14
14
  module Structurer
15
15
  module_function
16
16
 
17
- def structure(path, source, blocks)
17
+ def structure(path, source, blocks, idx = Offsets.index(source))
18
18
  examples = []
19
19
  orphan_attachments = []
20
20
  headings = []
@@ -51,7 +51,7 @@ module Varar
51
51
  when 'table', 'fence'
52
52
  if attachment_open && last_example_idx >= 0
53
53
  prev = examples[last_example_idx]
54
- new_span = Offsets.span_from_offsets(source, prev.span.start_offset, block.span.end_offset)
54
+ new_span = Offsets.span_at(idx, prev.span.start_offset, block.span.end_offset)
55
55
  examples[last_example_idx] = Example.new(
56
56
  scope_stack: prev.scope_stack,
57
57
  span: new_span,
@@ -10,8 +10,9 @@ module Varar
10
10
  module_function
11
11
 
12
12
  # Split a `| a | b |` row into [cells, cell_spans]. +line_start_offset+
13
- # is the UTF-16 offset of the row's first character within +source+.
14
- def parse_row_cells(line_text, line_start_offset, source)
13
+ # is the UTF-16 offset of the row's first character within the source
14
+ # +idx+ (an Offsets.index) indexes.
15
+ def parse_row_cells(line_text, line_start_offset, idx)
15
16
  first_cp = line_text.index('|')
16
17
  last_cp = line_text.rindex('|')
17
18
  return [[], []] if first_cp.nil? || last_cp.nil? || last_cp <= first_cp
@@ -33,7 +34,7 @@ module Varar
33
34
  leading = Offsets.utf16_len(seg) - Offsets.utf16_len(seg.lstrip)
34
35
  abs_start = line_start_offset + inner_start_u16 + cursor + leading
35
36
  cells << trimmed
36
- cell_spans << Offsets.span_from_offsets(source, abs_start, abs_start + Offsets.utf16_len(trimmed))
37
+ cell_spans << Offsets.span_at(idx, abs_start, abs_start + Offsets.utf16_len(trimmed))
37
38
  cursor += Offsets.utf16_len(seg) + 1 # +1 for the '|' delimiter
38
39
  end
39
40
 
data/lib/varar/core.rb CHANGED
@@ -4,7 +4,7 @@ module Varar
4
4
  # The pure functional core: parse, match, plan, execute, diffs, drift, and
5
5
  # the conformance projections. No filesystem, network, globals, or time.
6
6
  module Core
7
- VERSION = '0.8.1'
7
+ VERSION = '0.9.0'
8
8
  end
9
9
  end
10
10
 
@@ -29,5 +29,4 @@ require 'varar/core/failure'
29
29
  require 'varar/core/execute'
30
30
  require 'varar/core/hash'
31
31
  require 'varar/core/drift'
32
- require 'varar/core/canonical_json'
33
32
  require 'varar/core/conformance'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: varar-core
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.1
4
+ version: 0.9.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Aslak Hellesøy
@@ -15,14 +15,14 @@ dependencies:
15
15
  requirements:
16
16
  - - '='
17
17
  - !ruby/object:Gem::Version
18
- version: 20.0.0
18
+ version: 20.2.0
19
19
  type: :runtime
20
20
  prerelease: false
21
21
  version_requirements: !ruby/object:Gem::Requirement
22
22
  requirements:
23
23
  - - '='
24
24
  - !ruby/object:Gem::Version
25
- version: 20.0.0
25
+ version: 20.2.0
26
26
  description: The pure functional pipeline (parse, match, plan, execute, drift) behind
27
27
  Varar.
28
28
  email:
@@ -33,7 +33,6 @@ extra_rdoc_files: []
33
33
  files:
34
34
  - lib/varar/core.rb
35
35
  - lib/varar/core/ast.rb
36
- - lib/varar/core/canonical_json.rb
37
36
  - lib/varar/core/cell_diff.rb
38
37
  - lib/varar/core/conformance.rb
39
38
  - lib/varar/core/diagnostics.rb
@@ -53,6 +52,7 @@ files:
53
52
  - lib/varar/core/scanner.rb
54
53
  - lib/varar/core/sentences.rb
55
54
  - lib/varar/core/span.rb
55
+ - lib/varar/core/step_index.rb
56
56
  - lib/varar/core/step_role.rb
57
57
  - lib/varar/core/structurer.rb
58
58
  - lib/varar/core/table_cells.rb
@@ -75,7 +75,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
75
75
  - !ruby/object:Gem::Version
76
76
  version: '0'
77
77
  requirements: []
78
- rubygems_version: 4.0.16
78
+ rubygems_version: 4.0.20
79
79
  specification_version: 4
80
80
  summary: Markdown-native BDD — pure functional core engine
81
81
  test_files: []
@@ -1,47 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- require 'json'
4
-
5
- module Varar
6
- module Core
7
- # Writes varar.lock.json the way JS `JSON.stringify(v, null, 2)` does:
8
- # 2-space indent, LF, trailing newline, non-ASCII raw, empty containers as
9
- # {}/[], keys in insertion order.
10
- #
11
- # A committed, language-shared file, so the layout is hand-rolled rather
12
- # than left to JSON.pretty_generate, which renders empty arrays/objects as
13
- # "[\n\n]" — a Ruby run would otherwise churn the file against every other
14
- # port's. Scalar encoding is delegated to the stdlib, which matches JS
15
- # (escapes " \ control chars, keeps non-ASCII raw).
16
- #
17
- # Conformance goldens are NOT compared through here: a port has to agree
18
- # with the goldens' CONTENT, and every spec parses them and compares deep
19
- # equality.
20
- module CanonicalJson
21
- module_function
22
-
23
- def ordered_stringify(value)
24
- "#{encode(value, '')}\n"
25
- end
26
-
27
- def encode(value, indent)
28
- case value
29
- when Hash
30
- return '{}' if value.empty?
31
-
32
- inner = "#{indent} "
33
- items = value.keys.map { |key| "#{inner}#{key.to_s.to_json}: #{encode(value[key], inner)}" }
34
- "{\n#{items.join(",\n")}\n#{indent}}"
35
- when Array
36
- return '[]' if value.empty?
37
-
38
- inner = "#{indent} "
39
- items = value.map { |element| "#{inner}#{encode(element, inner)}" }
40
- "[\n#{items.join(",\n")}\n#{indent}]"
41
- else
42
- value.to_json
43
- end
44
- end
45
- end
46
- end
47
- end