forked from rebolsource/r3
-
Notifications
You must be signed in to change notification settings - Fork 27
/
uparse.r
3189 lines (2801 loc) · 108 KB
/
uparse.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
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
370
371
372
373
374
375
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
415
416
417
418
419
420
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Rebol [
Title: "UPARSE: Usermode Implementation of Evolved PARSE Dialect"
License: "LGPL 3.0"
Type: module
Name: Usermode-PARSE
Exports: [
combinator
parse
default-combinators
parse-trace-hook
using ; TBD: will become new meaning of USE
]
Description: {
Rebol's PARSE is a tool for performing RegEx-style tasks using an
English-like dialect. It permits breaking down complex expressions
into named subrules, and has a very freeform model for escaping into
and back out of imperative code:
http://www.rebol.com/docs/core23/rebolcore-15.html
http://www.codeconscious.com/rebol/parse-tutorial.html
https://www.red-lang.org/2013/11/041-introducing-parse.html
The implementation of PARSE engines has traditionally been as
optimized systems-level code (e.g. C or Red/System), built into the
interpreter. This does not offer flexibility to make any minor or
major changes to the dialect that a user might imagine.
This script attempts to make PARSE more "hackable", by factoring the
implementation out so that each keyword or data behavior is handled
by an individual `parser` function. The parameters to this function
are stylized so that the parse engine can compose these smaller
parsers together as part of larger processing operations. This
approach is typically called "Parser Combinators":
https://en.wikipedia.org/wiki/Parser_combinator
While this overlaps with typical parser combinators, Rebol's design
affords it a unique spin. By building the backbone of the dialect as
a BLOCK!, there's no SEQUENCE or ALTERNATIVE combinators. Instead,
blocks make sequencing implicit just by steps being ordered after one
another. The alternates are managed by means of `|` markers, which
are detected by the implementation of the block combinator--and `|` is
not a combinator in its own right. With novel operators and convenient
ways of switching into imperative processing, it gets a unique and
literate feel with a relatively clean appearance.
By making the combinator list passed to UPARSE as a MAP!, is possible
to easily create overrides or variations of the dialect. (For
instance, a version that is compatible with older Rebols.) But the
goal is to facilitate even more ambitious features.
}
Notes: {
* This implementation will be *extremely* slow for the foreseeable
future. But since it is built on usermode facilities, any
optimizations that are applied to it will bring systemic benefits.
Ultimately the goal is to merge this architecture in with the
"messier" C code...hopefully preserving enough of the hackability
while leveraging low-level optimizations where possible.
}
]
; All combinators receive the INPUT to be processed. They are also given an
; object representing the STATE of the parse (currently that is just the
; FRAME! of the main UPARSE call which triggered the operation, so any of the
; locals or parameters to that can be accessed, e.g. the list of /COMBINATORS)
;
; The goal of a combinator is to decide whether to match (by returning a
; synthesized value and the updated position in the series) or fail to match
; (by returning an antiform error)
;
; Additional parameters to a combinator are fulfilled by the parse engine by
; looking at the ensuing rules in the rule block.
;
; One of the parameter types that can be given to these functions are another
; parser, to combine them (hence "parser combinator"). So you can take a
; combinator like TRY and parameterize it with SOME which is parameterized
; with "A", to get a composite parser that implements `try some "a"`.
;
; But if a parameter to a combinator is marked as quoted, then that will take
; a value from the callsite literally.
;
; A special COMBINATOR generator is used. This saves on repetition of
; parameters and also lets the engine get its hooks into the execution of
; parsers...for instance to diagnose the furthest point the parsing reached.
; !!! COMBINATOR is used so heavily that having it be usermode makes UPARSE
; prohibitively slow. So it was made native. However the usermode version is
; kept as a proof of concept that a user *could* have made such a thing. It
; should be swapped in occasionally in the tests to overwrite the native
; version just to keep tabs on it.
;
; We would like it to be possible to write an "easy" combinator that does not
; do piping of the pending elements, but takes it for granted as coming from
; the success or failure of each parser called in order. If you formally
; declare a return value for the `pending:` then that means you're going to
; manage it yourself, otherwise it will be automagic.
combinator: func [
{Make stylized code that fulfills the interface of a combinator}
return: [frame!]
spec [block!]
body [block!]
<static> wrapper (
func [
{Enclosing function for hooking all combinators}
return: [pack?]
f [frame!]
][
return either f.state.hook [
run f.state.hook f
][
do f
]
]
)
][
let autopipe: ~
let action: func compose [
; Get the text description if given
(if text? spec.1 [spec.1, elide spec: my next])
; Enforce a RETURN: definition. RETURN: [...] is allowed w/no text
(
assert [spec.1 = 'return:]
if block? spec.2 [ ; no description
spread reduce [spec.1 spec.2]
elide spec: my skip 2
] else [
assert [text? spec.2]
assert [block? spec.3]
spread reduce [spec.1 spec.2 spec.3]
elide spec: my skip 3
]
)
@remainder [any-series?] ; all combinators have remainder
(if spec.1 = '@pending [
assert [spec.2 = [~null~ block!]]
autopipe: false ; they're asking to handle pending themselves
spread reduce ['@pending spec.2]
elide spec: my skip 2
] else [
autopipe: true ; they didn't mention pending, handle automatically
spread [@pending [~null~ block!]]
])
state [frame!]
input [any-series?]
; Whatever arguments the combinator takes, if any
;
(spread spec)
] compose [
;
; !!! If we are "autopipe" then we need to make it so the parsers that
; we receive in will automatically bubble up their pending contents in
; order of being called.
(spread if autopipe '[
let f: binding of $return
pending: null
let in-args: false
for-each [key val] f [
if not in-args [
if key = 'input [in-args: true]
continue
]
all [
not unset? $val
action? :val
] then [
; All parsers passed as arguments, we want it to be
; rigged so that their results append to an aggregator in
; the order they are run (if they succeed).
;
f.(key): enclose (augment :val [/modded]) func [
f2
<local> result' remainder subpending
][
[^result' remainder subpending]: eval f2 except e -> [
return raise e
]
pending: glom pending maybe spread subpending
return pack [
unmeta result', remainder, subpending
]
]
]
]
])
; ** Currently parsers unify RETURN where a failure is done with
; a `return raise`. Should this instead be ACCEPT and REJECT, as
; local functions to the combinator, so that you can ACCEPT a failure
; from something like a GROUP! (and remove need for RAISE with the
; return?) Or RETURN ACCEPT and RETURN REJECT to make it clearer,
; where ACCEPT makes a pack and REJECT does RAISE?
do overbind binding of $return (body)
; If the body does not return and falls through here, the function
; will fail as it has a RETURN: that needs to be used to type check
; (and must always be used so all return paths get covered if hooked)
]
; Enclosing with the wrapper permits us to inject behavior before and
; after each combinator is executed.
;
return unrun enclose augment :action [
/rule-start [block!] /rule-end [block!]
] :wrapper ; returns plain ACTION!
]
; It should be possible to find out if something is a combinator in a more
; rigorous way than this. But just check the parameters for now.
;
combinator?: func [
{Crude test to try and determine if an ACTION! is a combinator}
return: [logic?]
frame [<unrun> frame!]
<local> keys
][
keys: words of frame ; test if it's a combinator
;
; could also check RETURNS OF for `pending` and `state`, but might exclude
; wrapped combinators which return packs directly.
;
return did all [
find keys 'input
find keys 'state
]
]
block-combinator: ~ ; need in variable for recursion implementing "..."
; !!! We use a MAP! here instead of an OBJECT! because if it were MAKE OBJECT!
; then the parse keywords would override the Rebol functions (so you couldn't
; use ANY during the implementation of a combinator, because there's a
; combinator named ANY). This is part of the general issues with binding that
; need to have answers.
;
default-combinators: make map! reduce [
=== BASIC KEYWORDS ===
'try combinator [
{If applying parser fails, succeed and return NULL; don't advance input}
return: "PARSER's result if it succeeds, otherwise NULL"
[any-value? pack?]
parser [action?]
<local> result'
][
fail "TRY combinator changed back to OPTIONAL (or abbreviate as OPT)"
]
'optional combinator [
{If applying parser fails, succeed and return NULL; don't advance input}
return: "PARSER's result if it succeeds, otherwise NULL"
[any-value? pack?]
parser [action?]
<local> result'
][
[^result' remainder]: parser input except e -> [
remainder: input ; succeed on parser fail but don't advance input
return null
]
return unmeta result' ; return successful parser result
]
'spread combinator [
{Return antiform group for array arguments}
return: "Splice antiform if input is array"
[~null~ ~void~ element? splice?]
parser [action?]
<local> result'
][
[^result' remainder]: parser input except e -> [
return raise e
]
if (not quoted? result') or (not any-array? result': unquote result') [
fail "SPREAD only accepts ANY-ARRAY? and QUOTED!"
]
return spread result' ; was unquoted above
]
'not combinator [
{Fail if the parser rule given succeeds, else continue}
return: [~not~]
parser [action?]
][
[@ remainder]: parser input except [ ; don't care about result
remainder: input ; parser failed, so NOT reports success
return ~not~ ; clearer than returning NULL
]
return raise "Parser called by NOT succeeded, so NOT fails"
]
'ahead combinator [
{Leave the parse position at the same location, but fail if no match}
return: "parser result if success, NULL if failure"
[any-value? pack?]
parser [action?]
][
remainder: input
return parser input ; don't care about what parser's remainder is
]
'further combinator [
{Pass through the result only if the input was advanced by the rule}
return: "parser result if it succeeded and advanced input, else NULL"
[any-value? pack?]
parser [action?]
<local> result' pos
][
[^result' pos]: parser input except e -> [
return raise e ; the parse rule did not match
]
if (index? pos) <= (index? input) [
return raise "FURTHER rule matched, but did not advance the input"
]
remainder: pos
return unmeta result'
]
=== LOOPING CONSTRUCT KEYWORDS ===
; UPARSE uses SOME as a loop operator, with TRY SOME or TRY FURTHER SOME
; taking the place of both ANY and WHILE. ANY is now used for more fitting
; semantics for the word, and WHILE is reclaimed as an arity-2 construct.
; The progress requirement that previously made ANY different from WHILE is
; achieved with FURTHER:
;
; https://forum.rebol.info/t/1540/12
;
; Note that TALLY can be used as a substitute for WHILE if the rule product
; isn't of interest.
;
; https://forum.rebol.info/t/1581/2
'some combinator [
{Run the parser argument in a loop, requiring at least one match}
return: "Result of last successful match"
[any-value? pack?]
parser [action?]
<local> result'
][
append state.loops binding of $return
[^result' input]: parser input except e -> [
take/last state.loops
return raise e
]
cycle [ ; if first try succeeds, we'll succeed overall--keep looping
[^result' input]: parser input except [
take/last state.loops
remainder: input
return unmeta result'
]
]
fail ~unreachable~
]
'while combinator [
{Run the body parser in a loop, for as long as condition matches}
return: "Result of last body parser (or void if body never matched)"
[any-value? pack?]
condition-parser [action?]
body-parser [action?]
<local> result'
][
append state.loops binding of $return
result': void'
cycle [
[^ input]: condition-parser input except [
take/last state.loops
remainder: input
return unmeta result'
]
; We don't worry about the body parser's success or failure, but
; if it fails we disregard the result
;
[^result' input]: body-parser input except [
result': nihil'
continue
]
]
fail ~unreachable~
]
'cycle combinator [
{Run the body parser continuously in a loop until BREAK or STOP}
return: "Result of last body parser (or void if body never matched)"
[any-value? pack?]
parser [action?]
<local> result'
][
append state.loops binding of $return
result': void'
cycle [
[^result' input]: parser input except [
result': trash'
continue
]
]
fail ~unreachable~
]
'tally combinator [
{Iterate a rule and count the number of times it matches}
return: "Number of matches (can be 0)"
[integer!]
parser [action?]
<local> count
][
append state.loops binding of $return
count: 0
cycle [
[^ input]: parser input except [
take/last state.loops
remainder: input
return count
]
count: count + 1
]
fail ~unreachable~
]
'break combinator [
{Break an iterated construct like SOME or REPEAT, failing the match}
return: [] ; divergent
<local> f
][
f: take/last state.loops except [
fail "No PARSE iteration to BREAK"
]
f.remainder: input
f.return raise "BREAK encountered"
]
'stop combinator [
{Break an iterated construct like SOME or REPEAT, succeeding the match}
return: [] ; divergent
parser [<end> action?]
<local> f result'
][
result': trash' ; default `[stop]` returns trash
if :parser [ ; parser argument is optional
[^result' input]: parser input except e -> [
return raise e
]
]
f: take/last state.loops except [
fail "No PARSE iteration to STOP"
]
f.remainder: input
f.return unmeta result'
]
=== ACCEPT KEYWORD ===
; ACCEPT is like R3-Alpha's RETURN keyword, but with the name adjusted to
; help distinguish it from the overall return of a function (as well as cue
; the reader it is not unconditional, e.g. you can say something like
; `[accept integer! | ...]`).
;
; RETURN was removed for a time in Ren-C due to concerns about how it
; could lead to abruptly ending a parse before all the matching was
; complete. Now UPARSE can return ANY-VALUE? (or PACK?) and the only
; reason you'd ever use ACCEPT would be specifically for the abrupt exit,
; so it's fit for purpose.
'accept combinator [
{Return a value explicitly from the parse, terminating early}
return: [] ; divergent
parser [action?]
<local> value'
][
[^value' _]: parser input except e -> [
return raise e
]
; !!! STATE is filled in as the frame of the top-level UPARSE call. If
; we UNWIND then we bypass any of its handling code, so it won't set
; things like PENDING (which gets type checked as a multi-return, so
; we can't leave it as unset). Review.
;
state.pending: null
state.return unmeta value'
]
=== INDEX and MEASUREMENT COMBINATORS ===
; The historical pattern:
;
; s: <here>, some rule, e: <here>, (len: (index of e) - (index of s))
;
; Can be done more conveniently with the <index> tag combinator:
;
; s: <index>, some rule, e: <index>, (len: e - s)
;
; But even more conveniently with the MEASURE combinator:
;
; len: measure some rule
;
; Note this is distinct from TALLY, which is an iterative construct that
; counts the number of times it can match the rule it is given:
;
; >> parse "ababab" [tally "ab"]
; == 3
;
; >> parse "ababab" [measure some "ab"]
; == 6
<index> combinator [
{Get the current series index of the PARSE operation}
return: "The INDEX OF the parse position"
[integer!]
][
remainder: input
return index of input
]
'measure combinator [
{Get the length of a matched portion of content}
return: "Length in series units"
[integer!]
parser [action?]
<local> start end
][
[^ remainder]: parser input except e -> [return raise e]
end: index of remainder
start: index of input
; Because parse operations can SEEK, this can potentially create
; issues. We currently fail if the index is before.
;
if start > end [
fail "Can't MEASURE region where rules did a SEEK before the INPUT"
]
return end - start
]
=== MUTATING KEYWORDS ===
; Topaz moved away from the idea that PARSE was used for doing mutations
; entirely. It does complicate the implementation to be changing positions
; out from under things...so it should be considered carefully.
;
; UPARSE continues with the experiment, but does things a bit differently.
; Here CHANGE is designed to be used with value-bearing rules, and the
; value-bearing rule is run against the same position as the start of
; the input.
;
; !!! Review what happens if the input rule can modify, too.
'change combinator [
{Substitute a match with new data}
return: [~change~]
parser [action?]
replacer [action?] ; !!! How to say result is used here?
<local> replacement'
][
[^ remainder]: parser input except e -> [ ; first find end position
return raise e
]
[^replacement' _]: replacer input except e -> [
return raise e
]
; CHANGE returns tail, use as new remainder
;
remainder: change/part input (unmeta replacement') remainder
return ~change~
]
'remove combinator [
{Remove data that matches a parse rule}
return: [~remove~]
parser [action?]
][
[^ remainder]: parser input except e -> [ ; first find end position
return raise e
]
remainder: remove/part input remainder
return ~remove~
]
'insert combinator [
{Insert literal data into the input series}
return: [~insert~]
parser [action?]
<local> insertion'
][
[^insertion' _]: parser input except e -> [ ; remainder ignored
return raise e
]
remainder: insert input (unmeta insertion')
return ~insert~
]
=== SEEKING KEYWORDS ===
'to combinator [
{Match up TO a certain rule (result position before succeeding rule)}
return: "The rule's product"
[any-value? pack?]
parser [action?]
<local> result'
][
cycle [
[^result' _]: parser input except [
if tail? input [ ; could be `to <end>`, so check tail *after*
return raise "TO did not find desired pattern"
]
input: next input
continue
]
remainder: input ; TO means do not include match range
return unmeta result'
]
fail ~unreachable~
]
'thru combinator [
{Match up THRU a certain rule (result position after succeeding rule)}
return: "The rule's product"
[any-value? pack?]
parser [action?]
<local> result'
][
cycle [
[^result' remainder]: parser input except [
if tail? input [ ; could be `thru <end>`, check TAIL? *after*
return raise "THRU did not find desired pattern"
]
input: next input
continue
]
return unmeta result'
]
fail ~unreachable~
]
'seek combinator [
return: "seeked position"
[any-series?]
parser [action?]
<local> where
][
[^where remainder]: parser input except e -> [
return raise e
]
case [
'~void~ = where [
remainder: input
]
quasi? where [
fail "Cannot SEEK to antiform"
]
(elide where: my unquote)
integer? where [
remainder: at head input where
]
any-series? :where [
if not same? head input head where [
fail "Series SEEK in UPARSE must be in the same series"
]
remainder: where
]
fail "SEEK requires INTEGER!, series position, or VOID"
]
return remainder
]
'between combinator [
return: "Copy of content between the left and right parsers"
[any-series?]
parser-left [action?]
parser-right [action?]
<local> start limit
][
[^ start]: (parser-left input) except e -> [
return raise e
]
limit: start
cycle [
[^ remainder]: (parser-right limit) except e -> [
if tail? limit [ ; remainder of null
return raise e
]
limit: next limit
continue ; don't try to assign the `[^ remainder]:`
]
return copy/part start limit
]
fail ~unreachable~
]
=== TAG! SUB-DISPATCHING COMBINATOR ===
; Historical PARSE matched tags literally, while UPARSE pushes to the idea
; that they are better leveraged as "special nouns" to avoid interfering
; with the user variables in wordspace.
;
; There is an overall TAG! combinator which looks in the combinator map for
; specific tags. You can replace individual tag combinators or change the
; behavior of tags overall completely.
tag! combinator [
{Special noun-like keyword subdispatcher for TAG!s}
return: "What the delegated-to tag returned"
[any-value? pack?]
@pending [~null~ block!]
value [tag!]
<local> comb
][
if not comb: state.combinators.(value) [
fail ["No TAG! Combinator registered for" value]
]
return [@ remainder pending]: run comb state input
]
<here> combinator [
{Get the current parse input position, without advancing input}
return: "parse position"
[any-series?]
][
remainder: input
return input
]
<end> combinator [
{Only match if the input is at the end}
return: "Invisible"
[nihil?]
][
if tail? input [
remainder: input
return nihil
]
return raise "PARSE position not at <end>"
]
<input> combinator [
{Get the original input of the PARSE operation}
return: "parse position"
[any-series?]
][
remainder: input
return state.input
]
<subinput> combinator [
{Get the input of the SUBPARSE operation}
return: "parse position"
[any-series?]
][
remainder: input
return head of input ; !!! What if SUBPARSE series not at head?
]
<any> combinator [ ; historically called "SKIP"
{Match one series item in input, succeeding so long as it's not at END}
return: "One element of series input"
[element?]
][
if tail? input [
return raise "PARSE position at tail, <any> has no item to match"
]
remainder: next input
return input.1
]
=== ACROSS (COPY?) ===
; Historically Rebol used COPY to mean "match across a span of rules and
; then copy from the first position to the tail of the match". That could
; have assignments done during, which extract some values and omit others.
; You could thus end up with `y: copy x: ...` and wind up with x and y
; being different things, which is not intuitive.
'across combinator [
{Copy from the current parse position through a rule}
return: "Copied series"
[any-series?]
parser [action?]
][
[^ remainder]: parser input except e -> [
return raise e
]
if any-array? input [
return as block! copy/part input remainder
]
if any-string? input [
return as text! copy/part input remainder
]
return copy/part input remainder
]
'copy combinator [
{Disabled combinator, included to help guide to use ACROSS}
return: [] ; divergent
][
fail [
"Transitionally (maybe permanently?) the COPY function in UPARSE"
"is done with ACROSS:" https://forum.rebol.info/t/1595
]
]
=== SUBPARSE COMBINATOR ===
; Rebol2 had a INTO combinator which only took one argument: a rule to use
; when processing the nested input. There was a popular proposal that
; INTO would take a datatype, which would help simplify a common pattern.
;
; ahead text! into [some "a"] ; arity-1 form
; =>
; into text! [some "a"] ; arity-2 form, from proposals/Topaz
;
; The belief being that wanting to test the type you were going "INTO" was
; needed more often than not, and that at worst it would incentivize adding
; the type as a comment. Neither R3-Alpha nor Red adopted this proposal
; (but Topaz did).
;
; UPARSE reframes this not to take just a datatype, but a "value-bearing
; rule". This means you can use it with generated data that is not
; strictly resident in the series, effectively parameterizing it like
; PARSE itself...so it's called SUBPARSE:
;
; parse "((aaaa)))" [subparse [between some "(" some ")"] [some "a"]]
;
; Because any value-bearing rule can be used, GROUP! rules are also legal,
; which lets you break the rules up for legibility (and avoids interpreting
; arrays as rules themselves)
;
; parse [| | any any any | | |] [
; content: between some '| some '|
; subparse (content) [some 'any]
; ]
;
; arity-1 INTO may still be useful as a shorthand for SUBPARSE <ANY>, but
; it's also a little bit obtuse when read in context.
'subparse combinator [
"Recursion into other data with a rule, result of rule if match"
return: "Result of the subparser"
[any-value? pack?]
parser [action?] ; !!! Easier expression of value-bearing parser?
subparser [action?]
<local> subseries result'
][
[^subseries remainder]: parser input except e -> [
;
; If the parser in the first argument can't get a value to subparse
; then we don't process it.
;
; !!! Review: should we allow non-value-bearing parsers that just
; set limits on the input?
;
return raise e
]
if void' = subseries [
fail "Cannot SUPBARSE into a void"
]
if quasi? subseries [
fail "Cannot SUBPARSE an antiform synthesized result"
]
subseries: my unquote
case [
any-series? subseries []
any-sequence? subseries [subseries: as block! subseries]
return raise "Need SERIES! or SEQUENCE! input for use with SUBPARSE"
]
; If the entirety of the item at the input array is matched by the
; supplied parser rule, then we advance past the item.
;
[^result' subseries]: subparser subseries except e -> [return raise e]
if not tail? subseries [
return raise "SUBPARSE rule succeeded, but didn't complete subseries"
]
return unmeta result'
]
'validate combinator [
"Recurse into other data with a rule, other data if match"
return: "Input if the rules matched"
[any-series?]
parser [action?] ; !!! Easier expression of value-bearing parser?
subparser [action?]
<local> subseries subremainder
][
[^subseries remainder]: parser input except e -> [
;
; If the parser in the first argument can't get a value to subparse
; then we don't process it.
;
; !!! Review: should we allow non-value-bearing parsers that just
; set limits on the input?
;
return raise e
]
if void' = subseries [
fail "Cannot VALIDATE a void"
]
if quasi? subseries [
fail "Cannot VALIDATE an antiform synthesized result"
]
subseries: my unquote
case [
any-series? subseries []
any-sequence? subseries [subseries: as block! subseries]
return raise "Need SERIES! or SEQUENCE! input for use with VALIDATE"
]
; If the entirety of the item at the input array is matched by the
; supplied parser rule, then we advance past the item.
;
[_ subremainder]: subparser subseries except e -> [
return raise e
]
if not tail? subremainder [
return raise "VALIDATE rule succeeded, but didn't complete subseries"
]
return subseries
]
=== COLLECT AND KEEP ===
; The COLLECT feature was first added by Red. However, it did not use
; rollback across any KEEPs that happened when a parse rule failed, which
; makes the feature of limited use.
;
; UPARSE has a generic framework for bubbling up gathered items. We look
; through that list of items here for anything marked as collect material
; and remove it.
'collect combinator [
return: "Block of collected values"
[block!]
@pending [~null~ block!]
parser [action?]
<local> collected
][
[^ remainder pending]: parser input except e -> [
return raise e
]
; PENDING can be NULL or a block full of items that may or may
; not be intended for COLLECT. Right now the logic is that all QUOTED!
; items are intended for collect, extract those from the pending array.
;
; !!! More often than not a COLLECT probably is going to be getting an
; array of all QUOTED! items. If so, there's probably no great reason
; to do a new allocation...instead the quoteds should be mutated into
; unquoted forms. Punt on such optimizations for now.
;
collected: collect [
remove-each item (maybe pending) [
if quoted? item [keep unquote item, true]
]