-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtracerz.h
1792 lines (1580 loc) · 61.9 KB
/
tracerz.h
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
#pragma once
/**
* @file tracerz.h tracerz.h: a single-header, modern C++ port/extension of @galaxykate's tracery tool
*/
#include <cctype>
#include <functional>
#include <memory>
#include <optional>
#include <random>
#include <regex>
#include <stack>
#include <string>
#include <vector>
#include "json.hpp"
namespace tracerz {
// Forward declaration
class Tree;
class TreeNode;
namespace details {
/**
* This interface represents a generic modifier function that takes an input string and 0 or more string params, and
* returns a string.
*/
class IModifierFn {
public:
/**
* Calls the modifier function with the given info
*
* @param input the input string to modify
* @param params the additional params to pass into the function
* @return the modified input string
*/
virtual std::string callVec(const std::string& input, const std::vector<std::string>& params) = 0;
/**
* Calls the modifier function with the given info
*
* @param input the input Tree to modify
* @param ruleName the name of the rule this modifier was called on
* @param params the additional params to pass into the function
* @return empty string
*/
virtual std::string callVec(const std::shared_ptr<Tree>& input,
const std::string& ruleName,
const std::vector<std::string>& params) = 0;
/**
* Calls the modifier function with the given info
*
* @param input the input TreeNode to modify
* @param ruleName the name of
* @param params the additional params to pass into the function
* @return empty string
*/
virtual std::string callVec(const std::shared_ptr<TreeNode>& input,
const std::string& ruleName,
const std::vector<std::string>& params) = 0;
/**
* Returns true if this modifier takes a string as its input.
*
* @return true if this modifier takes a string as its input.
*/
virtual bool isStringModifier() const = 0;
/**
* Returns true if this modifier takes a Tree as its input.
*
* @return true if this modifier takes a Tree as its input.
*/
virtual bool isTreeModifier() const = 0;
/**
* Returns true if this modifier takes a TreeNode as its input.
*
* @return true if this modifier takes a TreeNode as its input.
*/
virtual bool isTreeNodeModifier() const = 0;
/**
* Default virtual destructor.
*/
virtual ~IModifierFn() = default;
};
/**
* Given a function that accepts an input and at least one additional parameter, the static function of this class
* recursively unpacks a vector into a parameter pack, and then calls the given function on the input and the parameter
* pack.
*
* @tparam N the number of items remaining in the vector
* @tparam F the type of the function to call on the unpacked parameters
* @tparam I the type of the input
* @tparam PTs a parameter pack of the types of the items already unpacked from the vector
*/
template<int N,
typename F,
typename I,
typename... PTs>
class CallVector_R {
public:
/**
* Unpacks the first parameter from the parameter vector, moves it to the parameter pack, and then recurses. When it
* is fully unpacked, calls the function on the parameter pack.
*
* @param fun the function to ultimately call on the input and list of parameters
* @param input the input to pass to `fun`
* @param paramVec the remaining parameters
* @param params the parameter pack of parameters that have been unpacked from the vector so far
* @return the result of calling `fun` on the input string with all parameters
*/
static decltype(auto) callVec(F fun,
I input,
std::vector<std::string> paramVec,
PTs... params) {
if constexpr (N > 0) {
// Unpack the first parameter from the vector
std::string param = paramVec[0];
// Create a vector containing the rest of the parameters
std::vector<std::string> restOfVec(++paramVec.begin(), paramVec.end());
// Recurse, placing `param` at the end of the parameter pack
return CallVector_R<N - 1, F, I, const std::string&, PTs...>::callVec(fun,
input,
restOfVec,
params...,
param);
} else {
return fun(input, params...);
}
}
};
/**
* This class provides a static function to call a given function with the given input and the contents of a given
* parameter vector as parameters to the function
*
* @tparam N the number of parameters F takes, excluding the input string
* @tparam F the type of the function to be called on the supplied parameters
* @tparam I the type of the input
*/
template<int N, typename F, typename I>
class CallVector {
public:
/**
* Calls function `fun` with `input` and the contents of `params` as parameters
*
* @param fun the function to call
* @param input the input
* @param params the remaining parameters
* @return the result of calling `fun(input, params...)`
*/
static decltype(auto) callVec(F fun,
I input,
const std::vector<std::string>& params) {
if constexpr (N > 0) {
// Peel off the first parameter
std::string param = params[0];
// Create a vector of the remaining parameters
std::vector<std::string> restOfParams(++params.begin(), params.end());
// Use CallVector_R to recurse over the remaining parameters
return CallVector_R<N - 1, F, I, const std::string&>::callVec(fun,
input,
restOfParams,
param);
} else {
return fun(input);
}
}
};
/**
* Encapsulates a modifier function taking one or more string inputs and returning a string. Provides two calling
* methods: a parameter pack of type Ts or a vector of strings with size equal to the number of parameters taken by the
* function.
*
* **Note**: there is no validation on the number of parameters in the vector.
*
* @tparam Ts parameter pack of the types of the parameters to the function
*/
template<typename I, typename... Ts>
class ModifierFn : public IModifierFn {
public:
static constexpr bool is_string_modifier = std::is_same_v<std::string, std::decay_t<I>>;
static constexpr bool is_tree_modifier = std::is_same_v<std::shared_ptr<Tree>, std::decay_t<I>>;
static constexpr bool is_tree_node_modifier = std::is_same_v<std::shared_ptr<TreeNode>, std::decay_t<I>>;
/**
* Construct a ModifierFn for the given modifier function
* @param fun the modifier function
*/
explicit ModifierFn(std::function<std::string(I, Ts...)> fun)
: callback(std::move(fun)) {
}
/**
* Default virtual copy constructor.
*/
~ModifierFn() override = default;
/**
* Calls the encapsulated function with the given parameter pack
*
* @tparam PTs the parameter pack of param types
* @param params the parameters to pass to the function
* @return the result of calling the function on the parameters
*/
template<typename... PTs>
std::string call(PTs... params) {
return callf(this->callback, params...);
}
/**
* Calls the encapsulated function with the given input string and the given vector of params, unpacked to type `PTs...`
*
* **NOTE**: there is no checking on the size of vector
*
* @param input the input string to the modifier
* @param params the vector of parameters to pass to the encapsulated function
* @return the result of calling the function on the parameters
*/
std::string callVec(const std::string& input, const std::vector<std::string>& params) override {
if constexpr (ModifierFn<I, Ts...>::is_string_modifier) {
return CallVector<sizeof...(Ts), decltype(this->callback), const std::string&>::callVec(this->callback, input,
params);
} else {
return "";
}
}
std::string callVec(const std::shared_ptr<Tree>& input,
const std::string& ruleName,
const std::vector<std::string>& params) override {
if constexpr (ModifierFn<I, Ts...>::is_tree_modifier) {
std::vector<std::string> ruleNameWithParams;
ruleNameWithParams.push_back(ruleName);
std::copy(params.begin(), params.end(), std::back_inserter(ruleNameWithParams));
return CallVector<sizeof...(Ts), decltype(this->callback), const std::shared_ptr<Tree>&>::callVec(this->callback,
input,
ruleNameWithParams);
} else {
return "";
}
}
std::string callVec(const std::shared_ptr<TreeNode>& input,
const std::string& ruleName,
const std::vector<std::string>& params) override {
if constexpr (ModifierFn<I, Ts...>::is_tree_node_modifier) {
std::vector<std::string> ruleNameWithParams;
ruleNameWithParams.push_back(ruleName);
std::copy(params.begin(), params.end(), std::back_inserter(ruleNameWithParams));
return CallVector<sizeof...(Ts), decltype(this->callback), const std::shared_ptr<TreeNode>&>::callVec(
this->callback,
input,
ruleNameWithParams);
} else {
return "";
}
}
bool isStringModifier() const override {
return ModifierFn<I, Ts...>::is_string_modifier;
}
bool isTreeModifier() const override {
return ModifierFn<I, Ts...>::is_tree_modifier;
}
bool isTreeNodeModifier() const override {
return ModifierFn<I, Ts...>::is_tree_node_modifier;
}
private:
/** The encapsulated function */
std::function<std::string(I, Ts...)> callback;
};
/** Represents a mapping of modifier names to modifier functions */
typedef std::map<std::string, std::shared_ptr<IModifierFn>> callback_map_t;
/** Represents a map of rule names to ruleset stacks */
typedef std::map<std::string, std::stack<nlohmann::json>> runtime_dictionary_t;
/**
* Returns the action regular expression
*
* An action is defined as follows:
* An open bracket: [
* Followed by zero or more non-close bracket characters
* A close bracket: ]
*
* It has one capture group: the entire contents of the bracketed characters
*
* @return the regex
*/
const std::regex& getActionRegex() {
static const std::regex rgx(R"(\[([^\]]*)\])");
return rgx;
}
/**
* Gets a comma regex (to make splitting on commas into a container with iterators easy)
*
* It's literally just a comma
*
* It contains no capture group.
*
* @return the regex
*/
const std::regex& getCommaRegex() {
static const std::regex rgx(",");
return rgx;
}
/**
* Gets a basic modifier regex.
*
* It consists of the following:
* A dot: .
* Followed by one or more not dots
*
* It has one capture group: the non-dot matching characters
*
* @return the regex
*/
const std::regex& getModifierRegex() {
static const std::regex rgx(R"(\.([^\.]+))");
return rgx;
}
/**
* Gets a regex that will match iff the input contains only tracery action groups
*
* It consists of the following:
* The beginning of a line
* One or more of the non-capturing group:
* An opening bracket: [
* Zero or more non-close brackets
* A closing bracket: ]
* The end of a line
*
* It contains no capture group.
*
* @return the regex
*/
const std::regex& getOnlyActionsRegex() {
// (?: ... ) is a non-capturing group
static const std::regex rgx(R"(^(?:\[[^\]]*\])+$)");
return rgx;
}
/**
* Gets a regex that will match iff the input contains only an action that sets a key to plain text
*
* It consists of the following:
* The beginning of a line
* An opening bracket: [
* One or more alpha numeric characters (representing a key name)
* A colon: :
* One or more non-# and non-] characters
* A closing bracket: ]
* The end of a line
*
* It contains two capture groups:
* The key name (the alphanumeric characters before the colon)
* The plain text value (the characters between the colon and the closing bracket)
*
* @return the regex
*/
const std::regex& getOnlyKeyWithTextActionRegex() {
static const std::regex rgx(R"(^\[([[:alnum:]]+):([^#\]]+)\]$)");
return rgx;
}
/**
* Gets a regex that will match iff the input contains only an action group that sets a key to the result of a rule with
* zero or more modifiers
*
* It consists of the following:
* The beginning of a line
* An opening bracket: [
* One or more alphanumeric characters, representing a key name
* A colon: :
* An octothorpe: #
* One or more alphanumeric characters, representing a rule name
* Zero or more of the non-capturing group, each representing a modifier:
* A dot: .
* One or more non-#, non-. characters
* An octothorpe: #
* A closing bracket: ]
* The end of a line
*
* It contains two capture groups:
* The key name
* The rule and optional modifiers, including surrounding octothorpes
*
* @return the regex
*/
const std::regex& getOnlyKeyWithRuleActionRegex() {
static const std::regex rgx(R"(^\[([[:alnum:]]+):(#[[:alnum:]]+(?:\.[^.#]+)*#)\]$)");
return rgx;
}
/**
* Gets a regex that will match iff the input contains only an action group that does not set a key. These action groups
* contain one rule, possibly with modifiers. Usually these rules create keys themselves, acting as a kind of
* function within the language.
*
* It consists of the following:
* The beginning of a line
* An opening bracket: [
* An octothorpe: #
* One or more alphanumeric characters, representing a rule name
* Zero or more of the non-capturing group, each representing a modifier:
* A dot: .
* One or more non-#, non-. characters
* An octothorpe: #
* A closing bracket: ]
* The end of a line
*
* It contains one capture groups: the rule and optional modifiers, including surrounding octothorpes
*
* @return the regex
*/
const std::regex& getOnlyKeylessRuleActionRegex() {
static const std::regex rgx(R"(^\[(#[[:alnum:]]+(?:\.[^.#]+)*#)\]$)");
return rgx;
}
/**
* Gets a regex that will match iff the input contains only a rule with an optional set of modifiers
*
* It consists of the following:
* The beginning of a line
* An octothorpe: #
* One or more alphanumeric characters, representing a rule name
* Zero or more of the non-capturing group, each representing a modifier:
* A dot: .
* One or more non-#, non-. characters
* An octothorpe: #
* The end of a line
*
* It contains two capture groups:
* The rule name
* The string of all characters representing zero or more modifiers (possibly empty)
*
* @return the regex
*/
const std::regex& getOnlyRuleRegex() {
static const std::regex rgx(R"(^#([[:alnum:]]+)((?:\.[^.#]+)*)#$)");
return rgx;
}
/**
* Gets a regex that will match iff the input contains only a rule with at least one action and an optional set of
* modifiers
*
* It consists of the following:
* The beginning of a line
* An octothorpe: #
* One or more of the non-capturing group, each representing an action group:
* An opening bracket: [
* Zero or more characters
* A closing bracket: ]
* One or more alphanumeric characters, representing a rule name
* Zero or more of the non-capturing group, each representing a modifier:
* A dot: .
* One or more non-#, non-. characters
* An octothorpe: #
* The end of a line
*
* It contains three capture groups:
* The string of all characters representing the one or more action groups
* The rule name
* The string of all characters representing zero or more modifiers (possibly empty)
*
* @return the regex
*/
const std::regex& getOnlyRuleWithActionsRegex() {
static const std::regex rgx(R"(^#((?:\[.*\])+)([[:alnum:]]+)((?:\.[^.#]+)*)#$)");
return rgx;
}
/**
* Gets a regex that will match if the input contains a rule with an optional action and an optional set of modifiers.
*
* It consists of the following:
* An octothorpe: #
* Zero or more of the non-capturing group, each representing an action group:
* An opening bracket: [
* Zero or more characters
* A closing bracket: ]
* One or more alphanumeric characters, representing a rule name
* Zero or more of the non-capturing group, each representing a modifier:
* A dot: .
* One or more non-#, non-. characters
* An octothorpe: #
*
* It contains three capture groups:
* The string of all characters representing the one or more action groups
* The rule name
* The string of all characters representing zero or more modifiers (possibly empty)
*
* @return the regex
*/
const std::regex& getRuleRegex() {
static const std::regex rgx(R"(#(?:\[[^\]]*\])*([[:alnum:]]+)((?:\.[^.#]+)*)#)");
return rgx;
}
/**
* Gets a regex that will match if the string contains
*
* It consists of the following:
* One or more non-opening parentheses characters
* An open parentheses: (
* Zero or more non-closing parentheses
* A close parentheses: )
*
* It contains two capture groups:
* The characters before the open parentheses, representing the modifier name
* The characters between the parentheses, representing the parameter list
*
* @return the regex
*/
const std::regex& getParametricModifierRegex() {
static const std::regex rgx(R"(([^\(]+)\(([^\)]*)\))");
return rgx;
}
/**
* True if the input contains a match for the regex returned by @see tracerz::details::getRuleRegex()
*
* @param input the input string to test
* @return true if the input contains a match
*/
bool containsRule(const std::string& input) {
return std::regex_search(input, details::getRuleRegex());
}
/**
* True if the input contains a match for the regex returned by @see tracerz::details::getOnlyActionsRegex()
*
* @param input the input string to test
* @return true if the input contains a match
*/
bool containsOnlyActions(const std::string& input) {
return std::regex_match(input, details::getOnlyActionsRegex());
}
/**
* True if the input contains a match for the regex returned by @see tracerz::details::getOnlyKeylessRuleActionRegex()
*
* @param input the input string to test
* @return true if the input contains a match
*/
bool containsOnlyKeylessRuleAction(const std::string& input) {
return std::regex_match(input, details::getOnlyKeylessRuleActionRegex());
}
/**
* True if the input contains a match for the regex returned by @see tracerz::details::getOnlyKeyWithTextActionRegex()
*
* @param input the input string to test
* @return true if the input contains a match
*/
bool containsOnlyKeyWithTextAction(const std::string& input) {
return std::regex_match(input, details::getOnlyKeyWithTextActionRegex());
}
/**
* True if the input contains a match for the regex returned by @see tracerz::details::getOnlyKeyWithRuleActionRegex()
*
* @param input the input string to test
* @return true if the input contains a match
*/
bool containsOnlyKeyWithRuleAction(const std::string& input) {
return std::regex_match(input, details::getOnlyKeyWithRuleActionRegex());
}
/**
* True if the input contains a match for the regex returned by @see tracerz::details::getOnlyRuleRegex()
*
* @param input the input string to test
* @return true if the input contains a match
*/
bool containsOnlyRule(const std::string& input) {
return std::regex_match(input, details::getOnlyRuleRegex());
}
/**
* True if the input contains a match for the regex returned by @see tracerz::details::getOnlyRuleWithActionsRegex()
*
* @param input the input string to test
* @return true if the input contains a match
*/
bool containsOnlyRuleWithActions(const std::string& input) {
return std::regex_match(input, details::getOnlyRuleWithActionsRegex());
}
/**
* True if the input contains a match for the regex returned by @see tracerz::details::getOnlyParametricModifierRegex()
*
* @param input the input string to test
* @return true if the input contains a match
*/
bool containsParametricModifier(const std::string& input) {
return std::regex_match(input, details::getParametricModifierRegex());
}
} // End namespace details
/**
* Represents a single node in the parse tree
*
* TODO: enumerate node types
*/
class TreeNode : public std::enable_shared_from_this<TreeNode> {
public:
/**
* Default constructor. Contains no input, used by the tree to point to certain nodes within the tree, from outside it
*/
TreeNode()
: input()
, isNodeComplete_(false)
, prevLeaf(nullptr)
, nextLeaf(nullptr)
, prevUnexpandedLeaf(nullptr)
, nextUnexpandedLeaf(nullptr)
, isNodeHidden_(false) {
}
/**
* Constructs a new tree node from the given parameters. The only required parameter is the input string, all others
* default to nullptr
*
* @param input the input string
* @param prev the leaf prior to this leaf
* @param next the next leaf from this leaf
* @param prevUnexpanded the unexpanded leaf prior to this unexpanded leaf
* @param nextUnexpanded the next unexpanded leaf from this unexpanded leaf
*/
explicit TreeNode(const std::string& input,
std::shared_ptr<TreeNode> prev = nullptr,
std::shared_ptr<TreeNode> next = nullptr,
std::shared_ptr<TreeNode> prevUnexpanded = nullptr,
std::shared_ptr<TreeNode> nextUnexpanded = nullptr)
: input(input)
, isNodeComplete_(!details::containsRule(input)
&& !details::containsOnlyActions(input))
, prevLeaf(std::move(prev))
, nextLeaf(std::move(next))
, prevUnexpandedLeaf(std::move(prevUnexpanded))
, nextUnexpandedLeaf(std::move(nextUnexpanded))
, isNodeHidden_(false) {
}
/**
* Default virtual destructor
*/
virtual ~TreeNode() = default;
/**
* Creates a new TreeNode from the given input string and adds it as a child to this node.
*
* @param inputStr the input string
*/
void addChild(const std::string& inputStr) {
std::shared_ptr<TreeNode> prev = nullptr;
std::shared_ptr<TreeNode> next = nullptr;
if (this->children.empty()) {
// If there are no children, then the previous and next leaves are the ones of this node
prev = this->prevLeaf;
next = this->nextLeaf;
} else {
// If there are children, the new node's previous leaf is the last child and its next leaf is the one of this node
prev = this->children.back();
next = prev->nextLeaf;
}
// Create the child with the input string, previous leaf, and next leaf
std::shared_ptr<TreeNode> child(new TreeNode(inputStr,
prev,
next));
// If the child's previous leaf is not null, set its next leaf to the new node
if (child->prevLeaf)
child->prevLeaf->nextLeaf = child;
// If the child's next leaf is not null, set its previous leaf to the new node
if (child->nextLeaf)
child->nextLeaf->prevLeaf = child;
// If this new child is not complete, set its previous and next unexpanded leaves
if (!child->isNodeComplete()) {
std::shared_ptr<TreeNode> prevUnexpanded = nullptr;
std::shared_ptr<TreeNode> nextUnexpanded = nullptr;
if (this->prevUnexpandedLeaf) {
// If this leaf has a previous unexpanded leaf, then this is its first expansion. Set the child's previous and
// next unexpanded leaves to this one's.
prevUnexpanded = this->prevUnexpandedLeaf;
nextUnexpanded = this->nextUnexpandedLeaf;
} else if (!this->children.empty()) {
// If this node has children, get the last child *C* with a previous unexpanded leaf, set the new child's
// previous unexpanded leaf to *C*, and set the new child's next unexpanded leaf to *C*'s next unexpanded node.
for (auto i = this->children.rbegin();
i != this->children.rend();
i++) {
if ((*i)->hasPrevUnexpandedLeaf()) {
prevUnexpanded = *i;
nextUnexpanded = (*i)->nextUnexpandedLeaf;
break;
}
}
}
// Set the child object's previous and next unexpanded leaves
child->prevUnexpandedLeaf = prevUnexpanded;
child->nextUnexpandedLeaf = nextUnexpanded;
// If the child's previous unexpanded leaf is not null, set its next unexpanded leaf to the new child
if (child->prevUnexpandedLeaf)
child->prevUnexpandedLeaf->nextUnexpandedLeaf = child;
// If the child's next unexpanded leaf is not null, set its previous unexpanded leaf to the new child
if (child->nextUnexpandedLeaf)
child->nextUnexpandedLeaf->prevUnexpandedLeaf = child;
// This node has been at least partially expanded and is no longer part of the chain of unexpanded leaves
this->prevUnexpandedLeaf = this->nextUnexpandedLeaf = nullptr;
}
// If this is a hidden node, hide the child
child->isNodeHidden_ = this->isNodeHidden_;
// Add the child to the list of children
this->children.push_back(child);
// This is no longer a leaf, unset its previous and next leaves
this->prevLeaf = this->nextLeaf = nullptr;
}
/**
* Returns true if this node has children nodes
*
* @return true if this node has children nodes
*/
bool hasChildren() const {
return !this->children.empty();
}
/**
* Returns true if every child of this node is complete, or there are no children
*
* @return true if every child of this node is complete, or there are no children
*/
bool areChildrenComplete() const {
for (auto& child : this->children) {
if (!child->isNodeComplete()) return false;
}
return true;
}
/**
* Gets the last child of this node that is unexpanded
*
* @return the last child of this node that is unexpanded
*/
std::shared_ptr<TreeNode> getLastExpandableChild() const {
for (auto riter = this->children.rbegin();
riter != this->children.rend();
riter++) {
// If this child is not complete, return it
if (!(*riter)->isNodeComplete()) return *riter;
}
// No expandable child found, return nullptr
return nullptr;
}
/**
* Flattens the sub-tree represented by this node and its descendents into a single string representation, using the
* given modifier map to handle any modifiers (if applicable).
*
* @param modFuns the modifier function map
* @param ignoreHidden exclude hidden subtrees from the flattened string
* @param ignoreModifiers if true, modifier functions will not be called
* @return the flattened string representation
*/
std::string flatten(details::callback_map_t modFuns,
std::shared_ptr<Tree> tree,
bool ignoreHidden = true,
bool ignoreModifiers = false) {
if (!(this->modifiers.empty() || ignoreModifiers)) {
// If this node has modifiers and ignoreModifiers is not true, then we need to apply modifiers. First we get the
// flattened string representation without calling modifiers
std::string output = this->flatten(modFuns, tree, ignoreHidden, true);
// If the output is empty at this point, then return the empty string
if (output.empty()) return output;
// Loop over each modifier being applied to this node
for (auto& mod : this->modifiers) {
std::vector<std::string> params; // Starts empty, may be filled if this is a parametric modifier
std::string modName = mod;
if (details::containsParametricModifier(mod)) {
// If it contains a modifier that takes parameters, we need to handle those. First extract the modifier name
// from the first capture group of this regex
modName = std::regex_replace(mod,
details::getParametricModifierRegex(),
"$1");
// Get the string representing the list of params from the second capture group
std::string paramsStr = std::regex_replace(mod,
details::getParametricModifierRegex(),
"$2");
// Use comma regex to separate params and fill params vector
std::copy(std::sregex_token_iterator(paramsStr.begin(),
paramsStr.end(),
details::getCommaRegex(),
-1),
std::sregex_token_iterator(),
std::back_inserter(params));
}
if (modFuns.find(modName) != modFuns.end()) {
// If the modifier name names a real modifier, call it with the appropriate input and parameters (if any), and
// update the output string.
auto& modFun = modFuns[modName];
if (modFun->isStringModifier()) {
output = modFun->callVec(output, params);
} else {
// Because of the way the parse tree is built, this node will never have actions attached to the front of
// the input. Therefore, the first capture group from this regex will be the rule name.
std::string ruleName = std::regex_replace(this->input, details::getRuleRegex(), "$1");
if (modFun->isTreeModifier()) {
output = modFun->callVec(tree, ruleName, params);
} else if (modFun->isTreeNodeModifier()) {
output = modFun->callVec(this->shared_from_this(), ruleName, params);
}
}
}
}
// Return the modified string
return output;
}
// If this doesn't have children...
if (!this->hasChildren()) {
// Then if the node is hidden and we are ignoring hidden nodes...
if (ignoreHidden && this->isNodeHidden()) {
// Return an empty string, since it's ignored
return "";
}
// Node isn't hidden, return its input string
return this->input;
}
// This node has children and isn't hidden, flatten and assemble the output of all its children
std::string ret;
for (auto& child : this->children) {
// We can't ignore modifiers, because we will get the wrong output from flattening our children if we do.
ret += child->flatten(modFuns, tree, ignoreHidden, false);
}
// Return the flattened children's string
return ret;
}
template<typename RNG, typename UniformIntDistributionT>
void expandNode(const nlohmann::json&, RNG&, details::runtime_dictionary_t&);
/**
* Gets the input string for this node
*
* @return the input string for this node
*/
const std::string& getInput() const { return this->input; }
/**
* Gets the next leaf (if applicable). If this is the last leaf or if this node is not a leaf, will return nullptr.
*
* @return the next leaf (if applicable)
*/
std::shared_ptr<TreeNode> getNextLeaf() const {
return this->nextLeaf;
}
/**
* Gets the next unexpanded leaf (if applicable). If this is the last unexpanded leaf, is partiall or fully expanded,
* or is not a leaf, will return nullptr.
*
* @return the next unexpanded leaf (if applicable)
*/
std::shared_ptr<TreeNode> getNextUnexpandedLeaf() const {
return this->nextUnexpandedLeaf;
}
/**
* Gets the previous leaf (if applicable). If this node is not a leaf, will return nullptr.
*
* @return the previous leaf (if applicable)
*/
std::shared_ptr<TreeNode> getPrevLeaf() const {
return this->prevLeaf;
}
/**
* Gets the previous unexpanded leaf (if applicable). If this is partially or fully expanded, or is not a leaf, this
* will return nullptr.
*
* @return the previous unexpanded leaf (if applicable)
*/
std::shared_ptr<TreeNode> getPrevUnexpandedLeaf() const {
return this->prevUnexpandedLeaf;
}
/**
* Returns true if this node has a next unexpanded leaf
*
* @return true if this node has a next unexpanded leaf
*/
bool hasNextUnexpandedLeaf() const {
return this->nextUnexpandedLeaf ? true : false;
}
/**
* Returns true if this node has a previous unexpanded leaf
*
* @return true if this node has a previous unexpanded leaf
*/
bool hasPrevUnexpandedLeaf() const {
return this->prevUnexpandedLeaf ? true : false;
}
/**
* Returns true if this node is complete (cannot be expanded)
*
* @return true if this node is complete (cannot be expanded)
*/
bool isNodeComplete() const { return this->isNodeComplete_; }
/**
* Sets the next leaf
*
* @param next the next leaf
*/
void setNextLeaf(std::shared_ptr<TreeNode> next) {
this->nextLeaf = std::move(next);
}
/**
* Sets the next unexpanded leaf
*
* @param next the next unexpanded leaf
*/
void setNextUnexpandedLeaf(std::shared_ptr<TreeNode> next) {
this->nextUnexpandedLeaf = std::move(next);
}
/**
* Sets the previous leaf
*
* @param next the previous leaf
*/
void setPrevLeaf(std::shared_ptr<TreeNode> prev) {
this->prevLeaf = std::move(prev);
}
/**
* Sets the previous unexpanded leaf
*
* @param next the previous unexpanded leaf
*/
void setPrevUnexpandedLeaf(std::shared_ptr<TreeNode> prev) {
this->prevUnexpandedLeaf = std::move(prev);
}
/**
* Marks this node has having a key with the given name, which will be set to the result of flattening this node and
* stored in the runtime grammar.
*
* @param next the key name
*/
void setKeyName(std::optional<std::string> key) {
this->keyName = std::move(key);