Module: Stupidedi::Parser::Navigation

Included in:
StateMachine
Defined in:
lib/stupidedi/parser/navigation.rb

Querying the Current Position collapse

Accessing the Current Node collapse

Navigating the Tree collapse

Instance Method Details

#count(id, *elements) ⇒ Integer

Returns:

  • (Integer)


488
489
490
# File 'lib/stupidedi/parser/navigation.rb', line 488

def count(id, *elements)
  __count(false, id, elements)
end

#count!(id, *elements) ⇒ Integer

Returns:

  • (Integer)


493
494
495
# File 'lib/stupidedi/parser/navigation.rb', line 493

def count!(id, *elements)
  __count(true, id, elements)
end

#deterministic?Boolean

Is there exactly one valid parse tree in the current state?

Returns:

  • (Boolean)


16
17
18
# File 'lib/stupidedi/parser/navigation.rb', line 16

def deterministic?
  @active.length == 1
end

#distance(other) ⇒ Either<Integer>

Note:

This method uses AbstractCursor#between, which assumes the two cursors point to the same tree. If that is not the case, the results are undefined.

Returns the number of segments apart the current state is from the given StateMachine's state. Note the direction is not indicated by the return value, so a.distance(b) == b.distance(a) for all states a and b.

Examples:

m.distance(m)                          #=> Either.success(0)
m.next(10).flatmap{|n| n.distance(m) } #=> Either.success(10)

Returns:



68
69
70
71
72
73
74
# File 'lib/stupidedi/parser/navigation.rb', line 68

def distance(other)
  zipper.flatmap do |a|
    other.zipper.map do |b|
      a.between(b).count(&:segment?) - 1
    end
  end
end

#element(m, n = nil, o = nil) ⇒ Either<Zipper::AbstractCursor<Values::AbstractElementVal>>

Extracts the mth element from the current segment, if the current state is deterministic. Accepts optional arguments to extract a specific occurrence of a repeated element and/or a specific component from a composite element.



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/stupidedi/parser/navigation.rb', line 119

def element(m, n = nil, o = nil)
  if m <= 0 or (n || 1) <= 0 or (o || 1) <= 0
    raise ArgumentError,
      "all arguments must be positive"
  end

  if n.nil? and not o.nil?
    raise ArgumentError,
      "third argument cannot be present unless second argument is present"
  end

  segment.flatmap do |s|
    if s.node.invalid?
      # InvalidSegmentVal doesn't have child AbstractElementVals, its
      # children are SimpleElementTok, CompositeElementTok, etc, which
      # are not parsed values.
      return Either.failure("invalid segment")
    end

    segment_id  = s.node.id.to_s
    segment_def = s.node.definition
    descriptor  = segment_id

    unless m <= segment_def.element_uses.length
      raise ArgumentError,
        "segment #{descriptor} has only #{segment_def.element_uses.length} elements"
    end

    element_use = segment_def.element_uses.at(m - 1)
    element_def = element_use.definition
    element_zip = s.child(m - 1)

    if n.nil?
      return Either.success(element_zip)

    elsif element_use.composite? and not element_use.repeatable?
      # m: element   of segment
      # n: component of composite element
      # o: occurence of repeated component (commented-out below)
      descriptor = "%s%02d" % [segment_id, m]
      components = element_def.component_uses.length
      unless n <= components
        raise ArgumentError,
          "composite element #{descriptor} only has #{components} components"
      end

      # component_use = element_def.component_uses.at(n - 1)

      if o.nil?
        if element_zip.node.blank?
          Either.failure("#{descriptor} is empty")
        else
          # This is a component of a composite element
          Either.success(element_zip.child(n - 1))
        end

      # @todo: There currently doesn't seem to be any instances of this in
      # the real world (a composite element that has a component that can
      # repeat), but perhaps this will happen in the future.
      #
      # elsif component_use.repeatable?
      #   repeat_count = component_use.repeat_count
      #   occurs_count = component_val.children.length
      #   descriptor   = "%s%02d-%02d" % [segment_id, m, n]
      #   unless repeat_count.include?(o)
      #     raise ArgumentError,
      #       "repeatable component element #{descriptor} can only occur #{repeat_count.max} times"
      #   end
      #   component_zip = element_zip.child(n - 1)
      #   if component_zip.node.blank?
      #     return Either.failure("repeating component element #{descriptor} is blank")
      #   elsif occurs_count < n
      #     return Either.failure("repeating component element #{descriptor} only occurs #{occurs_count} times")
      #   else
      #     return Either.success(component_zip.child(o - 1))
      #   end

      else
        descriptor = "%s%02d-%02d" % [segment_id, m, n]
        raise ArgumentError,
          "component element #{descriptor} cannot be further deconstructed"
      end

    elsif element_use.repeatable?
      # m: element   of segment
      # n: occurence of repeated element
      # o: component of composite element
      descriptor   = "%s%02d" % [segment_id, m]
      occurs_count = element_zip.children.count
      unless element_use.repeat_count.include?(n)
        raise ArgumentError,
          "repeatable element #{descriptor} can only occur #{element_use.repeat_count.max} times"
      end

      if o.nil?
        description = (element_use.composite?) ? "repeatable composite" : "repeatable"
        if element_zip.node.blank?
          Either.failure("#{description} element #{descriptor} does not occur")
        elsif occurs_count < n
          Either.failure("#{description} element #{descriptor} only occurs #{occurs_count} times")
        else
          Either.success(element_zip.child(n - 1))
        end

      elsif element_use.composite?
        components = element_def.component_uses.length
        unless o <= components
          raise ArgumentError,
            "repeatable composite element #{descriptor} only has #{components} components"
        end

        descriptor = "%s%02d" % [segment_id, m]

        if element_zip.node.blank?
          Either.failure("repeatable composite element #{descriptor} does not occur")
        elsif occurs_count < n
          Either.failure("repeatable composite element #{descriptor} only occurs #{occurs_count} times")
        else
          component_zip = element_zip.children.at(n - 1)
          Either.success(component_zip.child(o - 1))
        end

      else
        raise ArgumentError,
          "repeatable element #{descriptor} cannot be further deconstructed"
      end

    else
      raise ArgumentError,
        "#{segment_id}#{"%02d" % m} is not a composite or repeated element"
    end
  end
end

#elementn(m, n = nil, o = nil) ⇒ Either<Values::AbstractElementVal>

Extracts the mth element from the current segment, if the current state is deterministic. Accepts optional arguments to extract a specific occurrence of a repeated element and/or a specific component from a composite element.



259
260
261
# File 'lib/stupidedi/parser/navigation.rb', line 259

def elementn(m, n = nil, o = nil)
  element(m, n, o).map(&:node)
end

#empty?Boolean

Returns:

  • (Boolean)


20
21
22
23
24
25
26
27
28
# File 'lib/stupidedi/parser/navigation.rb', line 20

def empty?
  value = @active.head.node.zipper

  until value.root?
    value = value.up
  end

  value.node.children.empty?
end

#find(id, *elements) ⇒ Either<StateMachine>

Returns a StateMachine positioned on the next matching segment, excluding Values::InvalidSegmentVals, that satisfies the given element constraints. The search space is limited to certain related elements described in [Navigating.md]

Examples:

machine.find(:ST, nil, nil, "005010X222")

Returns:



470
471
472
# File 'lib/stupidedi/parser/navigation.rb', line 470

def find(id, *elements)
  __find(false, id, elements)
end

#find!(id, *elements) ⇒ Either<StateMachine>

Returns a StateMachine positioned on the next matching segment, including Values::InvalidSegmentVals, that satisfies the given element constraints. The search space is limited to certain related elements described in [Navigating.md]

Examples:

machine.find!(:ST, nil, nil, "005010X222")

Returns:



483
484
485
# File 'lib/stupidedi/parser/navigation.rb', line 483

def find!(id, *elements)
  __find(true, id, elements)
end

#firstEither<StateMachine>

Returns a new StateMachine positioned on the first segment in the parse tree, if there are any segments in the parse tree.

Returns:



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/stupidedi/parser/navigation.rb', line 270

def first
  active = roots.map do |zipper|
    state = zipper
    value = zipper.node.zipper

    until value.node.segment? or value.leaf?
      value = value.down
      state = state.down
    end

    unless value.node.segment?
      return Either.failure("no segments")
    end

    # Synchronize the two parallel state and value nodes
    unless value.eql?(state.node.zipper)
      state = state.replace(state.node.copy(:zipper => value))
    end

    state
  end

  Either.success(StateMachine.new(@config, active))
end

#first?Boolean

Is this the first segment?

Returns:

  • (Boolean)


31
32
33
34
35
36
37
38
39
40
# File 'lib/stupidedi/parser/navigation.rb', line 31

def first?
  value = @active.head.node.zipper

  until value.root?
    return false unless value.first?
    value = value.up
  end

  return true
end

#iterate(id, *elements) {|| ... } ⇒ Either<Array<Object>>

Convenience method to iterate repeated occurrences of a segment by iteratively calling find. Beware this doesn't check that the segment is allowed to repeat, so calling iterate(:XYZ) may yield an XYZ segment and then throw an exception when searching for the second, if XYZ is not repeatable.

Yield Parameters:

Yield Returns:

  • (Object)

Returns:



506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/stupidedi/parser/navigation.rb', line 506

def iterate(id, *elements)
  a = []
  m = __find(false, id, elements, true)
  return m unless m.defined?

  while m.defined?
    m = m.flatmap do |n|
      a << yield(n)
      n.find(id, *elements)
    end
  end

  Either.success(a)
end

#lastEither<StateMachine>

Returns a new StateMachine positioned on the last segment in the parse tree, if there are any segments in the parse tree.

Returns:



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/stupidedi/parser/navigation.rb', line 299

def last
  active = roots.map do |zipper|
    state = zipper
    value = zipper.node.zipper

    until value.node.segment? or value.leaf?
      value = value.down.last
      state = state.down.last
    end

    unless value.node.segment?
      return Either.failure("no segments")
    end

    # Synchronize the two parallel state and value nodes
    unless value.eql?(state.node.zipper)
      state = state.replace(state.node.copy(:zipper => value))
    end

    state
  end

  Either.success(StateMachine.new(@config, active))
end

#last?Boolean

Is this the last segment?

Returns:

  • (Boolean)


43
44
45
46
47
48
49
50
51
52
# File 'lib/stupidedi/parser/navigation.rb', line 43

def last?
  value = @active.head.node.zipper

  until value.root?
    return false unless value.last?
    value = value.up
  end

  return true
end

#next(count = 1) ⇒ Either<StateMachine>

Returns a new StateMachine positioned on the next segment, if there is a next segment. Optionally, a count argument may be provided that indicates how many segments to advance.

Returns:



376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/stupidedi/parser/navigation.rb', line 376

def next(count = 1)
  unless count > 0
    raise ArgumentError,
      "count must be positive"
  end

  active = @active.map do |zipper|
    state = zipper
    value = zipper.node.zipper

    count.times do
      while not value.root? and value.last?
        value = value.up
        state = state.up
      end

      if value.root?
        return Either.failure("cannot move to next after last segment")
      end

      value = value.next
      state = state.next

      until value.node.segment?
        value = value.down
        state = state.down
      end
    end

    # Synchronize the two parallel state and value nodes
    unless value.eql?(state.node.zipper)
      state = state.replace(state.node.copy(:zipper => value))
    end

    state
  end

  Either.success(StateMachine.new(@config, active))
end

#parentEither<StateMachine>

Returns a new StateMachine positioned on the first segment of the parent structure. For example, when the current segment belongs to a loop but it's not the first segment in that loop, this method will rewind to the first segment in the loop. If the current position is the first segment of a loop, this method will rewind to the first segment in the loop's parent structure.

Returns:



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/stupidedi/parser/navigation.rb', line 332

def parent
  active = []

  @active.each do |zipper|
    state = zipper
    value = zipper.node.zipper

    while value.first? and not value.root?
      value = value.up
      state = state.up
    end

    if value.root?
      break
    end

    value = value.first
    state = state.first

    until value.node.segment?
      value = value.down
      state = state.down
    end

    # Synchronize the two parallel state and value nodes
    unless value.eql?(state.node.zipper)
      state = state.replace(state.node.copy(:zipper => value))
    end

    active << state
  end

  if active.empty?
    Either.failure("no parent segment")
  else
    Either.success(StateMachine.new(@config, active))
  end
end

#prev(count = 1) ⇒ Either<StateMachine>

Returns a new StateMachine positioned on the previous segment, if there is a previous segment. Optionally, a count argument may be provided that indicates how many segments to rewind.

Returns:



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/stupidedi/parser/navigation.rb', line 421

def prev(count = 1)
  unless count > 0
    raise ArgumentError,
      "count must be positive"
  end

  active = @active.map do |zipper|
    state = zipper
    value = zipper.node.zipper

    count.times do
      while not value.root? and value.first?
        value = value.up
        state = state.up
      end

      if value.root?
        return Either.failure("cannot move to prev before first segment")
      end

      state = state.prev
      value = value.prev

      until value.node.segment?
        value = value.down.last
        state = state.down.last
      end
    end

    # Synchronize the two parallel state and value nodes
    unless value.eql?(state.node.zipper)
      state = state.replace(state.node.copy(:zipper => value))
    end

    state
  end

  Either.success(StateMachine.new(@config, active))
end

#segmentEither<Zipper::AbstractCursor<Values::SegmentVal>>

Extracts the segment from the current state, if the current state is deterministic and positioned on a segment.



95
96
97
98
99
100
101
102
103
# File 'lib/stupidedi/parser/navigation.rb', line 95

def segment
  zipper.flatmap do |z|
    if z.node.segment?
      Either.success(z)
    else
      Either.failure("not a segment")
    end
  end
end

#segmentnEither<Values::SegmentVal>

Extracts the segment from the current state, if the current state is deterministic and positioned on a segment.

Returns:



109
110
111
# File 'lib/stupidedi/parser/navigation.rb', line 109

def segmentn
  segment.map(&:node)
end

#sequence(pattern, *patterns) ⇒ Either<StateMachine>

Sequence multiple traversals together, by iteratively calling find. Each argument must be either a single segment ID or a list whose first element is a segment ID and remaining elements are segment constraints.

Examples:

machine.sequence(:GS, :ST, :HL)
machine.sequence(:GS, [:ST, "837"], [:HL, nil, "20"])

Returns:



531
532
533
534
535
# File 'lib/stupidedi/parser/navigation.rb', line 531

def sequence(pattern, *patterns)
  patterns.inject(find(*pattern)) do |m, p|
    m = m.flatmap{|n| n.find(*p) }
  end
end

#successorsArray<InstructionTable>

Returns:



11
12
13
# File 'lib/stupidedi/parser/navigation.rb', line 11

def successors
  @active.map{|a| a.node.instructions }
end

#zipperEither<Zipper::AbstractCursor<Values::AbstractVal>>

Returns the current position within the parse tree, if the current state is deterministic.



83
84
85
86
87
88
89
# File 'lib/stupidedi/parser/navigation.rb', line 83

def zipper
  if deterministic?
    Either.success(@active.head.node.zipper)
  else
    Either.failure("non-deterministic state")
  end
end