aboutsummaryrefslogtreecommitdiffstats
path: root/config-model/src/main/javacc/SDParser.jj
blob: 11ebd7c8b3e897fb8628d86f6ec6735255bc5503 (plain) (blame)
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
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// --------------------------------------------------------------------------------
//
// JavaCC options. When this file is changed, run "mvn generate-sources" to rebuild
// the parser classes.
//
// --------------------------------------------------------------------------------
options {
    UNICODE_INPUT = true;
    CACHE_TOKENS  = false;
    STATIC = false;
    DEBUG_PARSER = false;
    ERROR_REPORTING = true;
    FORCE_LA_CHECK = true;
    USER_CHAR_STREAM = true;
}

// --------------------------------------------------------------------------------
//
// Parser body.
//
// --------------------------------------------------------------------------------
PARSER_BEGIN(SDParser)

package com.yahoo.searchdefinition.parser;

import com.yahoo.document.*;
import com.yahoo.documentmodel.*;
import com.yahoo.compress.Compressor;
import com.yahoo.compress.CompressionType;
import com.yahoo.searchdefinition.document.*;
import com.yahoo.searchdefinition.document.annotation.SDAnnotationType;
import com.yahoo.searchdefinition.document.annotation.TemporaryAnnotationReferenceDataType;
import com.yahoo.searchdefinition.RankingConstant;
import com.yahoo.searchdefinition.OnnxModel;
import com.yahoo.searchdefinition.Index;
import com.yahoo.searchdefinition.RankProfile;
import com.yahoo.searchdefinition.DocumentsOnlyRankProfile;
import com.yahoo.searchdefinition.DefaultRankProfile;
import com.yahoo.searchdefinition.RankProfileRegistry;
import com.yahoo.searchdefinition.RankProfile.MatchPhaseSettings;
import com.yahoo.searchdefinition.RankProfile.DiversitySettings;
import com.yahoo.searchdefinition.Search;
import com.yahoo.searchdefinition.DocumentOnlySearch;
import com.yahoo.searchdefinition.UnrankedRankProfile;
import com.yahoo.searchdefinition.fieldoperation.*;
import com.yahoo.searchlib.rankingexpression.FeatureList;
import com.yahoo.searchlib.rankingexpression.evaluation.Value;
import com.yahoo.searchlib.rankingexpression.evaluation.TensorValue;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
import com.yahoo.vespa.documentmodel.DocumentSummary;
import com.yahoo.vespa.documentmodel.SummaryField;
import com.yahoo.vespa.documentmodel.SummaryTransform;
import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.config.application.api.ApplicationPackage;
import com.yahoo.config.application.api.DeployLogger;
import com.yahoo.config.application.api.FileRegistry;
import com.yahoo.config.model.api.ModelContext;
import com.yahoo.language.Linguistics;
import com.yahoo.language.process.Embedder;
import com.yahoo.language.simple.SimpleLinguistics;
import com.yahoo.search.query.ranking.Diversity;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.logging.Level;

/**
 * A search definition parser
 *
 * @author bratseth
 */
 @SuppressWarnings("deprecation")
public class SDParser {

    private DocumentTypeManager docMan = null;
    private ApplicationPackage app;
    private FileRegistry fileRegistry;
    private DeployLogger deployLogger;
    private ModelContext.Properties properties;
    private RankProfileRegistry rankProfileRegistry;
    private boolean documentsOnly;

    /**
     * Creates a parser
     *
     * @param documentsOnly true to only parse the document aspect of a search definition (e.g skip rank profiles)
     */
    public SDParser(SimpleCharStream stream,
                    FileRegistry fileRegistry,
                    DeployLogger deployLogger,
                    ModelContext.Properties properties,
                    ApplicationPackage applicationPackage,
                    RankProfileRegistry rankProfileRegistry,
                    boolean documentsOnly) {
        this(stream);
        this.fileRegistry = fileRegistry;
        this.deployLogger = deployLogger;
        this.properties = properties;
        this.app = applicationPackage;
        this.rankProfileRegistry = rankProfileRegistry;
        this.documentsOnly = documentsOnly;
    }

    /**
     * Consumes an indexing language script which will use the simple linguistics implementation
     * for testing, by taking input from the current input stream.
     *
     * @param multiline Whether or not to allow multi-line expressions.
     */
    @SuppressWarnings("deprecation")
    private IndexingOperation newIndexingOperation(boolean multiline) throws ParseException {
        return newIndexingOperation(multiline, new SimpleLinguistics(), Embedder.throwsOnUse);
    }

    /**
     * Consumes an indexing language script from the current input stream.
     *
     * @param multiline Whether or not to allow multi-line expressions.
     * @param linguistics What to use for tokenizing.
     */
    private IndexingOperation newIndexingOperation(boolean multiline, Linguistics linguistics, Embedder embedder) throws ParseException {
        SimpleCharStream input = (SimpleCharStream)token_source.input_stream;
        if (token.next != null) {
            input.backup(token.next.image.length());
        }
        try {
            return IndexingOperation.fromStream(input, multiline, linguistics, embedder);
        } finally {
            token.next = null;
            jj_ntk = -1;
        }
    }

    /**
     * Parses the given token image as a ranking expression feature list.
     *
     * @param image The token image to parse.
     * @return The consumed feature list.
     * @throws ParseException Thrown if the image could not be parsed.
     */
    private FeatureList getFeatureList(String image) throws ParseException {
        try {
            return new FeatureList(image);
        }
        catch (com.yahoo.searchlib.rankingexpression.parser.ParseException e) {
            throw (ParseException) new ParseException("Could not parse feature list '" + image + "' at line " +
                                                      token_source.input_stream.getBeginLine() + ", column " +
                                                      token_source.input_stream.getBeginColumn() + ".").initCause(e);
        }
    }

    /**
     * Sets the compression threshold in each item in the compression config array.
     *
     * @param cfg The array of configs to modify.
     * @param val The compression threshold to set.
     */
    private void setCompressionThreshold(CompressionConfig cfg, int val) {
        cfg.threshold = val;
    }

    /**
     * Sets the compression level in each item in the compression config array.
     *
     * @param cfg The array of configs to modify.
     * @param val The compression level to set.
     */
    private void setCompressionLevel(CompressionConfig cfg, int val) {
        cfg.compressionLevel = val;
    }
}

PARSER_END(SDParser)


// --------------------------------------------------------------------------------
//
// Token declarations.
//
// --------------------------------------------------------------------------------

// Declare white space characters. These do not include newline because it has
// special meaning in several of the production rules.
SKIP :
{
  " " | "\t" | "\r" | "\f"
}

// Declare all tokens to be recognized. When a word token is added it MUST be
// added to the identifier() production rule.
TOKEN :
{
  < NL: "\n" >
| < ANNOTATION: "annotation" >
| < ANNOTATIONREFERENCE: "annotationreference" >
| < SCHEMA: "schema" >
| < SEARCH: "search" >
| < DIVERSITY: "diversity" >
| < MIN_GROUPS: "min-groups" >
| < CUTOFF_FACTOR: "cutoff-factor" >
| < CUTOFF_STRATEGY: "cutoff-strategy" >
| < LOOSE: "loose" >
| < STRICT: "strict" >
| < DOCUMENT: "document" >
| < EXECUTE: "execute" >
| < OPERATION: "operation" >
| < ON_MATCH: "on-match" >
| < ON_RERANK: "on-rerank" >
| < ON_SUMMARY: "on-summary" >
| < STRUCT: "struct" >
| < INHERITS: "inherits" >
| < FIELD: "field" >
| < FIELDS: "fields" >
| < FIELDSET: "fieldset" >
| < STRUCTFIELD: "struct-field" >
| < IMPORT: "import" >
| < AS: "as" >
| < INDEXING: "indexing" >
| < SUMMARYTO: "summary-to" >
| < DOCUMENTSUMMARY: "document-summary" >
| < RANKTYPE: "rank-type" >
| < WEIGHT: "weight" >
| < TYPE: "type" >
| < INDEX: "index" >
| < MTOKEN: "token" >
| < TEXT: "text" >
| < WORD: "word" >
| < GRAM: "gram" >
| < GRAMSIZE: "gram-size" >
| < MAXLENGTH: "max-length" >
| < PREFIX: "prefix" >
| < SUBSTRING: "substring" >
| < SUFFIX: "suffix" >
| < CONSTANT: "constant">
| < ONNXMODEL: "onnx-model">
| < MODEL: "model" >
| < RANKPROFILE: "rank-profile" >
| < RANKDEGRADATIONFREQ: "rank-degradation-frequency" >
| < RANKDEGRADATION: "rank-degradation" >
| < RAW_AS_BASE64_IN_SUMMARY: "raw-as-base64-in-summary" >
| < RPBINSIZE: "doc-frequency" >
| < RPBINLOW:  "min-fullrank-docs">
| < RPPOSBINSIZE: "occurrences-per-doc" >
| < SUMMARY: "summary" >
| < FULL: "full" >
| < STATIC: "static" >
| < DYNAMIC: "dynamic" >
| < MATCHEDELEMENTSONLY: "matched-elements-only" >
| < SSCONTEXTUAL: "contextual" >
| < SSOVERRIDE: "override" >
| < SSTITLE: "title" >
| < SSURL: "url" >
| < PROPERTIES: "properties" >
| < ATTRIBUTE: "attribute" >
| < SORTING: "sorting" >
| < DICTIONARY: "dictionary" >
| < ASCENDING: "ascending" >
| < DESCENDING: "descending" >
| < UCA: "uca" >
| < RAW: "raw" >
| < LOWERCASE: "lowercase" >
| < FUNCTION: "function" >
| < LOCALE: "locale" >
| < STRENGTH: "strength" >
| < PRIMARY: "primary" >
| < SECONDARY: "secondary" >
| < TERTIARY: "tertiary" >
| < QUATERNARY: "quaternary" >
| < IDENTICAL: "identical" >
| < STEMMING: "stemming" >
| < NORMALIZING: "normalizing" >
| < HASH: "hash" >
| < BTREE: "btree" >
| < CASED: "cased" >
| < UNCASED: "uncased" >
| < BOLDING: "bolding" >
| < BODY: "body" >
| < HEADER: "header" >
| < NONE: "none" >
| < ON: "on" >
| < OFF: "off" >
| < TRUE: "true" >
| < FALSE: "false" >
| < SYMMETRIC: "symmetric" >
| < QUERYCOMMAND: "query-command" >
| < ALIAS: "alias" >
| < MATCH: "match" >
| < RANK: "rank" >
| < LITERAL: "literal" >
| < EXACT: "exact" >
| < FILTER: "filter" >
| < NORMAL: "normal" >
| < EXACTTERMINATOR: "exact-terminator" >
| < INDEXINGREWRITE: "indexing-rewrite" >
| < IGNOREDEFAULTRANKFEATURES: "ignore-default-rank-features" >
| < ID: "id" >
| < SOURCE: "source" >
| < TO: "to" >
| < DIRECT: "direct" >
| < FROMDISK: "from-disk" >
| < OMITSUMMARYFEATURES: "omit-summary-features" >
| < ALWAYS: "always" >
| < ONDEMAND: "on-demand" >
| < NEVER: "never" >
| < ENABLEBITVECTORS: "enable-bit-vectors" >
| < ENABLEONLYBITVECTOR: "enable-only-bit-vector" >
| < FASTACCESS: "fast-access" >
| < MUTABLE: "mutable" >
| < PAGED: "paged" >
| < FASTSEARCH: "fast-search" >
| < HUGE: "huge" >
| < TENSOR_TYPE: "tensor" ("<" (~["<",">"])+ ">")? "(" (~["(",")"])+ ")" >
| < TENSOR_VALUE_SL: "value" (" ")* ":" (" ")* ("{"<BRACE_SL_LEVEL_1>) ("\n")? >
| < TENSOR_VALUE_ML: "value" (<SEARCHLIB_SKIP>)? "{" (["\n"," "])* ("{"<BRACE_ML_LEVEL_1>) (["\n"," "])* "}" ("\n")? >
| < COMPRESSION: "compression" >
| < COMPRESSIONLEVEL: "level" >
| < COMPRESSIONTHRESHOLD: "threshold" >
| < LZ4: "lz4" >
| < USEDOCUMENT: "use-document" >
| < LBRACE: "{" >
| < RBRACE: "}" >
| < COLON: ":" >
| < DOT: "." >
| < COMMA: "," >
| < ARRAY: "array" >
| < WEIGHTEDSET: "weightedset" >
| < MAP: "map" >
| < REFERENCE: "reference" >
| < QUESTIONMARK: "?" >
| < CREATEIFNONEXISTENT: "create-if-nonexistent" >
| < REMOVEIFZERO: "remove-if-zero" >
| < MATCHPHASE: "match-phase" >
| < EVALUATION_POINT: "evaluation-point" >
| < PRE_POST_FILTER_TIPPING_POINT: "pre-post-filter-tipping-point" >
| < ORDER: "order" >
| < MAXFILTERCOVERAGE: "max-filter-coverage" >
| < MAXHITS: "max-hits" >
| < FIRSTPHASE: "first-phase" >
| < SECONDPHASE: "second-phase" >
| < MACRO: "macro" >
| < INLINE: "inline" >
| < ARITY: "arity" >
| < LOWERBOUND: "lower-bound" >
| < UPPERBOUND: "upper-bound" >
| < DENSEPOSTINGLISTTHRESHOLD: "dense-posting-list-threshold" >
| < ENABLE_BM25: "enable-bm25" >
| < HNSW: "hnsw" >
| < MAXLINKSPERNODE: "max-links-per-node" >
| < DISTANCEMETRIC: "distance-metric" >
| < NEIGHBORSTOEXPLOREATINSERT: "neighbors-to-explore-at-insert" >
| < MULTITHREADEDINDEXING: "multi-threaded-indexing" >
| < SUMMARYFEATURES_SL: "summary-features" (" ")* ":" (~["}","\n"])* ("\n")? >
| < SUMMARYFEATURES_ML: "summary-features" (<SEARCHLIB_SKIP>)? "{" (~["}"])* "}" >
| < SUMMARYFEATURES_ML_INHERITS: "summary-features inherits " (<IDENTIFIER>) (<SEARCHLIB_SKIP>)? "{" (~["}"])* "}" >
| < RANKFEATURES_SL: "rank-features" (" ")* ":" (~["}","\n"])* ("\n")? >
| < RANKFEATURES_ML: "rank-features" (<SEARCHLIB_SKIP>)? "{" (~["}"])* "}" >
| < EXPRESSION_SL: "expression" (" ")* ":" (("{"<BRACE_SL_LEVEL_1>)|<BRACE_SL_CONTENT>)* ("\n")? >
| < EXPRESSION_ML: "expression" (<SEARCHLIB_SKIP>)? "{" (("{"<BRACE_ML_LEVEL_1>)|<BRACE_ML_CONTENT>)* "}" >
| < #BRACE_SL_LEVEL_1: (("{"<BRACE_SL_LEVEL_2>)|<BRACE_SL_CONTENT>)* "}" >
| < #BRACE_SL_LEVEL_2: (("{"<BRACE_SL_LEVEL_3>)|<BRACE_SL_CONTENT>)* "}" >
| < #BRACE_SL_LEVEL_3: <BRACE_SL_CONTENT> "}" >
| < #BRACE_SL_CONTENT: (~["{","}","\n"])* >
| < #BRACE_ML_LEVEL_1: (("{"<BRACE_ML_LEVEL_2>)|<BRACE_ML_CONTENT>)* "}" >
| < #BRACE_ML_LEVEL_2: (("{"<BRACE_ML_LEVEL_3>)|<BRACE_ML_CONTENT>)* "}" >
| < #BRACE_ML_LEVEL_3: <BRACE_ML_CONTENT> "}" >
| < #BRACE_ML_CONTENT: (~["{","}"])* >
| < #SEARCHLIB_SKIP: ([" ","\f","\n","\r","\t"])+ >
| < RANKPROPERTIES: "rank-properties" >
| < RERANKCOUNT: "rerank-count" >
| < NUMTHREADSPERSEARCH: "num-threads-per-search" >
| < MINHITSPERTHREAD: "min-hits-per-thread" >
| < NUMSEARCHPARTITIONS: "num-search-partitions" >
| < TERMWISELIMIT: "termwise-limit" >
| < KEEPRANKCOUNT: "keep-rank-count" >
| < RANKSCOREDROPLIMIT: "rank-score-drop-limit" >
| < CONSTANTS: "constants" >
| < FILE: "file" >
| < URI: "uri" >
| < IDENTIFIER:           ["a"-"z","A"-"Z", "_"] (["a"-"z","A"-"Z","0"-"9","_"])* >
| < IDENTIFIER_WITH_DASH: ["a"-"z","A"-"Z", "_"] (["a"-"z","A"-"Z","0"-"9","_","-"])* >
| < QUOTEDSTRING: "\"" ( ~["\""] )* "\"" >
| < CONTEXT: ["a"-"z","A"-"Z"] (["a"-"z", "A"-"Z", "0"-"9"])* >
| < DOUBLE: ("-")? (["0"-"9"])+ "." (["0"-"9"])+ >
| < INTEGER: ("-")? (["0"-"9"])+ >
| < LONG: ("-")? (["0"-"9"])+"L" >
| < STRING: (["a"-"z","A"-"Z","_","0"-"9","."])+ >
| < FILE_PATH: ["a"-"z","A"-"Z", "_"] (["a"-"z","A"-"Z","0"-"9","_","-", "/", "."])+ >
| < HTTP: ["h","H"] ["t","T"] ["t","T"] ["p","P"] (["s","S"])? >
| < URI_PATH: <HTTP> <COLON> ("//")? (["a"-"z","A"-"Z","0"-"9","_","-", "/", ".",":"])+ >
| < LESSTHAN: "<" >
| < GREATERTHAN: ">" >
| < VARIABLE: "$" <IDENTIFIER> >
| < ONNX_INPUT_SL: "input" (" ")* (<IDENTIFIER>|<QUOTEDSTRING>) (" ")* ":" (" ")* (~["\n"])* ("\n")? >
| < ONNX_OUTPUT_SL: "output" (" ")* (<IDENTIFIER>|<QUOTEDSTRING>) (" ")* ":" (" ")* (~["\n"])* ("\n")? >
}

// Declare a special skip token for comments.
SPECIAL_TOKEN :
{
  <SINGLE_LINE_COMMENT: "#" (~["\n","\r"])* >
}


// --------------------------------------------------------------------------------
//
// Production rules.
//
// --------------------------------------------------------------------------------

/**
 * The rule consumes any search definition and returns the corresponding object. This is the only production that should
 * ever consume leading newlines.
 *
 * @param dir The directory containing the file being parsed.
 * @return The search definition object.
 */
Search search(DocumentTypeManager docMan, String dir) :
{
    this.docMan = docMan;
    Search search;
}
{
    (<NL>)* (search = rootSchema(dir) | search = rootDocument(dir))
    { return search; }
}

/**
 * This rule consumes a proper schema block. This and rootDocument() are the only rules that should ever consume
 * trailing newline tokens.
 *
 * @param dir the directory containing the file being parsed.
 * @return the schema definition object.
 */
Search rootSchema(String dir) :
{
    String name;
    Search search;
}
{
    ( ( <SCHEMA> | <SEARCH> ) name = identifier() {
        search = new Search(name, app, fileRegistry,deployLogger, properties);
        rankProfileRegistry.add(new DefaultRankProfile(search, rankProfileRegistry, search.rankingConstants()));
        rankProfileRegistry.add(new UnrankedRankProfile(search, rankProfileRegistry, search.rankingConstants()));}
      lbrace() (rootSchemaItem(search) (<NL>)*)* <RBRACE> (<NL>)* <EOF>)
    { return search; }
}

/**
 * Consumes an element of a schema block. This and rootSearch() are the only rules that should ever consume
 * trailing newline tokens.
 *
 * @param search The search object to modify.
 * @return Null.
 */
Object rootSchemaItem(Search search) : { }
{
    ( document(search)
      | rawAsBase64(search)
      | documentSummary(search)
      | field(null, search)
      | index(search, null)
      | rankingConstant(search)
      | rankProfile(search)
      | searchStemming(search)
      | useDocument(search)
      | structOutside(search)
      | annotationOutside(search)
      | fieldSet(search)
      | importField(search)
      | onnxModel(search) )
    { return null; }
}

/**
 * Consumes a schema definition that contains only documents to be used for inheritance, etc.
 *
 * @param dir the directory containing the file being parsed.
 * @return the schema definition object.
 */
Search rootDocument(String dir) :
{
    Search search = new DocumentOnlySearch(app, fileRegistry, deployLogger, properties);
}
{
    ( (rootDocumentItem(search) (<NL>)*)*<EOF> )
    { return search; }
}

/**
 * Consumes a single item from within a root document node.
 *
 * @param search The search object to modify.
 * @return Null.
 */
Object rootDocumentItem(Search search) : { }
{
    ( namedDocument(search) )
    { return null; }
}

/**
 * Consumes a use-document statement. This currently does nothing.
 *
 * @param search the search object to modify.
 */
void useDocument(Search search) : { }
{
    <USEDOCUMENT> <COLON> identifier()
}

/**
 * Consumes a document element. The name defaults to the search's name, but may be set.
 *
 * @param search the search object to add content to.
 */
void document(Search search) :
{
    String name=search.getName();
    SDDocumentType document;
}
{
    ( <DOCUMENT> (name = identifier())? (<NL>)* { document = new SDDocumentType(name, search); }
      [ inheritsDocument(document) (<NL>)* ]
      <LBRACE> (<NL>)* (documentBody(document, search) (<NL>)*)* <RBRACE> )
    {
        search.addDocument(document);
    }
}

/**
 * Consumes a document element, explicitly named
 *
 * @param search the search object to add content to.
 */
void namedDocument(Search search) :
{
    String name;
    SDDocumentType document;
}
{
    ( <DOCUMENT> name = identifier() (<NL>)* { document = new SDDocumentType(name, search); }
      [ inheritsDocument(document) (<NL>)* ]
      <LBRACE> (<NL>)* (documentBody(document, search) (<NL>)*)* <RBRACE> )
    {
        search.addDocument(document);
    }
}

/**
 * Consumes a document body block
 *
 * @param document The document type to modify.
 * @param search   The search object to add content to.
 * @return Null.
 */
Object documentBody(SDDocumentType document, Search search) :
{
}
{
    ( annotation(search, document)
      | compression(document, null)
      | headercfg(document)
      | bodycfg(document)
      | structInside(document, search)
      | field(document, search) )
    { return null; }
}

void rawAsBase64(Search search) :
{}
{
    <RAW_AS_BASE64_IN_SUMMARY> { search.enableRawAsBase64(); }
}

/**
 * Consumes a document head block.
 *
 * @param document The document type to modify.
 */
void headercfg(SDDocumentType document) : { }
{
    <HEADER> lbrace() [compression(document, "header") (<NL>)*] <RBRACE>
}

/**
 * Consumes a document body block.
 *
 * @param document The document type to modify.
 */
void bodycfg(SDDocumentType document) : { }
{
    <BODY> lbrace() [compression(document, "body") (<NL>)*] <RBRACE>
}

/**
 * Consumes a compression block. This can be set in both document header and -body block.
 *
 * @param document The document type to modify.
 * @param name     The name of the document block to modify.
 */
void compression(SDDocumentType document, String name) :
{
    deployLogger.logApplicationPackage(Level.WARNING, "'compression' for a document is deprecated and ignored");
    CompressionConfig cfg = new CompressionConfig(CompressionType.LZ4);
}
{
    <COMPRESSION> lbrace() (cfg = compressionItem(cfg) (<NL>)*)* <RBRACE>
    {
        if (name == null || name.equals("header")) {
            document.getDocumentType().contentStruct().setCompressionConfig(cfg);
        }
    }
}

/**
 * Consumes the body of a compression block.
 *
 * @param cfg The compression config to modify.
 */
CompressionConfig compressionItem(CompressionConfig cfg) :
{
    int val = -1;
}
{
    ( ( <TYPE> <COLON> <LZ4> { cfg = new CompressionConfig(CompressionType.LZ4, cfg.compressionLevel, cfg.threshold); } )
      | (<COMPRESSIONTHRESHOLD> <COLON> val = integer()) { setCompressionThreshold(cfg, val); }
      | (<COMPRESSIONLEVEL>   <COLON> val = integer())  { setCompressionLevel(cfg, val); }
    )
    {
       return cfg;
    }
}

/**
 * Consumes a document inheritance statement.
 *
 * @param document The document type to modify.
 */
void inheritsDocument(SDDocumentType document) :
{
    String name;
}
{
    <INHERITS> name = identifier() { document.inherit(new DataTypeName(name)); }
    ( <COMMA>  name = identifier() { document.inherit(new DataTypeName(name)); } )*
}

/**
 * Consumes a field block from within a document element.
 *
 * @param document The document type to modify.
 * @param search   The search object to add content to.
 */
void field(SDDocumentType document, Search search) :
{
    String name;
    SDField field;
    DataType type;
}
{
    <FIELD> name = identifier() <TYPE> type = dataType()
    {
        if (name != null && com.yahoo.searchdefinition.Search.isReservedName(name.toLowerCase())) {
            throw new IllegalArgumentException("Reserved name '" + name + "' can not be used as a field name.");
        }
        field = new TemporarySDField(name, type, document);
    }
    lbrace() (fieldBody(field, search, document) (<NL>)*)* <RBRACE>
    {
        if (document != null) {
            document.addField(field);
        } else {
            search.addExtraField(field);
        }
    }
}

void fieldSet(Search search) :
{
  String setName;
  String field;
  String queryCommand;
  List queryCommands = new ArrayList();
  FieldOperationContainer matchSetting;
  List matchSettings = new ArrayList();
}
{
  <FIELDSET> setName = identifier() lbrace()
    ((
      ( <FIELDS><COLON> field = identifier() { search.fieldSets().addUserFieldSetItem(setName, field); }
      ( <COMMA> field = identifier() { search.fieldSets().addUserFieldSetItem(setName, field); } )* )
    |
      ( <QUERYCOMMAND> <COLON> (queryCommand = identifierWithDash() | queryCommand = quotedString())) { queryCommands.add(queryCommand); }
    |
      ( matchSetting = match(new SDField(setName, DataType.STRING)) ) { matchSettings.add(matchSetting); }
    )(<NL>)*)+
  <RBRACE>
  {
     // Apply settings after parsing since all user field items must be set first

     for (Object command : queryCommands)
         search.fieldSets().userFieldSets().get(setName).queryCommands().add((String)command);

     for (Object setting : matchSettings) {
         ((SDField)setting).applyOperations();
         search.fieldSets().userFieldSets().get(setName).setMatching(((SDField)setting).getMatching());
     }
  }
}

/**
 * This rule consumes a annotation block from within either a document element or a search element.

 * @param search the search object to add content to.
 */
void annotationOutside(Search search) :
{
    String name;
    SDAnnotationType type;
}
{
    <ANNOTATION> name = identifier()
    {
        type = new SDAnnotationType(name.trim());
    }
    [ inheritsAnnotation(type) (<NL>)* ]
    lbrace() (type = annotationBody(search, type)) <RBRACE>
    {
        if (search.getDocument()==null) throw new IllegalArgumentException("Can't add annotation '"+name+"' to a document type, define a document type first or declare the annotation inside of one.");
        search.addAnnotation(type);
    }
}

/**
 * This rule consumes a annotation block from within either a document element.
 *
 * @param document The document object to add content to.
 */
void annotation(Search search, SDDocumentType document) :
{
    String name;
    SDAnnotationType type;
}
{
    <ANNOTATION> name = identifier()
    {
        type = new SDAnnotationType(name.trim());
    }
    [ inheritsAnnotation(type) (<NL>)* ]
    lbrace() (type = annotationBody(search, type)) <RBRACE>
    {
        document.addAnnotation(type);
    }
}


/**
 * This rule consumes a single element of an annotation body block.
 *
 * @param search   The search object to add content to.
 * @param type     The type being built.
 * @return a modified or new AnnotationType instance
 */
SDAnnotationType annotationBody(Search search, SDAnnotationType type) :
{
    SDDocumentType struct = new SDDocumentType("annotation." + type.getName(), search);
}
{
    (structFieldDefinition(struct) (<NL>)*)*
    {
        if (struct.getFieldCount() > 0) { // Must account for the temporary TemporarySDField.
            type = new SDAnnotationType(type.getName(), struct, type.getInherits());
            struct.setStruct(null);
        }
        return type;
    }
}

void inheritsAnnotation(SDAnnotationType annotation) :
{
    String name;
}
{
    <INHERITS> name = identifier() { annotation.inherit(name); }
}


/**
 * This rule consumes a struct block from within a document element.
 *
 * @param search The search object to add content to.
 */
void structInside(SDDocumentType document, Search search) :
{
    SDDocumentType struct;
}
{
    (
        struct = structDefinition(search, document)
    )
    {
        document.addType(struct);
    }
}

/**
 * This rule consumes a struct block from within a document element.
 *
 * @param search The search object to add content to.
 */
void structOutside(Search search) :
{
    SDDocumentType struct;
}
{
    (
        struct = structDefinition(search, search.getDocument())
    )
    {
        search.addType(struct);
    }
}

/**
 * This rule consumes a struct block from within a document element.
 *
 * @param search The search object to add content to.
 */
SDDocumentType structDefinition(Search search, SDDocumentType repo) :
{
    String name;
    SDDocumentType struct;
}
{
    <STRUCT> name = identifier()
    {
        struct = new SDDocumentType(name, search);
    }
    lbrace() (structFieldDefinition(struct) (<NL>)*)* <RBRACE>
    {
        try {
            docMan.getDataType(name);
            throw new ParseException("Reserved name '" + name + "' can not be used to declare a struct.");
        } catch (IllegalArgumentException e) {
            // empty
        }
        if (repo==null) throw new IllegalArgumentException("Can't add struct '"+name+"' to a document type, define a document type first or declare the struct inside of one.");
        SDDocumentType sdtype = repo.getOwnedType(struct.getDocumentName());
        DataType stype = sdtype != null
                         ? sdtype.getStruct()
                         : TemporaryStructuredDataType.create(struct.getName());
        struct.setStruct(stype);
        return struct;
    }
}

/**
 * This rule consumes a data type block from within a field element.
 *
 * @return The consumed data type.
 */
DataType dataType() :
{
    String typeName = null;
    boolean isArrayOldStyle = false;
    DataType mapType = null;
	DataType arrayType = null;
    DataType wsetType = null;
    TensorType tensorType;
    TemporaryStructuredDataType referenceType;
}
{
    (   LOOKAHEAD(<ARRAY> <LESSTHAN>)               ( <ARRAY> <LESSTHAN> arrayType = dataType() <GREATERTHAN> { return DataType.getArray(arrayType); } )
      | LOOKAHEAD(<WEIGHTEDSET> <LESSTHAN>)         ( <WEIGHTEDSET> <LESSTHAN> wsetType = dataType() <GREATERTHAN> { return  DataType.getWeightedSet(wsetType); } )
      | LOOKAHEAD(<MAP> <LESSTHAN>)                 ( mapType = mapDataType() { return mapType; } )
      | LOOKAHEAD(<ANNOTATIONREFERENCE> <LESSTHAN>) ( mapType = annotationRefDataType() { return mapType; } )
      | LOOKAHEAD(<TENSOR_TYPE>)                    ( tensorType = tensorType("Field type") { return DataType.getTensor(tensorType); } )
      | LOOKAHEAD(<REFERENCE>)                      ( <REFERENCE> <LESSTHAN> referenceType = referenceType() <GREATERTHAN> { return ReferenceDataType.createWithInferredId(referenceType); } )
      | ( typeName = identifier() ["[]" { isArrayOldStyle = true; }] )
    )
    {
        DataType type = VespaDocumentType.INSTANCE.getDataType(typeName);

        if (type == null) {
            // we are basically creating TemporaryStructDataType instances for ANYTHING here!!
            // we must do this and clean them up later.
            type = TemporaryStructuredDataType.create(typeName);
        }

        if (isArrayOldStyle) {
            deployLogger.logApplicationPackage(Level.WARNING, "Data type syntax '" + typeName + "[]' is deprecated, use 'array<" + typeName + ">' instead.");
            type = DataType.getArray(type);
        }
        if ("tag".equalsIgnoreCase(typeName) && type instanceof WeightedSetDataType) ((WeightedSetDataType)type).setTag(true);
        return type;
    }
}

TemporaryStructuredDataType referenceType() :
{
    String documentName;
}
{
    ( documentName = identifier() )
    {
        return TemporaryStructuredDataType.create(documentName);
    }
}

DataType annotationRefDataType() :
{
    DataType dataType;
    String targetName;
}
{
    ( <ANNOTATIONREFERENCE> <LESSTHAN> targetName = identifier() <GREATERTHAN> )
    {
        return new TemporaryAnnotationReferenceDataType(targetName);
    }
}

DataType mapDataType() :
{
    DataType keyType;
    DataType valType;
}
{
  ( <MAP> <LESSTHAN> keyType = dataType() <COMMA> valType = dataType() <GREATERTHAN> )
  {
    return DataType.getMap(keyType, valType);
  }

}

/* Note: not currently used, remove when decided that map type will not support
polymorphism */
DataType wildCardType() :
{
}
{
(<QUESTIONMARK>) { return DataType.NONE; }
}

/**
 * This rule consumes a field block of a struct body.
 *
 * @param struct The struct to modify.
 */
void structFieldDefinition(SDDocumentType struct) :
{
    String name;
    SDField field;
    DataType type;
}
{
    <FIELD> name = identifier() <TYPE> type = dataType() {
        if (name != null && com.yahoo.searchdefinition.Search.isReservedName(name.toLowerCase())) {
            throw new IllegalArgumentException("Reserved name '" + name + "' can not be used as a field name.");
        }
        field = new TemporarySDField(name, type, struct);
        struct.addField(field);
    }
    lbrace() (id(field,struct) (<NL>)*)? (match(field) (<NL>)*)* <RBRACE> {
    }
}

/**
 * This rule consumes a struct subfield from a document field body. This is not to be confused with a document
 * struct's fields, but rather this is a subfield of a document field of type struct.
 *
 * @param field    The field to modify.
 * @param search   The search object to add content to.
 * @param document The document type to modify.
 */
void structField(FieldOperationContainer field, Search search,SDDocumentType document) :
{
    String name;
    SDField structField;
}
{
    <STRUCTFIELD> name = identifier() {
        if (name != null && com.yahoo.searchdefinition.Search.isReservedName(name.toLowerCase())) {
            throw new IllegalArgumentException("Reserved name '" + name + "' can not be used as a field name.");
        }
        FieldOperationContainer structFieldOp = new StructFieldOperation(name);
        field.addOperation((StructFieldOperation) structFieldOp);
    }
    lbrace() (structFieldBody(structFieldOp, search, document) (<NL>)*)* <RBRACE>
}


/**
 * This rule consumes a single element of a field body block.
 *
 * @param field    The field being built.
 * @param search   The search object to add content to.
 * @param document The owning document, or null if this is a search field.
 * @return Null.
 */
String fieldBody(SDField field, Search search, SDDocumentType document) : { }
{
    ( alias(field) |
      attribute(field) |
      body(field) |
      bolding(field) |
      dictionary(field) |
      fieldStemming(field) |
      header(field) |
      id(field, document) |
      summaryInField(field) |
      index(search, field) |
      indexing(field) |
      indexingRewrite(field) |
      match(field) |
      normalizing(field) |
      queryCommand(field) |
      rank(field) |
      rankType(field) |
      sorting(field, field.getName()) |
      structField(field, search, document) |
      summaryTo(field) |
      weight(field) |
      weightedset(field) )
    { return null; }
}

/**
 * This rule consumes a single element of a struct subfield body block.
 * Only elements that are supported in streaming search and indexed search (with complex attributes) are allowed.
 *
 * @param field    The field being built.
 * @param search   The search object to add content to.
 * @param document The owning document, or null if this is a search field.
 * @return Null.
 */
String structFieldBody(FieldOperationContainer field, Search search, SDDocumentType document) : { }
{
    ( summaryInField(field) |
      indexing(field) |
      attribute(field) |
      match(field) |
      queryCommand(field) |
      structField(field, search, document) |
      summaryTo(field) )
    { return null; }
}

/**
 * This rule consumes an indexing block of a field element.
 *
 * @param field The field to modify.
 * @return Null.
 */
Object indexing(FieldOperationContainer field) : { }
{
    ( <INDEXING> ( (<COLON> indexingOperation(field, false)) | indexingOperation(field, true) ) )
    { return null; }
}

/**
 * This rule consumes an IL script block. This is expected to consume trailing newlines.
 *
 * @param field The field to modify.
 */
void indexingOperation(FieldOperationContainer field, boolean multiLine) : { }
{
    { field.addOperation(newIndexingOperation(multiLine)); }
}

/**
 * This rule consumes a summary-to statement of a field element.
 *
 * @param field The field to modify.
 */
void summaryTo(FieldOperationContainer field) :
{
    SummaryToOperation op = new SummaryToOperation();
    String destination;
    String name = field.getName();
}
{
    <SUMMARYTO> [name = identifier()] <COLON> destination = identifier()
    {
        op.setName(name);
        op.addDestination(destination);
    }
    ( <COMMA> destination = identifier() {op.addDestination(destination); } )*
    {
        field.addOperation(op);
    }
}


/**
 * This rule consumes a weight statement of a field element.
 *
 * @param field The field to modify.
 */
void weight(FieldOperationContainer field) :
{
    int num;
}
{
    <WEIGHT> <COLON> num = integer()
    {
        WeightOperation op = new WeightOperation();
        op.setWeight(num);
        field.addOperation(op);
    }
}

/**
 * This rule consumes a weighted set statement of a field element.
 *
 * @param field The field to modify.
 * @return Null.
 */
Object weightedset(FieldOperationContainer field) :
{
    WeightedSetOperation op = new WeightedSetOperation();
}
{
    <WEIGHTEDSET> ( (<COLON> weightedsetBody(op))
                    | (lbrace() (weightedsetBody(op) (<NL>)*)* <RBRACE>) )
    {
        field.addOperation(op);
        return null;
    }
}

/**
 * This rule consumes one body item of a weighted set block.
 *
 * @param field The field to modify.
 * @return Null.
 */
Object weightedsetBody(WeightedSetOperation field) : { }
{
    ( <CREATEIFNONEXISTENT> { field.setCreateIfNonExistent(true); }
      | <REMOVEIFZERO>      { field.setRemoveIfZero(true); } )
    {
        return null;
    }
}

/**
 * This rule consumes a rank-type statement of a field element.
 *
 * @param field The field to modify.
 */
void rankType(FieldOperationContainer field) :
{
    String typeName;
    String indexName = null;
}
{
    <RANKTYPE> [indexName = identifier()] <COLON> typeName = identifier()
    {
        RankTypeOperation op = new RankTypeOperation();
        op.setType(RankType.fromString(typeName));
        op.setIndexName(indexName);
        field.addOperation(op);
    }
}

/**
 * This rule consumes an attribute statement of a field element.
 *
 * @param field The field to modify.
 * @return Null.
 */
Object attribute(FieldOperationContainer field) :
{
    String name = field.getName();
}
{
    <ATTRIBUTE> [name = identifier()]
    {
        AttributeOperation op = new AttributeOperation(name);
    }
         ( (<COLON> attributeSetting(field, op, name))
           | (lbrace() (attributeSetting(field, op, name) (<NL>)*)* <RBRACE>) )
    {
        field.addOperation(op);
        return null;
    }
}

Object sorting(FieldOperationContainer field, String name) :
{
    SortingOperation op = new SortingOperation(name);
}
{
    <SORTING>
         ( (<COLON> sortingSetting(op, name))
           | (lbrace() (sortingSetting(op, name) (<NL>)*)* <RBRACE>) )
    {
        field.addOperation(op);
        return null;
    }
}

Object sortingSetting(SortingOperation sorting, String attributeName) :
{
    String locale;
}
{
    (
        <ASCENDING> { sorting.setAscending(); }
      | <DESCENDING> { sorting.setDescending(); }
      | <FUNCTION> <COLON> (
                               <UCA>       { sorting.setFunction(Sorting.Function.UCA); }
                             | <RAW>       { sorting.setFunction(Sorting.Function.RAW); }
                             | <LOWERCASE> { sorting.setFunction(Sorting.Function.LOWERCASE); }
                           )
      | <STRENGTH> <COLON> (
                               <PRIMARY>    { sorting.setStrength(Sorting.Strength.PRIMARY); }
                             | <SECONDARY>  { sorting.setStrength(Sorting.Strength.SECONDARY); }
                             | <TERTIARY>   { sorting.setStrength(Sorting.Strength.TERTIARY); }
                             | <QUATERNARY> { sorting.setStrength(Sorting.Strength.QUATERNARY); }
                             | <IDENTICAL>  { sorting.setStrength(Sorting.Strength.IDENTICAL); }
                           )
      | <LOCALE> <COLON> locale = identifierWithDash() { sorting.setLocale(locale); }
    )
    { return null; }
}

/**
 * This rule consumes a single attribute setting statement of an attribute element.
 *
 * @param field The field to modify.
 * @param attributeName The name of the attribute to change.
 * @return Null.
 */
Object attributeSetting(FieldOperationContainer field, AttributeOperation attribute, String attributeName) :
{
    String str;
}
{
    (
        <HUGE>                 { attribute.setHuge(true); }
      | <FASTSEARCH>           { attribute.setFastSearch(true); }
      | <FASTACCESS>           { attribute.setFastAccess(true); }
      | <MUTABLE>              { attribute.setMutable(true); }
      | <PAGED>                { attribute.setPaged(true); }
      | <ENABLEBITVECTORS>     { attribute.setEnableBitVectors(true); }
      | <ENABLEONLYBITVECTOR>  { attribute.setEnableOnlyBitVector(true); }
      | sorting(field, attributeName)
      | <ALIAS> { String alias; String aliasedName=attributeName; } [aliasedName = identifier()] <COLON> alias = identifierWithDash() {
          attribute.setDoAlias(true);
          attribute.setAlias(alias);
          attribute.setAliasedName(aliasedName);
      }
      | attributeTensorType(attribute)
      | <DISTANCEMETRIC> <COLON> str = identifierWithDash() { attribute.setDistanceMetric(str); }
    )
    { return null; }
}

/**
 * This rule consumes a tensor type statement for an attribute element.
 *
 * @param attribute The attribute to modify.
 * @return Null.
 */
Object attributeTensorType(AttributeOperation attribute) :
{
    TensorType tensorType;
}
{
    tensorType = tensorType("For attribute field '" + attribute.getName() + "'")
    {
        // TODO: Remove on Vespa 8
        deployLogger.logApplicationPackage(Level.WARNING, "In field '" + attribute.getName() + "': Specifying tensor type on the attribute is deprecated and has no effect.");
    }
    { return null; }
}

/**
 * This rule consumes a summary statement defined inside a document-summary block.
 *
 * @param document The document summary to modify.
 * @return Null.
 */
Object summaryInDocument(DocumentSummary document) :
{
    String name;
    DataType type;
    SummaryField summary;

}
{
    <SUMMARY> name = identifierWithDash() { }
    <TYPE>    type = dataType()   {
        summary = new SummaryField(name, type);
        summary.setVsmCommand(SummaryField.VsmCommand.FLATTENSPACE);

        SummaryInFieldLongOperation op = new SummaryInFieldLongOperation();

    }
    lbrace() (summaryItem(op) (<NL>)*)* <RBRACE>
    {
	    if (op.destinationIterator().hasNext()) {
            throw new ParseException("Summaries defined in a document-summary section " +
                                     "can not have a 'to' line.");
        }

        op.applyToSummary(summary);

        document.add(summary);
        return null;
    }
}

/**
 * The rule consumes a summary statement defined inside a field.
 *
 * @param field The field to modify.
 * @return Null.
 */
Object summaryInField(FieldOperationContainer field) :
{
    SummaryInFieldOperation summary;
}
{
    ( <SUMMARY> ( LOOKAHEAD(2) summary = summaryInFieldShort(field)
                  | summary = summaryInFieldLong(field)) )
    {
        field.addOperation(summary);
        return null;
    }
}

/**
 * This rule consumes a single-line summary field.
 *
 * @param field The field to modify.
 * @return The consumed summary field.
 */
SummaryInFieldOperation summaryInFieldShort(FieldOperationContainer field) :
{
    String name = field.getName();
    SummaryField ret;
}
{
    [ name = identifier() ]
    {
        SummaryInFieldShortOperation op = new SummaryInFieldShortOperation(name);
    }
    <COLON> ( <DYNAMIC> { op.setTransform(SummaryTransform.DYNAMICTEASER);
                          op.addSource(name);
                        }
              | <MATCHEDELEMENTSONLY> { op.setTransform(SummaryTransform.MATCHED_ELEMENTS_FILTER); }
              | (<FULL> | <STATIC>) { op.setTransform(SummaryTransform.NONE); } )
    { return op; }
}

/**
 * This rule consumes a multi-line summary field.
 *
 * @return The consumed summary field.
 */
SummaryInFieldOperation summaryInFieldLong(FieldOperationContainer field) :
{
    String name = field.getName();
    DataType type = null;
}
{
    ( [ name = identifier() [ <TYPE> type = dataType() ] ]
      lbrace()
      {
          SummaryInFieldLongOperation op = new SummaryInFieldLongOperation(name);
          op.setType(type);
      }
      (summaryItem(op) (<NL>)*)* <RBRACE> )
    { return op; }
}

/**
 * This rule consumes an item of a summary field block.
 *
 * @param field The field to modify.
 * @return Null.
 */
Object summaryItem(SummaryInFieldLongOperation field) : { }
{
    ( summaryTransform(field)
      | summaryBolding(field)
      | summarySourceList(field)
      | summaryDestinationList(field)
      | summaryProperties(field) )
    { return null; }
}

/**
 * This rule consumes a transform statement for a summary field element.
 *
 * @param field            The field to modify.
 * @return Null.
 */
Object summaryTransform(SummaryInFieldOperation field) : { }
{
    ( <DYNAMIC>             { field.setTransform(SummaryTransform.DYNAMICTEASER); }
     | <MATCHEDELEMENTSONLY> { field.setTransform(SummaryTransform.MATCHED_ELEMENTS_FILTER); }
     | (<FULL> | <STATIC>) { field.setTransform(SummaryTransform.NONE); } )
    { return null; }
}

/**
 * This rule consumes a bolding statement for a summary field element.
 *
 * @param field The summary field to modify.
 */
void summaryBolding(SummaryInFieldLongOperation field) :
{
    boolean bold;
}
{
    <BOLDING> <COLON> bold = bool()
    { field.setBold(bold); }
}

/**
 * This rule consumes a source-list statement for a summary field element.
 *
 * @param field The summary field to modify.
 */
void summarySourceList(SummaryInFieldOperation field) :
{
    String str;
}
{
    ( <SOURCE> <COLON> str = identifier() { field.addSource(str); }
      (        <COMMA> str = identifier() { field.addSource(str); } )* ) +
}

/**
 * This rule consumes a destination-list statement for a summary field element.
 *
 * @param field The summary field to modify.
 */
void summaryDestinationList(SummaryInFieldLongOperation field) :
{
    String str;
}
{
    <TO> <COLON> str = identifier() { field.addDestination(str); }
    (    <COMMA> str = identifier() { field.addDestination(str); } )*
}

/**
 * This rule consumes properties for a summary field element.
 *
 * @param field The summary field to modify.
 */
void summaryProperties(SummaryInFieldLongOperation field) : { }
{
    <PROPERTIES> lbrace() (summaryProperty(field) <NL>)+ <RBRACE>
}

/**
 * This rule consumes a single summary property pair for a summary field element.
 *
 * @param field The summary field to modify.
 */
void summaryProperty(SummaryInFieldLongOperation field) :
{
    String name, value;
}
{
    name = identifierWithDash() <COLON> (value = identifierWithDash() | value = quotedString())
    { field.addProperty(new SummaryField.Property(name, value)); }
}

/**
 * This rule consumes a stemming block of a field element.
 *
 * @param field The field to modify.
 */
void fieldStemming(FieldOperationContainer field) :
{
    String setting;
    StemmingOperation op = new StemmingOperation();
}
{
    <STEMMING> <COLON> setting = identifierWithDash()
    {
        op.setSetting(setting);
        field.addOperation(op);
    }
}

/**
 * This rule consumes a stemming statement for a search element.
 *
 * @param search The search to modify.
 */
void searchStemming(Search search) :
{
    String setting;
}
{
    <STEMMING> <COLON> setting = identifierWithDash()
    { search.setStemming(Stemming.get(setting)); }
}

/**
 * This rule consumes a normalizing statement of a field element. At the moment, this can only be used to turn off
 * normalizing.
 *
 * @param field The field to modify.
 */
void normalizing(FieldOperationContainer field) :
{
    String setting;
}
{
    <NORMALIZING> <COLON> setting = identifierWithDash()
    {
        field.addOperation(new NormalizingOperation(setting));
    }
}

/**
 * This rule consumes a bolding statement of a field element.
 *
 * @param field The field to modify.
 */
void bolding(FieldOperationContainer field) :
{
    boolean bold;
}
{
    <BOLDING> <COLON> bold = bool()
    {
        field.addOperation(new BoldingOperation(bold));
    }
}

/**
 * This rule consumes a dictionary statement of a field element.
 *
 * @param field The field to modify.
 */
void dictionary(FieldOperationContainer field) :
{
}
{
    <DICTIONARY>
    ( (<COLON> dictionarySetting(field))
    | (lbrace() (dictionarySetting(field) (<NL>)*)* <RBRACE>))
    {
    }
}

void dictionarySetting(FieldOperationContainer field) :
{
    Dictionary.Type type;
}
{
    (   <HASH>            { field.addOperation(new DictionaryOperation(DictionaryOperation.Operation.HASH)); }
      | <BTREE>           { field.addOperation(new DictionaryOperation(DictionaryOperation.Operation.BTREE)); }
      | <CASED>           { field.addOperation(new DictionaryOperation(DictionaryOperation.Operation.CASED)); }
      | <UNCASED>           { field.addOperation(new DictionaryOperation(DictionaryOperation.Operation.UNCASED)); })
    {
    }
}

/**
 * This rule consumes a body statement of a field element.
 *
 * @param field The field to modify.
 */
void body(SDField field) : { }
{
    <BODY>
    {
        deployLogger.logApplicationPackage(Level.WARNING, field + ": 'header/body' is deprecated and has no effect.");
    }
}

/**
 * This rule consumes a header statement of a field element.
 *
 * @param field The field to modify.
 */
void header(SDField field) : { }
{
    <HEADER>
    {
        deployLogger.logApplicationPackage(Level.WARNING, field + ": 'header/body' is deprecated and has no effect.");
    }
}

void queryCommand(FieldOperationContainer container) :
{
    String command;
    QueryCommandOperation field = new QueryCommandOperation();
}
{
    <QUERYCOMMAND> <COLON> ( command = identifierWithDash() | command = quotedString() )
    {
        field.addQueryCommand(command);
        container.addOperation(field);
    }
}

void alias(FieldOperationContainer container) :
{
    String aliasedName = null;
    String alias;
}
{
    <ALIAS> [aliasedName = identifier()] <COLON> alias = identifierWithDash()
    {
       AliasOperation op = new AliasOperation(aliasedName, alias);
       container.addOperation(op);
    }
}

FieldOperationContainer match(FieldOperationContainer field) : { }
{
    <MATCH> ( (<COLON> matchType(field))
              | (lbrace() (matchItem(field) (<NL>)*)* <RBRACE>) )
    { return field; }
}

/**
 * This rule consumes a single match item for a match block.
 *
 * @param field The field to modify.
 * @return Null.
 */
Object matchItem(FieldOperationContainer field) : { }
{
    ( matchType(field) | exactTerminator(field) | gramSize(field) | matchSize(field) )
    { return null; }
}

Object matchType(FieldOperationContainer container) :
{
    MatchOperation matchOp = new MatchOperation();
}
{
    (   <MTOKEN>    { matchOp.setMatchingType(Matching.Type.TEXT); } // Deprecated synonym to TEXT
      | <TEXT>      { matchOp.setMatchingType(Matching.Type.TEXT); }
      | <WORD>      { matchOp.setMatchingType(Matching.Type.WORD); }
      | <EXACT>     { matchOp.setMatchingType(Matching.Type.EXACT); }
      | <GRAM>      { matchOp.setMatchingType(Matching.Type.GRAM); }
      | <CASED>     { matchOp.setCase(Case.CASED); }
      | <UNCASED>   { matchOp.setCase(Case.UNCASED); }
      | <PREFIX>    { matchOp.setMatchingAlgorithm(Matching.Algorithm.PREFIX); }
      | <SUBSTRING> { matchOp.setMatchingAlgorithm(Matching.Algorithm.SUBSTRING); }
      | <SUFFIX>    { matchOp.setMatchingAlgorithm(Matching.Algorithm.SUFFIX); } )
    {
        container.addOperation(matchOp);
        return null;
    }
}

void exactTerminator(FieldOperationContainer container) :
{
    String terminator;
    MatchOperation field = new MatchOperation();
}
{
    <EXACTTERMINATOR> <COLON> terminator = quotedString()
    {
        field.setExactMatchTerminator(terminator);
        container.addOperation(field);
    }
}

void gramSize(FieldOperationContainer container) :
{
    int gramSize;
    MatchOperation field = new MatchOperation();
}
{
    <GRAMSIZE> <COLON> gramSize = integer()
    {
        field.setGramSize(gramSize);
        container.addOperation(field);
    }
}

void matchSize(FieldOperationContainer container) :
{
    int matchSize;
    MatchOperation field = new MatchOperation();
}
{
    <MAXLENGTH> <COLON> matchSize = integer()
    {
        field.setMaxLength(matchSize);
        container.addOperation(field);
    }
}
/**
 * Consumes a rank statement of a field element.
 *
 * @param field The field to modify.
 * @return Null.
 */
Object rank(FieldOperationContainer field) :
{
    RankOperation op = new RankOperation();
}
{
    <RANK> ( (<COLON> rankSetting(op))
             | (lbrace() (rankSetting(op) (<NL>)*)* <RBRACE>) )
    {
        field.addOperation(op);
        return null;
    }
}

/**
 * Consumes a single rank setting of a rank statement.
 *
 * @param field The field to modify.
 * @return Null.
 */
Object rankSetting(RankOperation field) : { }
{
    ( <LITERAL>   { field.setLiteral(true); }
      | <NORMAL>  { field.setNormal(true); }
      | <FILTER>  { field.setFilter(true); } )
    { return null; }
}

/**
 * Consumes an id statement of a field body block.
 *
 * @param field    The field to modify.
 * @param document The document type to modify.
 */
void id(FieldOperationContainer field, SDDocumentType document) :
{
    int fieldId;
    IdOperation op = new IdOperation();
}
{
    <ID> <COLON> fieldId = integer()
    {
        op.setDocument(document);
        op.setFieldId(fieldId);
        field.addOperation(op);
    }
}

/**
 * Consumes an indexing-rewrite statement of a field body block.
 *
 * @param field The field to modify.
 */
void indexingRewrite(FieldOperationContainer field) : { }
{
    <INDEXINGREWRITE> <COLON> <NONE>
    { field.addOperation(new IndexingRewriteOperation()); }
}

/**
 * Consumes a document-summary block from within a search block.
 *
 * @param search The search object to add content to.
 * @return Null.
 */
Object documentSummary(Search search) :
{
    String name;
    DocumentSummary summary;
}
{
    ( <DOCUMENTSUMMARY>
      name = identifierWithDash() { search.addSummary(summary = new DocumentSummary(name)); }
      [inheritsDocumentSummary(summary, search)]
      lbrace()
         (
           <FROMDISK> { summary.setFromDisk(true); } |
           <OMITSUMMARYFEATURES> { summary.setOmitSummaryFeatures(true); } |
           documentSummaryItem(summary) |
           <NL>
         )*
      <RBRACE>
      )
    { return null; }
}

/**
 * This rule consumes an inherits statement of a document summary.
 *
 * @param documentSummary The document summary to modify.
 * @param search The search object documentSummary is being added to.
 */
void inheritsDocumentSummary(DocumentSummary documentSummary, Search search) :
{
    String name;
}
{
    <INHERITS> name = identifierWithDash()
    {
        documentSummary.setInherited(search.getSummaries().get(name));
    }
}

/**
 * Consumes a single document-summary item.
 *
 * @param summary The document summary to modify.
 * @return Null.
 */
Object documentSummaryItem(DocumentSummary summary) : { }
{
    summaryInDocument(summary)
    { return null; }
}

/**
 * Consumes an index block for a field element.
 *
 * @param search The search object to add content to.
 * @param field  The field to modify.
 * @return Null.
 */
Object index(Search search, FieldOperationContainer field) :
{
    IndexOperation op = new IndexOperation();
    String indexName = (field != null) ? field.getName() : null;
}
{
    <INDEX> [indexName = identifier()]
    {
        if (indexName == null) {
            throw new ParseException("Index statements outside fields must have an explicit name.");
        }
        op.setIndexName(indexName);
    }
    ( (<COLON> indexBody(op) (<COMMA> indexBody(op))*) |
      (lbrace() (indexBody(op) (<NL>)*)* <RBRACE>) )
    {
        if (field == null) {

            Index index = new Index(indexName);
            op.applyToIndex(index);
            search.addIndex(index);
        } else {
            field.addOperation(op);
        }
        return null;
    }
}

/**
 * Consumes a single index statement for an index block.
 *
 * @param index The index to modify.
 * @return Null.
 */
Object indexBody(IndexOperation index) :
{
    String str;
    int arity;
    long num;
    double threshold;
}
{
    ( <PREFIX>                                           { index.setPrefix(true); }
      | <ALIAS> <COLON> str = identifierWithDash()       { index.addAlias(str); }
      | <STEMMING> <COLON> str = identifierWithDash()    { index.setStemming(str); }
      | <ARITY> <COLON> arity = integer()                              { index.setArity(arity); }
      | <LOWERBOUND> <COLON> num = consumeLong()                       { index.setLowerBound(num); }
      | <UPPERBOUND> <COLON> num = consumeLong()                       { index.setUpperBound(num); }
      | <DENSEPOSTINGLISTTHRESHOLD> <COLON> threshold = consumeFloat() { index.setDensePostingListThreshold(threshold); }
      | <ENABLE_BM25>                                                  { index.setEnableBm25(true); }
      | hnswIndex(index)                                               { }
    )
    { return null; }
}

void hnswIndex(IndexOperation index) :
{
    HnswIndexParams.Builder params = new HnswIndexParams.Builder();
}
{
    ( LOOKAHEAD(<HNSW> lbrace())
      <HNSW> ( (lbrace() (hnswIndexBody(params) (<NL>)*)* <RBRACE>) ) |
      <HNSW> )
    {
        index.setHnswIndexParams(params);
    }
}

void hnswIndexBody(HnswIndexParams.Builder params) :
{
    int num;
    boolean bool;
}
{
    ( <MAXLINKSPERNODE> <COLON> num = integer() { params.setMaxLinksPerNode(num); }
      | <NEIGHBORSTOEXPLOREATINSERT> <COLON> num = integer() { params.setNeighborsToExploreAtInsert(num); }
      | <MULTITHREADEDINDEXING> <COLON> bool = bool() { params.setMultiThreadedIndexing(bool); } )
}

/**
 * Consumes a onnx-model block of a search element.
 *
 * @param search The search object to add content to.
 */
void onnxModel(Search search) :
{
    String name;
    OnnxModel onnxModel;
}
{
    ( <ONNXMODEL> name = identifier()
        {
            onnxModel = new OnnxModel(name);
        }
      lbrace() (onnxModelItem(onnxModel) (<NL>)*)+ <RBRACE> )
    {
        if (documentsOnly) return;
        search.onnxModels().add(onnxModel);
    }
}

/**
 * This rule consumes an onnx-model block.
 *
 * @param onnxModel The onnxModel to modify.
 * @return Null.
 */
Object onnxModelItem(OnnxModel onnxModel) :
{
    String path = null;
}
{
    (
        (<FILE> <COLON> path = filePath() { } (<NL>)*) { onnxModel.setFileName(path); } |
        (<URI> <COLON> path = uriPath() { } (<NL>)*) { onnxModel.setUri(path); } |
        (<ONNX_INPUT_SL>) {
            String name = token.image.substring(5, token.image.lastIndexOf(":")).trim();
            if (name.startsWith("\"")) { name = name.substring(1, name.length() - 1); }
            String source = token.image.substring(token.image.lastIndexOf(":") + 1).trim();
            onnxModel.addInputNameMapping(name, source);
        } |
        (<ONNX_OUTPUT_SL>) {
            String name = token.image.substring(6, token.image.lastIndexOf(":")).trim();
            if (name.startsWith("\"")) { name = name.substring(1, name.length() - 1); }
            String as = token.image.substring(token.image.lastIndexOf(":") + 1).trim();
            onnxModel.addOutputNameMapping(name, as);
        }
    )
    {
        return null;
    }
}

/**
 * Consumes a constant block of a search element.
 *
 * @param search The search object to add content to.
 */
void rankingConstant(Search search) :
{
    String name;
    RankingConstant constant;
}
{
    ( <CONSTANT> name = identifier()
        {
            constant = new RankingConstant(name);
        }
      lbrace() (rankingConstantItem(constant) (<NL>)*)+ <RBRACE> )
    {
        if (documentsOnly) return;
        search.rankingConstants().add(constant);
    }
}

/**
 * This rule consumes a constant block.
 *
 * @param constant The constant to modify.
 * @return Null.
 */
Object rankingConstantItem(RankingConstant constant) :
{
    String path = null;
    TensorType type = null;
}
{
    ( (<FILE> <COLON> path = filePath() { } (<NL>)*) { constant.setFileName(path); }
      | (<URI> <COLON> path = uriPath() { } (<NL>)*) { constant.setUri(path); }
      | type = tensorTypeWithPrefix(rankingConstantErrorMessage(constant.getName())) (<NL>)* { constant.setType(type); }
    )
    {
        return null;
    }
}

String rankingConstantErrorMessage(String name) : {}
{
    { return "For ranking constant ' " + name + "'"; }
}

String filePath() : { }
{
    ( <FILE_PATH> | <STRING> | <IDENTIFIER>)
    { return token.image; }
}

String uriPath() : { }
{
    ( <URI_PATH> )
    { return token.image; }
}

/**
 * Consumes a rank-profile block of a search element.
 *
 * @param search The search object to add content to.
 */
void rankProfile(Search search) :
{
    String name;
    RankProfile profile;
}
{
    ( ( <MODEL> | <RANKPROFILE> ) name = identifierWithDash()
        {
            if (documentsOnly) {
                profile = new DocumentsOnlyRankProfile(name, search, rankProfileRegistry, search.rankingConstants());
            }
            else if ("default".equals(name)) {
                profile = rankProfileRegistry.get(search, "default");
            } else {
                profile = new RankProfile(name, search, rankProfileRegistry, search.rankingConstants());
            }
        }
      [inheritsRankProfile(profile)]
      lbrace() (rankProfileItem(profile) (<NL>)*)* <RBRACE> )
    {
        if (documentsOnly) return;
        rankProfileRegistry.add(profile);
    }
}

/**
 * This rule consumes a single statement for a rank-profile block.
 *
 * @param profile The rank profile to modify.
 * @return Null.
 */
Object rankProfileItem(RankProfile profile) : { }
{
    ( fieldRankType(profile)
      | fieldWeight(profile)
      | fieldRankFilter(profile)
      | firstPhase(profile)
      | matchPhase(profile)
      | function(profile)
      | execute(profile)
      | ignoreRankFeatures(profile)
      | numThreadsPerSearch(profile)
      | minHitsPerThread(profile)
      | numSearchPartitions(profile)
      | termwiseLimit(profile)
      | rankFeatures(profile)
      | rankProperties(profile)
      | secondPhase(profile)
      | rankDegradation(profile)
      | constants(profile)
      | summaryFeatures(profile) )
    { return null; }
}

/**
 * This rule consumes an inherits statement of a rank-profile.
 *
 * @param profile The profile to modify.
 */
void inheritsRankProfile(RankProfile profile) :
{
    String str;
}
{
    <INHERITS> str = identifierWithDash()
    { profile.setInherited(str); }
}

/**
 * This rule consumes an execute statement of a rank-profile.
 *
 * @param profile The profile to modify.
 */
void execute(RankProfile profile) :
{
}
{
    <EXECUTE> lbrace() (execute_operation(profile) <NL>)+ <RBRACE>
    {  }
}

void execute_operation(RankProfile profile) :
{
    String attribute, operation;
    RankProfile.ExecuteOperation.Phase phase;
}
{
   ( <ON_MATCH> { phase = RankProfile.ExecuteOperation.Phase.onmatch; }
   | <ON_RERANK> { phase = RankProfile.ExecuteOperation.Phase.onrerank; }
   | <ON_SUMMARY> { phase = RankProfile.ExecuteOperation.Phase.onsummary; }
   )
   lbrace() attribute = identifier() operation = execute_expr() (<NL>)* <RBRACE>
   { profile.addExecuteOperation(phase, attribute, operation); }
}

String execute_expr() :
{
     String op;
     Number constant = null;
}
{
    (("++" | "--") { op = token.image; } | ("+=" | "-=" | "*=" | "/=" | "%=" | "=") { op = token.image; } constant = consumeNumber())
    { return constant != null ? (op + constant) : op; }
}

/**
 * This rule consumes a function statement of a rank-profile.
 *
 * @param profile The profile to modify.
 */
void function(RankProfile profile) :
{
    String name, expression, parameter;
    List parameters = new ArrayList();
    boolean inline = false;
}
{
    (  ( <FUNCTION> | <MACRO> ) inline = inline() name = identifier() [ "$" { name = name + token.image; } ]
      "("
          [ parameter = identifier()         { parameters.add(parameter); }
          ( <COMMA> parameter = identifier() { parameters.add(parameter); } )* ]
      ")"
      lbrace() expression = expression() (<NL>)* <RBRACE> )
    { profile.addFunction(name, parameters, expression, inline); }
}

boolean inline() :
{
}
{
    ( <INLINE> { return true; } ) ?
    { return false; }
}

/**
 * This rule consumes a match-phase block of a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void matchPhase(RankProfile profile) :
{
    MatchPhaseSettings settings = new MatchPhaseSettings();
}
{
    <MATCHPHASE> lbrace() (matchPhaseItem(settings) (<NL>)*)* <RBRACE>
    {
        settings.checkValid();
 	    profile.setMatchPhaseSettings(settings);
    }
}

void matchPhaseItem(MatchPhaseSettings settings) :
{
    String str;
    int num;
    double multiplier;
    double coverage;
}
{
    ( <ATTRIBUTE> <COLON> str = identifier() { settings.setAttribute(str); }
      | diversity(settings)
      | <ORDER> <COLON> ( <ASCENDING> { settings.setAscending(true); } 
                          | <DESCENDING> { settings.setAscending(false); } )
      | <MAXHITS> <COLON> num = integer() { settings.setMaxHits(num); }
      | <MAXFILTERCOVERAGE> <COLON> coverage = consumeFloat() { settings.setMaxFilterCoverage(coverage); }
      | <EVALUATION_POINT> <COLON> multiplier = consumeFloat() { settings.setEvaluationPoint(multiplier); }
      | <PRE_POST_FILTER_TIPPING_POINT> <COLON> multiplier = consumeFloat() { settings.setPrePostFilterTippingPoint(multiplier); }
    )
    { return; }
}

/**
 * This rule consumes a diversity block of a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void diversity(MatchPhaseSettings profile) :
{
    DiversitySettings settings = new DiversitySettings();
}
{
    <DIVERSITY> lbrace() (diversityItem(settings) (<NL>)*)* <RBRACE>
    {
 	    profile.setDiversity(settings);
    }
}

void diversityItem(DiversitySettings settings) :
{
    String str;
    int num;
    double multiplier;
}
{
    (   <ATTRIBUTE> <COLON> str = identifier() { settings.setAttribute(str); }
      | <MIN_GROUPS> <COLON> num = integer() { settings.setMinGroups(num); }
      | <CUTOFF_FACTOR> <COLON> multiplier = consumeFloat() { settings.setCutoffFactor(multiplier); }
      | <CUTOFF_STRATEGY> <COLON>
        (   <STRICT> { settings.setCutoffStrategy(Diversity.CutoffStrategy.strict); }
          | <LOOSE>  { settings.setCutoffStrategy(Diversity.CutoffStrategy.loose); }
        )
    )
    { return; }
}



/**
 * Consumes the first-phase block of a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void firstPhase(RankProfile profile) :
{
    String exp;
}
{
    <FIRSTPHASE> lbrace() (firstPhaseItem(profile) (<NL>)*)* <RBRACE>
}

Object firstPhaseItem(RankProfile profile) :
{
  String expression;
  int rerankCount;
  double dropLimit;
}
{
    ( expression = expression()                        { profile.setFirstPhaseRanking(expression); }
      | (<KEEPRANKCOUNT> <COLON> rerankCount = integer()) { profile.setKeepRankCount(rerankCount); }
      | (<RANKSCOREDROPLIMIT> <COLON> dropLimit = consumeFloat()) { profile.setRankScoreDropLimit(dropLimit); }
    )
    { return null; }
}

/**
 * Consumes the second-phase block of a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void secondPhase(RankProfile profile) : { }
{
    <SECONDPHASE> lbrace() (secondPhaseItem(profile) (<NL>)*)* <RBRACE>
}

/**
 * Consumes a statement for a second-phase block.
 *
 * @param profile The rank profile to modify.
 * @return Null.
 */
Object secondPhaseItem(RankProfile profile) :
{
    String expression;
    int rerankCount;
}
{
    ( expression = expression()                 { profile.setSecondPhaseRanking(expression); }
      | (<RERANKCOUNT> <COLON> rerankCount = integer()) { profile.setRerankCount(rerankCount); }
    )
    { return null; }
}

/**
 * This rule consumes a summary-features block of a rank profile.
 *
 * @param profile The rank profile to modify.
 * @return Null.
 */
Object summaryFeatures(RankProfile profile) :
{
    String features;
    String inherited = null;
}
{
    ( <SUMMARYFEATURES_SL> { features = token.image.substring(token.image.indexOf(":") + 1).trim(); } |
      <SUMMARYFEATURES_ML> { features = token.image.substring(token.image.indexOf("{") + 1,
                                                              token.image.lastIndexOf("}")).trim(); } |
      <SUMMARYFEATURES_ML_INHERITS> {
          int inheritsIndex = token.image.indexOf("inherits ");
          String rest = token.image.substring(inheritsIndex + "inherits ".length());
          profile.setInheritedSummaryFeatures(rest.substring(0, rest.indexOf(" ")).trim());
          features = token.image.substring(token.image.indexOf("{") + 1, token.image.lastIndexOf("}")).trim();
      }
    )
    {
        profile.addSummaryFeatures(getFeatureList(features));
        return null;
    }
}

/** Consumes a rank-features block of a rank profile */
Object rankFeatures(RankProfile profile) :
{
    String features;
}
{
    ( <RANKFEATURES_SL> { features = token.image.substring(token.image.indexOf(":") + 1).trim(); } |
      <RANKFEATURES_ML> { features = token.image.substring(token.image.indexOf("{") + 1,
                                                           token.image.lastIndexOf("}")).trim(); } )
    {
        profile.addRankFeatures(getFeatureList(features));
        return null;
    }
}

/**
 * This rule consumes a ignore-default-rank-features statement for a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void ignoreRankFeatures(RankProfile profile) : { }
{
    <IGNOREDEFAULTRANKFEATURES> { profile.setIgnoreDefaultRankFeatures(true); }
}

/**
 * This rule consumes a num-threads-per-search statement for a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void numThreadsPerSearch(RankProfile profile) :
{
    int num;
}
{
    (<NUMTHREADSPERSEARCH> <COLON> num = integer()) { profile.setNumThreadsPerSearch(num); }
}

/**
 * This rule consumes a min-hits-per-thread statement for a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void minHitsPerThread(RankProfile profile) :
{
    int num;
}
{
    (<MINHITSPERTHREAD> <COLON> num = integer()) { profile.setMinHitsPerThread(num); }
}

/**
 * This rule consumes a num-search-partitions statement for a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void numSearchPartitions(RankProfile profile) :
{
    int num;
}
{
    (<NUMSEARCHPARTITIONS> <COLON> num = integer()) { profile.setNumSearchPartitions(num); }
}

/**
 * This rule consumes a num-threads-per-search statement for a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void termwiseLimit(RankProfile profile) :
{
    double num;
}
{
    (<TERMWISELIMIT> <COLON> num = consumeFloat()) { profile.setTermwiseLimit(num); }
}
/**
 * This rule consumes a rank-properties block of a rank profile. There is a little trick within this rule to allow the
 * final rank property to skip the terminating newline token.
 *
 * @param profile The rank profile to modify.
 */
void rankProperties(RankProfile profile) : { }
{
    <RANKPROPERTIES> lbrace() (LOOKAHEAD(rankPropertyItem() <COLON> rankPropertyItem() <NL>)
                               rankProperty(profile) (<NL>)+)* [rankProperty(profile)] <RBRACE>
}

/**
 * This rule consumes a single rank property pair for a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void rankProperty(RankProfile profile) :
{
    String key, val;
}
{
    key = rankPropertyItem() <COLON> val = rankPropertyItem()
    { profile.addRankProperty(key, val); }
}


/**
 * This rule consumes a single rank property for a rank-properties block.
 *
 * @return The token image of the consumed item.
 */
String rankPropertyItem() :
{
    String image, ret = "";
}
{
    ( ( image = identifierWithDash()              { ret += image; }
        | image = quotedString()                  { ret += image; }
        | ( "(" | ")" | <DOT> | <COMMA> )         { ret += token.image; } )+ )
    { return ret; }
}

/**
 * This rule consumes a field-weight statement of a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void fieldWeight(RankProfile profile) :
{
    Integer num;
    String name;
}
{
    <WEIGHT> name = identifier() <COLON> num = integer()
    { profile.addRankSetting(name, RankProfile.RankSetting.Type.WEIGHT, num); }
}

/**
 * This rule consumes a rank-type statement of a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void fieldRankType(RankProfile profile) :
{
    String name;
    String type;
}
{
    <RANKTYPE> name = identifier() <COLON> type = identifier()
    { profile.addRankSetting(name, RankProfile.RankSetting.Type.RANKTYPE, RankType.fromString(type)); }
}

/**
 * This rule consumes a rank filter statement of a rank profile.
 *
 * @param profile The rank profile to modify.
 */
void fieldRankFilter(RankProfile profile) :
{
    String name;
}
{
    <RANK> name = identifier() <COLON> <FILTER>
    { profile.addRankSetting(name, RankProfile.RankSetting.Type.PREFERBITVECTOR, Boolean.TRUE); }
}

/**
 * This rule consumes part of a rank-degradation statement of a rank profile.
 */
void rankDegradationBinSize() :
{
    double freq;
}
{
    <RPBINSIZE> <COLON> freq = consumeFloat()
    { deployLogger.logApplicationPackage(Level.WARNING, "Specifying 'doc-frequency' in 'rank-degradation' is deprecated and has no effect."); }
}


/**
 * This rule consumes part of a rank-degradation statement of a rank profile.
 */
void rankDegradationBinLow() :
{
    int n;
}
{
    <RPBINLOW> <COLON> n = integer()
    { deployLogger.logApplicationPackage(Level.WARNING, "Specifying 'min-fullrank-docs' in 'rank-degradation' is deprecated and has no effect."); }
}


/**
 * This rule consumes part of a rank-degradation statement of a rank profile.
 */
void rankDegradationPosbinSize() :
{
    double avgOcc;
}
{
    <RPPOSBINSIZE> <COLON> avgOcc = consumeFloat()
    { deployLogger.logApplicationPackage(Level.WARNING, "Specifying 'occurrences-per-doc' in 'rank-degradation' is deprecated and has no effect."); }
}


/**
 * This rule consumes part of a rank-degradation statement of a rank profile.
 */
Object rankDegradationItem() :
{
}
{
    ( rankDegradationBinSize()
      | rankDegradationBinLow()
      | rankDegradationPosbinSize() )
    { return null; }
}

/**
 * This rule consumes a rank-degradation statement of a rank profile.
 *
 * @param profile The rank profile to modify.
 */
Object rankDegradation(RankProfile profile) :
{
    double freq;
}
{
    ( <RANKDEGRADATIONFREQ> <COLON> freq = consumeFloat()
    { deployLogger.logApplicationPackage(Level.WARNING, "Specifying 'rank-degradation-frequency' in 'rank-profile' is deprecated and has no effect."); }
      | <RANKDEGRADATION> lbrace() ( rankDegradationItem() (<NL>)*)+ <RBRACE>
    )
    {
        return null;
    }
}

/**
 * Consumes a set of constants available in ranking expressions in the enclosing profile.
 */
void constants(RankProfile profile) :
{
    String name;
}
{
    <CONSTANTS> <LBRACE> (<NL>)*
      ( name = identifier() ( constantValue(profile, name) |
                              constantTensor(profile, name) ) (<NL>)* )*
    <RBRACE>
}

void constantValue(RankProfile profile, String name) :
{
    String value;
}
{
    <COLON> value = identifier() { profile.addConstant(name, Value.parse(value)); }
}

void constantTensor(RankProfile profile, String name) :
{
    String tensorString = "";
    TensorType tensorType = null;
}
{
    <LBRACE> (<NL>)*
      (( tensorString = tensorValue() |
         tensorType = tensorTypeWithPrefix(constantTensorErrorMessage(profile.getName(), name)) ) (<NL>)* )* <RBRACE>
    {
        if (tensorType != null) {
            profile.addConstantTensor(name, new TensorValue(Tensor.from(tensorType, tensorString)));
        } else {
            profile.addConstantTensor(name, new TensorValue(Tensor.from(tensorString)));
        }
    }
}

String constantTensorErrorMessage(String rankProfileName, String constantTensorName) : {}
{
    { return "For constant tensor '" + constantTensorName + "' in rank profile '" + rankProfileName + "'"; }
}

String tensorValue() :
{
    String tensor;
}
{
    ( <TENSOR_VALUE_SL> { tensor = token.image.substring(token.image.indexOf(":") + 1); } |
      <TENSOR_VALUE_ML> { tensor = token.image.substring(token.image.indexOf("{") + 1,
                                                         token.image.lastIndexOf("}")); } )
    {
        return tensor;
    }
}

TensorType tensorTypeWithPrefix(String errorMessage) :
{ TensorType type; }
{
    <TYPE> <COLON> type= tensorType(errorMessage)
    { return type; }
}

TensorType tensorType(String errorMessage) :
{
    String tensorTypeString;
}
{
    ( <TENSOR_TYPE> ) { tensorTypeString = token.image; }
    {
        TensorType tensorType;
        try {
            tensorType = TensorType.fromSpec(tensorTypeString);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(errorMessage + ": Illegal tensor type spec: " + e.getMessage());
        }
        return tensorType;
    }
}

void importField(Search search) :
{
    String fieldRefSpec;
    String aliasFieldName;
}
{
    <IMPORT> <FIELD> fieldRefSpec = identifier() <AS> aliasFieldName = identifier() lbrace()
    <RBRACE>
    {
        long nDots = Utils.count(fieldRefSpec, '.');
        if (nDots != 1) {
            throw new IllegalArgumentException("Illegal field reference spec '" + fieldRefSpec + "': Does not include a single '.'");
        }
        int indexOfDot = fieldRefSpec.indexOf('.');
        String documentReferenceFieldName = fieldRefSpec.substring(0, indexOfDot);
        String foreignFieldName = fieldRefSpec.substring(indexOfDot + 1);
        TemporaryImportedFields importedFields = search.temporaryImportedFields().get();
        if (importedFields.hasField(aliasFieldName)) {
            throw new IllegalArgumentException("For search '" + search.getName() + "', import field as '" + aliasFieldName + "': Field already imported");
        }
        importedFields.add(new TemporaryImportedField(aliasFieldName, documentReferenceFieldName, foreignFieldName));
    }
}


/**
 * This rule consumes an expression token and returns its image.
 *
 * @return The consumed token image.
 */
String expression() :
{
    String exp;
}
{
    ( <EXPRESSION_SL> { exp = token.image.substring(token.image.indexOf(":") + 1); } |
      <EXPRESSION_ML> { exp = token.image.substring(token.image.indexOf("{") + 1,
                                                    token.image.lastIndexOf("}")); } )
    { return exp; }
}

String identifierWithDash() :
{
    String identifier;
}
{
    ( identifier = identifier() { return identifier; } )
    |
    ( <IDENTIFIER_WITH_DASH> { return token.image; } )
}

/**
 * Consumes an identifier. This must be kept in sync with all word tokens that should be parseable as
 * identifiers.
 *
 * @return the identifier string
 */
String identifier() : { }
{
    ( <ALIAS>
      | <ALWAYS>
      | <ANNOTATION>
      | <ANNOTATIONREFERENCE>
      | <ARITY>
      | <ARRAY>
      | <AS>
      | <ASCENDING>
      | <ATTRIBUTE>
      | <BODY>
      | <BOLDING>
      | <BTREE>
      | <CASED>
      | <COMPRESSION>
      | <COMPRESSIONLEVEL>
      | <COMPRESSIONTHRESHOLD>
      | <CONTEXT>
      | <CREATEIFNONEXISTENT>
      | <DENSEPOSTINGLISTTHRESHOLD>
      | <DESCENDING>
      | <DICTIONARY>
      | <DIRECT>
      | <DOCUMENT>
      | <DOCUMENTSUMMARY>
      | <DOUBLE>
      | <DYNAMIC>
      | <ENABLEBITVECTORS>
      | <ENABLEONLYBITVECTOR>
      | <EXACT>
      | <EXACTTERMINATOR>
      | <FALSE>
      | <FASTACCESS>
      | <FASTSEARCH>
      | <FIELD>
      | <FIELDS>
      | <FIELDSET>
      | <FILE>
      | <FILTER>
      | <FIRSTPHASE>
      | <FULL>
      | <FUNCTION>
      | <GRAM>
      | <HASH>
      | <HEADER>
      | <HUGE>
      | <ID>
      | <IDENTICAL>
      | <IDENTIFIER>
      | <IGNOREDEFAULTRANKFEATURES>
      | <IMPORT>
      | <INDEX>
      | <INDEXING>
      | <INDEXINGREWRITE>
      | <INHERITS>
      | <INTEGER>
      | <KEEPRANKCOUNT>
      | <LITERAL>
      | <LOCALE>
      | <LONG>
      | <LOWERBOUND>
      | <LOWERCASE>
      | <MACRO>
      | <MAP>
      | <MATCH>
      | <MATCHPHASE>
      | <MAXFILTERCOVERAGE>
      | <MAXHITS>
      | <MTOKEN>
      | <MUTABLE>
      | <NEVER>
      | <NONE>
      | <NORMAL>
      | <NORMALIZING>
      | <OFF>
      | <ON>
      | <ONDEMAND>
      | <ORDER>
      | <PREFIX>
      | <PRIMARY>
      | <PROPERTIES>
      | <QUATERNARY>
      | <QUERYCOMMAND>
      | <RANK>
      | <MODEL>
      | <RANKPROFILE>
      | <RANKPROPERTIES>
      | <RANKSCOREDROPLIMIT>
      | <RANKTYPE>
      | <RAW>
      | <REFERENCE>
      | <REMOVEIFZERO>
      | <RERANKCOUNT>
      | <SCHEMA>
      | <SEARCH>
      | <SECONDARY>
      | <SECONDPHASE>
      | <SORTING>
      | <SOURCE>
      | <PAGED>
      | <SSCONTEXTUAL>
      | <SSOVERRIDE>
      | <SSTITLE>
      | <SSURL>
      | <STATIC>
      | <STEMMING>
      | <STRENGTH>
      | <STRING>
      | <STRUCT>
      | <SUBSTRING>
      | <SUFFIX>
      | <SUMMARY>
      | <SUMMARYTO>
      | <SYMMETRIC>
      | <TERTIARY>
      | <TEXT>
      | <TO>
      | <TRUE>
      | <TYPE>
      | <UCA>
      | <UNCASED>
      | <URI>
      | <UPPERBOUND>
      | <USEDOCUMENT>
      | <VARIABLE>
      | <WEIGHT>
      | <WEIGHTEDSET>
      | <WORD>
      | <INLINE>
      | <CONSTANTS>
    )
    { return token.image; }
}

/**
 * Consumes a string token and returns the token image.
 *
 * @return The consumed token image.
 */
String string() : { }
{
    <STRING> { return token.image; }
}

/**
 * Consumes a quoted string token and returns the token image minus the quotes. This does not perform
 * unescaping of the content, it simply removes the first and last character of the image. However, the token itself can
 * contain anything but a double quote.
 *
 * @return The unquoted token image.
 */
String quotedString() : { }
{
    <QUOTEDSTRING> { return token.image.substring(1, token.image.length() - 1); }
}

/**
 * This rule consumes a boolean value.
 *
 * @return The consumed boolean value.
 */
Boolean bool() : { }
{
    ( ( <ON>  | <TRUE> )  { return true; } |
      ( <OFF> | <FALSE> ) { return false; } )
}

/**
 * This rule consumes an integer token and returns its numeric value.
 *
 * @return The consumed integer value.
 */
int integer() : { }
{
    <INTEGER> { return Integer.parseInt(token.image); }
}

/**
 * This rule consumes a long or integer token and returns its numeric value.
 *
 * @return The consumed long value.
 */
long consumeLong() : { }
{
    ( <INTEGER> { return Long.parseLong(token.image); } |
      <LONG>    { return Long.parseLong(token.image.substring(0, token.image.length()-1)); }
    )
}

/**
 * This rule consumes a floating-point token and returns its numeric value.
 *
 * @return The consumed value.
 */
double consumeFloat() : { }
{
    <DOUBLE> { return Double.valueOf(token.image); }
}

Number consumeNumber() :
{
    Number num;
}
{
    (num = consumeFloat() | num = consumeLong()) { return num; }
}

/**
 * This rule consumes an opening brace with leading and trailing newline tokens.
 */
void lbrace() : { }
{
    (<NL>)* <LBRACE> (<NL>)*
}