aboutsummaryrefslogtreecommitdiffstats
path: root/yql/essentials/sql/v1/format/sql_format.cpp
blob: 262f9b29198e1be26ec01c3efcdb341f4a5c9c9e (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
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
#include "sql_format.h"

#include <yql/essentials/parser/lexer_common/lexer.h>
#include <yql/essentials/core/sql_types/simple_types.h>

#include <yql/essentials/sql/v1/lexer/lexer.h>
#include <yql/essentials/sql/v1/proto_parser/proto_parser.h>

#include <yql/essentials/parser/proto_ast/gen/v1_proto_split/SQLv1Parser.pb.main.h>

#include <library/cpp/protobuf/util/simple_reflection.h>
#include <library/cpp/resource/resource.h>

#include <util/string/builder.h>
#include <util/string/split.h>
#include <util/string/strip.h>
#include <util/string/subst.h>
#include <util/generic/hash_set.h>


namespace NSQLFormat {

namespace {

using namespace NSQLv1Generated;

using NSQLTranslation::TParsedToken;
using NSQLTranslation::TParsedTokenList;
using NSQLTranslationV1::IsProbablyKeyword;
using TTokenIterator = TParsedTokenList::const_iterator;

TTokenIterator SkipWS(TTokenIterator curr, TTokenIterator end) {
    while (curr != end && curr->Name == "WS") {
        ++curr;
    }
    return curr;
}

TTokenIterator SkipWSOrComment(TTokenIterator curr, TTokenIterator end) {
    while (curr != end && (curr->Name == "WS" || curr->Name == "COMMENT")) {
        ++curr;
    }
    return curr;
}

bool Validate(const TParsedTokenList& query, const TParsedTokenList& formattedQuery) {
    auto in = query.begin();
    auto out = formattedQuery.begin();
    auto inEnd = query.end();
    auto outEnd = formattedQuery.end();

    while (in != inEnd && out != outEnd) {
        in = SkipWS(in, inEnd);
        out = SkipWS(out, outEnd);
        if (in != inEnd && out != outEnd) {
            if (in->Name != out->Name) {
                return false;
            }
            if (IsProbablyKeyword(*in)) {
                if (!AsciiEqualsIgnoreCase(in->Content, out->Content)) {
                    return false;
                }
            } else {
                if (in->Content != out->Content) {
                    return false;
                }
            }
            ++in;
            ++out;
        }
    }
    in = SkipWS(in, inEnd);
    out = SkipWS(out, outEnd);
    return in == inEnd && out == outEnd;
}

enum EParenType {
    Open,
    Close,
    None
};

using TAdvanceCallback = std::function<EParenType(TTokenIterator& curr, TTokenIterator end)>;

TTokenIterator SkipToNextBalanced(TTokenIterator begin, TTokenIterator end, const TAdvanceCallback& advance) {
    i64 level = 0;
    TTokenIterator curr = begin;
    while (curr != end) {
        switch (advance(curr, end)) {
            case EParenType::Open: {
                ++level;
                break;
            }
            case EParenType::Close: {
                --level;
                if (level < 0) {
                    return end;
                } else if (level == 0) {
                    return curr;
                }
                break;
            }
            case EParenType::None:
                break;
        }
    }
    return curr;
}

TTokenIterator GetNextStatementBegin(TTokenIterator begin, TTokenIterator end) {
    TAdvanceCallback advanceLambdaBody = [](TTokenIterator& curr, TTokenIterator end) -> EParenType {
        Y_UNUSED(end);
        if (curr->Name == "LBRACE_CURLY") {
            ++curr;
            return EParenType::Open;
        } else if (curr->Name == "RBRACE_CURLY") {
            ++curr;
            return EParenType::Close;
        } else {
            ++curr;
            return EParenType::None;
        }
    };

    TAdvanceCallback advanceAction = [](TTokenIterator& curr, TTokenIterator end) -> EParenType {
        auto tmp = curr;
        if (curr->Name == "DEFINE") {
            ++curr;
            curr = SkipWSOrComment(curr, end);
            if (curr != end && (curr->Name == "ACTION" || curr->Name == "SUBQUERY")) {
                ++curr;
                return EParenType::Open;
            }
        } else if (curr->Name == "END") {
            ++curr;
            curr = SkipWSOrComment(curr, end);
            if (curr != end && curr->Name == "DEFINE") {
                ++curr;
                return EParenType::Close;
            }
        }

        curr = tmp;
        ++curr;
        return EParenType::None;
    };

    TAdvanceCallback advanceInlineAction = [](TTokenIterator& curr, TTokenIterator end) -> EParenType {
        auto tmp = curr;
        if (curr->Name == "DO") {
            ++curr;
            curr = SkipWSOrComment(curr, end);
            if (curr != end && curr->Name == "BEGIN") {
                ++curr;
                return EParenType::Open;
            }
        } else if (curr->Name == "END") {
            ++curr;
            curr = SkipWSOrComment(curr, end);
            if (curr != end && curr->Name == "DO") {
                ++curr;
                return EParenType::Close;
            }
        }

        curr = tmp;
        ++curr;
        return EParenType::None;
    };

    TTokenIterator curr = begin;
    while (curr != end) {
        bool matched = false;
        for (auto cb : {advanceLambdaBody, advanceAction, advanceInlineAction}) {
            TTokenIterator tmp = curr;
            if (cb(tmp, end) == EParenType::Open) {
                curr = SkipToNextBalanced(curr, end, cb);
                matched = true;
                if (curr == end) {
                    return curr;
                }
            }
        }
        if (matched) {
            continue;
        }
        if (curr->Name == "SEMICOLON") {
            ++curr;
            break;
        }
        ++curr;
    }

    return curr;
}

void SplitByStatements(TTokenIterator begin, TTokenIterator end, TVector<TTokenIterator>& output) {
    output.clear();
    if (begin == end) {
        return;
    }
    output.push_back(begin);
    auto curr = begin;
    while (curr != end) {
        curr = GetNextStatementBegin(curr, end);
        output.push_back(curr);
    }
}

enum class EScope {
    Default,
    TypeName,
    Identifier,
    DoubleQuestion
};

class TPrettyVisitor;
using TPrettyFunctor = std::function<void(TPrettyVisitor&, const NProtoBuf::Message& msg)>;
class TObfuscatingVisitor;
using TObfuscatingFunctor = std::function<void(TObfuscatingVisitor&, const NProtoBuf::Message& msg)>;

struct TStaticData {
    TStaticData();
    static const TStaticData& GetInstance() {
        return *Singleton<TStaticData>();
    }

    THashSet<TString> Keywords;
    THashMap<const NProtoBuf::Descriptor*, EScope> ScopeDispatch;
    THashMap<const NProtoBuf::Descriptor*, TPrettyFunctor> PrettyVisitDispatch;
    THashMap<const NProtoBuf::Descriptor*, TObfuscatingFunctor> ObfuscatingVisitDispatch;
};

template <typename T, void (T::*Func)(const NProtoBuf::Message&)>
void VisitAllFieldsImpl(T* obj, const NProtoBuf::Descriptor* descr, const NProtoBuf::Message& msg) {
    for (int i = 0; i < descr->field_count(); ++i) {
        const NProtoBuf::FieldDescriptor* fd = descr->field(i);
        NProtoBuf::TConstField field(msg, fd);
        if (field.IsMessage()) {
            for (size_t j = 0; j < field.Size(); ++j) {
                (obj->*Func)(*field.template Get<NProtoBuf::Message>(j));
            }
        }
    }
}

class TObfuscatingVisitor {
friend struct TStaticData;
public:
    TObfuscatingVisitor()
        : StaticData(TStaticData::GetInstance())
    {}

    TString Process(const NProtoBuf::Message& msg) {
        Scopes.push_back(EScope::Default);
        Visit(msg);
        return SB;
    }

private:
    void VisitToken(const TToken& token) {
        auto str = token.GetValue();
        if (str == "<EOF>") {
            return;
        }

        if (!First) {
            SB << ' ';
        } else {
            First = false;
        }

        if (str == "$" && FuncCall) {
            FuncCall = false;
        }

        if (Scopes.back() == EScope::Identifier && !FuncCall) {
            if (str != "$" && !NYql::LookupSimpleTypeBySqlAlias(str, true)) {
                SB << "id";
            } else {
                SB << str;
            }
        } else if (NextToken) {
            SB << *NextToken;
            NextToken = Nothing();
        } else {
            SB << str;
        }
    }

    void VisitPragmaValue(const TRule_pragma_value& msg) {
        switch (msg.Alt_case()) {
        case TRule_pragma_value::kAltPragmaValue1: {
            NextToken = "0";
            break;
        }
        case TRule_pragma_value::kAltPragmaValue3: {
            NextToken = "'str'";
            break;
        }
        case TRule_pragma_value::kAltPragmaValue4: {
            NextToken = "false";
            break;
        }
        default:;
        }
        VisitAllFields(TRule_pragma_value::GetDescriptor(), msg);
    }

    void VisitLiteralValue(const TRule_literal_value& msg) {
        switch (msg.Alt_case()) {
        case TRule_literal_value::kAltLiteralValue1: {
            NextToken = "0";
            break;
        }
        case TRule_literal_value::kAltLiteralValue2: {
            NextToken = "0.0";
            break;
        }
        case TRule_literal_value::kAltLiteralValue3: {
            NextToken = "'str'";
            break;
        }
        case TRule_literal_value::kAltLiteralValue9: {
            NextToken = "false";
            break;
        }
        default:;
        }

        VisitAllFields(TRule_literal_value::GetDescriptor(), msg);
    }

    void VisitAtomExpr(const TRule_atom_expr& msg) {
        switch (msg.Alt_case()) {
        case TRule_atom_expr::kAltAtomExpr7: {
            FuncCall = true;
            break;
        }
        default:;
        }

        VisitAllFields(TRule_atom_expr::GetDescriptor(), msg);
        FuncCall = false;
    }

    void VisitInAtomExpr(const TRule_in_atom_expr& msg) {
        switch (msg.Alt_case()) {
        case TRule_in_atom_expr::kAltInAtomExpr6: {
            FuncCall = true;
            break;
        }
        default:;
        }

        VisitAllFields(TRule_in_atom_expr::GetDescriptor(), msg);
        FuncCall = false;
    }

    void VisitUnaryCasualSubexpr(const TRule_unary_casual_subexpr& msg) {
        bool invoke = false;
        for (auto& b : msg.GetRule_unary_subexpr_suffix2().GetBlock1()) {
            switch (b.GetBlock1().Alt_case()) {
            case TRule_unary_subexpr_suffix::TBlock1::TBlock1::kAlt2: {
                invoke = true;
                break;
            }
            default:;
            }

            break;
        }

        if (invoke) {
            FuncCall = true;
        }

        Visit(msg.GetBlock1());
        if (invoke) {
            FuncCall = false;
        }

        Visit(msg.GetRule_unary_subexpr_suffix2());
    }

    void VisitInUnaryCasualSubexpr(const TRule_in_unary_casual_subexpr& msg) {
        bool invoke = false;
        for (auto& b : msg.GetRule_unary_subexpr_suffix2().GetBlock1()) {
            switch (b.GetBlock1().Alt_case()) {
            case TRule_unary_subexpr_suffix::TBlock1::TBlock1::kAlt2: {
                invoke = true;
                break;
            }
            default:;
            }

            break;
        }

        if (invoke) {
            FuncCall = true;
        }

        Visit(msg.GetBlock1());
        if (invoke) {
            FuncCall = false;
        }

        Visit(msg.GetRule_unary_subexpr_suffix2());
    }

    void Visit(const NProtoBuf::Message& msg) {
        const NProtoBuf::Descriptor* descr = msg.GetDescriptor();
        auto scopePtr = StaticData.ScopeDispatch.FindPtr(descr);
        if (scopePtr) {
            Scopes.push_back(*scopePtr);
        }

        auto funcPtr = StaticData.ObfuscatingVisitDispatch.FindPtr(descr);
        if (funcPtr) {
            (*funcPtr)(*this, msg);
        } else {
            VisitAllFields(descr, msg);
        }

        if (scopePtr) {
            Scopes.pop_back();
        }
    }

    void VisitAllFields(const NProtoBuf::Descriptor* descr, const NProtoBuf::Message& msg) {
        VisitAllFieldsImpl<TObfuscatingVisitor, &TObfuscatingVisitor::Visit>(this, descr, msg);
    }

    const TStaticData& StaticData;
    TStringBuilder SB;
    bool First = true;
    TMaybe<TString> NextToken;
    TVector<EScope> Scopes;
    bool FuncCall = false;
};

class TPrettyVisitor {
friend struct TStaticData;
public:
    TPrettyVisitor(const TParsedTokenList& parsedTokens, const TParsedTokenList& comments)
        : StaticData(TStaticData::GetInstance())
        , ParsedTokens(parsedTokens)
        , Comments(comments)
    {
    }

    TString Process(const NProtoBuf::Message& msg, bool& addLine) {
        Scopes.push_back(EScope::Default);
        MarkedTokens.reserve(ParsedTokens.size());
        MarkTokens(msg);
        Y_ENSURE(MarkTokenStack.empty());
        Y_ENSURE(TokenIndex == ParsedTokens.size());
        TokenIndex = 0;
        Visit(msg);
        Y_ENSURE(TokenIndex == ParsedTokens.size());
        Y_ENSURE(MarkTokenStack.empty());
        for (; LastComment < Comments.size(); ++LastComment) {
            const auto text = Comments[LastComment].Content;
            AddComment(text);
        }
        addLine = AddLine.GetOrElse(true);

        return SB;
    }

private:
    struct TTokenInfo {
        bool OpeningBracket = false;
        bool ClosingBracket = false;
        bool BracketForcedExpansion = false;
        ui32 ClosingBracketIndex = 0;
    };

    using TMarkTokenStack = TVector<ui32>;

    void Out(TStringBuf s) {
        for (ui32 i = 0; i < s.size(); ++i) {
            Out(s[i], i == 0);
        }
    }

    void Out(char c, bool useIndent = true) {
        if (c == '\n' || c == '\r') {
            SB << c;
            if (!(c == '\n' && !SB.empty() && SB.back() == '\r')) {
                // do not increase OutLine if \n is preceded by \r
                // this way we handle \r, \n, or \r\n as single new line
                ++OutLine;
            }
            OutColumn = 0;
        } else {
            if (!OutColumn && useIndent) {
                ui32 indent = (CurrentIndent >= 0) ? CurrentIndent : 0;
                for (ui32 i = 0; i < indent; ++i) {
                    SB << ' ';
                }
            }

            SB << c;
            ++OutColumn;
        }
    }

    void NewLine() {
        if (OutColumn) {
            Out('\n');
        }
    }

    void AddComment(TStringBuf text) {
        if (text.StartsWith("--") && !SB.empty() && SB.back() == '-') {
            Out(' ');
        }

        Out(text);
    }

    void MarkTokens(const NProtoBuf::Message& msg) {
        const NProtoBuf::Descriptor* descr = msg.GetDescriptor();
        auto scopePtr = StaticData.ScopeDispatch.FindPtr(descr);
        if (scopePtr) {
            if (*scopePtr == EScope::TypeName) {
                ++InsideType;
            }

            Scopes.push_back(*scopePtr);
        }

        bool suppressExpr = false;
        if (descr == TToken::GetDescriptor()) {
            const auto& token = dynamic_cast<const TToken&>(msg);
            MarkToken(token);
        } else if (descr == TRule_sql_stmt_core::GetDescriptor()) {
            if (AddLine.Empty()) {
                AddLine = !IsSimpleStatement(dynamic_cast<const TRule_sql_stmt_core&>(msg)).GetOrElse(false);
            }
        } else if (descr == TRule_lambda_body::GetDescriptor()) {
            Y_ENSURE(TokenIndex >= 1);
            auto prevIndex = TokenIndex - 1;
            Y_ENSURE(prevIndex < ParsedTokens.size());
            Y_ENSURE(ParsedTokens[prevIndex].Content == "{");
            MarkedTokens[prevIndex].OpeningBracket = false;
            ForceExpandedColumn = ParsedTokens[prevIndex].LinePos;
            ForceExpandedLine = ParsedTokens[prevIndex].Line;
        } else if (descr == TRule_in_atom_expr::GetDescriptor()) {
            const auto& value = dynamic_cast<const TRule_in_atom_expr&>(msg);
            if (value.Alt_case() == TRule_in_atom_expr::kAltInAtomExpr7) {
                suppressExpr = true;
            }
        } else if (descr == TRule_select_kind_parenthesis::GetDescriptor()) {
            const auto& value = dynamic_cast<const TRule_select_kind_parenthesis&>(msg);
            if (value.Alt_case() == TRule_select_kind_parenthesis::kAltSelectKindParenthesis2) {
                suppressExpr = true;
            }
        } else if (descr == TRule_window_specification::GetDescriptor()) {
            const auto& value = dynamic_cast<const TRule_window_specification&>(msg);
            const auto& details = value.GetRule_window_specification_details2();
            const bool needsNewline = details.HasBlock1() || details.HasBlock2() ||
                                      details.HasBlock3() || details.HasBlock4();
            if (needsNewline) {
                auto& paren = value.GetToken1();
                ForceExpandedColumn = paren.GetColumn();
                ForceExpandedLine = paren.GetLine();
            }
            suppressExpr = true;
        } else if (descr == TRule_exists_expr::GetDescriptor()) {
            const auto& value = dynamic_cast<const TRule_exists_expr&>(msg);
            auto& paren = value.GetToken2();
            ForceExpandedColumn = paren.GetColumn();
            ForceExpandedLine = paren.GetLine();
            suppressExpr = true;
        } else if (descr == TRule_case_expr::GetDescriptor()) {
            const auto& value = dynamic_cast<const TRule_case_expr&>(msg);
            auto& token = value.GetToken1();
            ForceExpandedColumn = token.GetColumn();
            ForceExpandedLine = token.GetLine();
        }

        const bool expr = (descr == TRule_expr::GetDescriptor() || descr == TRule_in_expr::GetDescriptor());
        if (expr) {
            ++InsideExpr;
        }

        ui64 prevInsideExpr = InsideExpr;
        if (suppressExpr) {
            InsideExpr = 0;
        }

        VisitAllFieldsImpl<TPrettyVisitor, &TPrettyVisitor::MarkTokens>(this, descr, msg);
        if (suppressExpr) {
            InsideExpr = prevInsideExpr;
        }

        if (scopePtr) {
            if (*scopePtr == EScope::TypeName) {
                --InsideType;
            }

            Scopes.pop_back();
        }

        if (expr) {
            --InsideExpr;
        }
    }

    void MarkToken(const TToken& token) {
        auto str = token.GetValue();
        if (str == "<EOF>") {
            return;
        }

        MarkedTokens.emplace_back();
        if (str == "(" || str == "[" || str == "{" || str == "<|" || (InsideType && str == "<")) {
            MarkTokenStack.push_back(TokenIndex);
            auto& info = MarkedTokens[TokenIndex];
            info.OpeningBracket = (InsideExpr > 0);
        } else if (str == ")") {
            PopBracket("(");
        } else if (str == "]") {
            PopBracket("[");
        } else if (str == "}") {
            PopBracket("{");
        } else if (str == "|>") {
            PopBracket("<|");
        } else if (InsideType && str == ">") {
            PopBracket("<");
        }

        TokenIndex++;
    }

    void PopBracket(const TString& expected) {
        Y_ENSURE(!MarkTokenStack.empty());
        Y_ENSURE(MarkTokenStack.back() < ParsedTokens.size());
        auto& openToken = ParsedTokens[MarkTokenStack.back()];
        Y_ENSURE(openToken.Content == expected);
        auto& openInfo = MarkedTokens[MarkTokenStack.back()];
        auto& closeInfo = MarkedTokens[TokenIndex];
        const bool forcedExpansion = openToken.Line == ForceExpandedLine && openToken.LinePos <= ForceExpandedColumn;

        if (openInfo.OpeningBracket) {
            openInfo.ClosingBracketIndex = TokenIndex;
            openInfo.BracketForcedExpansion = forcedExpansion;
            closeInfo.BracketForcedExpansion = forcedExpansion;
            closeInfo.ClosingBracket = true;
        }

        MarkTokenStack.pop_back();
    }

    void Visit(const NProtoBuf::Message& msg) {
        const NProtoBuf::Descriptor* descr = msg.GetDescriptor();
        //Cerr << descr->name() << "\n";
        auto scopePtr = StaticData.ScopeDispatch.FindPtr(descr);
        if (descr == TRule_invoke_expr::GetDescriptor()) {
            AfterInvokeExpr = true;
        }

        if (descr == TRule_unary_op::GetDescriptor()) {
            AfterUnaryOp = true;
        }

        if (scopePtr) {
            if (*scopePtr == EScope::TypeName) {
                ++InsideType;
            }

            Scopes.push_back(*scopePtr);
        }

        auto funcPtr = StaticData.PrettyVisitDispatch.FindPtr(descr);
        if (funcPtr) {
            (*funcPtr)(*this, msg);
        } else {
            VisitAllFields(descr, msg);
        }

        if (scopePtr) {
            if (*scopePtr == EScope::TypeName) {
                --InsideType;
            }

            Scopes.pop_back();
        }
    }

    TMaybe<bool> IsSimpleStatement(const TRule_sql_stmt_core& msg) {
        switch (msg.Alt_case()) {
            case TRule_sql_stmt_core::kAltSqlStmtCore1: // pragma
            case TRule_sql_stmt_core::kAltSqlStmtCore5: // drop table
            case TRule_sql_stmt_core::kAltSqlStmtCore6: // use
            case TRule_sql_stmt_core::kAltSqlStmtCore8: // commit
            case TRule_sql_stmt_core::kAltSqlStmtCore11: // rollback
            case TRule_sql_stmt_core::kAltSqlStmtCore12: // declare
            case TRule_sql_stmt_core::kAltSqlStmtCore13: // import
            case TRule_sql_stmt_core::kAltSqlStmtCore14: // export
            case TRule_sql_stmt_core::kAltSqlStmtCore32: // drop external data source
            case TRule_sql_stmt_core::kAltSqlStmtCore34: // drop replication
                return true;
            case TRule_sql_stmt_core::kAltSqlStmtCore3: { // named nodes
                const auto& stmt = msg.GetAlt_sql_stmt_core3().GetRule_named_nodes_stmt1();
                if (stmt.GetBlock3().HasAlt1()) {
                    return true;
                }
                break;
            }
            case TRule_sql_stmt_core::kAltSqlStmtCore17: { // do
                const auto& stmt = msg.GetAlt_sql_stmt_core17().GetRule_do_stmt1();
                if (stmt.GetBlock2().HasAlt1()) {
                    return true;
                }
                break;
            }
            case TRule_sql_stmt_core::kAltSqlStmtCore19: // if
            case TRule_sql_stmt_core::kAltSqlStmtCore20: // for
                return false;
            default:
                break;
        }

        return {};
    }

    template <typename T>
    void VisitRepeated(const ::google::protobuf::RepeatedPtrField<T>& field) {
        for (const auto& m : field) {
            Visit(m);
        }
    }

    void VisitDefineActionOrSubqueryBody(const TRule_define_action_or_subquery_body& msg) {
        VisitRepeated(msg.GetBlock1());
        if (msg.HasBlock2()) {
            const auto& b = msg.GetBlock2();
            Visit(b.GetRule_sql_stmt_core1());
            for (auto block : b.GetBlock2()) {
                VisitRepeated(block.GetBlock1());
                if (!IsSimpleStatement(block.GetRule_sql_stmt_core2()).GetOrElse(false)) {
                    Out('\n');
                }
                Visit(block.GetRule_sql_stmt_core2());
            }

            VisitRepeated(b.GetBlock3());
        }
    }

    void VisitPragma(const TRule_pragma_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitKeyword(msg.GetToken1());
        auto prefix = msg.GetRule_opt_id_prefix_or_type2();
        if (prefix.HasBlock1()) {
            Visit(prefix.GetBlock1().GetRule_an_id_or_type1());
            VisitKeyword(prefix.GetBlock1().GetToken2());
            AfterDot = true;
        }

        Visit(msg.GetRule_an_id3());
        if (msg.GetBlock4().HasAlt2()) {
            AfterInvokeExpr = true;
            const auto& alt2 = msg.GetBlock4().GetAlt2();
            VisitKeyword(alt2.GetToken1());
            Visit(alt2.GetRule_pragma_value2());
            VisitRepeated(alt2.GetBlock3());
            VisitKeyword(alt2.GetToken4());
        } else {
            Visit(msg.GetBlock4());
        }
    }

    void PosFromPartial(const TRule_select_kind_partial& partial) {
        const auto& kind = partial.GetRule_select_kind1();
        if (kind.HasBlock1()) { // DISCARD
            PosFromToken(kind.GetBlock1().GetToken1());
        } else {
            switch (kind.GetBlock2().Alt_case()) {
            case TRule_select_kind_TBlock2::kAlt1:
                PosFromToken(kind.GetBlock2().GetAlt1().GetRule_process_core1().GetToken1());
                break;
            case TRule_select_kind_TBlock2::kAlt2:
                PosFromToken(kind.GetBlock2().GetAlt2().GetRule_reduce_core1().GetToken1());
                break;
            case TRule_select_kind_TBlock2::kAlt3: {
                const auto& selCore = kind.GetBlock2().GetAlt3().GetRule_select_core1();
                if (selCore.HasBlock1()) {
                    PosFromToken(selCore.GetBlock1().GetToken1());
                } else {
                    PosFromToken(selCore.GetToken2());
                }

                break;
            }

            default:
                ythrow yexception() << "Alt is not supported";
            }
        }
    }

    void VisitSelect(const TRule_select_stmt& msg) {
        const auto& paren = msg.GetRule_select_kind_parenthesis1();
        if (paren.Alt_case() == TRule_select_kind_parenthesis::kAltSelectKindParenthesis1) {
            const auto& partial = paren.GetAlt_select_kind_parenthesis1().GetRule_select_kind_partial1();
            PosFromPartial(partial);
        } else {
            PosFromToken(paren.GetAlt_select_kind_parenthesis2().GetToken1());
        }

        NewLine();
        Visit(msg.GetRule_select_kind_parenthesis1());
        for (const auto& block : msg.GetBlock2()) {
            NewLine();
            Visit(block.GetRule_select_op1());
            NewLine();
            Visit(block.GetRule_select_kind_parenthesis2());
        }
    }

    void VisitSelectUnparenthesized(const TRule_select_unparenthesized_stmt& msg) {
        const auto& partial = msg.GetRule_select_kind_partial1();
        PosFromPartial(partial);
        NewLine();
        Visit(msg.GetRule_select_kind_partial1());
        for (const auto& block : msg.GetBlock2()) {
            NewLine();
            Visit(block.GetRule_select_op1());
            NewLine();
            Visit(block.GetRule_select_kind_parenthesis2());
        }
    }

    void VisitNamedNodes(const TRule_named_nodes_stmt& msg) {
        PosFromToken(msg.GetRule_bind_parameter_list1().GetRule_bind_parameter1().GetToken1());
        NewLine();
        Visit(msg.GetRule_bind_parameter_list1());
        Visit(msg.GetToken2());
        switch (msg.GetBlock3().Alt_case()) {
        case TRule_named_nodes_stmt::TBlock3::kAlt1: {
            const auto& alt = msg.GetBlock3().GetAlt1();
            Visit(alt);
            break;
        }

        case TRule_named_nodes_stmt::TBlock3::kAlt2: {
            const auto& alt = msg.GetBlock3().GetAlt2();
            const auto& subselect = alt.GetRule_subselect_stmt1();
            switch (subselect.GetBlock1().Alt_case()) {
            case TRule_subselect_stmt::TBlock1::kAlt1: {
                const auto& alt = subselect.GetBlock1().GetAlt1();
                Visit(alt.GetToken1());
                NewLine();
                PushCurrentIndent();
                Visit(alt.GetRule_select_stmt2());
                PopCurrentIndent();
                NewLine();
                Visit(alt.GetToken3());
                break;
            }

            case TRule_subselect_stmt::TBlock1::kAlt2: {
                const auto& alt = subselect.GetBlock1().GetAlt2();
                NewLine();
                PushCurrentIndent();
                Visit(alt);
                PopCurrentIndent();
                break;
            }

            default:
                ythrow yexception() << "Alt is not supported";
            }

            break;
        }

        default:
            ythrow yexception() << "Alt is not supported";
        }
    }

    void VisitCreateTable(const TRule_create_table_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        Visit(msg.GetToken1());
        Visit(msg.GetBlock2());
        Visit(msg.GetBlock3());
        Visit(msg.GetBlock4());
        Visit(msg.GetRule_simple_table_ref5());
        Visit(msg.GetToken6());
        PushCurrentIndent();
        NewLine();
        Visit(msg.GetRule_create_table_entry7());
        for (const auto& b : msg.GetBlock8()) {
            Visit(b.GetToken1());
            NewLine();
            Visit(b.GetRule_create_table_entry2());
        }
        if (msg.HasBlock9()) {
            Visit(msg.GetBlock9());
        }

        PopCurrentIndent();
        NewLine();
        Visit(msg.GetToken10());
        if (msg.HasBlock11()) {
            NewLine();
            Visit(msg.GetBlock11());
        }
        if (msg.HasBlock12()) {
            NewLine();
            Visit(msg.GetBlock12());
        }
        if (msg.HasBlock13()) {
            NewLine();
            Visit(msg.GetBlock13());
        }
        if (msg.HasBlock14()) {
            NewLine();
            Visit(msg.GetBlock14());
        }
        if (msg.HasBlock15()) {
            NewLine();
            Visit(msg.GetBlock15());
        }
    }

    void VisitDropTable(const TRule_drop_table_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_drop_table_stmt::GetDescriptor(), msg);
    }

    void VisitAnalyze(const TRule_analyze_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_analyze_stmt::GetDescriptor(), msg);
    }

    void VisitBackup(const TRule_backup_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_backup_stmt::GetDescriptor(), msg);
    }

    void VisitRestore(const TRule_restore_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_restore_stmt::GetDescriptor(), msg);
    }

    void VisitUse(const TRule_use_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_use_stmt::GetDescriptor(), msg);
    }

    void VisitIntoTable(const TRule_into_table_stmt& msg) {
        switch (msg.GetBlock1().Alt_case()) {
        case TRule_into_table_stmt_TBlock1::AltCase::kAlt1:
            PosFromToken(msg.GetBlock1().GetAlt1().GetToken1());
            break;
        case TRule_into_table_stmt_TBlock1::AltCase::kAlt2:
            PosFromToken(msg.GetBlock1().GetAlt2().GetToken1());
            break;
        case TRule_into_table_stmt_TBlock1::AltCase::kAlt3:
            PosFromToken(msg.GetBlock1().GetAlt3().GetToken1());
            break;
        case TRule_into_table_stmt_TBlock1::AltCase::kAlt4:
            PosFromToken(msg.GetBlock1().GetAlt4().GetToken1());
            break;
        case TRule_into_table_stmt_TBlock1::AltCase::kAlt5:
            PosFromToken(msg.GetBlock1().GetAlt5().GetToken1());
            break;
        case TRule_into_table_stmt_TBlock1::AltCase::kAlt6:
            PosFromToken(msg.GetBlock1().GetAlt6().GetToken1());
            break;
        default:
            ythrow yexception() << "Alt is not supported";
        }

        NewLine();
        VisitAllFields(TRule_into_table_stmt::GetDescriptor(), msg);
    }

    void VisitCommit(const TRule_commit_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_commit_stmt::GetDescriptor(), msg);
    }

    void VisitUpdate(const TRule_update_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        Visit(msg.GetToken1());
        Visit(msg.GetRule_simple_table_ref2());
        switch (msg.GetBlock3().Alt_case()) {
        case TRule_update_stmt_TBlock3::kAlt1: {
            const auto& alt = msg.GetBlock3().GetAlt1();
            NewLine();
            Visit(alt.GetToken1());
            const auto& choice = alt.GetRule_set_clause_choice2();
            NewLine();

            switch (choice.Alt_case()) {
            case TRule_set_clause_choice::kAltSetClauseChoice1: {
                const auto& clauses = choice.GetAlt_set_clause_choice1().GetRule_set_clause_list1();
                PushCurrentIndent();
                Visit(clauses.GetRule_set_clause1());
                for (auto& block : clauses.GetBlock2()) {
                    Visit(block.GetToken1());
                    NewLine();
                    Visit(block.GetRule_set_clause2());
                }

                PopCurrentIndent();
                break;
            }
            case TRule_set_clause_choice::kAltSetClauseChoice2: {
                const auto& multiColumn = choice.GetAlt_set_clause_choice2().GetRule_multiple_column_assignment1();
                const auto& targets = multiColumn.GetRule_set_target_list1();
                Visit(targets.GetToken1());
                NewLine();
                PushCurrentIndent();
                Visit(targets.GetRule_set_target2());
                for (auto& block : targets.GetBlock3()) {
                    Visit(block.GetToken1());
                    NewLine();
                    Visit(block.GetRule_set_target2());
                }

                NewLine();
                PopCurrentIndent();
                Visit(targets.GetToken4());
                Visit(multiColumn.GetToken2());
                Visit(multiColumn.GetToken3());
                NewLine();
                const auto& simpleValues = multiColumn.GetRule_simple_values_source4();
                switch (simpleValues.Alt_case()) {
                case TRule_simple_values_source::kAltSimpleValuesSource1: {
                    const auto& exprs = simpleValues.GetAlt_simple_values_source1().GetRule_expr_list1();
                    PushCurrentIndent();
                    Visit(exprs.GetRule_expr1());
                    for (const auto& block : exprs.GetBlock2()) {
                        Visit(block.GetToken1());
                        NewLine();
                        Visit(block.GetRule_expr2());
                    }

                    PopCurrentIndent();
                    break;
                }
                case TRule_simple_values_source::kAltSimpleValuesSource2: {
                    PushCurrentIndent();
                    Visit(simpleValues.GetAlt_simple_values_source2());
                    PopCurrentIndent();
                    break;
                }
                default:
                    ythrow yexception() << "Alt is not supported";
                }

                NewLine();
                Visit(multiColumn.GetToken5());
                break;
            }
            default:
                ythrow yexception() << "Alt is not supported";
            }

            PopCurrentIndent();
            if (alt.HasBlock3()) {
                NewLine();
                Visit(alt.GetBlock3());
            }

            PopCurrentIndent();
            break;
        }
        case TRule_update_stmt_TBlock3::kAlt2: {
            const auto& alt = msg.GetBlock3().GetAlt2();
            NewLine();
            Visit(alt.GetToken1());
            Visit(alt.GetRule_into_values_source2());
            break;
        }
        default:
            ythrow yexception() << "Alt is not supported";
        }
    }

    void VisitDelete(const TRule_delete_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        Visit(msg.GetToken1());
        Visit(msg.GetToken2());
        Visit(msg.GetRule_simple_table_ref3());
        if (msg.HasBlock4()) {
            switch (msg.GetBlock4().Alt_case()) {
            case TRule_delete_stmt_TBlock4::kAlt1: {
                const auto& alt = msg.GetBlock4().GetAlt1();
                NewLine();
                Visit(alt);
                break;
            }
            case TRule_delete_stmt_TBlock4::kAlt2: {
                const auto& alt = msg.GetBlock4().GetAlt2();
                NewLine();
                Visit(alt);
                break;
            }
            default:
                ythrow yexception() << "Alt is not supported";
            }
        }
    }

    void VisitRollback(const TRule_rollback_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_rollback_stmt::GetDescriptor(), msg);
    }

    void VisitDeclare(const TRule_declare_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_declare_stmt::GetDescriptor(), msg);
    }

    void VisitImport(const TRule_import_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_import_stmt::GetDescriptor(), msg);
    }

    void VisitExport(const TRule_export_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_export_stmt::GetDescriptor(), msg);
    }

    void VisitAlterTable(const TRule_alter_table_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitKeyword(msg.GetToken1());
        VisitKeyword(msg.GetToken2());
        Visit(msg.GetRule_simple_table_ref3());
        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_alter_table_action4());
        for (auto& b : msg.GetBlock5()) {
            Visit(b.GetToken1());
            NewLine();
            Visit(b.GetRule_alter_table_action2());
        }

        PopCurrentIndent();
    }

    void VisitAlterTableStore(const TRule_alter_table_store_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_alter_table_store_stmt::GetDescriptor(), msg);
    }

    void VisitAlterExternalTable(const TRule_alter_external_table_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitKeyword(msg.GetToken1());
        VisitKeyword(msg.GetToken2());
        VisitKeyword(msg.GetToken3());
        Visit(msg.GetRule_simple_table_ref4());
        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_alter_external_table_action5());
        for (auto& b : msg.GetBlock6()) {
            Visit(b.GetToken1());
            NewLine();
            Visit(b.GetRule_alter_external_table_action2());
        }

        PopCurrentIndent();
    }

    void VisitDo(const TRule_do_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitKeyword(msg.GetToken1());
        switch (msg.GetBlock2().Alt_case()) {
        case TRule_do_stmt_TBlock2::kAlt1: { // CALL
            const auto& alt = msg.GetBlock2().GetAlt1().GetRule_call_action1();
            Visit(alt.GetBlock1());
            AfterInvokeExpr = true;
            Visit(alt.GetToken2());
            if (alt.HasBlock3()) {
                Visit(alt.GetBlock3());
            }

            Visit(alt.GetToken4());
            break;
        }
        case TRule_do_stmt_TBlock2::kAlt2: { // INLINE
            const auto& alt = msg.GetBlock2().GetAlt2().GetRule_inline_action1();
            VisitKeyword(alt.GetToken1());
            PushCurrentIndent();
            NewLine();
            Visit(alt.GetRule_define_action_or_subquery_body2());
            PopCurrentIndent();
            NewLine();
            VisitKeyword(alt.GetToken3());
            VisitKeyword(alt.GetToken4());
            break;
        }
        default:
            ythrow yexception() << "Alt is not supported";
        }
    }

    void VisitAction(const TRule_define_action_or_subquery_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitKeyword(msg.GetToken1());
        VisitKeyword(msg.GetToken2());
        Visit(msg.GetRule_bind_parameter3());
        AfterInvokeExpr = true;
        Visit(msg.GetToken4());
        if (msg.HasBlock5()) {
            Visit(msg.GetBlock5());
        }

        Visit(msg.GetToken6());
        VisitKeyword(msg.GetToken7()); // AS
        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_define_action_or_subquery_body8());
        PopCurrentIndent();
        NewLine();
        VisitKeyword(msg.GetToken9());
        VisitKeyword(msg.GetToken10());
    }

    void VisitIf(const TRule_if_stmt& msg) {
        if (msg.HasBlock1()) {
            PosFromToken(msg.GetBlock1().GetToken1());
        } else {
            PosFromToken(msg.GetToken2());
        }

        NewLine();
        if (msg.HasBlock1()) {
            Visit(msg.GetBlock1());
        }

        Visit(msg.GetToken2());
        Visit(msg.GetRule_expr3());
        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_do_stmt4());
        PopCurrentIndent();
        if (msg.HasBlock5()) {
            NewLine();
            Visit(msg.GetBlock5().GetToken1());
            NewLine();
            PushCurrentIndent();
            Visit(msg.GetBlock5().GetRule_do_stmt2());
            PopCurrentIndent();
        }
    }

    void VisitFor(const TRule_for_stmt& msg) {
        if (msg.HasBlock1()) {
            PosFromToken(msg.GetBlock1().GetToken1());
        } else if (msg.HasBlock2()) {
            PosFromToken(msg.GetBlock2().GetToken1());
        } else {
            PosFromToken(msg.GetToken3());
        }

        NewLine();
        if (msg.HasBlock1()) {
            Visit(msg.GetBlock1());
        }

        if (msg.HasBlock2()) {
            Visit(msg.GetBlock2());
        }

        Visit(msg.GetToken3());
        Visit(msg.GetRule_bind_parameter4());
        Visit(msg.GetToken5());
        Visit(msg.GetRule_expr6());
        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_do_stmt7());
        PopCurrentIndent();
        if (msg.HasBlock8()) {
            NewLine();
            Visit(msg.GetBlock8().GetToken1());
            NewLine();
            PushCurrentIndent();
            Visit(msg.GetBlock8().GetRule_do_stmt2());
            PopCurrentIndent();
        }
    }

    void VisitValues(const TRule_values_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitKeyword(msg.GetToken1());
        const auto& rowList = msg.GetRule_values_source_row_list2();
        PushCurrentIndent();
        NewLine();
        Visit(rowList.GetRule_values_source_row1());
        for (const auto& b : rowList.GetBlock2()) {
            Visit(b.GetToken1());
            NewLine();
            Visit(b.GetRule_values_source_row2());
        }

        PopCurrentIndent();
    }

    void VisitGrantPermissions(const TRule_grant_permissions_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_grant_permissions_stmt::GetDescriptor(), msg);
    }

    void VisitRevokePermissions(const TRule_revoke_permissions_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_revoke_permissions_stmt::GetDescriptor(), msg);
    }

    void VisitCreateUser(const TRule_create_user_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_create_user_stmt::GetDescriptor(), msg);
    }

    void VisitAlterUser(const TRule_alter_user_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_alter_user_stmt::GetDescriptor(), msg);
    }

    void VisitCreateGroup(const TRule_create_group_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_create_group_stmt::GetDescriptor(), msg);
    }

    void VisitAlterGroup(const TRule_alter_group_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_alter_group_stmt::GetDescriptor(), msg);
    }

    void VisitDropRole(const TRule_drop_role_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_drop_role_stmt::GetDescriptor(), msg);
    }

    void VisitUpsertObject(const TRule_upsert_object_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_upsert_object_stmt::GetDescriptor(), msg);
    }

    void VisitCreateObject(const TRule_create_object_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_create_object_stmt::GetDescriptor(), msg);
    }

    void VisitAlterObject(const TRule_alter_object_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_alter_object_stmt::GetDescriptor(), msg);
    }

    void VisitDropObject(const TRule_drop_object_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_drop_object_stmt::GetDescriptor(), msg);
    }

    void VisitCreateTopic(const TRule_create_topic_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitKeyword(msg.GetToken1());
        VisitKeyword(msg.GetToken2());
        Visit(msg.GetBlock3());
        Visit(msg.GetRule_topic_ref4());
        if (msg.HasBlock5()) {
            PushCurrentIndent();
            auto& b = msg.GetBlock5().GetRule_create_topic_entries1();
            Visit(b.GetToken1());
            NewLine();
            Visit(b.GetRule_create_topic_entry2());
            for (auto& subEntry : b.GetBlock3()) {
                Visit(subEntry.GetToken1());
                NewLine();
                Visit(subEntry.GetRule_create_topic_entry2());
            }
            NewLine();
            PopCurrentIndent();
            Visit(b.GetToken4());
        }
        if (msg.HasBlock6()) {
            auto& b = msg.GetBlock6().GetRule_with_topic_settings1();
            VisitKeyword(b.GetToken1());
            VisitKeyword(b.GetToken2());
            PushCurrentIndent();
            NewLine();
            Visit(b.GetRule_topic_settings3());
            PopCurrentIndent();
            NewLine();
            VisitKeyword(b.GetToken4());
        }
    }

    void VisitAlterTopic(const TRule_alter_topic_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitKeyword(msg.GetToken1());
        VisitKeyword(msg.GetToken2());
        Visit(msg.GetBlock3());
        Visit(msg.GetRule_topic_ref4());
        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_alter_topic_action5());
        for (auto& b : msg.GetBlock6()) {
            Visit(b.GetToken1());
            NewLine();
            Visit(b.GetRule_alter_topic_action2());
        }

        PopCurrentIndent();
    }

    void VisitDropTopic(const TRule_drop_topic_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_drop_topic_stmt::GetDescriptor(), msg);
    }

    void VisitCreateExternalDataSource(const TRule_create_external_data_source_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_create_external_data_source_stmt::GetDescriptor(), msg);
    }

    void VisitAlterExternalDataSource(const TRule_alter_external_data_source_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitToken(msg.GetToken1());
        VisitToken(msg.GetToken2());
        VisitToken(msg.GetToken3());
        VisitToken(msg.GetToken4());
        Visit(msg.GetRule_object_ref5());

        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_alter_external_data_source_action6());
        for (const auto& action : msg.GetBlock7()) {
            Visit(action.GetToken1()); // comma
            NewLine();
            Visit(action.GetRule_alter_external_data_source_action2());
        }

        PopCurrentIndent();
    }

    void VisitDropExternalDataSource(const TRule_drop_external_data_source_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_drop_external_data_source_stmt::GetDescriptor(), msg);
    }

    void VisitCreateView(const TRule_create_view_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_create_view_stmt::GetDescriptor(), msg);
    }

    void VisitDropView(const TRule_drop_view_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_drop_view_stmt::GetDescriptor(), msg);
    }

    void VisitCreateAsyncReplication(const TRule_create_replication_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_create_replication_stmt::GetDescriptor(), msg);
    }

    void VisitAlterAsyncReplication(const TRule_alter_replication_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_alter_replication_stmt::GetDescriptor(), msg);
    }

    void VisitDropAsyncReplication(const TRule_drop_replication_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_drop_replication_stmt::GetDescriptor(), msg);
    }

    void VisitCreateResourcePool(const TRule_create_resource_pool_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_create_resource_pool_stmt::GetDescriptor(), msg);
    }

    void VisitAlterResourcePool(const TRule_alter_resource_pool_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitToken(msg.GetToken1());
        VisitToken(msg.GetToken2());
        VisitToken(msg.GetToken3());
        Visit(msg.GetRule_object_ref4());

        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_alter_resource_pool_action5());
        for (const auto& action : msg.GetBlock6()) {
            Visit(action.GetToken1()); // comma
            NewLine();
            Visit(action.GetRule_alter_resource_pool_action2());
        }

        PopCurrentIndent();
    }

    void VisitDropResourcePool(const TRule_drop_resource_pool_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_drop_resource_pool_stmt::GetDescriptor(), msg);
    }

    void VisitCreateBackupCollection(const TRule_create_backup_collection_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_create_backup_collection_stmt::GetDescriptor(), msg);
    }

    void VisitAlterBackupCollection(const TRule_alter_backup_collection_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitToken(msg.GetToken1());
        Visit(msg.GetRule_backup_collection2());

        NewLine();
        PushCurrentIndent();
        switch (msg.GetBlock3().Alt_case()) {
        case TRule_alter_backup_collection_stmt_TBlock3::kAlt1: {
            Visit(msg.GetBlock3().GetAlt1().GetRule_alter_backup_collection_actions1().GetRule_alter_backup_collection_action1());
            for (const auto& action : msg.GetBlock3().GetAlt1().GetRule_alter_backup_collection_actions1().GetBlock2()) {
                Visit(action.GetToken1()); // comma
                NewLine();
                Visit(action.GetRule_alter_backup_collection_action2());
            }
            break;
        }
        case TRule_alter_backup_collection_stmt_TBlock3::kAlt2: {
            Visit(msg.GetBlock3().GetAlt2().GetRule_alter_backup_collection_entries1().GetRule_alter_backup_collection_entry1());
            for (const auto& entry : msg.GetBlock3().GetAlt2().GetRule_alter_backup_collection_entries1().GetBlock2()) {
                Visit(entry.GetToken1()); // comma
                NewLine();
                Visit(entry.GetRule_alter_backup_collection_entry2());
            }
            break;
        }
        default:
            ythrow yexception() << "Alt is not supported";
        }

        PopCurrentIndent();
    }

    void VisitDropBackupCollection(const TRule_drop_backup_collection_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_drop_backup_collection_stmt::GetDescriptor(), msg);
    }

    void VisitCreateResourcePoolClassifier(const TRule_create_resource_pool_classifier_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_create_resource_pool_classifier_stmt::GetDescriptor(), msg);
    }

    void VisitAlterResourcePoolClassifier(const TRule_alter_resource_pool_classifier_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitToken(msg.GetToken1());
        VisitToken(msg.GetToken2());
        VisitToken(msg.GetToken3());
        VisitToken(msg.GetToken4());
        Visit(msg.GetRule_object_ref5());

        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_alter_resource_pool_classifier_action6());
        for (const auto& action : msg.GetBlock7()) {
            Visit(action.GetToken1()); // comma
            NewLine();
            Visit(action.GetRule_alter_resource_pool_classifier_action2());
        }

        PopCurrentIndent();
    }

    void VisitDropResourcePoolClassifier(const TRule_drop_resource_pool_classifier_stmt& msg) {
        PosFromToken(msg.GetToken1());
        NewLine();
        VisitAllFields(TRule_drop_resource_pool_classifier_stmt::GetDescriptor(), msg);
    }

    void VisitAllFields(const NProtoBuf::Descriptor* descr, const NProtoBuf::Message& msg) {
        VisitAllFieldsImpl<TPrettyVisitor, &TPrettyVisitor::Visit>(this, descr, msg);
    }

    void WriteComments() {
        while (LastComment < Comments.size()) {
            const auto& c = Comments[LastComment];
            if (c.Line > LastLine || c.Line == LastLine && c.LinePos > LastColumn) {
                break;
            }

            AddComment(c.Content);
            ++LastComment;
        }
    }

    void PosFromToken(const TToken& token) {
        LastLine = token.GetLine();
        LastColumn = token.GetColumn();
        WriteComments();
    }

    void PosFromParsedToken(const TParsedToken& token) {
        LastLine = token.Line;
        LastColumn = token.LinePos;
        WriteComments();
    }

    void VisitToken(const TToken& token) {
        VisitTokenImpl(token, false);
    }

    void VisitKeyword(const TToken& token) {
        VisitTokenImpl(token, true);
    }

    void VisitTokenImpl(const TToken& token, bool forceKeyword) {
        PosFromToken(token);
        auto str = token.GetValue();

        if (str == "<EOF>") {
            return;
        }

        //Cerr << str << "\n";
        auto currentScope = Scopes.back();
        if (!SkipSpaceAfterUnaryOp && !InMultiTokenOp) {
            if (AfterLess && str == ">") {
                Out(' ');
            } else if (AfterDigits && str == ".") {
                Out(' ');
            } else if (OutColumn && (currentScope == EScope::DoubleQuestion || str != "?")
                && str != ":" && str != "." && str != "," && str != ";" && str != ")" && str != "]"
                && str != "}" && str != "|>" && str != "::" && !AfterNamespace && !AfterBracket
                && !AfterInvokeExpr && !AfterDollarOrAt && !AfterDot && (!AfterQuestion || str != "?")
                && (!InsideType || (str != "<" && str != ">" && str != "<>"))
                && (!InsideType || !AfterLess)
                && (!AfterKeyExpr || str != "[")
                ) {
                Out(' ');
            }
        }

        SkipSpaceAfterUnaryOp = false;
        if (AfterUnaryOp) {
            if (str == "+" || str == "-" || str == "~") {
                SkipSpaceAfterUnaryOp = true;
            }

            AfterUnaryOp = false;
        }

        AfterInvokeExpr = false;
        AfterNamespace = (str == "::");
        AfterBracket = (str == "(" || str == "[" || str == "{" || str == "<|");
        AfterDot = (str == ".");
        AfterDigits = !str.empty() && AllOf(str, [](char c) { return c >= '0' && c <= '9'; });
        AfterQuestion = (str == "?");
        AfterLess = (str == "<");
        AfterKeyExpr = false;

        if (forceKeyword) {
            str = to_upper(str);
        } else if (currentScope == EScope::Default) {
            if (auto p = StaticData.Keywords.find(to_upper(str));  p != StaticData.Keywords.end()) {
                str = *p;
            }
        }

        AfterDollarOrAt = (str == "$" || str == "@");

        const auto& markedInfo = MarkedTokens[TokenIndex];
        if (markedInfo.ClosingBracket) {
            Y_ENSURE(!MarkTokenStack.empty());
            auto beginTokenIndex = MarkTokenStack.back();
            if (markedInfo.BracketForcedExpansion || ParsedTokens[beginTokenIndex].Line != ParsedTokens[TokenIndex].Line) {
                // multiline
                PopCurrentIndent();
                NewLine();
            }

            MarkTokenStack.pop_back();
        }

        Out(str);
        if (str == ";") {
            Out('\n');
        }

        if (markedInfo.OpeningBracket) {
            MarkTokenStack.push_back(TokenIndex);
            if (markedInfo.BracketForcedExpansion || ParsedTokens[TokenIndex].Line != ParsedTokens[markedInfo.ClosingBracketIndex].Line) {
                // multiline
                PushCurrentIndent();
                NewLine();
            }
        }

        if (str == "," && !MarkTokenStack.empty()) {
            const bool addNewline =
                (TokenIndex + 1 < ParsedTokens.size() && ParsedTokens[TokenIndex].Line != ParsedTokens[TokenIndex + 1].Line)
             || (TokenIndex > 0 && ParsedTokens[TokenIndex - 1].Line != ParsedTokens[TokenIndex].Line);
            // add line for trailing comma
            if (addNewline) {
                NewLine();
            }
        }

        TokenIndex++;
    }

    void VisitIntoValuesSource(const TRule_into_values_source& msg) {
        switch (msg.Alt_case()) {
        case TRule_into_values_source::kAltIntoValuesSource1: {
            const auto& alt = msg.GetAlt_into_values_source1();
            if (alt.HasBlock1()) {
                const auto& columns = alt.GetBlock1().GetRule_pure_column_list1();
                Visit(columns.GetToken1());
                NewLine();
                PushCurrentIndent();
                Visit(columns.GetRule_an_id2());
                for (const auto& block : columns.GetBlock3()) {
                    Visit(block.GetToken1());
                    NewLine();
                    Visit(block.GetRule_an_id2());
                }

                PopCurrentIndent();
                NewLine();
                Visit(columns.GetToken4());
                NewLine();
            }

            Visit(alt.GetRule_values_source2());
            break;
        }
        case TRule_into_values_source::kAltIntoValuesSource2: {
            VisitAllFields(TRule_into_values_source::GetDescriptor(), msg);
            break;
        }
        default:
            ythrow yexception() << "Alt is not supported";
        }
    }

    void VisitSelectKind(const TRule_select_kind& msg) {
        if (msg.HasBlock1()) {
            Visit(msg.GetBlock1());
        }

        Visit(msg.GetBlock2());
        if (msg.HasBlock3()) {
            NewLine();
            Visit(msg.GetBlock3());
        }
    }

    void VisitProcessCore(const TRule_process_core& msg) {
        Visit(msg.GetToken1());
        if (msg.HasBlock2()) {
            Visit(msg.GetBlock2());
        }

        Visit(msg.GetRule_named_single_source3());
        VisitRepeated(msg.GetBlock4());
        if (msg.HasBlock5()) {
            NewLine();
            const auto& block5 = msg.GetBlock5();
            Visit(block5.GetToken1());
            Visit(block5.GetRule_using_call_expr2());
            if (block5.HasBlock3()) {
                Visit(block5.GetBlock3());
            }

            if (block5.HasBlock4()) {
                NewLine();
                Visit(block5.GetBlock4());
            }

            if (block5.HasBlock5()) {
                NewLine();
                Visit(block5.GetBlock5());
            }

            if (block5.HasBlock6()) {
                NewLine();
                Visit(block5.GetBlock6());
            }

            if (block5.HasBlock7()) {
                NewLine();
                Visit(block5.GetBlock7());
            }
        }
    }

    void VisitReduceCore(const TRule_reduce_core& msg) {
        Visit(msg.GetToken1());
        Visit(msg.GetRule_named_single_source2());
        VisitRepeated(msg.GetBlock3());

        if (msg.HasBlock4()) {
            NewLine();
            Visit(msg.GetBlock4());
        }

        NewLine();
        Visit(msg.GetToken5());
        const auto& columns = msg.GetRule_column_list6();
        NewLine();
        PushCurrentIndent();
        Visit(columns.GetRule_column_name1());
        for (const auto& block : columns.GetBlock2()) {
            Visit(block.GetToken1());
            NewLine();
            Visit(block.GetRule_column_name2());
        }

        if (columns.HasBlock3()) {
            Visit(columns.GetBlock3());
        }

        PopCurrentIndent();
        NewLine();
        Visit(msg.GetToken7());
        if (msg.HasBlock8()) {
            Visit(msg.GetBlock8());
        }

        Visit(msg.GetRule_using_call_expr9());
        if (msg.HasBlock10()) {
            Visit(msg.GetBlock10());
        }

        if (msg.HasBlock11()) {
            NewLine();
            Visit(msg.GetBlock11());
        }

        if (msg.HasBlock12()) {
            NewLine();
            Visit(msg.GetBlock12());
        }

        if (msg.HasBlock13()) {
            NewLine();
            Visit(msg.GetBlock13());
        }
    }

    void VisitSortSpecificationList(const TRule_sort_specification_list& msg) {
        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_sort_specification1());
        for (const auto& block : msg.GetBlock2()) {
            Visit(block.GetToken1());
            NewLine();
            Visit(block.GetRule_sort_specification2());
        }

        PopCurrentIndent();
    }

    void VisitSelectCore(const TRule_select_core& msg) {
        if (msg.HasBlock1()) {
            Visit(msg.GetBlock1());
            NewLine();
        }

        Visit(msg.GetToken2());
        if (msg.HasBlock3()) {
            Visit(msg.GetBlock3());
        }

        Visit(msg.GetRule_opt_set_quantifier4());
        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_result_column5());
        for (const auto& block : msg.GetBlock6()) {
            Visit(block.GetToken1());
            NewLine();
            Visit(block.GetRule_result_column2());
        }

        if (msg.HasBlock7()) {
            Visit(msg.GetBlock7());
        }

        if (msg.HasBlock8()) {
            NewLine();
            Visit(msg.GetBlock8());
        }

        PopCurrentIndent();
        if (msg.HasBlock9()) {
            NewLine();
            Visit(msg.GetBlock9());
        }

        if (msg.HasBlock10()) {
            NewLine();
            Visit(msg.GetBlock10());
        }

        if (msg.HasBlock11()) {
            NewLine();
            Visit(msg.GetBlock11());
        }

        if (msg.HasBlock12()) {
            NewLine();
            Visit(msg.GetBlock12());
        }

        if (msg.HasBlock13()) {
            NewLine();
            Visit(msg.GetBlock13());
        }

        if (msg.HasBlock14()) {
            NewLine();
            Visit(msg.GetBlock14());
        }
    }

    void VisitJoinSource(const TRule_join_source& msg) {
        if (msg.HasBlock1()) {
            Visit(msg.GetBlock1());
        }

        Visit(msg.GetRule_flatten_source2());
        for (const auto& block : msg.GetBlock3()) {
            NewLine();
            Visit(block.GetRule_join_op1());
            if (block.HasBlock2()) {
                Visit(block.GetBlock2());
            }

            Visit(block.GetRule_flatten_source3());
            if (block.HasBlock4()) {
                NewLine();
                Visit(block.GetBlock4());
            }
        }
    }

    void VisitSingleSource(const TRule_single_source& msg) {
        switch (msg.Alt_case()) {
        case TRule_single_source::kAltSingleSource1: {
            const auto& alt = msg.GetAlt_single_source1();
            Visit(alt);
            break;
        }
        case TRule_single_source::kAltSingleSource2: {
            const auto& alt = msg.GetAlt_single_source2();
            Visit(alt.GetToken1());
            PushCurrentIndent();
            Visit(alt.GetRule_select_stmt2());
            PopCurrentIndent();
            NewLine();
            Visit(alt.GetToken3());
            break;
        }
        case TRule_single_source::kAltSingleSource3: {
            const auto& alt = msg.GetAlt_single_source3();
            Visit(alt.GetToken1());
            PushCurrentIndent();
            Visit(alt.GetRule_values_stmt2());
            PopCurrentIndent();
            NewLine();
            Visit(alt.GetToken3());
            break;
        }
        default:
            ythrow yexception() << "Alt is not supported";
        }
    }

    void VisitFlattenSource(const TRule_flatten_source& msg) {
        Visit(msg.GetRule_named_single_source1());
        if (msg.HasBlock2()) {
            PushCurrentIndent();
            NewLine();
            Visit(msg.GetBlock2());
            PopCurrentIndent();
        }
    }

    void VisitNamedSingleSource(const TRule_named_single_source& msg) {
        Visit(msg.GetRule_single_source1());
        if (msg.HasBlock2()) {
            const auto& matchRecognize = msg.GetBlock2();
            //TODO handle MATCH_RECOGNIZE block
            //https://st.yandex-team.ru/YQL-16186
            Visit(matchRecognize);
        }
        if (msg.HasBlock3()) {
            NewLine();
            PushCurrentIndent();
            const auto& block3 = msg.GetBlock3();
            Visit(block3.GetBlock1());
            if (block3.HasBlock2()) {
                const auto& columns = block3.GetBlock2().GetRule_pure_column_list1();
                Visit(columns.GetToken1());
                NewLine();
                PushCurrentIndent();
                Visit(columns.GetRule_an_id2());
                for (const auto& block : columns.GetBlock3()) {
                    Visit(block.GetToken1());
                    NewLine();
                    Visit(block.GetRule_an_id2());
                }

                NewLine();
                PopCurrentIndent();
                Visit(columns.GetToken4());
            }

            PopCurrentIndent();
        }

        if (msg.HasBlock4()) {
            NewLine();
            PushCurrentIndent();
            Visit(msg.GetBlock4());
            PopCurrentIndent();
        }
    }

    void VisitSimpleTableRef(const TRule_simple_table_ref& msg) {
        Visit(msg.GetRule_simple_table_ref_core1());
        if (msg.HasBlock2()) {
            NewLine();
            PushCurrentIndent();
            Visit(msg.GetBlock2());
            PopCurrentIndent();
        }
    }

    void VisitIntoSimpleTableRef(const TRule_into_simple_table_ref& msg) {
        Visit(msg.GetRule_simple_table_ref1());
        if (msg.HasBlock2()) {
            const auto& block2 = msg.GetBlock2();
            NewLine();
            PushCurrentIndent();
            Visit(block2.GetToken1());
            Visit(block2.GetToken2());
            const auto& columns = block2.GetRule_pure_column_list3();
            Visit(columns.GetToken1());
            NewLine();
            PushCurrentIndent();
            Visit(columns.GetRule_an_id2());
            for (const auto& block : columns.GetBlock3()) {
                Visit(block.GetToken1());
                NewLine();
                Visit(block.GetRule_an_id2());
            }

            PopCurrentIndent();
            NewLine();
            Visit(columns.GetToken4());
            PopCurrentIndent();
        }
    }

    void VisitSelectKindPartial(const TRule_select_kind_partial& msg) {
        Visit(msg.GetRule_select_kind1());
        if (msg.HasBlock2()) {
            NewLine();
            Visit(msg.GetBlock2());
        }
    }

    void VisitFlattenByArg(const TRule_flatten_by_arg& msg) {
        switch (msg.Alt_case()) {
        case TRule_flatten_by_arg::kAltFlattenByArg1: {
            const auto& alt = msg.GetAlt_flatten_by_arg1();
            NewLine();
            PushCurrentIndent();
            Visit(alt);
            PopCurrentIndent();
            break;
        }
        case TRule_flatten_by_arg::kAltFlattenByArg2: {
            const auto& alt = msg.GetAlt_flatten_by_arg2();
            Visit(alt.GetToken1());
            NewLine();
            PushCurrentIndent();
            const auto& exprs = alt.GetRule_named_expr_list2();
            Visit(exprs.GetRule_named_expr1());
            for (const auto& block : exprs.GetBlock2()) {
                Visit(block.GetToken1());
                NewLine();
                Visit(block.GetRule_named_expr2());
            }

            if (alt.HasBlock3()) {
                Visit(alt.GetBlock3());
            }

            NewLine();
            PopCurrentIndent();
            Visit(alt.GetToken4());
            break;
        }
        default:
            ythrow yexception() << "Alt is not supported";
        }
    }

    void VisitWithoutColumnList(const TRule_without_column_list& msg) {
        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_without_column_name1());
        for (const auto& block : msg.GetBlock2()) {
            Visit(block.GetToken1());
            NewLine();
            Visit(block.GetRule_without_column_name2());
        }

        if (msg.HasBlock3()) {
            Visit(msg.GetBlock3());
        }

        PopCurrentIndent();
    }

    void VisitTableRef(const TRule_table_ref& msg) {
        if (msg.HasBlock1()) {
            Visit(msg.GetBlock1());
        }

        if (msg.HasBlock2()) {
            Visit(msg.GetBlock2());
        }

        const auto& block3 = msg.GetBlock3();
        switch (block3.Alt_case()) {
        case TRule_table_ref::TBlock3::kAlt1: {
            const auto& alt = block3.GetAlt1();
            const auto& key = alt.GetRule_table_key1();
            Visit(key.GetRule_id_table_or_type1());
            if (key.HasBlock2()) {
                NewLine();
                PushCurrentIndent();
                Visit(key.GetBlock2());
                PopCurrentIndent();
            }

            break;
        }
        case TRule_table_ref::TBlock3::kAlt2: {
            const auto& alt = block3.GetAlt2();
            Visit(alt.GetRule_an_id_expr1());
            AfterInvokeExpr = true;
            Visit(alt.GetToken2());
            if (alt.HasBlock3()) {
                Visit(alt.GetBlock3());
            }

            Visit(alt.GetToken4());
            break;
        }
        case TRule_table_ref::TBlock3::kAlt3: {
            const auto& alt = block3.GetAlt3();
            Visit(alt.GetRule_bind_parameter1());
            if (alt.HasBlock2()) {
                AfterInvokeExpr = true;
                Visit(alt.GetBlock2());
            }

            if (alt.HasBlock3()) {
                NewLine();
                PushCurrentIndent();
                Visit(alt.GetBlock3());
                PopCurrentIndent();
            }

            break;
        }
        default:
            ythrow yexception() << "Alt is not supported";
        }

        if (msg.HasBlock4()) {
            NewLine();
            PushCurrentIndent();
            Visit(msg.GetBlock4());
            PopCurrentIndent();
        }
    }

    void VisitGroupingElementList(const TRule_grouping_element_list& msg) {
        NewLine();
        PushCurrentIndent();
        Visit(msg.GetRule_grouping_element1());
        for (const auto& block : msg.GetBlock2()) {
            Visit(block.GetToken1());
            NewLine();
            Visit(block.GetRule_grouping_element2());
        }

        PopCurrentIndent();
    }

    void VisitGroupByClause(const TRule_group_by_clause& msg) {
        Visit(msg.GetToken1());
        if (msg.HasBlock2()) {
            Visit(msg.GetBlock2());
        }

        Visit(msg.GetToken3());
        Visit(msg.GetRule_opt_set_quantifier4());
        Visit(msg.GetRule_grouping_element_list5());
        if (msg.HasBlock6()) {
            NewLine();
            PushCurrentIndent();
            Visit(msg.GetBlock6());
            PopCurrentIndent();
        }
    }

    void VisitWindowDefinitionList(const TRule_window_definition_list& msg) {
        NewLine();
        PushCurrentIndent();

        Visit(msg.GetRule_window_definition1());
        for (const auto& block : msg.GetBlock2()) {
            Visit(block.GetToken1());
            NewLine();
            Visit(block.GetRule_window_definition2());
        }

        PopCurrentIndent();
    }

    void VisitWindowSpecification(const TRule_window_specification& msg) {
        Visit(msg.GetToken1());
        const auto& details = msg.GetRule_window_specification_details2();
        const bool needsNewline = details.HasBlock1() || details.HasBlock2() ||
                                  details.HasBlock3() || details.HasBlock4();
        if (needsNewline) {
            NewLine();
            PushCurrentIndent();
        }

        if (details.HasBlock1()) {
            NewLine();
            Visit(details.GetBlock1());
        }

        if (details.HasBlock2()) {
            NewLine();
            Visit(details.GetBlock2());
        }

        if (details.HasBlock3()) {
            NewLine();
            Visit(details.GetBlock3());
        }

        if (details.HasBlock4()) {
            NewLine();
            Visit(details.GetBlock4());
        }

        if (needsNewline) {
            NewLine();
            PopCurrentIndent();
        }

        Visit(msg.GetToken3());
    }

    void VisitWindowParitionClause(const TRule_window_partition_clause& msg) {
        Visit(msg.GetToken1());
        if (msg.HasBlock2()) {
            Visit(msg.GetBlock2());
        }

        Visit(msg.GetToken3());
        const auto& exprs = msg.GetRule_named_expr_list4();
        PushCurrentIndent();
        NewLine();
        Visit(exprs.GetRule_named_expr1());
        for (const auto& block : exprs.GetBlock2()) {
            Visit(block.GetToken1());
            NewLine();
            Visit(block.GetRule_named_expr2());
        }

        PopCurrentIndent();
    }

    void VisitLambdaBody(const TRule_lambda_body& msg) {
        PushCurrentIndent();
        NewLine();
        VisitRepeated(msg.GetBlock1());
        for (const auto& block : msg.GetBlock2()) {
            Visit(block);
            NewLine();
        }

        Visit(msg.GetToken3());
        Visit(msg.GetRule_expr4());
        VisitRepeated(msg.GetBlock5());

        PopCurrentIndent();
        NewLine();
    }

    void VisitInAtomExpr(const TRule_in_atom_expr& msg) {
        if (msg.Alt_case() == TRule_in_atom_expr::kAltInAtomExpr7) {
            const auto& alt = msg.GetAlt_in_atom_expr7();
            Visit(alt.GetToken1());
            NewLine();
            PushCurrentIndent();
            Visit(alt.GetRule_select_stmt2());
            NewLine();
            PopCurrentIndent();
            Visit(alt.GetToken3());
        } else {
            VisitAllFields(TRule_in_atom_expr::GetDescriptor(), msg);
        }
    }

    void VisitSelectKindParenthesis(const TRule_select_kind_parenthesis& msg) {
        if (msg.Alt_case() == TRule_select_kind_parenthesis::kAltSelectKindParenthesis2) {
            const auto& alt = msg.GetAlt_select_kind_parenthesis2();
            Visit(alt.GetToken1());
            NewLine();
            PushCurrentIndent();
            Visit(alt.GetRule_select_kind_partial2());
            PopCurrentIndent();
            NewLine();
            Visit(alt.GetToken3());
        } else {
            VisitAllFields(TRule_select_kind_parenthesis::GetDescriptor(), msg);
        }
    }

    void VisitCastExpr(const TRule_cast_expr& msg) {
        Visit(msg.GetToken1());
        AfterInvokeExpr = true;
        Visit(msg.GetToken2());
        Visit(msg.GetRule_expr3());
        Visit(msg.GetToken4());
        Visit(msg.GetRule_type_name_or_bind5());
        Visit(msg.GetToken6());
    }

    void VisitBitCastExpr(const TRule_bitcast_expr& msg) {
        Visit(msg.GetToken1());
        AfterInvokeExpr = true;
        Visit(msg.GetToken2());
        Visit(msg.GetRule_expr3());
        Visit(msg.GetToken4());
        Visit(msg.GetRule_type_name_simple5());
        Visit(msg.GetToken6());
    }

    void VisitExtOrderByClause(const TRule_ext_order_by_clause& msg) {
        if (msg.HasBlock1()) {
            Visit(msg.GetBlock1());
        }

        Visit(msg.GetRule_order_by_clause2());
    }

    void VisitKeyExpr(const TRule_key_expr& msg) {
        AfterKeyExpr = true;
        VisitAllFields(TRule_key_expr::GetDescriptor(), msg);
    }

    void VisitExistsExpr(const TRule_exists_expr& msg) {
        VisitKeyword(msg.GetToken1());
        VisitToken(msg.GetToken2());

        NewLine();
        PushCurrentIndent();

        Visit(msg.GetBlock3());

        PopCurrentIndent();
        NewLine();

        VisitToken(msg.GetToken4());
    }

    void VisitCaseExpr(const TRule_case_expr& msg) {
        VisitKeyword(msg.GetToken1());
        if (msg.HasBlock2()) {
            Visit(msg.GetBlock2());
        }
        NewLine();
        PushCurrentIndent();

        for (const auto& block : msg.GetBlock3()) {
            Visit(block);
            NewLine();
        }

        if (msg.HasBlock4()) {
            const auto& block = msg.GetBlock4();
            VisitKeyword(block.GetToken1());
            Visit(block.GetRule_expr2());
        }

        PopCurrentIndent();
        NewLine();
        Visit(msg.GetToken5());
    }

    void VisitWhenExpr(const TRule_when_expr& msg) {
        VisitKeyword(msg.GetToken1());
        Visit(msg.GetRule_expr2());

        NewLine();
        PushCurrentIndent();
        VisitKeyword(msg.GetToken3());
        Visit(msg.GetRule_expr4());
        PopCurrentIndent();
    }

    void VisitWithTableSettingsExpr(const TRule_with_table_settings& msg) {
        VisitKeyword(msg.GetToken1());
        Visit(msg.GetToken2());

        const bool needIndent = msg.Block4Size() > 0; // more then one setting
        if (needIndent) {
            NewLine();
            PushCurrentIndent();
            Visit(msg.GetRule_table_settings_entry3()); // first setting

            for (const auto& entry : msg.GetBlock4()) {
                Visit(entry.GetToken1()); // comma
                NewLine();
                Visit(entry.GetRule_table_settings_entry2()); // other settings
            }
            PopCurrentIndent();
            NewLine();
        } else {
            Visit(msg.GetRule_table_settings_entry3());
        }

        Visit(msg.GetToken5());
    }

    void VisitTableSettingValue(const TRule_table_setting_value& msg) {
        switch (msg.GetAltCase()) {
            case TRule_table_setting_value::kAltTableSettingValue5: {
                // | ttl_tier_list ON an_id (AS (SECONDS | MILLISECONDS | MICROSECONDS | NANOSECONDS))?
                const auto& ttlSettings = msg.GetAlt_table_setting_value5();
                const auto& tierList = ttlSettings.GetRule_ttl_tier_list1();
                const bool needIndent = tierList.HasBlock2() && tierList.GetBlock2().Block2Size() > 0; // more then one tier
                if (needIndent) {
                    NewLine();
                    PushCurrentIndent();
                    Visit(tierList.GetRule_expr1());
                    VisitTtlTierAction(tierList.GetBlock2().GetRule_ttl_tier_action1());

                    for (const auto& tierEntry : tierList.GetBlock2().GetBlock2()) {
                        Visit(tierEntry.GetToken1()); // comma
                        NewLine();
                        Visit(tierEntry.GetRule_expr2());
                        VisitTtlTierAction(tierEntry.GetRule_ttl_tier_action3());
                    }

                    PopCurrentIndent();
                    NewLine();
                } else {
                    Visit(tierList.GetRule_expr1());
                    if (tierList.HasBlock2()) {
                        VisitTtlTierAction(tierList.GetBlock2().GetRule_ttl_tier_action1());
                    }
                }

                VisitKeyword(ttlSettings.GetToken2());
                Visit(ttlSettings.GetRule_an_id3());
                if (ttlSettings.HasBlock4()) {
                    VisitKeyword(ttlSettings.GetBlock4().GetToken1());
                    VisitKeyword(ttlSettings.GetBlock4().GetToken2());
                }
            } break;
            default:
                VisitAllFields(TRule_table_setting_value::GetDescriptor(), msg);
        }
    }

    void VisitTtlTierAction(const TRule_ttl_tier_action& msg) {
        switch (msg.GetAltCase()) {
            case TRule_ttl_tier_action::kAltTtlTierAction1:
                // | TO EXTERNAL DATA SOURCE an_id
                VisitKeyword(msg.GetAlt_ttl_tier_action1().GetToken1());
                VisitKeyword(msg.GetAlt_ttl_tier_action1().GetToken2());
                VisitKeyword(msg.GetAlt_ttl_tier_action1().GetToken3());
                VisitKeyword(msg.GetAlt_ttl_tier_action1().GetToken4());
                Visit(msg.GetAlt_ttl_tier_action1().GetRule_an_id5());
                break;
            case TRule_ttl_tier_action::kAltTtlTierAction2:
                // | DELETE
                VisitKeyword(msg.GetAlt_ttl_tier_action2().GetToken1());
                break;
            case TRule_ttl_tier_action::ALT_NOT_SET:
                break;
        }
    }

    void VisitExpr(const TRule_expr& msg) {
        if (msg.HasAlt_expr2()) {
            Visit(msg.GetAlt_expr2());
            return;
        }
        const auto& orExpr = msg.GetAlt_expr1();
        auto getExpr = [](const TRule_expr::TAlt1::TBlock2& b) -> const TRule_or_subexpr& { return b.GetRule_or_subexpr2(); };
        auto getOp = [](const TRule_expr::TAlt1::TBlock2& b) -> const TToken& { return b.GetToken1(); };
        VisitBinaryOp(orExpr.GetRule_or_subexpr1(), getOp, getExpr, orExpr.GetBlock2().begin(), orExpr.GetBlock2().end());
    }

    void VisitOrSubexpr(const TRule_or_subexpr& msg) {
        auto getExpr = [](const TRule_or_subexpr::TBlock2& b) -> const TRule_and_subexpr& { return b.GetRule_and_subexpr2(); };
        auto getOp = [](const TRule_or_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
        VisitBinaryOp(msg.GetRule_and_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
    }

    void VisitAndSubexpr(const TRule_and_subexpr& msg) {
        auto getExpr = [](const TRule_and_subexpr::TBlock2& b) -> const TRule_xor_subexpr& { return b.GetRule_xor_subexpr2(); };
        auto getOp = [](const TRule_and_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
        VisitBinaryOp(msg.GetRule_xor_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
    }

    void VisitEqSubexpr(const TRule_eq_subexpr& msg) {
        auto getExpr = [](const TRule_eq_subexpr::TBlock2& b) -> const TRule_neq_subexpr& { return b.GetRule_neq_subexpr2(); };
        auto getOp = [](const TRule_eq_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
        VisitBinaryOp(msg.GetRule_neq_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
    }

    void VisitNeqSubexpr(const TRule_neq_subexpr& msg) {
        VisitNeqSubexprImpl(msg, false);
    }

    void VisitNeqSubexprImpl(const TRule_neq_subexpr& msg, bool pushedIndent) {
        auto getExpr = [](const TRule_neq_subexpr::TBlock2& b) -> const TRule_bit_subexpr& { return b.GetRule_bit_subexpr2(); };
        auto getOp = [](const TRule_neq_subexpr::TBlock2& b) -> const TRule_neq_subexpr::TBlock2::TBlock1& { return b.GetBlock1(); };
        VisitBinaryOp(msg.GetRule_bit_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());

        if (msg.HasBlock3()) {
            const auto& b = msg.GetBlock3();
            switch (b.Alt_case()) {
            case TRule_neq_subexpr_TBlock3::kAlt1: {
                const auto& alt = b.GetAlt1();
                const bool hasFirstNewline = LastLine != ParsedTokens[TokenIndex].Line;
                // 2 is `??` size in tokens
                const bool hasSecondNewline = ParsedTokens[TokenIndex].Line != ParsedTokens[TokenIndex + 2].Line;
                const ui32 currentOutLine = OutLine;

                PosFromParsedToken(ParsedTokens[TokenIndex]);
                if (currentOutLine != OutLine || (hasFirstNewline && hasSecondNewline)) {
                    NewLine();
                    if (!pushedIndent) {
                        PushCurrentIndent();
                        pushedIndent = true;
                    }
                }

                Visit(alt.GetRule_double_question1());
                PosFromParsedToken(ParsedTokens[TokenIndex]);
                if (hasFirstNewline || hasSecondNewline) {
                    NewLine();
                    if (!pushedIndent) {
                        PushCurrentIndent();
                        pushedIndent = true;
                    }
                }

                VisitNeqSubexprImpl(alt.GetRule_neq_subexpr2(), pushedIndent);
                if (pushedIndent) {
                    PopCurrentIndent();
                }

                break;
            }
            case TRule_neq_subexpr_TBlock3::kAlt2:
                Visit(b.GetAlt2());
                break;
            default:
                ythrow yexception() << "Alt is not supported";
            }
        }
    }

    void VisitBitSubexpr(const TRule_bit_subexpr& msg) {
        auto getExpr = [](const TRule_bit_subexpr::TBlock2& b) -> const TRule_add_subexpr& { return b.GetRule_add_subexpr2(); };
        auto getOp = [](const TRule_bit_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
        VisitBinaryOp(msg.GetRule_add_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
    }

    void VisitAddSubexpr(const TRule_add_subexpr& msg) {
        auto getExpr = [](const TRule_add_subexpr::TBlock2& b) -> const TRule_mul_subexpr& { return b.GetRule_mul_subexpr2(); };
        auto getOp = [](const TRule_add_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
        VisitBinaryOp(msg.GetRule_mul_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
    }

    void VisitMulSubexpr(const TRule_mul_subexpr& msg) {
        auto getExpr = [](const TRule_mul_subexpr::TBlock2& b) -> const TRule_con_subexpr& { return b.GetRule_con_subexpr2(); };
        auto getOp = [](const TRule_mul_subexpr::TBlock2& b) -> const TToken& { return b.GetToken1(); };
        VisitBinaryOp(msg.GetRule_con_subexpr1(), getOp, getExpr, msg.GetBlock2().begin(), msg.GetBlock2().end());
    }

    ui32 BinaryOpTokenSize(const TToken&) {
        return 1;
    }

    ui32 BinaryOpTokenSize(const TRule_neq_subexpr::TBlock2::TBlock1& block) {
        switch (block.Alt_case()) {
        case TRule_neq_subexpr::TBlock2::TBlock1::kAlt1:
        case TRule_neq_subexpr::TBlock2::TBlock1::kAlt3:
        case TRule_neq_subexpr::TBlock2::TBlock1::kAlt5:
        case TRule_neq_subexpr::TBlock2::TBlock1::kAlt6:
        case TRule_neq_subexpr::TBlock2::TBlock1::kAlt7:
            return 1;
        case TRule_neq_subexpr::TBlock2::TBlock1::kAlt2:
            return 2;
        case TRule_neq_subexpr::TBlock2::TBlock1::kAlt4:
            return 3;
        default:
            ythrow yexception() << "Alt is not supported";
        }
    }

    void VisitShiftRight(const TRule_shift_right& msg) {
        VisitToken(msg.GetToken1());
        InMultiTokenOp = true;
        VisitToken(msg.GetToken2());
        InMultiTokenOp = false;
    }

    void VisitRotRight(const TRule_rot_right& msg) {
        VisitToken(msg.GetToken1());
        InMultiTokenOp = true;
        VisitToken(msg.GetToken2());
        VisitToken(msg.GetToken3());
        InMultiTokenOp = false;
    }

    template <typename TExpr, typename TGetOp, typename TGetExpr, typename TIter>
    void VisitBinaryOp(const TExpr& expr, TGetOp getOp, TGetExpr getExpr, TIter begin, TIter end) {
        Visit(expr);
        bool pushedIndent = false;

        for (; begin != end; ++begin) {
            const auto op = getOp(*begin);
            const auto opSize = BinaryOpTokenSize(op);
            const bool hasFirstNewline = LastLine != ParsedTokens[TokenIndex].Line;
            const bool hasSecondNewline = ParsedTokens[TokenIndex].Line != ParsedTokens[TokenIndex + opSize].Line;
            const ui32 currentOutLine = OutLine;

            PosFromParsedToken(ParsedTokens[TokenIndex]);
            if (currentOutLine != OutLine || (hasFirstNewline && hasSecondNewline)) {
                NewLine();
                if (!pushedIndent) {
                    PushCurrentIndent();
                    pushedIndent = true;
                }
            }
            Visit(op);

            PosFromParsedToken(ParsedTokens[TokenIndex]);
            if (hasFirstNewline || hasSecondNewline) {
                NewLine();
                if (!pushedIndent) {
                    PushCurrentIndent();
                    pushedIndent = true;
                }
            }

            Visit(getExpr(*begin));
        }

        if (pushedIndent) {
            PopCurrentIndent();
        }
    }

    void PushCurrentIndent() {
        CurrentIndent += OneIndent;
    }

    void PopCurrentIndent() {
        CurrentIndent -= OneIndent;
    }

private:
    const TStaticData& StaticData;
    const TParsedTokenList& ParsedTokens;
    const TParsedTokenList& Comments;
    TStringBuilder SB;
    ui32 OutColumn = 0;
    ui32 OutLine = 1;
    ui32 LastLine = 0;
    ui32 LastColumn = 0;
    ui32 LastComment = 0;
    i32 CurrentIndent = 0;
    TVector<EScope> Scopes;
    TMaybe<bool> AddLine;
    ui64 InsideType = 0;
    bool AfterNamespace = false;
    bool AfterBracket = false;
    bool AfterInvokeExpr = false;
    bool AfterUnaryOp = false;
    bool SkipSpaceAfterUnaryOp = false;
    bool AfterDollarOrAt = false;
    bool AfterDot = false;
    bool AfterDigits = false;
    bool AfterQuestion = false;
    bool AfterLess = false;
    bool AfterKeyExpr = false;
    bool InMultiTokenOp = false;
    ui32 ForceExpandedLine = 0;
    ui32 ForceExpandedColumn = 0;

    ui32 TokenIndex = 0;
    TMarkTokenStack MarkTokenStack;
    TVector<TTokenInfo> MarkedTokens;
    ui64 InsideExpr = 0;
};

template <typename T>
TPrettyFunctor MakePrettyFunctor(void (TPrettyVisitor::*memberPtr)(const T& msg)) {
    return [memberPtr](TPrettyVisitor& visitor, const NProtoBuf::Message& rawMsg) {
        (visitor.*memberPtr)(dynamic_cast<const T&>(rawMsg));
    };
}

template <typename T>
TObfuscatingFunctor MakeObfuscatingFunctor(void (TObfuscatingVisitor::*memberPtr)(const T& msg)) {
    return [memberPtr](TObfuscatingVisitor& visitor, const NProtoBuf::Message& rawMsg) {
        (visitor.*memberPtr)(dynamic_cast<const T&>(rawMsg));
    };
}

TStaticData::TStaticData()
    : Keywords(GetKeywords())
    , ScopeDispatch({
        {TRule_type_name::GetDescriptor(), EScope::TypeName},
        {TRule_type_name_composite::GetDescriptor(), EScope::TypeName},
        {TRule_double_question::GetDescriptor(), EScope::DoubleQuestion},
        {TRule_id::GetDescriptor(), EScope::Identifier},
        {TRule_id_or_type::GetDescriptor(), EScope::Identifier},
        {TRule_id_schema::GetDescriptor(), EScope::Identifier},
        {TRule_id_expr::GetDescriptor(), EScope::Identifier},
        {TRule_id_expr_in::GetDescriptor(), EScope::Identifier},
        {TRule_id_window::GetDescriptor(), EScope::Identifier},
        {TRule_id_table::GetDescriptor(), EScope::Identifier},
        {TRule_id_without::GetDescriptor(), EScope::Identifier},
        {TRule_id_hint::GetDescriptor(), EScope::Identifier},
        {TRule_identifier::GetDescriptor(), EScope::Identifier},
        {TRule_id_table_or_type::GetDescriptor(), EScope::Identifier},
        {TRule_bind_parameter::GetDescriptor(), EScope::Identifier},
        {TRule_an_id_as_compat::GetDescriptor(), EScope::Identifier},
        })
    , PrettyVisitDispatch({
        {TToken::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitToken)},
        {TRule_into_values_source::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitIntoValuesSource)},
        {TRule_select_kind::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelectKind)},
        {TRule_process_core::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitProcessCore)},
        {TRule_reduce_core::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitReduceCore)},
        {TRule_sort_specification_list::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSortSpecificationList)},
        {TRule_select_core::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelectCore)},
        {TRule_join_source::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitJoinSource)},
        {TRule_single_source::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSingleSource)},
        {TRule_flatten_source::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitFlattenSource)},
        {TRule_named_single_source::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitNamedSingleSource)},
        {TRule_simple_table_ref::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSimpleTableRef)},
        {TRule_into_simple_table_ref::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitIntoSimpleTableRef)},
        {TRule_select_kind_partial::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelectKindPartial)},
        {TRule_flatten_by_arg::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitFlattenByArg)},
        {TRule_without_column_list::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitWithoutColumnList)},
        {TRule_table_ref::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitTableRef)},
        {TRule_grouping_element_list::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitGroupingElementList)},
        {TRule_group_by_clause::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitGroupByClause)},
        {TRule_window_definition_list::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitWindowDefinitionList)},
        {TRule_window_specification::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitWindowSpecification)},
        {TRule_window_partition_clause::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitWindowParitionClause)},
        {TRule_lambda_body::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitLambdaBody)},
        {TRule_in_atom_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitInAtomExpr)},
        {TRule_select_kind_parenthesis::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelectKindParenthesis)},
        {TRule_cast_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCastExpr)},
        {TRule_bitcast_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitBitCastExpr)},
        {TRule_ext_order_by_clause::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitExtOrderByClause)},
        {TRule_key_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitKeyExpr)},
        {TRule_define_action_or_subquery_body::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDefineActionOrSubqueryBody)},
        {TRule_exists_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitExistsExpr)},
        {TRule_case_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCaseExpr)},
        {TRule_when_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitWhenExpr)},
        {TRule_with_table_settings::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitWithTableSettingsExpr)},
        {TRule_table_setting_value::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitTableSettingValue)},
        {TRule_ttl_tier_action::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitTtlTierAction)},

        {TRule_expr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitExpr)},
        {TRule_or_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitOrSubexpr)},
        {TRule_and_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAndSubexpr)},
        {TRule_eq_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitEqSubexpr)},
        {TRule_neq_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitNeqSubexpr)},
        {TRule_bit_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitBitSubexpr)},
        {TRule_add_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAddSubexpr)},
        {TRule_mul_subexpr::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitMulSubexpr)},

        {TRule_rot_right::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitRotRight)},
        {TRule_shift_right::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitShiftRight)},

        {TRule_pragma_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitPragma)},
        {TRule_select_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelect)},
        {TRule_select_unparenthesized_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitSelectUnparenthesized)},
        {TRule_named_nodes_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitNamedNodes)},
        {TRule_create_table_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateTable)},
        {TRule_drop_table_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropTable)},
        {TRule_use_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitUse)},
        {TRule_into_table_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitIntoTable)},
        {TRule_commit_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCommit)},
        {TRule_update_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitUpdate)},
        {TRule_delete_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDelete)},
        {TRule_rollback_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitRollback)},
        {TRule_declare_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDeclare)},
        {TRule_import_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitImport)},
        {TRule_export_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitExport)},
        {TRule_alter_table_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterTable)},
        {TRule_alter_external_table_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterExternalTable)},
        {TRule_do_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDo)},
        {TRule_define_action_or_subquery_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAction)},
        {TRule_if_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitIf)},
        {TRule_for_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitFor)},
        {TRule_values_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitValues)},
        {TRule_create_user_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateUser)},
        {TRule_alter_user_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterUser)},
        {TRule_create_group_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateGroup)},
        {TRule_alter_group_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterGroup)},
        {TRule_drop_role_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropRole)},
        {TRule_upsert_object_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitUpsertObject)},
        {TRule_create_object_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateObject)},
        {TRule_alter_object_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterObject)},
        {TRule_drop_object_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropObject)},
        {TRule_create_external_data_source_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateExternalDataSource)},
        {TRule_alter_external_data_source_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterExternalDataSource)},
        {TRule_drop_external_data_source_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropExternalDataSource)},
        {TRule_create_replication_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateAsyncReplication)},
        {TRule_alter_replication_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterAsyncReplication)},
        {TRule_drop_replication_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropAsyncReplication)},
        {TRule_create_topic_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateTopic)},
        {TRule_alter_topic_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterTopic)},
        {TRule_drop_topic_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropTopic)},
        {TRule_grant_permissions_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitGrantPermissions)},
        {TRule_revoke_permissions_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitRevokePermissions)},
        {TRule_alter_table_store_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterTableStore)},
        {TRule_create_view_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateView)},
        {TRule_drop_view_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropView)},
        {TRule_create_resource_pool_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateResourcePool)},
        {TRule_alter_resource_pool_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterResourcePool)},
        {TRule_drop_resource_pool_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropResourcePool)},
        {TRule_create_backup_collection_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateBackupCollection)},
        {TRule_alter_backup_collection_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterBackupCollection)},
        {TRule_drop_backup_collection_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropBackupCollection)},
        {TRule_analyze_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAnalyze)},
        {TRule_create_resource_pool_classifier_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitCreateResourcePoolClassifier)},
        {TRule_alter_resource_pool_classifier_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitAlterResourcePoolClassifier)},
        {TRule_drop_resource_pool_classifier_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitDropResourcePoolClassifier)},
        {TRule_backup_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitBackup)},
        {TRule_restore_stmt::GetDescriptor(), MakePrettyFunctor(&TPrettyVisitor::VisitRestore)},
        })
    , ObfuscatingVisitDispatch({
        {TToken::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitToken)},
        {TRule_literal_value::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitLiteralValue)},
        {TRule_pragma_value::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitPragmaValue)},
        {TRule_atom_expr::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitAtomExpr)},
        {TRule_in_atom_expr::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitInAtomExpr)},
        {TRule_unary_casual_subexpr::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitUnaryCasualSubexpr)},
        {TRule_in_unary_casual_subexpr::GetDescriptor(), MakeObfuscatingFunctor(&TObfuscatingVisitor::VisitInUnaryCasualSubexpr)},
        })
{
    // ensure that all statements have a visitor
    auto coreDescr = TRule_sql_stmt_core::GetDescriptor();
    for (int i = 0; i < coreDescr->field_count(); ++i) {
        const NProtoBuf::FieldDescriptor* fd = coreDescr->field(i);
        if (fd->cpp_type() != NProtoBuf::FieldDescriptor::CPPTYPE_MESSAGE) {
            continue;
        }

        auto altDescr = fd->message_type();
        for (int j = 0; j < altDescr->field_count(); ++j) {
            auto fd2 = altDescr->field(j);
            if (fd2->cpp_type() != NProtoBuf::FieldDescriptor::CPPTYPE_MESSAGE) {
                continue;
            }

            auto stmtMessage = fd2->message_type();
            Y_ENSURE(PrettyVisitDispatch.contains(stmtMessage), TStringBuilder() << "Missing visitor for " << stmtMessage->name());
        }
    }
}

class TSqlFormatter : public NSQLFormat::ISqlFormatter {
public:
    TSqlFormatter(const NSQLTranslation::TTranslationSettings& settings)
        : Settings(settings)
    {}

    bool Format(const TString& query, TString& formattedQuery, NYql::TIssues& issues, EFormatMode mode) override {
        formattedQuery = (mode == EFormatMode::Obfuscate) ? "" : query;
        auto parsedSettings = Settings;
        if (!NSQLTranslation::ParseTranslationSettings(query, parsedSettings, issues)) {
            return false;
        }

        if (parsedSettings.PgParser) {
            return mode != EFormatMode::Obfuscate;
        }

        if (mode == EFormatMode::Obfuscate) {
            auto message = NSQLTranslationV1::SqlAST(query, "Query", issues, NSQLTranslation::SQL_MAX_PARSER_ERRORS, parsedSettings.AnsiLexer, parsedSettings.Antlr4Parser, parsedSettings.TestAntlr4, parsedSettings.Arena);
            if (!message) {
                return false;
            }

            TObfuscatingVisitor visitor;
            return Format(visitor.Process(*message), formattedQuery, issues, EFormatMode::Pretty);
        }

        auto lexer = NSQLTranslationV1::MakeLexer(parsedSettings.AnsiLexer, parsedSettings.Antlr4Parser);
        TParsedTokenList allTokens;
        auto onNextToken = [&](NSQLTranslation::TParsedToken&& token) {
            if (token.Name != "EOF") {
                allTokens.push_back(token);
            }
        };

        if (!lexer->Tokenize(query, "Query", onNextToken, issues, NSQLTranslation::SQL_MAX_PARSER_ERRORS)) {
            return false;
        }

        TVector<TTokenIterator> statements;
        SplitByStatements(allTokens.begin(), allTokens.end(), statements);
        TStringBuilder finalFormattedQuery;
        for (size_t i = 1; i < statements.size(); ++i) {
            TStringBuilder currentQueryBuilder;
            for (auto it = statements[i - 1]; it != statements[i]; ++it) {
                currentQueryBuilder << it->Content;
            }

            TString currentQuery = currentQueryBuilder;
            currentQuery = StripStringLeft(currentQuery);
            bool isBlank = true;
            for (auto c : currentQuery) {
                if (c != ';') {
                    isBlank = false;
                    break;
                }
            };

            if (isBlank) {
                continue;
            }

            TVector<NSQLTranslation::TParsedToken> comments;
            TParsedTokenList parsedTokens, stmtTokens;
            bool hasTrailingComments = false;
            auto onNextRawToken = [&](NSQLTranslation::TParsedToken&& token) {
                stmtTokens.push_back(token);
                if (token.Name == "COMMENT") {
                    comments.emplace_back(std::move(token));
                    hasTrailingComments = true;
                } else if (token.Name != "WS" && token.Name != "EOF") {
                    parsedTokens.emplace_back(std::move(token));
                    hasTrailingComments = false;
                }
            };

            if (!lexer->Tokenize(currentQuery, "Query", onNextRawToken, issues, NSQLTranslation::SQL_MAX_PARSER_ERRORS)) {
                return false;
            }

            NYql::TIssues parserIssues;
            auto message = NSQLTranslationV1::SqlAST(currentQuery, "Query", parserIssues, NSQLTranslation::SQL_MAX_PARSER_ERRORS, parsedSettings.AnsiLexer, parsedSettings.Antlr4Parser, parsedSettings.TestAntlr4, parsedSettings.Arena);
            if (!message) {
                finalFormattedQuery << currentQuery;
                if (!currentQuery.EndsWith("\n")) {
                    finalFormattedQuery << "\n";
                }

                continue;
            }

            TPrettyVisitor visitor(parsedTokens, comments);
            bool addLine;
            auto currentFormattedQuery = visitor.Process(*message, addLine);
            TParsedTokenList stmtFormattedTokens;
            auto onNextFormattedToken = [&](NSQLTranslation::TParsedToken&& token) {
                stmtFormattedTokens.push_back(token);
            };

            if (!lexer->Tokenize(currentFormattedQuery, "Query", onNextFormattedToken, issues, NSQLTranslation::SQL_MAX_PARSER_ERRORS)) {
                return false;
            }

            if (!Validate(stmtFormattedTokens, stmtTokens)) {
                issues.AddIssue(NYql::TIssue({}, TStringBuilder() << "Validation failed: " << currentQuery.Quote() << " != " << currentFormattedQuery.Quote()));
                return false;
            }

            if (addLine && !finalFormattedQuery.empty()) {
                finalFormattedQuery << "\n";
            }

            finalFormattedQuery << currentFormattedQuery;
            if (parsedTokens.back().Name != "SEMICOLON") {
                if (hasTrailingComments
                     && !comments.back().Content.EndsWith("\n")
                     && comments.back().Content.StartsWith("--")) {
                    finalFormattedQuery << "\n";
                }
                finalFormattedQuery << ";\n";
            }
        }

        formattedQuery = finalFormattedQuery;
        return true;
    }

private:
    const NSQLTranslation::TTranslationSettings Settings;
};

}

ISqlFormatter::TPtr MakeSqlFormatter(const NSQLTranslation::TTranslationSettings& settings) {
    return ISqlFormatter::TPtr(new TSqlFormatter(settings));
}

TString MutateQuery(const TString& query, const NSQLTranslation::TTranslationSettings& settings) {
    auto parsedSettings = settings;
    NYql::TIssues issues;
    if (!NSQLTranslation::ParseTranslationSettings(query, parsedSettings, issues)) {
        throw yexception() << issues.ToString();
    }

    auto lexer = NSQLTranslationV1::MakeLexer(parsedSettings.AnsiLexer, parsedSettings.Antlr4Parser);
    TVector<NSQLTranslation::TParsedToken> allTokens;
    auto onNextToken = [&](NSQLTranslation::TParsedToken&& token) {
        if (token.Name != "EOF") {
            allTokens.push_back(token);
        }
    };

    if (!lexer->Tokenize(query, "Query", onNextToken, issues, NSQLTranslation::SQL_MAX_PARSER_ERRORS)) {
        throw yexception() << issues.ToString();
    }

    TStringBuilder newQueryBuilder;
    ui32 index = 0;
    for (const auto& x : allTokens) {
        newQueryBuilder << " /*" << index++ << "*/ ";
        newQueryBuilder << x.Content;
    }

    newQueryBuilder << " /*" << index++ << "*/ ";
    return newQueryBuilder;
}

bool SqlFormatSimple(const TString& query, TString& formattedQuery, TString& error) {
    try {
        google::protobuf::Arena arena;
        NSQLTranslation::TTranslationSettings settings;
        settings.Arena = &arena;

        auto formatter = MakeSqlFormatter(settings);
        NYql::TIssues issues;
        const bool result = formatter->Format(query, formattedQuery, issues);
        if (!result) {
            error = issues.ToString();
        }
        return result;
    } catch (const std::exception& e) {
        error = e.what();
        return false;
    }
}

THashSet<TString> GetKeywords() {
    TString grammar;
    // ANTLR4-MIGRATION: just change SQLv1 to SQLv1Antlr4
    Y_ENSURE(NResource::FindExact("SQLv1.g.in", &grammar));
    THashSet<TString> res;
    TVector<TString> lines;
    Split(grammar, "\n", lines);
    for (auto s : lines) {
        s = StripString(s);
        if (s.StartsWith("//")) {
            continue;
        }

        auto pos1 = s.find(':');
        auto pos2 = s.find(';');
        if (pos1 == TString::npos || pos2 == TString::npos || pos2 < pos1 + 2) {
            continue;
        }

        auto before = s.substr(0, pos1);
        auto after = s.substr(pos1 + 1, pos2 - pos1 - 1);
        SubstGlobal(after, " ", "");
        SubstGlobal(after, "'", "");
        if (after == before) {
            //Cerr << before << "\n";
            res.insert(before);
        }
    }

    return res;
}

} // namespace NSQLFormat