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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;

use pax_manifest::{escape_identifier, ComponentTemplate, TemplateNodeId, TreeLocation, TypeId};

use pax_manifest::{
    get_primitive_type_table, ComponentDefinition, ControlFlowRepeatPredicateDefinition,
    ControlFlowRepeatSourceDefinition, ControlFlowSettingsDefinition, LiteralBlockDefinition,
    LocationInfo, PropertyDefinition, SettingElement, SettingsBlockElement, TemplateNodeDefinition,
    Token, TokenType, TypeDefinition, TypeTable, ValueDefinition,
};

extern crate pest;
use pest::iterators::{Pair, Pairs};
use pest::{Parser, Span};
use pest_derive::Parser;

use pest::pratt_parser::{Assoc, Op, PrattParser};

#[derive(Parser)]
#[grammar = "pax.pest"]
pub struct PaxParser;

/// Returns (RIL output string, `symbolic id`s found during parse)
/// where a `symbolic id` may be something like `self.num_clicks` or `i`
pub fn run_pratt_parser(input_paxel: &str) -> (String, Vec<String>) {
    // Operator precedence is declared via the ordering here:
    let pratt = PrattParser::new()
        .op(Op::infix(Rule::xo_tern_then, Assoc::Left)
            | Op::infix(Rule::xo_tern_else, Assoc::Right))
        .op(Op::infix(Rule::xo_bool_and, Assoc::Left) | Op::infix(Rule::xo_bool_or, Assoc::Left))
        .op(Op::infix(Rule::xo_add, Assoc::Left) | Op::infix(Rule::xo_sub, Assoc::Left))
        .op(Op::infix(Rule::xo_mul, Assoc::Left) | Op::infix(Rule::xo_div, Assoc::Left))
        .op(Op::infix(Rule::xo_mod, Assoc::Left))
        .op(Op::infix(Rule::xo_exp, Assoc::Right))
        .op(Op::prefix(Rule::xo_neg))
        .op(Op::infix(Rule::xo_rel_eq, Assoc::Left)
            | Op::infix(Rule::xo_rel_neq, Assoc::Left)
            | Op::infix(Rule::xo_rel_lt, Assoc::Left)
            | Op::infix(Rule::xo_rel_lte, Assoc::Left)
            | Op::infix(Rule::xo_rel_gt, Assoc::Left)
            | Op::infix(Rule::xo_rel_gte, Assoc::Left))
        .op(Op::prefix(Rule::xo_bool_not));

    let pairs = PaxParser::parse(Rule::expression_body, input_paxel)
        .expect(&format!("unsuccessful pratt parse {}", &input_paxel));

    let symbolic_ids = Rc::new(RefCell::new(vec![]));
    let output = recurse_pratt_parse_to_string(pairs, &pratt, Rc::clone(&symbolic_ids));
    (output, symbolic_ids.take())
}

/// Removes leading `self.` or `this.`, escapes remaining symbol to be a suitable atomic identifier
fn convert_symbolic_binding_from_paxel_to_ril(xo_symbol: Pair<Rule>) -> String {
    let mut pairs = xo_symbol.clone().into_inner();
    let maybe_this_or_self = pairs.next().unwrap().as_str();

    let self_or_this_removed = if maybe_this_or_self == "this" || maybe_this_or_self == "self" {
        let mut output = "".to_string();

        //accumulate remaining identifiers, having skipped `this` or `self` with the original `.next()`
        pairs.for_each(|pair| output += &*(".".to_owned() + pair.as_str()));

        //remove initial fencepost "."
        output.replacen(".", "", 1)
    } else {
        //remove original binding; no self or this
        xo_symbol.as_str().to_string()
    };

    escape_identifier(self_or_this_removed)
}

/// Workhorse method for compiling Expressions into Rust Intermediate Language (RIL, a string of Rust)
fn recurse_pratt_parse_to_string<'a>(
    expression: Pairs<Rule>,
    pratt_parser: &PrattParser<Rule>,
    symbolic_ids: Rc<RefCell<Vec<String>>>,
) -> String {
    pratt_parser
        .map_primary(move |primary| match primary.as_rule() {
            /* expression_grouped | xo_enum_or_function_call | xo_range     */
            Rule::expression_grouped => {
                /* expression_grouped = { "(" ~ expression_body ~ ")" ~ literal_number_unit? } */
                let mut inner = primary.into_inner();

                let exp_bod = recurse_pratt_parse_to_string(inner.next().unwrap().into_inner(), pratt_parser, Rc::clone(&symbolic_ids));
                if let Some(literal_number_unit) = inner.next() {
                    let unit = literal_number_unit.as_str();

                    if unit == "px" {
                        format!("Size::Pixels({}.into())", exp_bod)
                    } else if unit == "%" {
                        format!("Percent({}.into())", exp_bod)
                    } else if unit == "deg" {
                        format!("Rotation::Degrees({}.into())", exp_bod)
                    } else if unit == "rad" {
                        format!("Rotation::Radians({}.into())", exp_bod)
                    } else {
                        unreachable!()
                    }
                } else {
                    exp_bod
                }
            },
            Rule::xo_enum_or_function_call => {
                /* xo_enum_or_function_call = {identifier ~ (("::") ~ identifier)* ~ ("("~xo_enum_or_function_args_list~")")}
                   xo_enum_or_function_args_list = {expression_body ~ ("," ~ expression_body)*} */

                if !primary.as_str().contains("(") {
                    //If no args, we just want to return this xo_enum_or_function_call exactly,
                    //such as StackerDirection::Vertical
                    primary.as_str().to_string()
                } else {
                    //prepend identifiers; recurse-pratt-parse `xo_function_args`' `expression_body`s
                    let mut pairs = primary.into_inner();

                    let mut output = "".to_string();
                    let mut next_pair = pairs.next().unwrap();

                    while let Rule::identifier = next_pair.as_rule() {
                        output = output + next_pair.as_str();
                        next_pair = pairs.next().unwrap();
                        if let Rule::identifier = next_pair.as_rule() {
                            //look-ahead
                            output = output + "::";
                        }
                    };

                    let mut expression_body_pairs = next_pair.into_inner();

                    output = output + "(";
                    while let Some(next_pair) = expression_body_pairs.next() {
                        output = output + "(" + &recurse_pratt_parse_to_string(next_pair.into_inner(), pratt_parser, Rc::clone(&symbolic_ids)) + ").into(),"
                    }
                    output = output + ")";

                    output
                }


            },
            Rule::xo_range => {
                /* { op0: (xo_literal | xo_symbol) ~ op1: (xo_range_inclusive | xo_range_exclusive) ~ op2: (xo_literal | xo_symbol)} */
                let mut pairs = primary.into_inner();

                let op0 = pairs.next().unwrap();

                let op0_out = match op0.as_rule() {
                    Rule::xo_literal => {
                        //return the literal exactly as it is
                        op0.as_str().to_string()
                    },
                    Rule::xo_symbol => {
                        symbolic_ids.borrow_mut().push(op0.as_str().to_string());
                        //for symbolic identifiers, remove any "this" or "self", then return string
                        format!("{}.to_int()",convert_symbolic_binding_from_paxel_to_ril(op0))
                    },
                    _ => unimplemented!("")
                };

                let op1 = pairs.next().unwrap();
                let op1_out = op1.as_str().to_string();

                let op2 = pairs.next().unwrap();
                let op2_out = match op2.as_rule() {
                    Rule::xo_literal => {
                        //return the literal exactly as it is
                        op2.as_str().to_string()
                    },
                    Rule::xo_symbol => {
                        symbolic_ids.borrow_mut().push(op2.as_str().to_string());
                        //for symbolic identifiers, remove any "this" or "self", then return string
                        format!("{}.to_int()",convert_symbolic_binding_from_paxel_to_ril(op2))
                    },
                    _ => unimplemented!("")
                };

                format!("({} as isize){}({} as isize)", &op0_out, &op1_out, &op2_out)
            },
            Rule::xo_literal => {
                let literal_kind = primary.into_inner().next().unwrap();

                match literal_kind.as_rule() {
                    Rule::literal_number_with_unit => {
                        let mut inner = literal_kind.into_inner();

                        let value = inner.next().unwrap().as_str();
                        let unit = inner.next().unwrap().as_str();

                        if unit == "px" {
                            format!("Size::Pixels({}.into())", value)
                        } else if unit == "%" {
                            format!("Percent({}.into())", value)
                        } else if unit == "deg" {
                            format!("Rotation::Degrees({}.into())", value)
                        } else if unit == "rad" {
                            format!("Rotation::Radians({}.into())", value)
                        } else {
                            unreachable!()
                        }
                    },
                    Rule::literal_number => {
                        let mut inner = literal_kind.into_inner();
                        let value = inner.next().unwrap().as_str();
                        format!("Numeric::from({})", value)
                    },
                    Rule::string => {
                        format!("StringBox::from({})",literal_kind.as_str().to_string())
                    },
                    Rule::literal_color => {
                        let mut inner = literal_kind.into_inner();
                        let next_pair = inner.next().unwrap();
                        if let Rule::literal_color_const = next_pair.as_rule() {
                            //Return color consts like WHITE underneath the Color enum
                            format!("Color::{}", next_pair.as_str())
                        } else {
                            //Recurse-pratt-parse the args list for color funcs, a la enums
                            let func = next_pair.as_str().split("(").next().unwrap().to_string();
                            let mut accum = "".to_string();
                            let mut inner = next_pair.into_inner();
                            while let Some(next_pair) = inner.next() {
                                // literal_color_channel = {literal_number_with_unit | literal_number_integer}
                                // while this case is trivial, recurse_pratt_parse is used here to manage literal_number_with_unit without duplicating code here
                                let literal_representation = next_pair.into_inner();
                                accum = accum + &recurse_pratt_parse_to_string(literal_representation, pratt_parser, Rc::clone(&symbolic_ids)) + ".into(),"
                            }
                            format!("Color::{}({})", &func, &accum )
                        }

                    },
                    _ => {
                        /* {literal_enum_value | literal_tuple_access | literal_tuple | string } */
                        literal_kind.as_str().to_string()
                    }
                }
            },
            Rule::xo_color_space_func => {
                let mut inner = primary.clone().into_inner();

                //Recurse-pratt-parse the args list for color funcs, a la enums
                let func = primary.as_str().split("(").next().unwrap().to_string();
                let mut accum = "".to_string();

                while let Some(next_pair) = inner.next() {
                    // literal_color_channel = {literal_number_with_unit | literal_number_integer}
                    // while this case is trivial, recurse_pratt_parse is used here to manage literal_number_with_unit without duplicating code here
                    let literal_representation = next_pair.into_inner();
                    accum = accum + &recurse_pratt_parse_to_string(literal_representation, pratt_parser, Rc::clone(&symbolic_ids)) + ".into(),"
                }
                format!("Color::{}({})", &func, &accum )
            },
            Rule::xo_object => {
                let mut output : String = "".to_string();

                let mut inner = primary.into_inner();
                let maybe_identifier = inner.next().unwrap();
                let rule = maybe_identifier.as_rule();

                //for parsing xo_object_settings_key_value_pair
                //iterate over key-value pairs; recurse into expressions
                fn handle_xoskvp<'a>(xoskvp: Pair<Rule>, pratt_parser: &PrattParser<Rule>, symbolic_ids: Rc<RefCell<Vec<String>>>) -> String {
                    let mut inner_kvp = xoskvp.into_inner();
                    let settings_key = inner_kvp.next().unwrap().as_str().to_string();
                    let expression_body = inner_kvp.next().unwrap().into_inner();

                    let ril = recurse_pratt_parse_to_string(expression_body, pratt_parser, Rc::clone(&symbolic_ids));
                    format!("{}: {},\n",settings_key, ril)
                }

                if let Rule::identifier = rule {
                    //explicit type declaration, like `SomeType {...}`
                    unimplemented!("Explicit struct type declarations are not yet supported.  Instead of `SomeType {{ ... }}`, try using simply `{{ ... }}`.");
                } else {
                    //no explicit type declaration, like `{...}`
                    // -- this token is the first k/v pair of object declaration; handle as such
                    let ril = handle_xoskvp(maybe_identifier, pratt_parser, Rc::clone(&symbolic_ids));
                    output += &ril;
                }

                let mut remaining_kvps = inner.into_iter();

                while let Some(xoskkvp) = remaining_kvps.next() {
                    let ril =  handle_xoskvp(xoskkvp, pratt_parser, Rc::clone(&symbolic_ids));
                    output += &ril;
                }

                output
            },
            Rule::xo_symbol => {
                symbolic_ids.borrow_mut().push(primary.as_str().to_string());
                format!("{}",convert_symbolic_binding_from_paxel_to_ril(primary))
            },
            Rule::xo_tuple => {
                let mut tuple = primary.into_inner();
                let exp0 = tuple.next().unwrap();
                let exp1 = tuple.next().unwrap();
                let exp0 = recurse_pratt_parse_to_string( exp0.into_inner(), pratt_parser, Rc::clone(&symbolic_ids));
                let exp1 = recurse_pratt_parse_to_string( exp1.into_inner(), pratt_parser, Rc::clone(&symbolic_ids));
                format!("({}.into(),{}.into())", exp0, exp1)
            },
            Rule::xo_list => {
                let mut list = primary.into_inner();
                let mut vec = Vec::new();

                while let Some(item) = list.next() {
                    let item_str = recurse_pratt_parse_to_string(item.into_inner(), pratt_parser, Rc::clone(&symbolic_ids));
                    vec.push(item_str);
                }
                format!("vec![{}]", vec.join(","))
            },
            Rule::expression_body => {
                recurse_pratt_parse_to_string(primary.into_inner(), pratt_parser, Rc::clone(&symbolic_ids))
            },
            _ => unreachable!("{}",primary.as_str()),
        })
        .map_prefix(|op, rhs| match op.as_rule() {
            Rule::xo_neg => format!("(-{})", rhs),
            Rule::xo_bool_not => format!("(!{})", rhs),
            _ => unreachable!(),
        })
        // .map_postfix(|lhs, op| match op.as_rule() {
        //     Rule::fac => format!("({}!)", lhs),
        //     _ => unreachable!(),
        // })
        .map_infix(|lhs, op, rhs| match op.as_rule() {
            Rule::xo_add => {format!("({}+{})", lhs, rhs)},
            Rule::xo_bool_and => {format!("({}&&{})", lhs, rhs)},
            Rule::xo_bool_or => {format!("({}||{})", lhs, rhs)},
            Rule::xo_div => {format!("({}/{})", lhs, rhs)},
            Rule::xo_exp => {format!("(({}).pow({}))", lhs, rhs)},
            Rule::xo_mod => {format!("({}%{})", lhs, rhs)},
            Rule::xo_mul => {format!("({}*{})", lhs, rhs)},
            Rule::xo_rel_eq => {format!("({}=={})", lhs, rhs)},
            Rule::xo_rel_gt => {format!("({}>{})", lhs, rhs)},
            Rule::xo_rel_gte => {format!("({}>={})", lhs, rhs)},
            Rule::xo_rel_lt => {format!("({}<{})", lhs, rhs)},
            Rule::xo_rel_lte => {format!("({}<={})", lhs, rhs)},
            Rule::xo_rel_neq => {format!("({}!={})", lhs, rhs)},
            Rule::xo_sub => {format!("({}-{})", lhs, rhs)},
            Rule::xo_tern_then => {format!("if {} {{ {} }}", lhs, rhs)},
            Rule::xo_tern_else => {format!("{} else {{ {} }}", lhs, rhs)},
            _ => unreachable!(),
        })
        .parse(expression)
}

pub fn parse_template_from_component_definition_string(
    ctx: &mut TemplateNodeParseContext,
    pax: &str,
) {
    let pax_component_definition = PaxParser::parse(Rule::pax_component_definition, pax)
        .expect(&format!("unsuccessful parse from {}", &pax)) // unwrap the parse result
        .next()
        .unwrap(); // get and unwrap the `pax_component_definition` rule

    pax_component_definition
        .into_inner()
        .for_each(|pair| match pair.as_rule() {
            Rule::root_tag_pair => {
                recurse_visit_tag_pairs_for_template(
                    ctx,
                    pair.into_inner().next().unwrap(),
                    pax,
                    TreeLocation::Root,
                );
            }
            _ => {}
        });
}

pub struct TemplateNodeParseContext {
    pub template: ComponentTemplate,
    pub pascal_identifier_to_type_id_map: HashMap<String, TypeId>,
}

fn recurse_visit_tag_pairs_for_template(
    ctx: &mut TemplateNodeParseContext,
    any_tag_pair: Pair<Rule>,
    pax: &str,
    location: TreeLocation,
) {
    match any_tag_pair.as_rule() {
        Rule::matched_tag => {
            //matched_tag => open_tag > pascal_identifier
            let matched_tag = any_tag_pair;
            let mut open_tag = matched_tag
                .clone()
                .into_inner()
                .next()
                .unwrap()
                .into_inner();
            let pascal_identifier = open_tag.next().unwrap().as_str();

            let template_node = TemplateNodeDefinition {
                type_id: TypeId::build_singleton(
                    &ctx.pascal_identifier_to_type_id_map
                        .get(pascal_identifier)
                        .expect(&format!("Template key not found {}", &pascal_identifier))
                        .to_string(),
                    Some(&pascal_identifier.to_string()),
                ),
                settings: parse_inline_attribute_from_final_pairs_of_tag(open_tag, pax),
                raw_comment_string: None,
                control_flow_settings: None,
            };

            let id = match location {
                TreeLocation::Root => ctx.template.add_root_node_back(template_node),
                TreeLocation::Parent(id) => ctx.template.add_child_back(id, template_node),
            };

            //recurse into inner_nodes
            let prospective_inner_nodes = matched_tag.into_inner().nth(1).unwrap();
            match prospective_inner_nodes.as_rule() {
                Rule::inner_nodes => {
                    let inner_nodes = prospective_inner_nodes;
                    inner_nodes.into_inner().for_each(|sub_tag_pair| {
                        recurse_visit_tag_pairs_for_template(
                            ctx,
                            sub_tag_pair,
                            pax,
                            TreeLocation::Parent(id.clone().get_template_node_id()),
                        );
                    })
                }
                _ => {
                    panic!("wrong prospective inner nodes (or nth)")
                }
            }
        }
        Rule::self_closing_tag => {
            let mut tag_pairs = any_tag_pair.into_inner();
            let pascal_identifier = tag_pairs.next().unwrap().as_str();

            let type_id = if let Some(type_id) =
                ctx.pascal_identifier_to_type_id_map.get(pascal_identifier)
            {
                type_id.clone()
            } else {
                TypeId::build_blank_component(pascal_identifier)
            };
            let template_node = TemplateNodeDefinition {
                type_id,
                settings: parse_inline_attribute_from_final_pairs_of_tag(tag_pairs, pax),
                raw_comment_string: None,
                control_flow_settings: None,
            };
            let _ = match location {
                TreeLocation::Root => ctx.template.add_root_node_back(template_node),
                TreeLocation::Parent(id) => ctx.template.add_child_back(id, template_node),
            };
        }
        Rule::statement_control_flow => {
            /* statement_control_flow = {(statement_if | statement_for | statement_slot)} */

            let any_tag_pair = any_tag_pair.into_inner().next().unwrap();
            let _template_node_definition = match any_tag_pair.as_rule() {
                Rule::statement_if => {
                    let mut statement_if = any_tag_pair.into_inner();
                    let expression_body = statement_if.next().unwrap();
                    let expression_body_location = span_to_location(&expression_body.as_span());
                    let expression_body_token = Token::new(
                        expression_body.as_str().to_string(),
                        TokenType::IfExpression,
                        expression_body_location,
                        pax,
                    );

                    //`if` TemplateNodeDefinition
                    let template_node = TemplateNodeDefinition {
                        control_flow_settings: Some(ControlFlowSettingsDefinition {
                            condition_expression_paxel: Some(expression_body_token),
                            condition_expression_info: None, //This will be written back to this data structure later, during expression compilation
                            slot_index_expression_paxel: None,
                            slot_index_expression_info: None,
                            repeat_predicate_definition: None,
                            repeat_source_definition: None,
                        }),
                        type_id: TypeId::build_if(),
                        settings: None,
                        raw_comment_string: None,
                    };

                    let id = match location {
                        TreeLocation::Root => ctx.template.add_root_node_back(template_node),
                        TreeLocation::Parent(id) => ctx.template.add_child_back(id, template_node),
                    };

                    let prospective_inner_nodes = statement_if.next();

                    if let Some(inner_nodes) = prospective_inner_nodes {
                        inner_nodes.into_inner().for_each(|sub_tag_pair| {
                            recurse_visit_tag_pairs_for_template(
                                ctx,
                                sub_tag_pair,
                                pax,
                                TreeLocation::Parent(id.clone().get_template_node_id()),
                            );
                        })
                    }
                }
                Rule::statement_for => {
                    let mut cfavd = ControlFlowSettingsDefinition::default();
                    let mut for_statement = any_tag_pair.clone().into_inner();
                    let mut predicate_declaration = for_statement.next().unwrap().into_inner();
                    let source = for_statement.next().unwrap();

                    let prospective_inner_nodes = for_statement.next();

                    if predicate_declaration.clone().count() > 1 {
                        //tuple, like the `elem, i` in `for (elem, i) in self.some_list`
                        let elem = predicate_declaration.next().unwrap();
                        let elem_location = span_to_location(&elem.as_span());
                        let elem_token = Token::new(
                            elem.as_str().to_string(),
                            TokenType::ForPredicate,
                            elem_location,
                            pax,
                        );
                        let index = predicate_declaration.next().unwrap();
                        let index_location = span_to_location(&index.as_span());
                        let index_token = Token::new(
                            index.as_str().to_string(),
                            TokenType::ForPredicate,
                            index_location,
                            pax,
                        );
                        cfavd.repeat_predicate_definition =
                            Some(ControlFlowRepeatPredicateDefinition::ElemIdIndexId(
                                elem_token,
                                index_token,
                            ));
                    } else {
                        let elem = predicate_declaration.next().unwrap();
                        //single identifier, like the `elem` in `for elem in self.some_list`
                        let predicate_declaration_location = span_to_location(&elem.as_span());
                        let predicate_declaration_token = Token::new(
                            elem.as_str().to_string(),
                            TokenType::ForPredicate,
                            predicate_declaration_location,
                            pax,
                        );
                        cfavd.repeat_predicate_definition =
                            Some(ControlFlowRepeatPredicateDefinition::ElemId(
                                predicate_declaration_token,
                            ));
                    }

                    let inner_source = source.into_inner().next().unwrap();
                    let inner_source_location = span_to_location(&inner_source.as_span());
                    let mut inner_source_token = Token::new(
                        inner_source.as_str().to_string(),
                        TokenType::ForSource,
                        inner_source_location,
                        pax,
                    );
                    /* statement_for_source = { xo_range | xo_symbol } */
                    let repeat_source_definition = match inner_source.as_rule() {
                        Rule::xo_range => {
                            let mut inner = inner_source.into_inner();
                            let left = inner.next().unwrap();
                            //skip middle
                            inner.next();
                            let right = inner.next().unwrap();
                            let mut range_symbolic_bindings = vec![];
                            if matches!(left.as_rule(), Rule::xo_symbol) {
                                let inner_source_location = span_to_location(&left.as_span());
                                let left_range_token = Token::new(
                                    convert_symbolic_binding_from_paxel_to_ril(left),
                                    TokenType::ForSource,
                                    inner_source_location,
                                    pax,
                                );
                                range_symbolic_bindings.push(left_range_token);
                            }
                            if matches!(right.as_rule(), Rule::xo_symbol) {
                                let inner_source_location = span_to_location(&right.as_span());
                                let left_range_token = Token::new(
                                    convert_symbolic_binding_from_paxel_to_ril(right),
                                    TokenType::ForSource,
                                    inner_source_location,
                                    pax,
                                );
                                range_symbolic_bindings.push(left_range_token);
                            }
                            ControlFlowRepeatSourceDefinition {
                                range_expression_paxel: Some(inner_source_token),
                                range_symbolic_bindings,
                                expression_info: None, //This will be written back to this data structure later, during expression compilation
                                symbolic_binding: None,
                            }
                        }
                        Rule::xo_symbol => {
                            inner_source_token.token_value =
                                convert_symbolic_binding_from_paxel_to_ril(inner_source);
                            ControlFlowRepeatSourceDefinition {
                                range_expression_paxel: None,
                                range_symbolic_bindings: vec![],
                                expression_info: None,
                                symbolic_binding: Some(inner_source_token),
                            }
                        }
                        _ => {
                            unreachable!()
                        }
                    };

                    cfavd.repeat_source_definition = Some(repeat_source_definition);

                    //`for` TemplateNodeDefinition
                    let template_node = TemplateNodeDefinition {
                        type_id: TypeId::build_repeat(),
                        control_flow_settings: Some(cfavd),
                        settings: None,
                        raw_comment_string: None,
                    };

                    let id = match location {
                        TreeLocation::Root => ctx.template.add_root_node_back(template_node),
                        TreeLocation::Parent(id) => ctx.template.add_child_back(id, template_node),
                    };

                    if let Some(inner_nodes) = prospective_inner_nodes {
                        inner_nodes.into_inner().for_each(|sub_tag_pair| {
                            recurse_visit_tag_pairs_for_template(
                                ctx,
                                sub_tag_pair,
                                pax,
                                TreeLocation::Parent(id.clone().get_template_node_id()),
                            );
                        })
                    }
                }
                Rule::statement_slot => {
                    let mut statement_slot = any_tag_pair.into_inner();
                    let expression_body = statement_slot.next().unwrap();
                    let expression_body_location = span_to_location(&expression_body.as_span());
                    let expression_body_token = Token::new(
                        expression_body.as_str().to_string(),
                        TokenType::SlotExpression,
                        expression_body_location,
                        pax,
                    );
                    let prospective_inner_nodes = statement_slot.next();

                    let template_node = TemplateNodeDefinition {
                        control_flow_settings: Some(ControlFlowSettingsDefinition {
                            condition_expression_paxel: None,
                            condition_expression_info: None,
                            slot_index_expression_paxel: Some(expression_body_token),
                            slot_index_expression_info: None, //This will be written back to this data structure later, during expression compilation
                            repeat_predicate_definition: None,
                            repeat_source_definition: None,
                        }),
                        type_id: TypeId::build_slot(),
                        settings: None,
                        raw_comment_string: None,
                    };

                    let id = match location {
                        TreeLocation::Root => ctx.template.add_root_node_back(template_node),
                        TreeLocation::Parent(id) => ctx.template.add_child_back(id, template_node),
                    };

                    if let Some(inner_nodes) = prospective_inner_nodes {
                        inner_nodes.into_inner().for_each(|sub_tag_pair| {
                            recurse_visit_tag_pairs_for_template(
                                ctx,
                                sub_tag_pair,
                                pax,
                                TreeLocation::Parent(id.clone().get_template_node_id()),
                            );
                        })
                    }
                }
                _ => {
                    unreachable!("Parsing error: {:?}", any_tag_pair.as_rule());
                }
            };
        }
        Rule::comment => {
            let template_node = TemplateNodeDefinition {
                control_flow_settings: None,
                type_id: TypeId::build_comment(),
                settings: None,
                raw_comment_string: Some(any_tag_pair.as_str().to_string()),
            };
            let _ = match location {
                TreeLocation::Root => ctx.template.add_root_node_back(template_node),
                TreeLocation::Parent(id) => ctx.template.add_child_back(id, template_node),
            };
        }
        Rule::node_inner_content => {
            //For example:  `<Text>"I am inner content"</Text>`
            unimplemented!("Inner content not yet supported");
        }
        _ => {
            unreachable!("Parsing error: {:?}", any_tag_pair.as_rule());
        }
    }
}

fn parse_literal_function(literal_function_full: Pair<Rule>, pax: &str) -> Token {
    let literal_function = literal_function_full.clone().into_inner().next().unwrap();

    let location_info = span_to_location(&literal_function.as_span());
    let literal_function_token = Token::new_with_raw_value(
        literal_function.as_str().to_string(),
        literal_function_full.as_str().to_string().replace(",", ""),
        TokenType::Handler,
        location_info,
        pax,
    );
    literal_function_token
}

fn parse_event_id(event_id_full: Pair<Rule>, pax: &str) -> Token {
    let event_id = event_id_full.clone().into_inner().next().unwrap();

    let event_id_location = span_to_location(&event_id.as_span());
    let event_id_token = Token::new_with_raw_value(
        event_id.as_str().to_string(),
        event_id_full.as_str().to_string(),
        TokenType::EventId,
        event_id_location,
        pax,
    );
    event_id_token
}

fn parse_inline_attribute_from_final_pairs_of_tag(
    final_pairs_of_tag: Pairs<Rule>,
    pax: &str,
) -> Option<Vec<SettingElement>> {
    let vec: Vec<SettingElement> = final_pairs_of_tag
        .map(|attribute_key_value_pair| {
            match attribute_key_value_pair
                .clone()
                .into_inner()
                .next()
                .unwrap()
                .as_rule()
            {
                Rule::attribute_event_binding => {
                    // attribute_event_binding = {event_id ~ "=" ~ literal_function}
                    let mut kv = attribute_key_value_pair.into_inner();
                    let mut attribute_event_binding = kv.next().unwrap().into_inner();

                    let event_id_token =
                        parse_event_id(attribute_event_binding.next().unwrap(), pax);

                    let literal_function_token =
                        parse_literal_function(attribute_event_binding.next().unwrap(), pax);
                    SettingElement::Setting(
                        event_id_token,
                        ValueDefinition::EventBindingTarget(literal_function_token),
                    )
                }
                Rule::id_binding => {
                    let mut kv = attribute_key_value_pair
                        .into_inner()
                        .next()
                        .unwrap()
                        .into_inner();
                    let id_binding_key = kv.next().unwrap();
                    let id_binding_key_location = span_to_location(&id_binding_key.as_span());
                    let id_binding_key_token = Token::new(
                        id_binding_key.as_str().to_string(),
                        TokenType::SettingKey,
                        id_binding_key_location,
                        pax,
                    );
                    let id_binding_value = kv.next().unwrap();
                    let id_binding_value_location = span_to_location(&id_binding_value.as_span());
                    let id_binding_value_token = Token::new(
                        id_binding_value.as_str().to_string(),
                        TokenType::LiteralValue,
                        id_binding_value_location,
                        pax,
                    );
                    SettingElement::Setting(
                        id_binding_key_token,
                        ValueDefinition::LiteralValue(id_binding_value_token),
                    )
                }
                _ => {
                    //Vanilla `key=value` setting pair

                    let mut kv = attribute_key_value_pair.into_inner();
                    let key = kv.next().unwrap();
                    let key_location = span_to_location(&key.as_span());
                    let key_token = Token::new(
                        key.as_str().to_string(),
                        TokenType::SettingKey,
                        key_location,
                        pax,
                    );
                    // exact tokens used, includes {} from expression wrapped
                    let raw_value = kv.peek().unwrap().as_str();
                    let value = kv.next().unwrap().into_inner().next().unwrap();
                    let location_info = span_to_location(&value.as_span());
                    let value_definition = match value.as_rule() {
                        Rule::literal_value => {
                            //we want to pratt-parse literals, mostly to unpack `px` and `%` (recursively)
                            let (output_string, _) =
                                crate::parsing::run_pratt_parser(value.as_str());
                            let literal_value_token = Token::new_with_raw_value(
                                output_string,
                                raw_value.to_string(),
                                TokenType::LiteralValue,
                                location_info,
                                pax,
                            );
                            ValueDefinition::LiteralValue(literal_value_token)
                        }
                        Rule::literal_object => ValueDefinition::Block(
                            derive_value_definition_from_literal_object_pair(value, pax),
                        ),
                        Rule::expression_body => {
                            let expression_token = Token::new_with_raw_value(
                                value.as_str().to_string(),
                                raw_value.to_string(),
                                TokenType::Expression,
                                location_info,
                                pax,
                            );
                            ValueDefinition::Expression(expression_token, None)
                        }
                        Rule::identifier => {
                            let identifier_token = Token::new(
                                value.as_str().to_string(),
                                TokenType::Identifier,
                                location_info,
                                pax,
                            );
                            ValueDefinition::Identifier(identifier_token, None)
                        }
                        _ => {
                            unreachable!("Parsing error 3342638857230: {:?}", value.as_rule());
                        }
                    };
                    SettingElement::Setting(key_token, value_definition)
                }
            }
        })
        .collect();

    if vec.len() > 0 {
        Some(vec)
    } else {
        None
    }
}

fn derive_value_definition_from_literal_object_pair(
    literal_object: Pair<Rule>,
    pax: &str,
) -> LiteralBlockDefinition {
    let mut literal_object_pairs = literal_object.into_inner();

    if let None = literal_object_pairs.peek() {
        return LiteralBlockDefinition {
            explicit_type_pascal_identifier: None,
            elements: vec![],
        };
    }

    let explicit_type_pascal_identifier = match literal_object_pairs.peek().unwrap().as_rule() {
        Rule::pascal_identifier => {
            let raw_value = literal_object_pairs.next().unwrap();
            let raw_value_location = span_to_location(&raw_value.as_span());
            let token = Token::new(
                raw_value.as_str().to_string(),
                TokenType::PascalIdentifier,
                raw_value_location,
                pax,
            );
            Some(token)
        }
        _ => None,
    };

    LiteralBlockDefinition {
        explicit_type_pascal_identifier,
        elements: literal_object_pairs
            .map(|settings_key_value_pair| {
                match settings_key_value_pair.as_rule() {
                    Rule::settings_key_value_pair => {
                        let mut pairs = settings_key_value_pair.into_inner();

                        let setting_key = pairs.next().unwrap().into_inner().next().unwrap();
                        let setting_key_location = span_to_location(&setting_key.as_span());
                        let setting_key_token = Token::new(
                            setting_key.as_str().to_string(),
                            TokenType::SettingKey,
                            setting_key_location,
                            pax,
                        );
                        let raw_value = pairs.peek().unwrap().as_str();
                        let value = pairs.next().unwrap().into_inner().next().unwrap();
                        let location_info = span_to_location(&value.as_span());
                        let setting_value_definition = match value.as_rule() {
                            Rule::literal_value => {
                                //we want to pratt-parse literals, mostly to unpack `px` and `%` (recursively)
                                let (output_string, _) =
                                    crate::parsing::run_pratt_parser(value.as_str());
                                let token = Token::new_with_raw_value(
                                    output_string,
                                    raw_value.to_string(),
                                    TokenType::LiteralValue,
                                    location_info,
                                    pax,
                                );
                                ValueDefinition::LiteralValue(token)
                            }
                            Rule::literal_object => {
                                ValueDefinition::Block(
                                    //Recurse
                                    derive_value_definition_from_literal_object_pair(value, pax),
                                )
                            }
                            // Rule::literal_enum_value => {ValueDefinition::Enum(raw_value.as_str().to_string())},
                            Rule::expression_body => {
                                let token = Token::new_with_raw_value(
                                    value.as_str().to_string(),
                                    raw_value.to_string(),
                                    TokenType::Expression,
                                    location_info,
                                    pax,
                                );
                                ValueDefinition::Expression(token, None)
                            }
                            _ => {
                                unreachable!("Parsing error 231453468: {:?}", value.as_rule());
                            }
                        };

                        SettingElement::Setting(setting_key_token, setting_value_definition)
                    }
                    Rule::comment => {
                        let comment = settings_key_value_pair.as_str().to_string();
                        SettingElement::Comment(comment)
                    }
                    _ => {
                        unreachable!(
                            "Parsing error 2314314145: {:?}",
                            settings_key_value_pair.as_rule()
                        );
                    }
                }
            })
            .collect(),
    }
}

pub fn parse_settings_from_component_definition_string(pax: &str) -> Vec<SettingsBlockElement> {
    let pax_component_definition = PaxParser::parse(Rule::pax_component_definition, pax)
        .expect(&format!("unsuccessful parse from {}", &pax)) // unwrap the parse result
        .next()
        .unwrap(); // get and unwrap the `pax_component_definition` rule

    let mut settings: Vec<SettingsBlockElement> = vec![];

    pax_component_definition
        .into_inner()
        .for_each(|top_level_pair| {
            match top_level_pair.as_rule() {
                Rule::settings_block_declaration => {
                    top_level_pair
                        .into_inner()
                        .for_each(|top_level_settings_block_entity| {
                            match top_level_settings_block_entity.as_rule() {
                                Rule::settings_event_binding => {
                                    //event handler binding in the form of `@pre_render: handle_pre_render`
                                    let mut settings_event_binding_pairs =
                                        top_level_settings_block_entity.into_inner();
                                    let event_id_token = parse_event_id(
                                        settings_event_binding_pairs.next().unwrap(),
                                        pax,
                                    );
                                    let literal_function_token = parse_literal_function(
                                        settings_event_binding_pairs.next().unwrap(),
                                        pax,
                                    );
                                    let handler_element: SettingsBlockElement =
                                        SettingsBlockElement::Handler(
                                            event_id_token,
                                            vec![literal_function_token],
                                        );
                                    settings.push(handler_element);
                                }
                                Rule::selector_block => {
                                    //selector_block => settings_key_value_pair where v is a ValueDefinition
                                    let mut selector_block_pairs =
                                        top_level_settings_block_entity.into_inner();
                                    //first pair is the selector itself
                                    let raw_selector = selector_block_pairs.next().unwrap();
                                    let raw_value_location =
                                        span_to_location(&raw_selector.as_span());
                                    let selector: String = raw_selector
                                        .as_str()
                                        .chars()
                                        .filter(|c| !c.is_whitespace())
                                        .collect();
                                    let token = Token::new(
                                        selector,
                                        TokenType::Selector,
                                        raw_value_location,
                                        pax,
                                    );
                                    let literal_object = selector_block_pairs.next().unwrap();

                                    settings.push(SettingsBlockElement::SelectorBlock(
                                        token,
                                        derive_value_definition_from_literal_object_pair(
                                            literal_object,
                                            pax,
                                        ),
                                    ));
                                }
                                Rule::comment => {
                                    let comment =
                                        top_level_settings_block_entity.as_str().to_string();
                                    settings.push(SettingsBlockElement::Comment(comment));
                                }
                                _ => {
                                    unreachable!(
                                        "Parsing error: {:?}",
                                        top_level_settings_block_entity.as_rule()
                                    );
                                }
                            }
                        });
                }
                _ => {}
            }
        });
    settings
}

pub struct ParsingContext {
    /// Used to track which files/sources have been visited during parsing,
    /// to prevent duplicate parsing
    pub visited_type_ids: HashSet<TypeId>,

    pub main_component_type_id: TypeId,

    pub component_definitions: HashMap<TypeId, ComponentDefinition>,

    pub template_map: HashMap<String, TypeId>,

    pub template_node_definitions: ComponentTemplate,

    pub type_table: TypeTable,

    pub import_paths: HashSet<String>,
}

impl Default for ParsingContext {
    fn default() -> Self {
        Self {
            main_component_type_id: TypeId::default(),
            visited_type_ids: HashSet::new(),
            component_definitions: HashMap::new(),
            template_map: HashMap::new(),
            type_table: get_primitive_type_table(),
            template_node_definitions: ComponentTemplate::default(),
            import_paths: HashSet::new(),
        }
    }
}

#[derive(Debug)]
pub struct ParsingError {
    pub error_name: String,
    pub error_message: String,
    pub matched_string: String,
    pub start: (usize, usize),
    pub end: (usize, usize),
}

/// Extract all errors from a Pax parse result
pub fn extract_errors(pairs: pest::iterators::Pairs<Rule>) -> Vec<ParsingError> {
    let mut errors = vec![];

    for pair in pairs {
        let error = match pair.as_rule() {
            Rule::block_level_error => Some((
                format!("{:?}", pair.as_rule()),
                "Unexpected template structure encountered.".to_string(),
            )),
            Rule::attribute_key_value_pair_error => Some((
                format!("{:?}", pair.as_rule()),
                "Attribute key-value pair is malformed.".to_string(),
            )),
            Rule::inner_tag_error => Some((
                format!("{:?}", pair.as_rule()),
                "Inner tag doesn't match any expected format.".to_string(),
            )),
            Rule::selector_block_error => Some((
                format!("{:?}", pair.as_rule()),
                "Selector block structure is not well-defined.".to_string(),
            )),
            Rule::expression_body_error => Some((
                format!("{:?}", pair.as_rule()),
                "Expression inside curly braces is not well defined.".to_string(),
            )),
            Rule::open_tag_error => Some((
                format!("{:?}", pair.as_rule()),
                "Open tag is malformed".to_string(),
            )),
            Rule::tag_error => Some((
                format!("{:?}", pair.as_rule()),
                "Tag structure is unexpected.".to_string(),
            )),
            _ => None,
        };
        if let Some((error_name, error_message)) = error {
            let span = pair.as_span();
            let ((line_start, start_col), (line_end, end_col)) =
                (pair.line_col(), span.end_pos().line_col());
            let error = ParsingError {
                error_name,
                error_message,
                matched_string: span.as_str().to_string(),
                start: (line_start, start_col),
                end: (line_end, end_col),
            };
            errors.push(error);
        }
        errors.extend(extract_errors(pair.into_inner()));
    }

    errors
}

/// From a raw string of Pax representing a single component, parse a complete ComponentDefinition
pub fn assemble_component_definition(
    mut ctx: ParsingContext,
    pax: &str,
    is_main_component: bool,
    template_map: HashMap<String, TypeId>,
    module_path: &str,
    self_type_id: TypeId,
    component_source_file_path: &str,
) -> (ParsingContext, ComponentDefinition) {
    let _ast = PaxParser::parse(Rule::pax_component_definition, pax)
        .expect(&format!("unsuccessful parse from {}", &pax)) // unwrap the parse result
        .next()
        .unwrap(); // get and unwrap the `pax_component_definition` rule

    let errors = extract_errors(_ast.clone().into_inner());
    if !errors.is_empty() {
        let mut error_messages = String::new();

        for error in &errors {
            let msg = format!(
                "error: {}\n   --> {}:{}\n    |\n{}  | {}\n    |{}\n\n",
                error.error_message,
                error.start.0,
                error.start.1,
                error.start.0,
                error.matched_string,
                "^".repeat(error.matched_string.len())
            );
            error_messages.push_str(&msg);
        }

        panic!("{}", error_messages);
    }

    if is_main_component {
        ctx.main_component_type_id = self_type_id.clone();
    }

    let mut tpc = TemplateNodeParseContext {
        pascal_identifier_to_type_id_map: template_map,
        template: ComponentTemplate::new(
            self_type_id.clone(),
            Some(component_source_file_path.to_owned()),
        ),
    };

    parse_template_from_component_definition_string(&mut tpc, pax);
    let modified_module_path = if module_path.starts_with("parser") {
        module_path.replacen("parser", "crate", 1)
    } else {
        module_path.to_string()
    };

    //populate template_node_definitions vec, needed for traversing node tree at codegen-time
    ctx.template_node_definitions = tpc.template.clone();

    let settings = parse_settings_from_component_definition_string(pax);

    let new_def = ComponentDefinition {
        is_primitive: false,
        is_struct_only_component: false,
        is_main_component,
        primitive_instance_import_path: None,
        type_id: self_type_id,
        template: Some(tpc.template),
        settings: Some(settings),
        module_path: modified_module_path,
    };

    (ctx, new_def)
}

pub fn clean_module_path(module_path: &str) -> String {
    if module_path.starts_with("parser") {
        module_path.replacen("parser", "crate", 1)
    } else {
        module_path.to_string()
    }
}

pub fn assemble_struct_only_component_definition(
    ctx: ParsingContext,
    module_path: &str,
    self_type_id: TypeId,
) -> (ParsingContext, ComponentDefinition) {
    let modified_module_path = clean_module_path(module_path);

    let new_def = ComponentDefinition {
        type_id: self_type_id,
        is_main_component: false,
        is_primitive: false,
        is_struct_only_component: true,
        module_path: modified_module_path,
        primitive_instance_import_path: None,
        template: None,
        settings: None,
    };
    (ctx, new_def)
}

pub fn assemble_primitive_definition(
    module_path: &str,
    primitive_instance_import_path: String,
    self_type_id: TypeId,
) -> ComponentDefinition {
    let modified_module_path = clean_module_path(module_path);

    ComponentDefinition {
        is_primitive: true,
        is_struct_only_component: false,
        primitive_instance_import_path: Some(primitive_instance_import_path),
        is_main_component: false,
        type_id: self_type_id,
        template: None,
        settings: None,
        module_path: modified_module_path,
    }
}

pub fn assemble_type_definition(
    mut ctx: ParsingContext,
    property_definitions: Vec<PropertyDefinition>,
    inner_iterable_type_id: Option<TypeId>,
    self_type_id: TypeId,
) -> (ParsingContext, TypeDefinition) {
    let new_def = TypeDefinition {
        type_id: self_type_id.clone(),
        inner_iterable_type_id,
        property_definitions,
    };

    ctx.type_table.insert(self_type_id, new_def.clone());

    (ctx, new_def)
}

/// Given a Pest Span returns starting and ending (line,col)
fn span_to_location(span: &Span) -> LocationInfo {
    let start = (
        span.start_pos().line_col().0 - 1,
        span.start_pos().line_col().1 - 1,
    );
    let end = (
        span.end_pos().line_col().0 - 1,
        span.end_pos().line_col().1 - 1,
    );
    LocationInfo {
        start_line_col: start,
        end_line_col: end,
    }
}

/// This trait is used only to extend primitives like u64
/// with the parser-time method `parse_to_manifest`.  This
/// allows the parser binary to codegen calls to `::parse_to_manifest()` even
/// on primitive types
pub trait Reflectable {
    fn parse_to_manifest(mut ctx: ParsingContext) -> (ParsingContext, Vec<PropertyDefinition>) {
        //Default impl for primitives and pax_runtime::api
        let type_id = Self::get_type_id();
        let td = TypeDefinition {
            type_id: type_id.clone(),
            inner_iterable_type_id: None,
            property_definitions: vec![],
        };

        if !ctx.type_table.contains_key(&type_id) {
            ctx.type_table.insert(type_id, td);
        }

        (ctx, vec![])
    }

    ///The import path is the fully namespace-qualified path for a type, like `std::vec::Vec`
    ///This is distinct from type_id ONLY when the type has generics, like Vec, where
    ///the type_id is distinct across a Vec<Foo> and a Vec<Bar>.  In both cases of Vec,
    ///the import_path will remain the same.
    fn get_import_path() -> String {
        //This default is used by primitives but expected to
        //be overridden by userland Pax components / primitives
        Self::get_self_pascal_identifier()
    }

    fn get_self_pascal_identifier() -> String;

    fn get_type_id() -> TypeId;

    fn get_iterable_type_id() -> Option<TypeId> {
        //Most types do not have an iterable type (e.g. the T in Vec<T>) —
        //it is the responsibility of iterable types to override this fn
        None
    }
}

impl Reflectable for usize {
    fn get_self_pascal_identifier() -> String {
        "usize".to_string()
    }

    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for isize {
    fn get_self_pascal_identifier() -> String {
        "isize".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for i128 {
    fn get_self_pascal_identifier() -> String {
        "i128".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for u128 {
    fn get_self_pascal_identifier() -> String {
        "u128".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for i64 {
    fn get_self_pascal_identifier() -> String {
        "i64".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for u64 {
    fn get_self_pascal_identifier() -> String {
        "u64".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for i32 {
    fn get_self_pascal_identifier() -> String {
        "i32".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for u32 {
    fn get_self_pascal_identifier() -> String {
        "u32".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for i8 {
    fn get_self_pascal_identifier() -> String {
        "i8".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for u8 {
    fn get_self_pascal_identifier() -> String {
        "u8".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for f64 {
    fn get_self_pascal_identifier() -> String {
        "f64".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for f32 {
    fn get_self_pascal_identifier() -> String {
        "f32".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for bool {
    fn get_self_pascal_identifier() -> String {
        "bool".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_primitive(&Self::get_self_pascal_identifier())
    }
}
impl Reflectable for std::string::String {
    fn get_import_path() -> String {
        "std::string::String".to_string()
    }
    fn get_self_pascal_identifier() -> String {
        "String".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        )
    }
}
impl<T> Reflectable for std::rc::Rc<T> {
    fn get_import_path() -> String {
        "std::rc::Rc".to_string()
    }
    fn get_self_pascal_identifier() -> String {
        "Rc".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        )
    }
}

impl<T: Reflectable> Reflectable for std::option::Option<T> {
    fn parse_to_manifest(mut ctx: ParsingContext) -> (ParsingContext, Vec<PropertyDefinition>) {
        let type_id = Self::get_type_id();
        let td = TypeDefinition {
            type_id: type_id.clone(),
            inner_iterable_type_id: None,
            property_definitions: vec![],
        };

        if !ctx.type_table.contains_key(&type_id) {
            ctx.type_table.insert(type_id, td);
        }

        let (ctx, _) = T::parse_to_manifest(ctx);
        (ctx, vec![]) //Option itself has no PAXEL-addressable properties
    }
    fn get_import_path() -> String {
        "std::option::Option".to_string()
    }
    fn get_self_pascal_identifier() -> String {
        "Option".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_option(&format!("{}{}", "{PREFIX}", &T::get_type_id()))
    }
}

impl Reflectable for TypeId {
    fn get_import_path() -> String {
        "pax_manifest::TypeId".to_string()
    }

    fn get_self_pascal_identifier() -> String {
        "TypeId".to_string()
    }

    fn get_type_id() -> TypeId {
        TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        )
    }
}

impl Reflectable for TemplateNodeId {
    fn get_import_path() -> String {
        "pax_manifest::TemplateNodeId".to_string()
    }

    fn get_self_pascal_identifier() -> String {
        "TemplateNodeId".to_string()
    }

    fn get_type_id() -> TypeId {
        TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        )
    }
}

impl Reflectable for pax_runtime::api::Size {
    fn get_import_path() -> String {
        "pax_engine::api::Size".to_string()
    }

    fn get_self_pascal_identifier() -> String {
        "Size".to_string()
    }

    fn get_type_id() -> TypeId {
        TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        )
    }
}

impl Reflectable for pax_runtime::api::Color {
    fn get_import_path() -> String {
        "pax_engine::api::Color".to_string()
    }

    fn get_self_pascal_identifier() -> String {
        "Color".to_string()
    }

    fn get_type_id() -> TypeId {
        TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        )
    }
}

impl Reflectable for pax_runtime::api::ColorChannel {
    fn get_import_path() -> String {
        "pax_engine::api::ColorChannel".to_string()
    }

    fn get_self_pascal_identifier() -> String {
        "ColorChannel".to_string()
    }

    fn get_type_id() -> TypeId {
        TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        )
    }
}

impl Reflectable for pax_runtime::api::Rotation {
    fn get_import_path() -> String {
        "pax_engine::api::Rotation".to_string()
    }

    fn get_self_pascal_identifier() -> String {
        "Rotation".to_string()
    }
    fn get_type_id() -> TypeId {
        let type_id = TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        );

        type_id
    }
}

impl Reflectable for pax_runtime::api::Numeric {
    fn get_import_path() -> String {
        "pax_engine::api::Numeric".to_string()
    }

    fn get_self_pascal_identifier() -> String {
        "Numeric".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        )
    }
}

impl Reflectable for kurbo::Point {
    fn get_import_path() -> String {
        "kurbo::Point".to_string()
    }

    fn get_self_pascal_identifier() -> String {
        "Point".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        )
    }
}

impl Reflectable for pax_runtime::api::Transform2D {
    fn get_import_path() -> String {
        "pax_engine::api::Transform2D".to_string()
    }

    fn get_self_pascal_identifier() -> String {
        "Transform2D".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        )
    }
}

impl Reflectable for pax_runtime::api::StringBox {
    fn get_import_path() -> String {
        "pax_engine::api::StringBox".to_string()
    }
    fn get_self_pascal_identifier() -> String {
        "StringBox".to_string()
    }
    fn get_type_id() -> TypeId {
        TypeId::build_singleton(
            &Self::get_import_path(),
            Some(&Self::get_self_pascal_identifier()),
        )
    }
}

impl<T: Reflectable> Reflectable for std::vec::Vec<T> {
    fn parse_to_manifest(mut ctx: ParsingContext) -> (ParsingContext, Vec<PropertyDefinition>) {
        let type_id = Self::get_type_id();
        let td = TypeDefinition {
            type_id: type_id.clone(),
            inner_iterable_type_id: Self::get_iterable_type_id(),
            property_definitions: vec![],
        };

        if !ctx.type_table.contains_key(&type_id) {
            ctx.type_table.insert(type_id, td);
        }

        // Also parse iterable type
        T::parse_to_manifest(ctx)
    }
    fn get_import_path() -> String {
        "std::vec::Vec".to_string()
    }
    fn get_self_pascal_identifier() -> String {
        "Vec".to_string()
    }
    fn get_type_id() -> TypeId {
        //Need to encode generics contents as part of unique id for iterables
        TypeId::build_vector(&format!(
            "{}{}",
            "{PREFIX}",
            &Self::get_iterable_type_id().unwrap()
        ))
    }
    fn get_iterable_type_id() -> Option<TypeId> {
        Some(T::get_type_id())
    }
}