Debian Codegraph @

pod/Glade.pod

raw
1 # Copyright 2022 Jeffrey Kegler
2 # This file is part of Marpa::R2. Marpa::R2 is free software: you can
3 # redistribute it and/or modify it under the terms of the GNU Lesser
4 # General Public License as published by the Free Software Foundation,
5 # either version 3 of the License, or (at your option) any later version.
6 #
7 # Marpa::R2 is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 # Lesser General Public License for more details.
11 #
12 # You should have received a copy of the GNU Lesser
13 # General Public License along with Marpa::R2. If not, see
14 # http://www.gnu.org/licenses/.
15
16 =head1 Name
17
18 Marpa::R2::Glade - Low-level interface to Marpa's Abstract Syntax Forests (ASF's)
19
20 =head1 Synopsis
21
22 =for Marpa::R2::Display
23 name: ASF low-level calls synopsis, code part 1
24 normalize-whitespace: 1
25
26 my $grammar = Marpa::R2::Scanless::G->new(
27 { source => \(<<'END_OF_SOURCE'),
28 :start ::= pair
29 pair ::= duple | item item
30 duple ::= item item
31 item ::= Hesperus | Phosphorus
32 Hesperus ::= 'a'
33 Phosphorus ::= 'a'
34 END_OF_SOURCE
35 }
36 );
37
38 my $slr = Marpa::R2::Scanless::R->new( { grammar => $grammar } );
39 $slr->read( \'aa' );
40 my $asf = Marpa::R2::ASF->new( { slr => $slr } );
41 die 'No ASF' if not defined $asf;
42 my $output_as_array = asf_to_basic_tree($asf);
43 my $actual_output = array_display($output_as_array);
44
45 =for Marpa::R2::Display::End
46
47 The code for C<asf_to_basic_tree()> represents a user-supplied call
48 using the interface described below. An full example of C<asf_to_basic_tree()>,
49 which constructs a Perl array "tree",
50 is given
51 L<below|/"The asf_to_basic_tree() code">.
52 C<array_display()> displays the tree in a compact form.
53 The code for it is also given L<below|/"The array_display() code">.
54 The return value of C<array_display()> is as follows:
55
56 =for Marpa::R2::Display
57 name: ASF low-level calls synopsis, output
58 remove-display-indent: 1
59 remove-blank-last-line: 1
60
61 Glade 2 has 2 symches
62 Glade 2, Symch 0, pair ::= duple
63 Glade 6, duple ::= item item
64 Glade 8 has 2 symches
65 Glade 8, Symch 0, item ::= Hesperus
66 Glade 13, Hesperus ::= 'a'
67 Glade 15, Symbol 'a': "a"
68 Glade 8, Symch 1, item ::= Phosphorus
69 Glade 1, Phosphorus ::= 'a'
70 Glade 17, Symbol 'a': "a"
71 Glade 7 has 2 symches
72 Glade 7, Symch 0, item ::= Hesperus
73 Glade 22, Hesperus ::= 'a'
74 Glade 24, Symbol 'a': "a"
75 Glade 7, Symch 1, item ::= Phosphorus
76 Glade 9, Phosphorus ::= 'a'
77 Glade 26, Symbol 'a': "a"
78 Glade 2, Symch 1, pair ::= item item
79 Glade 8 revisited
80 Glade 7 revisited
81
82 =for Marpa::R2::Display::End
83
84 =head1 About this document
85
86 This document describes the low-level interface to Marpa's abstract syntax forests (ASF's).
87 It assumes that you are already familiar with L<the high-level interface|Marpa::R2::ASF>.
88 This low-level interface allows the maximum flexiblity in building the forest,
89 but requires the application to do much of the work.
90
91 =head1 Ambiguity: factoring versus symches
92
93 An abstract syntax forest (ASF) is similar to an abstract syntax tree (AST), but it
94 has an additional ability -- it can represent an ambiguous parse.
95 Ambiguity in a parse can come in two forms, and Marpa's ASF's treat the
96 distinction as important. An ambiguity can be a symbolic choice
97 (a symch), or a factoring. Symbolic choices are the kind of ambiguity
98 that springs first to mind -- a choice between rules, or a choice
99 between a rule and token. Factorings involve only one rule,
100 but the RHS symbols of that rule divide the input up ("factor it") in different ways.
101 I'll give examples below.
102
103 Symches and factorings are treated separately,
104 because they behave very differently:
105
106 =over 4
107
108 =item * Symches are less common than factorings.
109
110 =item * Factorings are frequently not of interest; symches are almost
111 always of major interest.
112
113 =item * Symches usually have just a few alternatives; the
114 possible number of factorings easily grows into the thousands.
115
116 =item * In the worst case, the number of symches is a constant
117 that depends on size of the grammar.
118 In the worst case,
119 the number of factorings
120 grows exponentially with the length of the string being factored.
121
122 =item * The constant limiting the number of symches will
123 almost always be of manageable size.
124 The number of factorings can grow without limit.
125
126 =back
127
128 =head2 An example of a symch
129
130 Hesperus is Venus's traditional name as an evening star,
131 and Phosphorus (aka Lucifer) is its traditional name as a morning star.
132 For the grammar,
133
134 =for Marpa::R2::Display
135 name: ASF symch dump example grammar
136 remove-display-indent: 1
137 remove-blank-last-line: 1
138
139 :start ::= planet
140 planet ::= hesperus
141 planet ::= phosphorus
142 hesperus ::= venus
143 phosphorus ::= venus
144 venus ~ 'venus'
145
146 =for Marpa::R2::Display::End
147
148 and the input string 'C<venus>', the forest would look like
149
150 =for Marpa::R2::Display
151 name: ASF symch dump example output
152 remove-blank-last-line: 1
153 remove-display-indent: 1
154
155 Symbol #0 planet has 2 symches
156 Symch #0.0
157 GL2 Rule 0: planet ::= hesperus
158 GL3 Rule 2: hesperus ::= venus
159 GL4 Symbol venus: "venus"
160 Symch #0.1
161 GL2 Rule 1: planet ::= phosphorus
162 GL5 Rule 3: phosphorus ::= venus
163 GL6 Symbol venus: "venus"
164
165 =for Marpa::R2::Display::End
166
167 Notice the tags of the form "C<GLn>", where I<n> is an integer.
168 These identify the glade.
169 Glades will be described in detail below.
170
171 The rules allow the string 'C<venus>' to be parsed
172 as either one of two planets: 'C<hesperus>'
173 or 'C<phosphorus>',
174 depending on whether rule 0 or rule 1 is used.
175 The choice, at glade 2, between rules 0 and 1,
176 is a symch.
177
178 =head2 An example of a factoring
179
180 For the grammar,
181
182 =for Marpa::R2::Display
183 name: ASF factoring dump example grammar
184 normalize-whitespace: 1
185 partial: 1
186
187 :start ::= top
188 top ::= b b
189 b ::= a a
190 b ::= a
191 a ~ 'a'
192
193 =for Marpa::R2::Display::End
194
195 and the input 'C<aaa>',
196 a successful parse will always have two C<b>'s.
197 Of these two C<b>'s one will always be short, deriving
198 a string of length 1:
199 'C<a>'.
200 The other will always be long, deriving a string of length 2:
201 'C<aa>'.
202 But they can be in either order,
203 which means that the two C<b>'s can divide up the input stream in
204 two different ways: long string first; or short string first.
205
206 These two different ways of dividing the input stream using the rule
207
208 =for Marpa::R2::Display
209 name: ASF factoring dump example grammar
210 normalize-whitespace: 1
211 partial: 1
212
213 top ::= b b
214
215 =for Marpa::R2::Display::End
216
217 are called a B<factoring>. Here's Marpa's dump of the forest:
218
219 =for Marpa::R2::Display
220 name: ASF factoring dump example output
221 remove-blank-last-line: 1
222 remove-display-indent: 1
223
224 GL2 Rule 0: top ::= b b
225 Factoring #0
226 GL3 Rule 2: b ::= a
227 GL4 Symbol a: "a"
228 GL5 Rule 1: b ::= a a
229 GL6 Symbol a: "a"
230 GL7 Symbol a: "a"
231 Factoring #1
232 GL8 Rule 1: b ::= a a
233 GL9 Symbol a: "a"
234 GL10 Symbol a: "a"
235 GL11 Rule 2: b ::= a
236 GL12 Symbol a: "a"
237
238 =for Marpa::R2::Display::End
239
240 =head1 The structure of a forest
241
242 The terminology I use for ASF's pictures
243 an ASF as a forest on a mountain.
244 This mountain forest has glades,
245 and there are paths between the glades.
246 The term "glade" comes from the idea of a glade as a distinct place in a forest that is
247 open to light.
248
249 The paths between glades have a direction -- they are always thought of
250 as running one-way: downhill.
251 If a path connects two glades, the one uphill is called an upglade and the
252 one downhill is called a downglade.
253
254 There is a glade at the top of mountain called the "peak".
255 The peak has no upglades.
256
257 =head1 The glade hierarchy
258
259 The glade hierarchy is directed graph whose nodes are glades.
260 Internally,
261 glade nodes have an 3-level internal structure
262 made up of
263
264 =over 4
265
266 =item * one or more symches, which contain
267
268 =item * zero or more factorings, which contain
269
270 =item * one or more downglades.
271
272 =back
273
274 When discussing symches
275 and factorings inside the internal structure of a glade I<G>,
276 I<G> will be called the B<containing glade>.
277
278 If I<G> is a glade,
279 the downglades in the internal structure will be
280 the child nodes of I<G> in the directed graph of
281 glades.
282 There may not be any downglades, in which
283 case I<G> will be a terminal in
284 the directed graph of glades.
285
286 =head2 Glades
287
288 Each glade node represents an instance of a symbol in one of the possible parse trees.
289 This means that each glade has a symbol (called the "glade symbol"),
290 and an "input span".
291 An input span is an input start location, and a length in characters.
292 Because it has a start location and a length,
293 a span also specifies an end location in the input.
294
295 =head2 Symches
296
297 Every glade contains one or more symches.
298 If a glade has only one symch, that symch is said to be B<unique>.
299 A symch is either a B<token symch>
300 or a B<rule symch>.
301 For a token symch, the glade symbol is the token symbol.
302 For a rule symch, the glade symbol is the LHS of the rule.
303
304 =head2 Token symches
305
306 At most one of the symches in a glade can be a token symch.
307 Token symches have no children.
308 In the internal structure of a glade, they are terminals.
309 If a glade has a unique symch,
310 and that symch is a token symch,
311 that glade will be a terminal in the glade hierarchy.
312
313 =head2 Rule symches
314
315 There can be many rule symches in a glade --
316 one for every rule with the glade symbol on its LHS.
317 As the name suggests, every rule symch has a rule
318 associated with it.
319 In every rule symch,
320 the LHS of its rule will always be the same
321 as the glade symbol
322 of the glade that contains the rule symch.
323
324 =head2 Factorings
325
326 Every rule symch has one or more B<factorings>,
327 or B<factors>, as children.
328 A rule symch is said to B<contain>
329 its child factorings.
330 Each factoring is the RHS of the parent symch's
331 rule, mapped to a unique set of G1 locations.
332 The term "factoring" is traditional in the literature
333 and is meant to suggest that
334 a factoring is a way of
335 "dividing up" the input span
336 of the containing glade among its RHS symbols.
337
338 If a rule symch has only one factoring, that factoring is said to be B<unique>.
339 Because the number of factorings can get out of hand,
340 factorings may be omitted.
341 A symch which omits factorings is said to be B<truncated>.
342 By default, every symch is truncated down to its first 42 factorings.
343
344 =head2 Downglades
345
346 Every factoring has one or more downglades as children.
347 The number of downglades will be I<L>,
348 where I<L> is the length of the RHS
349 of the parent symch's rule.
350 (The parent symch will always be a rule symch.)
351 Each of I<L> RHS symbols will be located at
352 a specific G1 span,
353 and will therefore be a B<symbol instance>.
354 This symbol instance will be the symbol instance
355 of a glade,
356 and that glade will be the downglade.
357
358 Within a glade,
359 symches, factorings and downglades
360 are tracked using zero-based indexes.
361 Since the internal structure of a glade has
362 a 3-level structure,
363 within a given containing glade I<G>,
364 any downglade can be uniquely
365 identified as C<($symch_ix, $factor_ix, $downglade_ix)>,
366 where
367 C<$symch_ix> is a zero-based symch index,
368 C<$factor_ix> is a zero-based factoring index, and
369 C<$downglade_ix> is a zero-based downglade index.
370
371 =head1 The glade ID
372
373 Each glade has a glade ID.
374 This can be relied on to be a non-negative integer.
375 A glade ID may be zero.
376 Glade ID's are obtained from the L</"peak()">
377 and L</"factoring_downglades()"> methods.
378
379 =head1 Techniques for traversing ASF's
380
381 =head2 Memoization
382
383 When traversing a forest, you should take steps to avoid
384 traversing the same glades twice.
385 You can do this by memoizing the result of each glade, perhaps
386 using its glade ID to index an array.
387 When a glade is visited, the array can be checked to see if its result has
388 been memoized.
389 If so, the memoized result should be used.
390
391 This memoization eliminates the need to revisit the downglades
392 of an already visited glade.
393 It does not eliminate multiple visits to a glade, but it does
394 eliminate retraversal of the glades downhill from it.
395 In practice, the improvement in speed can be stunning.
396 It will often be the difference between
397 an program which is unuseably slow even for very small inputs,
398 and one which is extremely fast even for large inputs.
399
400 Repeated subtraversals happen when two glades share the same downglades,
401 something that occurs frequently in ASF's.
402 Additionally, some day the SLIF may allow cycles.
403 Memoization will prevent a cycle from causing an infinite loop.
404
405 The example in this POD includes a memoization scheme which is very simple,
406 but adequate for most purposes.
407 The main logic of its memoization is shown here.
408
409 =for Marpa::R2::Display
410 name: ASF low-level calls synopsis, code part 2
411 normalize-whitespace: 1
412 partial: 1
413
414 my ( $asf, $glade, $seen ) = @_;
415 return bless ["Glade $glade revisited"], 'My_Revisit'
416 if $seen->[$glade];
417 $seen->[$glade] = 1;
418
419 =for Marpa::R2::Display::End
420
421 Putting memoization in one of the very first drafts
422 of your code
423 will save you time and trouble.
424
425 =head1 Forest method
426
427 =head2 peak()
428
429 =for Marpa::R2::Display
430 name: ASF low-level calls synopsis, code part 2
431 normalize-whitespace: 1
432 partial: 1
433
434 my $peak = $asf->peak();
435
436 =for Marpa::R2::Display::End
437
438 Returns the glade ID of the peak.
439 This may be zero.
440 All failures are thrown as exceptions.
441
442 =head1 Glade methods
443
444 =head2 glade_literal()
445
446 =for Marpa::R2::Display
447 name: ASF low-level calls synopsis, code part 2
448 normalize-whitespace: 1
449 partial: 1
450
451 my $literal = $asf->glade_literal($glade);
452
453 =for Marpa::R2::Display::End
454
455 Returns the literal substring of the input associated
456 with the glade.
457 Every glade is associated with a span -- a start location in the input,
458 and a length.
459 On failure, throws an exception.
460
461 The literal is determined by the range.
462 This works as expected if your application reads the input characters
463 one-by-one, in order
464 and without gaps except for characters
465 that are normally discarded,
466 such as whitespace.
467 (We will call applications which read in this fashion, B<monotonic>.)
468 Most applications are monotonic,
469 and yours is, unless you've taken special pains to make it otherwise.
470 Computation of literal substrings for non-monotonic applications
471 is addressed in L<Marpa::R2::Scanless::R/"Literals and G1 spans">.
472
473 =head2 glade_span()
474
475 =for Marpa::R2::Display
476 name: glade_span() example
477 normalize-whitespace: 1
478
479 my ( $glade_start, $glade_length ) = $asf->glade_span($glade_id);
480
481 =for Marpa::R2::Display::End
482
483 Returns the span of the input associated
484 with the glade.
485 Every glade is associated with a span -- a start location in the input,
486 and a length.
487 On failure, throws an exception.
488
489 The span will be as expected if your application reads the input characters
490 one-by-one in order.
491 (We will call applications which read in this fashion, B<monotonic>.)
492 Most applications are monotonic,
493 and yours is, unless you've taken special pains to make it otherwise.
494 Computation of literal substrings for non-monotonic applications
495 is addressed in L<Marpa::R2::Scanless::R/"Literals and G1 spans">.
496
497 =head2 glade_symch_count()
498
499 =for Marpa::R2::Display
500 name: ASF low-level calls synopsis, code part 2
501 normalize-whitespace: 1
502 partial: 1
503
504 my $symch_count = $asf->glade_symch_count($glade);
505
506 =for Marpa::R2::Display::End
507
508 Requires a glade ID as its only argument.
509 Returns the number of symches contained in the glade specified by the argument.
510 On failure, throws an exception.
511
512 =head2 glade_symbol_id()
513
514 =for Marpa::R2::Display
515 name: ASF low-level calls synopsis, code part 2
516 normalize-whitespace: 1
517 partial: 1
518
519 my $symbol_id = $asf->glade_symbol_id($glade);
520 my $display_form = $grammar->symbol_display_form($symbol_id);
521
522 =for Marpa::R2::Display::End
523
524 Requires a glade ID as its only argument.
525 Returns the symbol ID of the "glade symbol" for the glade specified by the argument.
526 On failure, throws an exception.
527
528 =head1 Symch methods
529
530 =head2 symch_rule_id()
531
532 =for Marpa::R2::Display
533 name: ASF low-level calls synopsis, code part 2
534 normalize-whitespace: 1
535 partial: 1
536
537 my $rule_id = $asf->symch_rule_id( $glade, $symch_ix );
538
539 =for Marpa::R2::Display::End
540
541 Requires two arguments: a glade ID and a zero-based symch index.
542 These specify a symch.
543 If the symch specified is a rule symch, returns the rule ID.
544 If it is a token symch, returns -1.
545
546 Returns a Perl undef, if the glade exists, but the symch index is too high.
547 On other failure, throws an exception.
548
549 =head2 symch_is_truncated()
550
551 [ To be written. ]
552
553 =head2 symch_factoring_count()
554
555 =for Marpa::R2::Display
556 name: ASF low-level calls synopsis, code part 2
557 normalize-whitespace: 1
558 partial: 1
559
560 my $factoring_count =
561 $asf->symch_factoring_count( $glade, $symch_ix );
562
563 =for Marpa::R2::Display::End
564
565 Requires two arguments: a glade ID and a zero-based symch index.
566 These specify a symch.
567 Returns the count of factorings if the specified symch is a rule symch.
568 This count will always be one or greater.
569 Returns zero if the specified symch is a token symch.
570
571 Returns a Perl undef, if the glade exists, but the symch index is too high.
572 On other failure, throws an exception.
573
574 =head1 Factoring methods
575
576 =head2 factoring_downglades()
577
578 =for Marpa::R2::Display
579 name: ASF low-level calls synopsis, code part 2
580 normalize-whitespace: 1
581 partial: 1
582
583 my $downglades =
584 $asf->factoring_downglades( $glade, $symch_ix,
585 $factor_ix );
586
587 =for Marpa::R2::Display::End
588
589 Requires three arguments: a glade ID,
590 the zero-based index of a symch
591 and the zero-based index of a factoring.
592 These specify a factoring.
593 On success, returns a reference to an array.
594 The array contains the glade IDs of
595 the downglades in
596 the factoring specified.
597
598 Returns a Perl undef, if the glade and symch exist, but the factoring index is too high.
599 On other failure, throws an exception.
600 In particular, exceptions are thrown if the symch is for a token;
601 and if the glade exists, but the symch index is too high.
602
603 =head1 Methods for reporting ambiguity
604
605 =for Marpa::R2::Display
606 name: ASF ambiguity reporting
607 normalize-whitespace: 1
608 partial: 1
609
610 if ( $recce->ambiguity_metric() > 1 ) {
611 my $asf = Marpa::R2::ASF->new( { slr => $recce } );
612 die 'No ASF' if not defined $asf;
613 my $ambiguities = Marpa::R2::Internal::ASF::ambiguities($asf);
614
615 # Only report the first two
616 my @ambiguities = grep {defined} @{$ambiguities}[ 0 .. 1 ];
617
618 $actual_value = 'Application grammar is ambiguous';
619 $actual_result =
620 Marpa::R2::Internal::ASF::ambiguities_show( $asf, \@ambiguities );
621 last PROCESSING;
622 } ## end if ( $recce->ambiguity_metric() > 1 )
623
624 =for Marpa::R2::Display::End
625
626 =head2 ambiguities()
627
628 =for Marpa::R2::Display
629 name: ASF ambiguity reporting
630 normalize-whitespace: 1
631 partial: 1
632
633 my $ambiguities = Marpa::R2::Internal::ASF::ambiguities($asf);
634
635 =for Marpa::R2::Display::End
636
637 Returns a reference to an array of ambiguity reports in the ASF.
638 The first and only argument must be an ASF object.
639 The array returned will be be zero length if the parse was not ambiguous.
640 Ambiguity reports are as L<described below|"Ambiguity reports">.
641
642 While the C<ambiguities()> method can be called to determine whether
643 or not ambiguities exist, it is the more expensive way to do it.
644 The L<$slr-E<gt>ambiguity_metric() method|Marpa::R2::Scanless::R/"ambiguity_metric()">
645 tests an already-existing boolean and is therefore extremely fast.
646 If you are simply testing for ambiguity,
647 use the C<ambiguity_metric()> method instead.
648 If you can save time when you know that a parse is unambiguous,
649 you may want to test for ambiguity with the C<ambiguity_metric()> method
650 before calling the C<ambiguities()> method.
651
652 =head2 ambiguities_show()
653
654 =for Marpa::R2::Display
655 name: ASF ambiguity reporting
656 normalize-whitespace: 1
657 partial: 1
658
659 $actual_result =
660 Marpa::R2::Internal::ASF::ambiguities_show( $asf, \@ambiguities );
661
662 =for Marpa::R2::Display::End
663
664 Returns a string which contains a description of the ambiguities in its arguments.
665 Takes two arguments, both required.
666 The first is an ASF, and the second is a reference to an array of ambiguities,
667 in the format returned by L<the ambiguities() method|/"ambiguities()">.
668
669 Major applications will often have their own
670 customized ambiguity formatting routine, one which can formulate
671 error messages based, not just on the names of the rules and symbols,
672 but on knowledge of the role that
673 the rules and symbols play in
674 the application.
675 This method is intended for applications which do not have
676 their own customized ambiguity handling.
677 For those which do, it can be used
678 as a fallback for handling those reports that the customized method does not recognize
679 or that do not need special handling.
680 The format of the returned string
681 and is subject to change,
682 and is intended for reading by humans only.
683
684 =head1 Ambiguity reports
685
686 The ambiguity reports returned by the L<C<ambiguities()> method|/"ambiguities()">
687 are of two kinds: symch reports and factoring reports.
688 Only ambiguities uppermost on a path are reported --
689 in other words, an ambiguity
690 is not reported if it is downhill
691 and does not have a higher altitude.
692 (Because of cycles,
693 it is possible for a downhill glade to be at a higher altitude.)
694 Within glade, all of the factorings are
695 considered downhill from,
696 and of equal altitude to the symches,
697 so that if a glade has a symch ambiguity,
698 there will be no factoring ambiguity reports for that glade.
699
700 Typically, when there is more than one kind of ambiguity in an input span, only
701 one is of real interest,
702 and
703 symch ambiguities are usually of more interest than factorings.
704 And if one ambiguity is uphill from another, the downhill ambiguity is usually
705 a side effect of the uphill one and
706 of little interest.
707
708 =head2 Symch reports
709
710 A symch report is issued whenever, in a top-down traversal of the ASF,
711 a glade is encountered which has more than one symch.
712 A symch report takes the form
713
714 =for Marpa::R2::Display
715 ignore: 1
716
717 [ 'symch', $glade ]
718
719 =for Marpa::R2::Display::End
720
721 where C<$glade> is the ID of the glade with the symch ambiguity.
722 With this and the accessor methods in this document, an application can report full
723 details of the symch ambiguity.
724
725 =head2 Factoring reports
726
727 A factoring report identifies
728 a sequence of RHS symbols which has more than one factoring.
729 Factoring reports identify not just a rule,
730 but specific subsequences within the RHS
731 which are multiply factored -- B<multifactored stretches>.
732 Marpa goes down to the symbol level, because a Marpa RHS can be very long.
733 Marpa's sequence rules, especially,
734 can have long stretches where the symbols are in sync
735 with each other, broken by other stretches where they are out of sync.
736 (A detailed definition of multifactored stretches is L<below|/"Multifactored stretches">.)
737
738 A factoring report takes the form
739
740 =for Marpa::R2::Display
741 ignore: 1
742
743 [ 'factoring', $glade, $symch_ix, $rhs_ix1, $factor_ix2, $rhs_ix2 ];
744
745 =for Marpa::R2::Display::End
746
747 where C<$glade> is the ID of the glade with the factoring ambiguity,
748 and C<$symch_ix> is the index of the symch involved.
749 The multifactored stretch is described by
750 two "identifying downglades".
751 Both downglades are at the beginning of the stretch,
752 and both will have the same input start location.
753 The identifying downglades will differ in length.
754
755 The first of the two identifying factors has a factoring index of 0,
756 and its downglade index is C<$rhs_ix1>.
757 The second identifying factor has a factoring index of C<$factor_ix2>,
758 and its downglade index is C<$rhs_ix2>.
759
760 The identifying downglades will usually be enough
761 for error reporting, which is the usual application of these reports.
762 A multifactored stretch can be extremely large.
763 Full details of it
764 can be found by following up on the information in the factoring report
765 using the accessor methods described in this document.
766
767 =head1 The code for the synopsis
768
769 =head2 The asf_to_basic_tree() code
770
771 =for Marpa::R2::Display
772 name: ASF low-level calls synopsis, code part 2
773 normalize-whitespace: 1
774
775 sub asf_to_basic_tree {
776 my ( $asf, $glade ) = @_;
777 my $peak = $asf->peak();
778 return glade_to_basic_tree( $asf, $peak, [] );
779 } ## end sub asf_to_basic_tree
780
781 sub glade_to_basic_tree {
782 my ( $asf, $glade, $seen ) = @_;
783 return bless ["Glade $glade revisited"], 'My_Revisit'
784 if $seen->[$glade];
785 $seen->[$glade] = 1;
786 my $grammar = $asf->grammar();
787 my @symches = ();
788 my $symch_count = $asf->glade_symch_count($glade);
789 SYMCH: for ( my $symch_ix = 0; $symch_ix < $symch_count; $symch_ix++ ) {
790 my $rule_id = $asf->symch_rule_id( $glade, $symch_ix );
791 if ( $rule_id < 0 ) {
792 my $literal = $asf->glade_literal($glade);
793 my $symbol_id = $asf->glade_symbol_id($glade);
794 my $display_form = $grammar->symbol_display_form($symbol_id);
795 push @symches,
796 bless [qq{Glade $glade, Symbol $display_form: "$literal"}],
797 'My_Token';
798 next SYMCH;
799 } ## end if ( $rule_id < 0 )
800
801 # ignore any truncation of the factorings
802 my $factoring_count =
803 $asf->symch_factoring_count( $glade, $symch_ix );
804 my @symch_description = ("Glade $glade");
805 push @symch_description, "Symch $symch_ix" if $symch_count > 1;
806 push @symch_description, $grammar->rule_show($rule_id);
807 my $symch_description = join q{, }, @symch_description;
808
809 my @factorings = ($symch_description);
810 for (
811 my $factor_ix = 0;
812 $factor_ix < $factoring_count;
813 $factor_ix++
814 )
815 {
816 my $downglades =
817 $asf->factoring_downglades( $glade, $symch_ix,
818 $factor_ix );
819 push @factorings,
820 bless [ map { glade_to_basic_tree( $asf, $_, $seen ) }
821 @{$downglades} ], 'My_Rule';
822 } ## end for ( my $factor_ix = 0; $factor_ix < $factoring_count...)
823 if ( $factoring_count > 1 ) {
824 push @symches,
825 bless [
826 "Glade $glade, symch $symch_ix has $factoring_count factorings",
827 @factorings
828 ],
829 'My_Factorings';
830 next SYMCH;
831 } ## end if ( $factoring_count > 1 )
832 push @symches, bless [ @factorings[ 0, 1 ] ], 'My_Factorings';
833 } ## end SYMCH: for ( my $symch_ix = 0; $symch_ix < $symch_count; ...)
834 return bless [ "Glade $glade has $symch_count symches", @symches ],
835 'My_Symches'
836 if $symch_count > 1;
837 return $symches[0];
838 } ## end sub glade_to_basic_tree
839
840 =for Marpa::R2::Display::End
841
842 =head2 The array_display() code
843
844 Because of the blessings in this example,
845 a standard dump of the output array is
846 too cluttered for comfortable reading.
847 The following code displays the output from
848 C<asf_to_basic_tree()> in a more compact form.
849 Note that this code makes no use of Marpa,
850 and works for all Perl arrays.
851 It is included for completeness,
852 and as a simple example of array traversal.
853
854 =for Marpa::R2::Display
855 name: ASF low-level calls synopsis, code part 3
856 normalize-whitespace: 1
857
858 sub array_display {
859 my ($array) = @_;
860 my ( undef, @lines ) = @{ array_lines_display($array) };
861 my $text = q{};
862 for my $line (@lines) {
863 my ( $indent, $body ) = @{$line};
864 $indent -= 6;
865 $text .= ( q{ } x $indent ) . $body . "\n";
866 }
867 return $text;
868 } ## end sub array_display
869
870 sub array_lines_display {
871 my ($array) = @_;
872 my $reftype = Scalar::Util::reftype($array) // '!undef!';
873 return [ [ 0, $array ] ] if $reftype ne 'ARRAY';
874 my @lines = ();
875 ELEMENT: for my $element ( @{$array} ) {
876 for my $line ( @{ array_lines_display($element) } ) {
877 my ( $indent, $body ) = @{$line};
878 push @lines, [ $indent + 2, $body ];
879 }
880 } ## end ELEMENT: for my $element ( @{$array} )
881 return \@lines;
882 } ## end sub array_lines_display
883
884 =for Marpa::R2::Display::End
885
886 =head1 Details
887
888 This section contains details not essential to understanding
889 the main topic of this document.
890 These details include restatements of what is said above
891 in more formal terms,
892 and formal statements of concepts that have been left to
893 the intuition.
894 Some readers find these details helpful,
895 while others find them distracting.
896 Segregating these details here serves the needs of both.
897
898 =head2 An alternative way of defining glade terminology
899
900 Here's a way of defining some of the above terms which is less intuitive,
901 but more precise.
902 First, define the B<glade length> from glades A to glade B in an ASF as
903 the number of glades on the shortest path from A to B, not including glade A.
904 (Recall that paths are directional.)
905 If there is no path between glades A and B, the glade length is undefined.
906 Glade B is a B<downglade> of glade A,
907 and glade A is an B<upglade> of glade B,
908 if and only if the glade length from A to B is 1.
909
910 A glade A is B<uphill> with respect to glade B,
911 and a glade B is B<downhill> with respect to glade A,
912 if and only if the glade length from A to B is defined.
913
914 A B<peak> of an ASF is a node without upglades.
915 By construction of the ASF, there is only one peak.
916 The B<distance-to-peak> of a glade C<A> is the glade length from the peak to glade C<A>.
917 Glade C<A> is said to have a higher B<altitude> than glade C<B> if the distance-to-peak of glade C<A>
918 is less than that of glade C<B>.
919 Glade C<A> has a lower B<altitude> than glade C<B> if the distance-to-peak of glade C<A>
920 is greater than that of glade C<B>.
921 Glade C<A> has the same B<altitude> as glade C<B> if the distance-to-peak of glade C<A>
922 is equal to that of glade C<B>.
923
924 =head2 Cycles
925
926 In the current SLIF implementation, a forest is a directed acyclic graph (DAG).
927 (In the mathematical literature a DAG is also called a "tree", but that use is confusing
928 in the present context.)
929 The underlying Marpa algorithm allows parse trees with cycles,
930 and someday the SLIF probably will as well.
931 When that happens, ASF's will no longer be "acyclic" and therefore will be directed graphs
932 (DG's) but not DAG's.
933 This document talks about ASF's as if that day had already come --
934 it assumes that the ASF's might
935 contain cycles.
936
937 In an ASF that contains one or more cycles,
938 the concepts of uphill and downhill become much less useful
939 for describing the relative positions of glades.
940 For example, if glade A cycles back to itself through glade B, then
941
942 =over 4
943
944 =item * Glade A will be uphill from glade B, and
945
946 =item * Glade B will be uphill from glade A; so that
947
948 =item * Glade B will be downhill from glade A, and
949
950 =item * Glade A will be downhill from glade B; and
951
952 =item * Glade A will be both downhill and uphill from itself; and
953
954 =item * Glade B will be both downhill and uphill from itself.
955
956 =back
957
958 ASF's will always be constructed so that the peak has no upglades.
959 Because of this, the peak can never be part of a cycle.
960 This means that altitude will always be well defined in the sense that,
961 for any two glades C<A> and C<B>, one and only one of the following statements will be true:
962
963 =over 4
964
965 =item * Glade C<A> is lower in altitude than glade C<B>.
966
967 =item * Glade C<A> is higher in altitude than glade C<B>.
968
969 =item * Glade C<A> is equal in altitude to glade C<b>.
970
971 =back
972
973 =head2 Token symches
974
975 In the current SLIF implementation, a symbol is always either a token
976 or the LHS of a rule.
977 This means that any glade that contains a token symch
978 cannot contain any rule symches.
979 It also means that any glade that contains a rule symch will not
980 contain a token symch.
981
982 However, the underlying Marpa algorithm allows LHS terminals,
983 and someday the SLIF probably will as well.
984 This document is written as if that day has already come,
985 and describes
986 glades as if they could contain both rule symches and a token symch.
987
988 =head2 Maximum symches per glade
989
990 Above, the point is made that the number of symches in a glade,
991 even in the worst case, is a very manageable number.
992 For a particular case, it is not hard to work out the exact maximum.
993 Here are the details.
994
995 There can be at most one token symch.
996 There can be only rule symch for every rule.
997 In addition, all rules in a glade must have the glade symbol as their LHS.
998 Let the number of rules with the glade symbol on their LHS be C<r>.
999 The maximum number of symches in a glade is C<r+1>.
1000
1001 =head2 Multifactored stretches
1002
1003 Marpa locates factoring ambiguities, not just by rule,
1004 but by subsequences of symbols within a RHS.
1005 It finds B<multifactored stretches>, input spans where the sequence of symbols
1006 can have multiple factorings.
1007 Sequence rules can have a very long RHS.
1008 If ambiguity reporting is to be precise,
1009 it is necessary
1010 to narrow down factoring ambiguities to the specific input spans
1011 where they occur.
1012
1013 Marpa tries to break up each ambiguously factored RHS
1014 into as many multifactored stretches
1015 as possible.
1016 Nonetheless,
1017 there will be cases in which
1018 a multifactored stretch encompasses the entire RHS of a rule.
1019
1020 The main body of this document worked with an intuitive "know one when I see one"
1021 idea of multifactored stretches.
1022 In this section we will give an exact definition.
1023 First, we will need some preliminary definitions.
1024
1025 Consider the case of a arbitrary, ambiguous rule symch.
1026 The ambiguous rule symch can be seen as a set of factorings.
1027 We need a way to identify individual downglades within
1028 each factoring of the set.
1029 Within a factoring,
1030 there is a one-to-one correspondence between
1031 downglade and locations in the string of symbols that
1032 is the RHS.
1033 Therefore downglades can be identified uniquely as
1034 C<glade_id, symch_ix, factor_ix, rhs_ix>,
1035 where C<glade_id> is a unique identifier of the glade,
1036 C<symch_ix> is a zero-based symch index,
1037 C<factor_ix> is a zero-based factoring index, and
1038 C<rhs_ix> is a zero-based index identifying a
1039 symbol location in the RHS string.
1040
1041 In much of what follows,
1042 we will assume we are talking about a specific
1043 glade and rule symch, which is understood in context,
1044 so that we can take
1045 C<factor_ix, rhs_ix> as uniquely identifying a downglade.
1046 We will call
1047 C<factor_ix, rhs_ix> a downglade duple.
1048
1049 Let I<N> be the number of factorings in the rule symch of interest.
1050 Since we are dealing with a specific rule symch, we also
1051 have a specific rule that is of interest.
1052 Call the length of the RHS of that rule, C<rhs_length>.
1053 For every C<factor_ix>, the values of C<rhs_ix>
1054 will be in the range C<0 ... rhs_length-1>.
1055
1056 Each downglade C<factor_ix, rhs_ix>
1057 corresponds one-to-one to a G1 span.
1058 This means that
1059 there is a total function
1060 C<G1_start(factor_ix, rhs_ix)> from a downglade
1061 to a G1 start location;
1062 and that there is a total function
1063 C<G1_length(factor_ix, rhs_ix)>
1064 from a downglade
1065 to a G1 length.
1066
1067 A B<symch location set>
1068 is a set of I<N> downglade duples
1069 such there is exactly one element
1070 C<factor_ix, rhs_ix>
1071 in the set for each
1072 C<< 0 <= factor_ix < N >>.
1073 In other words, a symch location set is
1074 a total function from the factor indexes
1075 to the RHS indexes.
1076
1077 A B<symch alignment> is a symch location set
1078 whose elements shares a common G1 start location.
1079 A symch alignment is synced if its elements share a common G1 length as well.
1080 A symch alignment is unsynced if it is not synced.
1081
1082 More formally, if we represent the symch location set
1083 function as C<SLS>,
1084 C<SLS> is a symch alignment if and only if
1085 there is some constant G1 location I<pos> such
1086 that, for all C<factor_ix>
1087 such that C<< 0 <= factor_ix < N >>,
1088 C<G1_start(factor_ix, SLS(factor_ix)) = pos>.
1089 We say the C<pos> is the location of the symch alignment.
1090 C<SLS> is a synced symch alignment if and only if
1091 it is a symch aligment and
1092 there is some constant number I<L> such
1093 C<G1_length(factor_ix, SLS(factor_ix)) = L>.
1094
1095 Of special interest is the B<initial symch location set>.
1096 The initial symch location set is the symch position all of whose RHS indexes
1097 are 0.
1098 Equivalently, it is the constant function C<ISLS>
1099 where C<ISLS(factor_ix)=0> for all C<factor_ix>
1100 such that C<< 0 <= factor_ix < N >>.
1101 The initial symch location set is always a symch alignment,
1102 and is called the B<initial symch alignment>.
1103
1104 We are now in a position to define a B<multifactored stretch>
1105 for a specific rule symch.
1106 Call a G1 location an B<anchor> if it is the location
1107 of a synced symch alignment or,
1108 as a special case,
1109 if it is one past the last location of the G1 stream.
1110 We say that a G1 span is B<anchored> if its start
1111 and end G1 locations are anchors.
1112 A B<multifactored stretch> is an anchored G1 span
1113 which contains only one anchored G1 location.
1114 (Recall that, by the definition of a span,
1115 the end location of a span
1116 is not contained in the span.)
1117
1118 As a consequence of its definition,
1119 the start location of a multifactored stretch
1120 will always be an anchor,
1121 and the only anchored location in the multifactored
1122 stretch will be its start location.
1123 (Again, by definition,
1124 the end location of the stretch is not
1125 contained in the stretch.)
1126
1127 Multifactored stretches
1128 are aligned and anchored in terms of G1 locations,
1129 and B<not> in terms of input stream locations or RHS indexes.
1130 It may be useful, however, to look at syncing and alignment
1131 from other points of view.
1132 This is done in the next two sections.
1133
1134 =head3 Alignment and input stream locations
1135
1136 Because G1 spans map to input stream spans,
1137 symch location sets that are aligned or synced in
1138 G1 terms will be aligned or synced from
1139 the input stream point of view as well.
1140 But, if the input is not monotonic,
1141 the opposite is not necessarily the case.
1142 Because several G1 locations
1143 can share an input stream location, symch location sets that seem
1144 aligned or synced from the input stream point of view
1145 may not be considered aligned or synced from the G1 location
1146 point.
1147
1148 =head3 Alignment and RHS indexes
1149
1150 Symch location sets that are aligned
1151 from the G1 location point will typically not be
1152 aligned from the point of
1153 the RHS indexes.
1154 Non-aligned RHS indexes are particularly likely for
1155 long sequence rules,
1156 where the RHS is a long string containing
1157 many repetitions of a single symbol.
1158
1159 =head1 Copyright and License
1160
1161 =for Marpa::R2::Display
1162 ignore: 1
1163
1164 Copyright 2022 Jeffrey Kegler
1165 This file is part of Marpa::R2. Marpa::R2 is free software: you can
1166 redistribute it and/or modify it under the terms of the GNU Lesser
1167 General Public License as published by the Free Software Foundation,
1168 either version 3 of the License, or (at your option) any later version.
1169
1170 Marpa::R2 is distributed in the hope that it will be useful,
1171 but WITHOUT ANY WARRANTY; without even the implied warranty of
1172 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1173 Lesser General Public License for more details.
1174
1175 You should have received a copy of the GNU Lesser
1176 General Public License along with Marpa::R2. If not, see
1177 http://www.gnu.org/licenses/.
1178
1179 =for Marpa::R2::Display::End
1180
1181 =cut
1182
1183 # Local Variables:
1184 # mode: cperl
1185 # cperl-indent-level: 4
1186 # fill-column: 100
1187 # End:
1188 # vim: expandtab shiftwidth=4: