gullah 0.0.2 → 0.0.5

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: cdb5fc63d2f73407d20cfc3fdb709f27e800a1b4c4b572243e46af970d2563c6
4
- data.tar.gz: 4803e11f42479445bc125013777e797fe526f949e1d9620bea34a974f83fd3dc
3
+ metadata.gz: 32363fba2ea79db7e009c19747d3eb823aaee325cb479bba8e5345d5f95d8bf7
4
+ data.tar.gz: 0ea5918edff7eb25a6c6aae5fc4d26d9554884f9ca2cee004ed2128053268760
5
5
  SHA512:
6
- metadata.gz: 03ad7649f31e61e78cb7220809a13e68ce6e8bdc88c497b251c36c9c5a885688bb1fd075b8d0e31e8724ee4d697446ace38cce36381a9ef1f1a2ac5c5642d334
7
- data.tar.gz: 0d86b4e95ef0f6390cac7a47bafc45ed45e68d3bedc0524b95dd82fc2140281da3db3a380a71814f0862ca94e3b05f21634f3975a2b38eb42719254debbd03e3
6
+ metadata.gz: 766442a1c17238dff7827799edd689005527970d13d49e37e362460083ff57fad432606041d9fd6954a738e7b9c34d5016781edc6eea324015ce155fdebf3cb4
7
+ data.tar.gz: 43344ed14d153d3d81a709c84835b0fc8266e411c843d31781276da297693e77a959033b2feb7a809a7c21a30b592476d91714d6b5ba033514a9f2432578af2c
data/.gitignore CHANGED
@@ -1,2 +1,3 @@
1
1
  doc/*
2
2
  .yardoc/*
3
+ .byebug_history
data/ARCHITECTURE.md ADDED
@@ -0,0 +1,172 @@
1
+ # Architecture Review
2
+
3
+ This document reviews the current architecture of Gullah and sketches how it
4
+ could be changed at a fundamental level. It is an analysis, not an
5
+ implementation plan: the algorithm in `lib/` is deliberately untouched. The
6
+ goal is to identify which parts of the design are load-bearing for Gullah's
7
+ character (fault tolerance, ambiguity, arbitrary tests) and which parts are
8
+ merely incidental, so that future work can change the incidental parts freely.
9
+
10
+ ## How the current algorithm fits together
11
+
12
+ ```
13
+ text
14
+ │ Gullah#lex (lib/gullah.rb) every leaf rule tried at every offset;
15
+ ▼ unmatched spans become Trash nodes
16
+ leaf-node sequences ("lexes") ── Parse#split ──► segments split at boundaries/trash
17
+ │ Segment (lib/gullah/segment.rb)
18
+ ▼
19
+ Iterator over each parse (lib/gullah/iterator.rb) tries each rule's atoms at each root
20
+ │ Atom#match (lib/gullah/atom.rb) sequence matching with repetition
21
+ ▼
22
+ Hopper#vet (lib/gullah/hopper.rb) preconditions, dedup by summary,
23
+ │ Parse#add builds the reduced parse
24
+ ▼
25
+ Hopper bin of best parses (lib/gullah/hopper.rb) thresholds on correctness/completion/
26
+ │ pending/size prune inferior parses
27
+ ▼
28
+ Segment#results × continuations ──► Parse objects returned by Gullah.parse
29
+ ```
30
+
31
+ The search is a best-first search over *parse states*, where a state is a
32
+ flat sequence of root nodes. `Picker` (lib/gullah/picker.rb) orders iterators
33
+ by error count and length; `Segment#next` pulls the most promising iterator,
34
+ applies one reduction, and pushes the results back. `Hopper` keeps only the
35
+ parses that are optimal so far under the active filters.
36
+
37
+ ## What is load-bearing (do not change casually)
38
+
39
+ - **States as sequences of roots, reduced left-to-right by atoms.** This is
40
+ what makes the parser bottom-up and immune to left recursion. Any redesign
41
+ must preserve "rules consume nodes" semantics.
42
+ - **Trash and boundary nodes.** Fault tolerance depends on never failing
43
+ hard: unmatched text becomes a `Trash` node and parsing continues. This is
44
+ also what makes `Parse#split` able to segment text.
45
+ - **Tests and preconditions as user-supplied predicates**, with structure
46
+ tests deferred until an ancestor exists (`Node#adopt`). These give Gullah
47
+ its expressive power (lookarounds, agreement, calendar sanity checks).
48
+ - **The optimality filters** (correctness, completion, pending, size) and the
49
+ "return all equally good parses" contract.
50
+
51
+ ## What is incidental (fair game for redesign)
52
+
53
+ ### 1. Wholesale cloning of parses — the dominant cost
54
+
55
+ Every candidate reduction calls `Parse#add`, which clones the entire parse:
56
+ `roots.map(&:clone)` plus a recursive deep clone of every node's attributes and
57
+ children (lib/gullah/parse.rb, lib/gullah/node.rb). Most clones are
58
+ discarded. This is why the worst case is worse than the quadratic the README
59
+ estimates: each reduction costs O(current tree size), and there can be
60
+ O(n²) candidate reductions.
61
+
62
+ Alternatives, in increasing invasiveness:
63
+
64
+ - **Structural sharing / persistent vectors** for the roots sequence and
65
+ copy-on-write nodes. Cloning becomes O(1); only the path to the replaced
66
+ span is copied.
67
+ - **A mutable chart with an undo trail.** Instead of cloning, apply the
68
+ reduction, record an undo log, and roll back on backtrack. This is how
69
+ many practical parsers avoid copying.
70
+ - **A chart parser (CYK/Earley-style).** Record derived facts ("nonterminal
71
+ X spans [i, j)") in a table instead of enumerating parse states, then
72
+ reconstruct trees by walking the chart. This gives polynomial guarantees
73
+ and eliminates the `@seen` summary-string dedup in `Hopper#vet`, but it
74
+ constrains how tests and preconditions can be expressed, since they must
75
+ run on completed subtrees rather than on provisional ones.
76
+
77
+ ### 2. Stringly-typed dedup
78
+
79
+ `Hopper#vet` dedupes candidate reductions by building a summary string for
80
+ the whole parse. String building is a large share of runtime. A redesign
81
+ would dedup on structured state (e.g., a hash of `[rule, span]` plus child
82
+ identities) or avoid dedup entirely in a chart-based design.
83
+
84
+ ### 3. Lexing
85
+
86
+ `Gullah#lex` tries every leaf regex at every offset: O(text × leaves).
87
+ Combining all leaf regexes into one master alternation with named captures
88
+ lexes in a single pass and is a standard, behavior-preserving optimization.
89
+ Trash detection (nearest next match) can be folded into the same pass.
90
+
91
+ ### 4. Lazy enumeration
92
+
93
+ `parse` currently returns arrays and the `n:` parameter is an awkward
94
+ best-effort count (see the caveat in the `parse` docs). Returning a lazy
95
+ `Enumerator` driven by the best-first search would simplify the API: `first`
96
+ falls out naturally, and `n` becomes `take(n)`. This is already on the
97
+ author's TODO.
98
+
99
+ ### 5. Parallelism
100
+
101
+ Segments between boundaries are fully independent, and the grammar is
102
+ read-only after `commit`, so `Segment` processing is a natural fit for
103
+ Ractors (the grammar objects would need `Ractor.make_shareable` or to be
104
+ rebuilt per ractor). The `n:`-driven loop in `Gullah.parse`, which picks the
105
+ lightest unfinished segment, is the other obvious parallelization point.
106
+ The win is real but bounded: parsing is usually dominated by a single
107
+ segment, so expect gains mainly on multi-sentence input.
108
+
109
+ ## A coherent target architecture
110
+
111
+ If one were to redesign rather than patch, the pieces above suggest this
112
+ shape:
113
+
114
+ 1. **One-pass master-regex lexer** producing leaves + trash + boundaries.
115
+ 2. **A chart of spans** keyed by `[start, end]`, holding the nonterminals
116
+ derived for each span, with reductions applied bottom-up and memoized —
117
+ replacing the clone-heavy state search for the common case.
118
+ 3. **Tests/preconditions run as span facts are derived** (preconditions
119
+ before, tests after, structure tests on ancestor attachment), preserving
120
+ today's semantics.
121
+ 4. **A lazy enumerator of optimal parses** over the chart, keeping the
122
+ Hopper's filter ordering but yielding parses as they are proven optimal.
123
+ 5. **Optional Ractor-level parallelism across segments.**
124
+
125
+ The external API (`rule`, `leaf`, `ignore`, `boundary`, `parse`, `first`,
126
+ node tests, structure tests, processors) can survive all of this; what
127
+ changes is that parses are *reconstructed from a chart* instead of *grown by
128
+ cloning*, which is where most of the complexity and all of the super-linear
129
+ cost currently lives.
130
+
131
+ ## Non-goals
132
+
133
+ - Making Gullah competitive with a hand-written parser for a fixed,
134
+ unambiguous language. The README is explicit that this is not the aim.
135
+ - Changing the optimality criteria or the parse-tree shape returned to
136
+ users.
137
+
138
+ ## Status (as of 0.0.5)
139
+
140
+ Implemented:
141
+
142
+ - **Copy-on-write parse states.** `Parse#add` no longer deep-clones every
143
+ node of a parse per candidate reduction; roots are shared and only the
144
+ nodes on the reduced span (plus, for structure tests, the path down to each
145
+ tested node) are copied. Parses returned to the user are normalized
146
+ (`Parse#_normalized`) so parent links are consistent. Measured on a
147
+ 16-word sentence: node clones per parse dropped ~26x, total allocations
148
+ ~37% down, wall time ~30% down, with identical results.
149
+ - **Structured dedup in `Hopper#vet`.** The seen-set is keyed on the
150
+ resulting parse's sequence of root summaries as an array (candidate
151
+ strings memoized per rule + child summaries) instead of building a joined
152
+ summary string for every candidate. Note: the old string key was lossy
153
+ (summaries contain `,` and `;`), which accidentally merged some distinct
154
+ states; the structured key is exact.
155
+ - **Lazy enumeration API.** `Gullah.each_parse` returns an `Enumerator` of
156
+ the optimal parses, composable with `lazy`/`take`/`first`.
157
+
158
+ Deferred, with reasons:
159
+
160
+ - **Full chart-based core.** Profiling shows the remaining cost is the
161
+ best-first state search itself (`Atom#match`, ~160k calls on the 16-word
162
+ sentence), which a chart would address, but a chart rewrite must preserve
163
+ structure-test semantics exactly; the copy-on-write change captures most
164
+ of the available win at far lower risk.
165
+ - **One-pass master-regex lexer.** Profiling shows lexing is not hot
166
+ (a handful of regex matches per token vs. tens of thousands of node
167
+ operations), and a single alternation would change semantics where
168
+ several leaf rules can match at the same offset.
169
+ - **Ractors.** Rules hold user-supplied `Method`/`Proc` objects (tests,
170
+ preconditions, processors), which are not shareable across ractors;
171
+ parallelizing segments would require serializing or rebuilding the
172
+ grammar per ractor. Not worth it until the grammar is data-only.
data/CHANGES.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # Change Log
2
2
 
3
+ ## 0.0.5 *2025-11-24*
4
+ * copy-on-write parse states: candidate reductions no longer deep-clone the
5
+ whole parse (~26x fewer node clones, ~30% faster on a 16-word sentence,
6
+ identical results); parses returned to the user are normalized so parent
7
+ links are consistent
8
+ * structured dedup keys in `Hopper#vet` replace per-candidate summary-string
9
+ building (candidate strings are memoized)
10
+ * new `Gullah.each_parse` lazy `Enumerator` API
11
+ * see ARCHITECTURE.md for the review and implementation status
12
+
13
+ ## 0.0.4 *2025-11-24*
14
+ * bug fixes: leaf preconditions now honor truthy/falsy returns consistently,
15
+ `parse` rejects negative `n`, rule/leaf duplicate detection accounts for
16
+ processors and no longer mutates the caller's `tests` array
17
+ * simplifications: `Regexp.escape` replaces a hand-rolled escaper, clearer
18
+ `Hopper#satisfied?`
19
+ * modernization: tests use `JSON.generate`, drop unused `byebug` requires,
20
+ updated development dependencies and required Ruby version (>= 3.2)
21
+
22
+ ## 0.0.3 *2023-11-24*
23
+ * a few optimizations
24
+
3
25
  ## 0.0.2 *2021-8-29*
4
26
  * still more improvements to documentation
5
27
 
data/README.md CHANGED
@@ -78,10 +78,23 @@ I hope this causes no offense to speakers of Gullah.
78
78
 
79
79
  # Future
80
80
 
81
- Because Gullah is designed to handle ambiguous grammars and erroneous data, it can produce many parses for a given string. Right now you can ask for all parses (maybe very slow), or at least `n` equally good parses. This makes the API a little complicated and noisy. I have begun work rewriting it to return a lazy enumeration of parses. Ruby's `Enumerable` magic is nice. I haven't finished this, though, and I might not, but it may be that some future version of this will change the API dramatically.
81
+ Because Gullah is designed to handle ambiguous grammars and erroneous data, it can produce many parses for a given string. You can ask for all parses (maybe very slow), or at least `n` equally good parses via `parse(text, n: n)`. If you prefer to consume parses incrementally, `each_parse` returns a lazy `Enumerator` of the optimal parses:
82
+
83
+ ```ruby
84
+ Grammar.each_parse(text).lazy.select(&:success?).first
85
+ Grammar.each_parse(text).take(3)
86
+ ```
87
+
88
+ Internally, parses are now built copy-on-write rather than by cloning the whole parse per candidate reduction; see [ARCHITECTURE.md](ARCHITECTURE.md) for details.
82
89
 
83
90
  Another possibility, if I have sufficient spare time and am sufficiently ambitious, is that I may refactor the algorithm to use ractors. Certain parts of the algorithm are a natural fit for parallelization. We shall see.
84
91
 
92
+ For a review of the current architecture and how it might be changed at a fundamental level -- chart-based parsing instead of clone-heavy state search, a one-pass lexer, lazy parse enumeration, parallelism across segments -- see [ARCHITECTURE.md](ARCHITECTURE.md).
93
+
85
94
  # Acknowledgements
86
95
 
87
96
  I would like to thank my family and co-workers for tolerating me saying "Gullah" much more often than any of them expected.
97
+
98
+ # Dedication
99
+
100
+ I dedicate this gem to my son Jude, a.k.a [TurkeyMcMac](https://github.com/TurkeyMcMac). He was a better programmer than I will ever be and was only getting better. More importantly, he was a kind, funny, thoughtful person. I miss him every day. I love you, Jude.
data/gullah.gemspec CHANGED
@@ -18,14 +18,14 @@ Gem::Specification.new do |s|
18
18
  s.homepage =
19
19
  'https://github.com/dfhoughton/gullah'
20
20
  s.license = 'MIT'
21
- s.required_ruby_version = '>= 2.6'
21
+ s.required_ruby_version = '>= 3.2'
22
22
  s.files = `git ls-files -z`.split("\x0")
23
23
  s.test_files = s.files.grep(%r{^(test|spec|features)/})
24
24
  s.require_paths = ['lib']
25
25
 
26
- s.add_development_dependency 'bundler', '~> 1.7'
27
- s.add_development_dependency 'byebug', '~> 9.1.0'
26
+ s.add_development_dependency 'bundler', '~> 2.0'
27
+ s.add_development_dependency 'byebug', '~> 12.0'
28
28
  s.add_development_dependency 'json', '~> 2'
29
29
  s.add_development_dependency 'minitest', '~> 5'
30
- s.add_development_dependency 'rake', '~> 10.0'
30
+ s.add_development_dependency 'rake', '~> 13.0'
31
31
  end
data/lib/gullah/atom.rb CHANGED
@@ -70,7 +70,7 @@ module Gullah
70
70
  end
71
71
 
72
72
  count = 0
73
- nodes[offset...nodes.length].each_with_index do |n, i|
73
+ nodes[offset..].each_with_index do |n, i|
74
74
  next if n.ignorable?
75
75
 
76
76
  return returnable(nodes, i + offset + 1) if count == max_repeats
data/lib/gullah/hopper.rb CHANGED
@@ -24,14 +24,14 @@ module Gullah
24
24
  alias length size
25
25
 
26
26
  def satisfied?
27
- if @bin.length == @number_sought
28
- limits = @thresholds.values_at(:correctness, :pending).compact
29
- if limits.any? && limits.all?(&:zero?)
30
- # we could have accumulated some dross
31
- @bin.uniq!(&:summary)
32
- @bin.length == @number_sought
33
- end
34
- end
27
+ return false unless @bin.length == @number_sought
28
+
29
+ limits = @thresholds.values_at(:correctness, :pending).compact
30
+ return false unless limits.any? && limits.all?(&:zero?)
31
+
32
+ # we could have accumulated some dross
33
+ @bin.uniq!(&:summary)
34
+ @bin.length == @number_sought
35
35
  end
36
36
 
37
37
  def <<(parse)
@@ -97,26 +97,35 @@ module Gullah
97
97
  end
98
98
 
99
99
  def vet(parse, i, offset, rule, do_unary_branch_check)
100
+ # at this point, any prospective node will be non-terminal
101
+ kids = parse.roots[i...offset]
100
102
  preconditions_satisfied = rule.preconditions.all? do |pc|
101
- # at this point, any prospective node will be non-terminal
102
- kids = parse.roots[i...offset]
103
- pc.call rule.name, kids.first.start, kids.last.end, kids.first.text, kids
103
+ pass = pc.call rule.name, kids.first.start, kids.last.end, kids.first.text, kids
104
+ pass && pass != :fail
104
105
  end
105
106
  return unless preconditions_satisfied
106
107
 
107
- candidate = "#{rule.name}[#{parse.roots[i...offset].map(&:summary).join(',')}]"
108
+ # dedup on the resulting parse's sequence of root summaries (what the
109
+ # dedup has always keyed on), as a structured key to avoid building the
110
+ # joined summary string for candidates we've already seen; the
111
+ # candidate string itself is memoized per rule + child summaries
112
+ summaries = parse.roots.map { |r| r.summary.to_s }
113
+ candidate = (@candidate_cache ||= {})[[rule.name, kids.map(&:summary)]] ||=
114
+ "#{rule.name}[#{kids.map(&:summary).join(',')}]"
115
+ key = summaries.dup
116
+ key[i...offset] = [candidate]
117
+ return if @seen.include? key
118
+
119
+ @seen << key
108
120
  unvetted_summary = [
109
121
  parse.roots[0...i].map(&:summary) +
110
122
  [candidate] +
111
123
  parse.roots[offset..].map(&:summary)
112
124
  ].join(';')
113
- unless @seen.include? unvetted_summary
114
- @seen << unvetted_summary
115
- parse.add(i, offset, rule, do_unary_branch_check).tap do |new_parse|
116
- if new_parse
117
- new_parse._summary = unvetted_summary
118
- new_parse.roots[i]._summary = candidate
119
- end
125
+ parse.add(i, offset, rule, do_unary_branch_check).tap do |new_parse|
126
+ if new_parse
127
+ new_parse._summary = unvetted_summary
128
+ new_parse.roots[i]._summary = candidate
120
129
  end
121
130
  end
122
131
  end
data/lib/gullah/node.rb CHANGED
@@ -38,7 +38,9 @@ module Gullah
38
38
  @start = s
39
39
  @end = e
40
40
  else
41
- @children = parse.roots[s...e]
41
+ # copy-on-write: the parse's roots are shared with other parse states,
42
+ # so clone the children (cheaply) before adopt marks them
43
+ @children = parse.roots[s...e].map(&:clone)
42
44
  @children.each { |n| adopt n }
43
45
  end
44
46
  unless trash?
@@ -341,15 +343,12 @@ module Gullah
341
343
  end
342
344
 
343
345
  # @private
346
+ # Copy-on-write clone: children are shared with the original (they will
347
+ # themselves be copied if ever mutated), but the attribute hash is private
348
+ # to the copy so tests/adoption can mark it without affecting the original.
344
349
  def clone # :nodoc:
345
- super.tap do |c|
350
+ dup.tap do |c|
346
351
  c._attributes = deep_clone(attributes)
347
- unless c.leaf?
348
- c._children = deep_clone(children)
349
- c.children.each do |child|
350
- child._parent = c
351
- end
352
- end
353
352
  end
354
353
  end
355
354
 
@@ -459,6 +458,32 @@ module Gullah
459
458
  @children = children
460
459
  end
461
460
 
461
+ # @private
462
+ # produce a fully owned copy of this node's subtree with consistent
463
+ # parent links, for parses returned to the user (internal parse states
464
+ # share subtrees copy-on-write and may have stale parent links)
465
+ def _normalized(parent) # :nodoc:
466
+ c = clone
467
+ c._parent = parent
468
+ c._children = children.map { |ch| ch._normalized(c) } unless leaf?
469
+ c
470
+ end
471
+
472
+ # @private
473
+ # copy-on-write the path from this node down to each of the given positions,
474
+ # so those nodes have correct parent links, without copying the whole subtree
475
+ def _cow_path_to(positions, parent) # :nodoc:
476
+ c = clone
477
+ c._parent = parent
478
+ unless leaf?
479
+ c._children = children.map do |ch|
480
+ hits = positions.select { |p| ch.contains? p.first }
481
+ hits.empty? ? ch : ch._cow_path_to(hits, c)
482
+ end
483
+ end
484
+ c
485
+ end
486
+
462
487
  # @private
463
488
  def _descendants(skip) # :nodoc:
464
489
  Descendants.new(self, skip)
@@ -535,6 +560,13 @@ module Gullah
535
560
  def adopt(n)
536
561
  n._parent = self
537
562
  if (pending = n.attributes.delete :pending)
563
+ # structure tests may walk parent links from the tested node (e.g. via
564
+ # root or prior), and shared subtrees have stale links, so copy the
565
+ # path down to each tested node, giving it a correct chain up to self
566
+ positions = pending.map { |_, l| l }
567
+ positions.group_by { |l| children.index { |c| c.contains? l.first } }.each do |i, ls|
568
+ children[i] = children[i]._cow_path_to(ls, self)
569
+ end
538
570
  pending.each do |pair|
539
571
  r, l = pair
540
572
  child = find(l) # this will necessarily find some child
data/lib/gullah/parse.rb CHANGED
@@ -43,9 +43,11 @@ module Gullah
43
43
  end
44
44
 
45
45
  # produce a clone of this parse with a new node with the given offsets and rule
46
+ # the clone shares its root nodes copy-on-write: only the nodes actually
47
+ # adopted by the new node are copied (in Node#initialize)
46
48
  def add(s, e, rule, loop_check, trash = false, boundary = false) # :nodoc:
47
49
  clone.tap do |b|
48
- b._roots = roots.map(&:clone)
50
+ b._roots = roots.dup
49
51
  cz = if trash
50
52
  Trash
51
53
  elsif boundary
@@ -81,14 +83,14 @@ module Gullah
81
83
  # and the ancestor node where the test was run as erroneous,
82
84
  # so they will increase the +incorrectness_count+ by 2.
83
85
  def incorrectness_count
84
- @incorrectness_count ||= roots.select(&:failed?).count
86
+ @incorrectness_count ||= roots.count(&:failed?)
85
87
  end
86
88
 
87
89
  ##
88
90
  # The count of nodes which have some structure test which was never
89
91
  # successfully run.
90
92
  def pending_count
91
- @pending_count ||= roots.select(&:pending_tests?).count
93
+ @pending_count ||= roots.count(&:pending_tests?)
92
94
  end
93
95
 
94
96
  ##
@@ -122,7 +124,7 @@ module Gullah
122
124
  #
123
125
  # parses = Grammar.parse "this grammar uses the usual whitespace rule"
124
126
  #
125
- # parses.first.nodes.select { |n| n.name == :_ws }.count # => 6
127
+ # parses.first.nodes.count { |n| n.name == :_ws } # => 6
126
128
  def nodes
127
129
  NodeIterator.new self
128
130
  end
@@ -205,10 +207,22 @@ module Gullah
205
207
  # it would be conceptually simpler to lazily initialize the summary, but this
206
208
  # gives us a speed boost
207
209
  def initialize_summaries
208
- @summary = roots.each { |n| n._summary = n.name unless n.summary }.map(&:summary).join(';')
210
+ # roots may be shared with other parses, so copy-on-write before marking
211
+ @roots = roots.map { |n| n.summary ? n : n.clone.tap { |c| c._summary = n.name } }
212
+ @summary = @roots.map(&:summary).join(';')
209
213
  self
210
214
  end
211
215
 
216
+ # @private
217
+ # produce a fully owned copy of this parse with consistent parent links,
218
+ # suitable for handing to the user
219
+ def _normalized # :nodoc:
220
+ self.class.new(text).tap do |p|
221
+ p._roots = roots.map { |r| r._normalized(nil) }
222
+ p._summary = @summary
223
+ end
224
+ end
225
+
212
226
  def _summary=(str)
213
227
  @summary = str
214
228
  end
@@ -3,5 +3,5 @@
3
3
  module Gullah
4
4
  # This is an alpha release. Gullah has not yet been used in anything
5
5
  # other than unit tests.
6
- VERSION = '0.0.2'
6
+ VERSION = '0.0.5'
7
7
  end
data/lib/gullah.rb CHANGED
@@ -110,8 +110,9 @@ end
110
110
  # A precondition is just an instance method defined in the Gullah-fied class with an arity
111
111
  # of two: it takes the rule's name, a symbol, as its first argument, the start and end character
112
112
  # offsets of the match as its second and third arguments, the text being parsed as its fourth argument,
113
- # and the prospective child nodes, an array, as its last argument. If it returns a truthy value, the
114
- # precondition holds and the node can be made. Otherwise, Gullah tries the next thing.
113
+ # and the prospective child nodes, an array, as its last argument. If it returns a truthy value
114
+ # other than +:fail+, the precondition holds and the node can be made. If it returns +:fail+ or any
115
+ # falsy value, Gullah tries the next thing.
115
116
  #
116
117
  # == Preconditions versus Tests
117
118
  #
@@ -333,9 +334,9 @@ module Gullah
333
334
  init_check(name)
334
335
  name = name.to_sym
335
336
  body = body.to_s.strip.gsub(/\s+/, ' ')
337
+ tests = tests + [[process]] if process
336
338
  return if dup_check(:rule, name, body, tests + preconditions)
337
339
 
338
- tests << [process] if process
339
340
  r = Rule.new name, body, tests: tests, preconditions: preconditions
340
341
  subrules = r.subrules || [r]
341
342
  subrules.each do |sr|
@@ -459,7 +460,7 @@ module Gullah
459
460
  # all equally good, so rather than arbitrarily choosing 3 and discarding one, Gullah
460
461
  # will return all 4.
461
462
  def parse(text, filters: %i[correctness completion pending size], n: nil)
462
- raise Error, 'n must be positive' if n&.zero?
463
+ raise Error, 'n must be positive' if n && !n.positive?
463
464
 
464
465
  commit
465
466
  segments = segment(text.to_s, filters, n)
@@ -477,14 +478,34 @@ module Gullah
477
478
  s.next
478
479
  end
479
480
  end
480
- if segments.length > 1
481
- # pass the results through a new hopper to filter out duds
482
- hopper = Hopper.new filters, nil
483
- initial_segments.flat_map(&:results).each { |p| hopper << p }
484
- hopper.dump.each(&:initialize_summaries)
485
- else
486
- segments.first.results
487
- end
481
+ results =
482
+ if segments.length > 1
483
+ # pass the results through a new hopper to filter out duds
484
+ hopper = Hopper.new filters, nil
485
+ initial_segments.flat_map(&:results).each { |p| hopper << p }
486
+ hopper.dump.each(&:initialize_summaries)
487
+ else
488
+ segments.first.results
489
+ end
490
+ # internal parse states share subtrees copy-on-write; hand the user
491
+ # fully owned parses with consistent parent links
492
+ results.map(&:_normalized)
493
+ end
494
+
495
+ ##
496
+ # A lazy enumeration of the optimal parses of the given text, as an
497
+ # Enumerator. Takes the same arguments as +parse+. Because optimality is
498
+ # determined only once all candidate parses have been compared, the
499
+ # enumeration is computed as a whole and then yielded one parse at a time,
500
+ # but the Enumerator interface lets you consume parses incrementally --
501
+ # +each_parse(text).first+, +.take(n)+, chaining with other Enumerable
502
+ # operations, and so on.
503
+ #
504
+ # Grammar.each_parse('some text').lazy.select { |p| p.success? }.first
505
+ def each_parse(text, filters: %i[correctness completion pending size], n: nil)
506
+ return enum_for(:each_parse, text, filters: filters, n: n) unless block_given?
507
+
508
+ parse(text, filters: filters, n: n).each { |p| yield p }
488
509
  end
489
510
 
490
511
  ##
@@ -612,9 +633,9 @@ module Gullah
612
633
  init
613
634
  init_check(name)
614
635
  name = name.to_sym
636
+ tests = tests + [[process]] if process
615
637
  return if dup_check(:leaf, name, rx, tests + preconditions)
616
638
 
617
- tests << [process] if process
618
639
  @leaves << Leaf.new(name, rx, ignorable: ignorable, boundary: boundary, tests: tests, preconditions: preconditions)
619
640
  end
620
641
 
@@ -630,7 +651,7 @@ module Gullah
630
651
  next unless (md = leaf.rx.match(text, offset)) && md.begin(0) == offset
631
652
 
632
653
  e = md.end(0)
633
- next if leaf.preconditions.any? { |pc| pc.call(leaf.name, offset, e, text, []) == :fail }
654
+ next unless leaf.preconditions.all? { |pc| pass = pc.call(leaf.name, offset, e, text, []); pass && pass != :fail }
634
655
 
635
656
  added_any = true
636
657
  new_parse = parse.add(offset, e, leaf, @do_unary_branch_check, false, leaf.boundary)
@@ -651,7 +672,7 @@ module Gullah
651
672
  (b = md.begin(0)) &&
652
673
  (b < trash_offset) &&
653
674
  (e = md.end(0)) &&
654
- leaf.preconditions.none? { |pc| pc.call(leaf.name, b, e, text, []) == :fail }
675
+ leaf.preconditions.all? { |pc| pass = pc.call(leaf.name, b, e, text, []); pass && pass != :fail }
655
676
 
656
677
  trash_offset = b
657
678
  end
@@ -690,7 +711,8 @@ module Gullah
690
711
  # return true if perfect duplicate, false if novel
691
712
  def dup_check(type, name, body, tests)
692
713
  set = type == :leaf ? (@leaf_dup_check ||= ::Set.new) : (@rule_dup_check ||= ::Set.new)
693
- key = [name, body, tests.sort]
714
+ # tests may mix symbols and [processor] arrays, so sort on a comparable key
715
+ key = [name, body, tests.sort_by(&:inspect)]
694
716
  if set.include? key
695
717
  true
696
718
  else
@@ -727,7 +749,7 @@ module Gullah
727
749
  raise Error, "#{precond} is not defined"
728
750
  end
729
751
  raise Error, <<-MESSAGE.strip.gsub(/\s+/, ' ') unless m.arity == 5
730
- #{precond} must take four arguments:
752
+ #{precond} must take five arguments:
731
753
  the rule or leaf name,
732
754
  the start character offset,
733
755
  the end character offset,
@@ -741,13 +763,7 @@ module Gullah
741
763
 
742
764
  # escape a string literal for use in a regex
743
765
  def quotemeta(str)
744
- quoted = ''
745
- (0...str.length).each do |i|
746
- c = str[i]
747
- quoted += '\\' if c =~ /[{}()\[\].?+*\\^$]/
748
- quoted += c
749
- end
750
- quoted
766
+ Regexp.escape(str)
751
767
  end
752
768
 
753
769
  def procify(processor)
data/test/basic_test.rb CHANGED
@@ -3,7 +3,6 @@
3
3
  require 'minitest/autorun'
4
4
 
5
5
  require 'gullah'
6
- require 'byebug'
7
6
 
8
7
  # :stopdoc:
9
8
 
@@ -43,7 +42,7 @@ class BasicTest < Minitest::Test
43
42
  parses.each do |p|
44
43
  assert_equal 1, p.roots.length, 'parse has a root node'
45
44
  root = p.roots.first
46
- assert_equal 2, root.subtree.select(&:nonterminal?).count, 'parse has 2 nonterminal nodes'
45
+ assert_equal 2, root.subtree.count(&:nonterminal?), 'parse has 2 nonterminal nodes'
47
46
  assert root.subtree.select(&:nonterminal?).each do |_n|
48
47
  assert_equal 2, b.children.length, 'nonterminal nodes each have 2 children'
49
48
  end
@@ -96,10 +95,10 @@ class BasicTest < Minitest::Test
96
95
  parse = parses.first
97
96
  assert_equal 8, parse.roots.length, 'there are 8 nodes in the parse'
98
97
  assert parse.roots.all?(&:leaf?), 'all nodes are leaf nodes'
99
- assert_equal 3, parse.roots.select { |n| n.name == :ws }.count, 'there are 3 whitespace nodes'
100
- assert_equal 3, parse.roots.select(&:ignorable?).count, 'there are 3 ignorable nodes'
101
- assert_equal 4, parse.roots.select { |n| n.name == :word }.count, 'there are 4 word nodes'
102
- assert_equal 1, parse.roots.select(&:trash?).count, 'there is 1 trash node'
98
+ assert_equal 3, parse.roots.count { |n| n.name == :ws }, 'there are 3 whitespace nodes'
99
+ assert_equal 3, parse.roots.count(&:ignorable?), 'there are 3 ignorable nodes'
100
+ assert_equal 4, parse.roots.count { |n| n.name == :word }, 'there are 4 word nodes'
101
+ assert_equal 1, parse.roots.count(&:trash?), 'there is 1 trash node'
103
102
  last_node = parse.roots.last
104
103
  assert last_node.trash?, 'the last node is the trash node'
105
104
  end
@@ -156,9 +155,9 @@ class BasicTest < Minitest::Test
156
155
  assert_equal 1, parse.roots.reject(&:ignorable?).count, 'there is a root node for this parse'
157
156
  root = parse.roots.first
158
157
  assert_equal :s, root.name, 'found expected root'
159
- assert_equal 2, root.subtree.select { |n| n.name == :thing }.count, 'two things'
160
- assert_equal 1, root.subtree.select { |n| n.name == :word }.count, 'one word'
161
- assert_equal 1, root.subtree.select { |n| n.name == :integer }.count, 'one integer'
158
+ assert_equal 2, root.subtree.count { |n| n.name == :thing }, 'two things'
159
+ assert_equal 1, root.subtree.count { |n| n.name == :word }, 'one word'
160
+ assert_equal 1, root.subtree.count { |n| n.name == :integer }, 'one integer'
162
161
  end
163
162
 
164
163
  class SubRulesWithTest
@@ -185,8 +184,8 @@ class BasicTest < Minitest::Test
185
184
  things = root.subtree.select { |n| n.name == :thing }
186
185
  assert_equal 2, things.count, 'two things'
187
186
  assert things.all? { |n| n.attributes[:satisfied].include?(%i[foo etc]) }, 'passing tests stuff in extra bits'
188
- assert_equal 1, root.subtree.select { |n| n.name == :word }.count, 'one word'
189
- assert_equal 1, root.subtree.select { |n| n.name == :integer }.count, 'one integer'
187
+ assert_equal 1, root.subtree.count { |n| n.name == :word }, 'one word'
188
+ assert_equal 1, root.subtree.count { |n| n.name == :integer }, 'one integer'
190
189
  end
191
190
 
192
191
  class SubRulesWithAncestorTest
@@ -218,8 +217,8 @@ class BasicTest < Minitest::Test
218
217
  assert thing.attributes[:satisfied_descendant].include?([:foo, root.position]),
219
218
  'descendant is marked when ancestor test passes'
220
219
  end
221
- assert_equal 1, root.subtree.select { |n| n.name == :word }.count, 'one word'
222
- assert_equal 1, root.subtree.select { |n| n.name == :integer }.count, 'one integer'
220
+ assert_equal 1, root.subtree.count { |n| n.name == :word }, 'one word'
221
+ assert_equal 1, root.subtree.count { |n| n.name == :integer }, 'one integer'
223
222
  end
224
223
 
225
224
  class LeftAncestor
@@ -3,7 +3,6 @@
3
3
  require 'minitest/autorun'
4
4
 
5
5
  require 'gullah'
6
- require 'byebug'
7
6
 
8
7
  # :stopdoc:
9
8
 
@@ -3,7 +3,6 @@
3
3
  require 'minitest/autorun'
4
4
 
5
5
  require 'gullah'
6
- require 'byebug'
7
6
  require 'date'
8
7
 
9
8
  # :stopdoc:
data/test/date_test.rb CHANGED
@@ -3,7 +3,6 @@
3
3
  require 'minitest/autorun'
4
4
 
5
5
  require 'gullah'
6
- require 'byebug'
7
6
  require 'date'
8
7
 
9
8
  # :stopdoc:
data/test/error_test.rb CHANGED
@@ -3,7 +3,6 @@
3
3
  require 'minitest/autorun'
4
4
 
5
5
  require 'gullah'
6
- require 'byebug'
7
6
 
8
7
  # :stopdoc:
9
8
 
data/test/json_test.rb CHANGED
@@ -3,7 +3,6 @@
3
3
  require 'minitest/autorun'
4
4
 
5
5
  require 'gullah'
6
- require 'byebug'
7
6
  require 'json'
8
7
 
9
8
  # :stopdoc:
@@ -86,7 +85,7 @@ class JsonTest < Minitest::Test
86
85
  ['2', { 'a' => false }],
87
86
  [1, nil, '2', { 'a' => false }]
88
87
  ].each do |val|
89
- json = JSON.unparse(val)
88
+ json = JSON.generate(val)
90
89
  parses = clock(json) { Gson.parse json }
91
90
  assert_equal 1, parses.length, "unambiguous: #{json}"
92
91
  parse = parses.first
@@ -103,7 +102,7 @@ class JsonTest < Minitest::Test
103
102
  { 'foo' => [1, 2, true], 'bar' => ['baz'], 'baz' => { 'v1' => nil, 'v2' => [], 'v3' => 'corge' } },
104
103
  [{ 'foo bar' => 1, 'baz' => ['a string with a lot of spaces in it'] }]
105
104
  ].each do |val|
106
- json = JSON.unparse(val)
105
+ json = JSON.generate(val)
107
106
  parse = clock(json) { Gson.first json }
108
107
  root = parse.roots.first
109
108
  assert_equal val, root.atts[:value], "parsed value correctly: #{json}"
@@ -3,7 +3,6 @@
3
3
  require 'minitest/autorun'
4
4
 
5
5
  require 'gullah'
6
- require 'byebug'
7
6
  require 'date'
8
7
 
9
8
  # :stopdoc:
@@ -3,7 +3,6 @@
3
3
  require 'minitest/autorun'
4
4
 
5
5
  require 'gullah'
6
- require 'byebug'
7
6
 
8
7
  # :stopdoc:
9
8
 
@@ -3,7 +3,6 @@
3
3
  require 'minitest/autorun'
4
4
 
5
5
  require 'gullah'
6
- require 'byebug'
7
6
 
8
7
  # :stopdoc:
9
8
 
@@ -3,7 +3,6 @@
3
3
  require 'minitest/autorun'
4
4
 
5
5
  require 'gullah'
6
- require 'byebug'
7
6
 
8
7
  # :stopdoc:
9
8
 
metadata CHANGED
@@ -1,14 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: gullah
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.2
4
+ version: 0.0.5
5
5
  platform: ruby
6
6
  authors:
7
7
  - David F. Houghton
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2021-08-29 00:00:00.000000000 Z
10
+ date: 2026-11-28 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
13
  name: bundler
@@ -16,28 +15,28 @@ dependencies:
16
15
  requirements:
17
16
  - - "~>"
18
17
  - !ruby/object:Gem::Version
19
- version: '1.7'
18
+ version: '2.0'
20
19
  type: :development
21
20
  prerelease: false
22
21
  version_requirements: !ruby/object:Gem::Requirement
23
22
  requirements:
24
23
  - - "~>"
25
24
  - !ruby/object:Gem::Version
26
- version: '1.7'
25
+ version: '2.0'
27
26
  - !ruby/object:Gem::Dependency
28
27
  name: byebug
29
28
  requirement: !ruby/object:Gem::Requirement
30
29
  requirements:
31
30
  - - "~>"
32
31
  - !ruby/object:Gem::Version
33
- version: 9.1.0
32
+ version: '12.0'
34
33
  type: :development
35
34
  prerelease: false
36
35
  version_requirements: !ruby/object:Gem::Requirement
37
36
  requirements:
38
37
  - - "~>"
39
38
  - !ruby/object:Gem::Version
40
- version: 9.1.0
39
+ version: '12.0'
41
40
  - !ruby/object:Gem::Dependency
42
41
  name: json
43
42
  requirement: !ruby/object:Gem::Requirement
@@ -72,14 +71,14 @@ dependencies:
72
71
  requirements:
73
72
  - - "~>"
74
73
  - !ruby/object:Gem::Version
75
- version: '10.0'
74
+ version: '13.0'
76
75
  type: :development
77
76
  prerelease: false
78
77
  version_requirements: !ruby/object:Gem::Requirement
79
78
  requirements:
80
79
  - - "~>"
81
80
  - !ruby/object:Gem::Version
82
- version: '10.0'
81
+ version: '13.0'
83
82
  description: Gullah is a bottom-up parser generator than can handle errors, ambiguous
84
83
  syntax, and arbitrary matching conditions.
85
84
  email: dfhoughton@gmail.com
@@ -89,6 +88,7 @@ extra_rdoc_files: []
89
88
  files:
90
89
  - ".gitignore"
91
90
  - ".yardopts"
91
+ - ARCHITECTURE.md
92
92
  - CHANGES.md
93
93
  - LICENSE
94
94
  - README.md
@@ -127,7 +127,6 @@ homepage: https://github.com/dfhoughton/gullah
127
127
  licenses:
128
128
  - MIT
129
129
  metadata: {}
130
- post_install_message:
131
130
  rdoc_options: []
132
131
  require_paths:
133
132
  - lib
@@ -135,15 +134,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
135
134
  requirements:
136
135
  - - ">="
137
136
  - !ruby/object:Gem::Version
138
- version: '2.6'
137
+ version: '3.2'
139
138
  required_rubygems_version: !ruby/object:Gem::Requirement
140
139
  requirements:
141
140
  - - ">="
142
141
  - !ruby/object:Gem::Version
143
142
  version: '0'
144
143
  requirements: []
145
- rubygems_version: 3.2.15
146
- signing_key:
144
+ rubygems_version: 3.6.2
147
145
  specification_version: 4
148
146
  summary: A bottom up parser generator
149
147
  test_files: