summaryrefslogtreecommitdiffstats
path: root/src/mesa/shader/slang/slang_compile.c
blob: ad86676157076015637560fee71c14f2c1fadde1 (plain)
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
/*
 * Mesa 3-D graphics library
 *
 * Copyright (C) 2005-2006  Brian Paul   All Rights Reserved.
 * Copyright (C) 2008 VMware, Inc.  All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * \file slang_compile.c
 * slang front-end compiler
 * \author Michal Krol
 */

#include "main/imports.h"
#include "main/context.h"
#include "shader/program.h"
#include "shader/programopt.h"
#include "shader/prog_optimize.h"
#include "shader/prog_print.h"
#include "shader/prog_parameter.h"
#include "../../glsl/pp/sl_pp_public.h"
#include "../../glsl/cl/sl_cl_parse.h"
#include "slang_codegen.h"
#include "slang_compile.h"
#include "slang_storage.h"
#include "slang_log.h"
#include "slang_mem.h"
#include "slang_vartable.h"
#include "slang_simplify.h"

/*
 * This is a straightforward implementation of the slang front-end
 * compiler.  Lots of error-checking functionality is missing but
 * every well-formed shader source should compile successfully and
 * execute as expected. However, some semantically ill-formed shaders
 * may be accepted resulting in undefined behaviour.
 */


/** re-defined below, should be the same though */
#define TYPE_SPECIFIER_COUNT 36


/**
 * Check if the given identifier is legal.
 */
static GLboolean
legal_identifier(slang_atom name)
{
   /* "gl_" is a reserved prefix */
   if (strncmp((char *) name, "gl_", 3) == 0) {
      return GL_FALSE;
   }
   return GL_TRUE;
}


/*
 * slang_code_unit
 */

GLvoid
_slang_code_unit_ctr(slang_code_unit * self,
                     struct slang_code_object_ * object)
{
   _slang_variable_scope_ctr(&self->vars);
   _slang_function_scope_ctr(&self->funs);
   _slang_struct_scope_ctr(&self->structs);
   self->object = object;
}

GLvoid
_slang_code_unit_dtr(slang_code_unit * self)
{
   slang_variable_scope_destruct(&self->vars);
   slang_function_scope_destruct(&self->funs);
   slang_struct_scope_destruct(&self->structs);
}

/*
 * slang_code_object
 */

GLvoid
_slang_code_object_ctr(slang_code_object * self)
{
   GLuint i;

   for (i = 0; i < SLANG_BUILTIN_TOTAL; i++)
      _slang_code_unit_ctr(&self->builtin[i], self);
   _slang_code_unit_ctr(&self->unit, self);
   slang_atom_pool_construct(&self->atompool);
}

GLvoid
_slang_code_object_dtr(slang_code_object * self)
{
   GLuint i;

   for (i = 0; i < SLANG_BUILTIN_TOTAL; i++)
      _slang_code_unit_dtr(&self->builtin[i]);
   _slang_code_unit_dtr(&self->unit);
   slang_atom_pool_destruct(&self->atompool);
}


/* slang_parse_ctx */

typedef struct slang_parse_ctx_
{
   const unsigned char *I;
   slang_info_log *L;
   int parsing_builtin;
   GLboolean global_scope;   /**< Is object being declared a global? */
   slang_atom_pool *atoms;
   slang_unit_type type;     /**< Vertex vs. Fragment */
   GLuint version;           /**< user-specified (or default) #version */
} slang_parse_ctx;

/* slang_output_ctx */

typedef struct slang_output_ctx_
{
   slang_variable_scope *vars;
   slang_function_scope *funs;
   slang_struct_scope *structs;
   struct gl_program *program;
   struct gl_sl_pragmas *pragmas;
   slang_var_table *vartable;
   GLuint default_precision[TYPE_SPECIFIER_COUNT];
   GLboolean allow_precision;
   GLboolean allow_invariant;
   GLboolean allow_centroid;
   GLboolean allow_array_types;  /* float[] syntax */
} slang_output_ctx;

/* _slang_compile() */


/* Debugging aid, print file/line where parsing error is detected */
#define RETURN0 \
   do { \
      if (0) \
         printf("slang error at %s:%d\n", __FILE__, __LINE__); \
      return 0; \
   } while (0)


static void
parse_identifier_str(slang_parse_ctx * C, char **id)
{
   *id = (char *) C->I;
   C->I += strlen(*id) + 1;
}

static slang_atom
parse_identifier(slang_parse_ctx * C)
{
   const char *id;

   id = (const char *) C->I;
   C->I += strlen(id) + 1;
   return slang_atom_pool_atom(C->atoms, id);
}

static int
is_hex_digit(char c)
{
   return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}

static int
parse_general_number(slang_parse_ctx *ctx, float *number)
{
   char *flt = NULL;

   if (*ctx->I == '0') {
      int value = 0;
      const unsigned char *pi;

      if (ctx->I[1] == 'x' || ctx->I[1] == 'X') {
         ctx->I += 2;
         if (!is_hex_digit(*ctx->I)) {
            return 0;
         }
         do {
            int digit;

            if (*ctx->I >= '0' && *ctx->I <= '9') {
               digit = (int)(*ctx->I - '0');
            } else if (*ctx->I >= 'a' && *ctx->I <= 'f') {
               digit = (int)(*ctx->I - 'a') + 10;
            } else {
               digit = (int)(*ctx->I - 'A') + 10;
            }
            value = value * 0x10 + digit;
            ctx->I++;
         } while (is_hex_digit(*ctx->I));
         if (*ctx->I != '\0') {
            return 0;
         }
         ctx->I++;
         *number = (float)value;
         return 1;
      }

      pi = ctx->I;
      pi++;
      while (*pi >= '0' && *pi <= '7') {
         int digit;

         digit = (int)(*pi - '0');
         value = value * 010 + digit;
         pi++;
      }
      if (*pi == '\0') {
         pi++;
         ctx->I = pi;
         *number = (float)value;
         return 1;
      }
   }

   parse_identifier_str(ctx, &flt);
   flt = _mesa_strdup(flt);
   if (!flt) {
      return 0;
   }
   if (flt[strlen(flt) - 1] == 'f' || flt[strlen(flt) - 1] == 'F') {
      flt[strlen(flt) - 1] = '\0';
   }
   *number = _mesa_strtof(flt, (char **)NULL);
   free(flt);

   return 1;
}

static int
parse_number(slang_parse_ctx * C, int *number)
{
   const int radix = (int) (*C->I++);

   if (radix == 1) {
      float f = 0.0f;

      parse_general_number(C, &f);
      *number = (int)f;
   } else {
      *number = 0;
      while (*C->I != '\0') {
         int digit;
         if (*C->I >= '0' && *C->I <= '9')
            digit = (int) (*C->I - '0');
         else if (*C->I >= 'A' && *C->I <= 'Z')
            digit = (int) (*C->I - 'A') + 10;
         else
            digit = (int) (*C->I - 'a') + 10;
         *number = *number * radix + digit;
         C->I++;
      }
      C->I++;
   }
   if (*number > 65535)
      slang_info_log_warning(C->L, "%d: literal integer overflow.", *number);
   return 1;
}

static int
parse_float(slang_parse_ctx * C, float *number)
{
   if (*C->I == 1) {
      C->I++;
      parse_general_number(C, number);
   } else {
      char *integral = NULL;
      char *fractional = NULL;
      char *exponent = NULL;
      char *whole = NULL;

      parse_identifier_str(C, &integral);
      parse_identifier_str(C, &fractional);
      parse_identifier_str(C, &exponent);

      whole = (char *) _slang_alloc((strlen(integral) +
                                     strlen(fractional) +
                                     strlen(exponent) + 3) * sizeof(char));
      if (whole == NULL) {
         slang_info_log_memory(C->L);
         RETURN0;
      }

      slang_string_copy(whole, integral);
      slang_string_concat(whole, ".");
      slang_string_concat(whole, fractional);
      slang_string_concat(whole, "E");
      slang_string_concat(whole, exponent);

      *number = _mesa_strtof(whole, (char **) NULL);

      _slang_free(whole);
   }

   return 1;
}

/* revision number - increment after each change affecting emitted output */
#define REVISION 5

static int
check_revision(slang_parse_ctx * C)
{
   if (*C->I != REVISION) {
      slang_info_log_error(C->L, "Internal compiler error.");
      RETURN0;
   }
   C->I++;
   return 1;
}

static int parse_statement(slang_parse_ctx *, slang_output_ctx *,
                           slang_operation *);
static int parse_expression(slang_parse_ctx *, slang_output_ctx *,
                            slang_operation *);
static int parse_type_specifier(slang_parse_ctx *, slang_output_ctx *,
                                slang_type_specifier *);
static int
parse_type_array_size(slang_parse_ctx *C,
                      slang_output_ctx *O,
                      GLint *array_len);

static GLboolean
parse_array_len(slang_parse_ctx * C, slang_output_ctx * O, GLuint * len)
{
   slang_operation array_size;
   slang_name_space space;
   GLboolean result;

   if (!slang_operation_construct(&array_size))
      return GL_FALSE;
   if (!parse_expression(C, O, &array_size)) {
      slang_operation_destruct(&array_size);
      return GL_FALSE;
   }

   space.funcs = O->funs;
   space.structs = O->structs;
   space.vars = O->vars;

   /* evaluate compile-time expression which is array size */
   _slang_simplify(&array_size, &space, C->atoms);

   if (array_size.type == SLANG_OPER_LITERAL_INT) {
      result = GL_TRUE;
      *len = (GLint) array_size.literal[0];
   } else if (array_size.type == SLANG_OPER_IDENTIFIER) {
      slang_variable *var = _slang_variable_locate(array_size.locals, array_size.a_id, GL_TRUE);
      if (!var) {
         slang_info_log_error(C->L, "undefined variable '%s'",
                              (char *) array_size.a_id);
         result = GL_FALSE;
      } else if (var->type.qualifier == SLANG_QUAL_CONST &&
                 var->type.specifier.type == SLANG_SPEC_INT) {
         if (var->initializer &&
             var->initializer->type == SLANG_OPER_LITERAL_INT) {
            *len = (GLint) var->initializer->literal[0];
            result = GL_TRUE;
         } else {
            slang_info_log_error(C->L, "unable to parse array size declaration");
            result = GL_FALSE;
         }
      } else {
         slang_info_log_error(C->L, "unable to parse array size declaration");
         result = GL_FALSE;
      }
   } else {
      result = GL_FALSE;
   }

   slang_operation_destruct(&array_size);
   return result;
}

static GLboolean
calculate_var_size(slang_parse_ctx * C, slang_output_ctx * O,
                   slang_variable * var)
{
   slang_storage_aggregate agg;

   if (!slang_storage_aggregate_construct(&agg))
      return GL_FALSE;
   if (!_slang_aggregate_variable(&agg, &var->type.specifier, var->array_len,
                                  O->funs, O->structs, O->vars, C->atoms)) {
      slang_storage_aggregate_destruct(&agg);
      return GL_FALSE;
   }
   var->size = _slang_sizeof_aggregate(&agg);
   slang_storage_aggregate_destruct(&agg);
   return GL_TRUE;
}

static void
promote_type_to_array(slang_parse_ctx *C,
                      slang_fully_specified_type *type,
                      GLint array_len)
{
   slang_type_specifier *baseType =
      slang_type_specifier_new(type->specifier.type, NULL, NULL);

   type->specifier.type = SLANG_SPEC_ARRAY;
   type->specifier._array = baseType;
   type->array_len = array_len;
}


static GLboolean
convert_to_array(slang_parse_ctx * C, slang_variable * var,
                 const slang_type_specifier * sp)
{
   /* sized array - mark it as array, copy the specifier to the array element
    * and parse the expression */
   var->type.specifier.type = SLANG_SPEC_ARRAY;
   var->type.specifier._array = (slang_type_specifier *)
      _slang_alloc(sizeof(slang_type_specifier));
   if (var->type.specifier._array == NULL) {
      slang_info_log_memory(C->L);
      return GL_FALSE;
   }
   slang_type_specifier_ctr(var->type.specifier._array);
   return slang_type_specifier_copy(var->type.specifier._array, sp);
}

/* structure field */
#define FIELD_NONE 0
#define FIELD_NEXT 1
#define FIELD_ARRAY 2

static GLboolean
parse_struct_field_var(slang_parse_ctx * C, slang_output_ctx * O,
                       slang_variable * var, slang_atom a_name,
                       const slang_type_specifier * sp,
                       GLuint array_len)
{
   var->a_name = a_name;
   if (var->a_name == SLANG_ATOM_NULL)
      return GL_FALSE;

   switch (*C->I++) {
   case FIELD_NONE:
      if (array_len != -1) {
         if (!convert_to_array(C, var, sp))
            return GL_FALSE;
         var->array_len = array_len;
      }
      else {
         if (!slang_type_specifier_copy(&var->type.specifier, sp))
            return GL_FALSE;
      }
      break;
   case FIELD_ARRAY:
      if (array_len != -1)
         return GL_FALSE;
      if (!convert_to_array(C, var, sp))
         return GL_FALSE;
      if (!parse_array_len(C, O, &var->array_len))
         return GL_FALSE;
      break;
   default:
      return GL_FALSE;
   }

   return calculate_var_size(C, O, var);
}

static int
parse_struct_field(slang_parse_ctx * C, slang_output_ctx * O,
                   slang_struct * st, slang_type_specifier * sp)
{
   slang_output_ctx o = *O;
   GLint array_len;

   o.structs = st->structs;
   if (!parse_type_specifier(C, &o, sp))
      RETURN0;
   if (!parse_type_array_size(C, &o, &array_len))
      RETURN0;

   do {
      slang_atom a_name;
      slang_variable *var = slang_variable_scope_grow(st->fields);
      if (!var) {
         slang_info_log_memory(C->L);
         RETURN0;
      }
      a_name = parse_identifier(C);
      if (_slang_variable_locate(st->fields, a_name, GL_FALSE)) {
         slang_info_log_error(C->L, "duplicate field '%s'", (char *) a_name);
         RETURN0;
      }

      if (!parse_struct_field_var(C, &o, var, a_name, sp, array_len))
         RETURN0;
   }
   while (*C->I++ != FIELD_NONE);

   return 1;
}

static int
parse_struct(slang_parse_ctx * C, slang_output_ctx * O, slang_struct ** st)
{
   slang_atom a_name;
   const char *name;

   /* parse struct name (if any) and make sure it is unique in current scope */
   a_name = parse_identifier(C);
   if (a_name == SLANG_ATOM_NULL)
      RETURN0;

   name = slang_atom_pool_id(C->atoms, a_name);
   if (name[0] != '\0'
       && slang_struct_scope_find(O->structs, a_name, 0) != NULL) {
      slang_info_log_error(C->L, "%s: duplicate type name.", name);
      RETURN0;
   }

   /* set-up a new struct */
   *st = (slang_struct *) _slang_alloc(sizeof(slang_struct));
   if (*st == NULL) {
      slang_info_log_memory(C->L);
      RETURN0;
   }
   if (!slang_struct_construct(*st)) {
      _slang_free(*st);
      *st = NULL;
      slang_info_log_memory(C->L);
      RETURN0;
   }
   (**st).a_name = a_name;
   (**st).structs->outer_scope = O->structs;

   /* parse individual struct fields */
   do {
      slang_type_specifier sp;

      slang_type_specifier_ctr(&sp);
      if (!parse_struct_field(C, O, *st, &sp)) {
         slang_type_specifier_dtr(&sp);
         RETURN0;
      }
      slang_type_specifier_dtr(&sp);
   }
   while (*C->I++ != FIELD_NONE);

   /* if named struct, copy it to current scope */
   if (name[0] != '\0') {
      slang_struct *s;

      O->structs->structs =
         (slang_struct *) _slang_realloc(O->structs->structs,
                                         O->structs->num_structs
                                         * sizeof(slang_struct),
                                         (O->structs->num_structs + 1)
                                         * sizeof(slang_struct));
      if (O->structs->structs == NULL) {
         slang_info_log_memory(C->L);
         RETURN0;
      }
      s = &O->structs->structs[O->structs->num_structs];
      if (!slang_struct_construct(s))
         RETURN0;
      O->structs->num_structs++;
      if (!slang_struct_copy(s, *st))
         RETURN0;
   }

   return 1;
}


/* invariant qualifer */
#define TYPE_VARIANT    90
#define TYPE_INVARIANT  91

static int
parse_type_variant(slang_parse_ctx * C, slang_type_variant *variant)
{
   GLuint invariant = *C->I++;
   switch (invariant) {
   case TYPE_VARIANT:
      *variant = SLANG_VARIANT;
      return 1;
   case TYPE_INVARIANT:
      *variant = SLANG_INVARIANT;
      return 1;
   default:
      RETURN0;
   }
}


/* centroid qualifer */
#define TYPE_CENTER    95
#define TYPE_CENTROID  96

static int
parse_type_centroid(slang_parse_ctx * C, slang_type_centroid *centroid)
{
   GLuint c = *C->I++;
   switch (c) {
   case TYPE_CENTER:
      *centroid = SLANG_CENTER;
      return 1;
   case TYPE_CENTROID:
      *centroid = SLANG_CENTROID;
      return 1;
   default:
      RETURN0;
   }
}


/* Layout qualifiers */
#define LAYOUT_QUALIFIER_NONE                      0
#define LAYOUT_QUALIFIER_UPPER_LEFT                1
#define LAYOUT_QUALIFIER_PIXEL_CENTER_INTEGER      2

static int
parse_layout_qualifiers(slang_parse_ctx * C, slang_layout_qualifier *layout)
{
   *layout = 0x0;

   /* the layout qualifiers come as a list of LAYOUT_QUALIFER_x tokens,
    * terminated by LAYOUT_QUALIFIER_NONE.
    */
   while (1) {
      GLuint c = *C->I++;
      switch (c) {
      case LAYOUT_QUALIFIER_NONE:
         /* end of list of qualifiers */
         return 1;
      case LAYOUT_QUALIFIER_UPPER_LEFT:
         *layout |= SLANG_LAYOUT_UPPER_LEFT_BIT;
         break;
      case LAYOUT_QUALIFIER_PIXEL_CENTER_INTEGER:
         *layout |= SLANG_LAYOUT_PIXEL_CENTER_INTEGER_BIT;
         break;
      default:
         assert(0 && "Bad layout qualifier");
      }
   }
}


/* type qualifier */
#define TYPE_QUALIFIER_NONE 0
#define TYPE_QUALIFIER_CONST 1
#define TYPE_QUALIFIER_ATTRIBUTE 2
#define TYPE_QUALIFIER_VARYING 3
#define TYPE_QUALIFIER_UNIFORM 4
#define TYPE_QUALIFIER_FIXEDOUTPUT 5
#define TYPE_QUALIFIER_FIXEDINPUT 6

static int
parse_type_qualifier(slang_parse_ctx * C, slang_type_qualifier * qual)
{
   GLuint qualifier = *C->I++;
   switch (qualifier) {
   case TYPE_QUALIFIER_NONE:
      *qual = SLANG_QUAL_NONE;
      break;
   case TYPE_QUALIFIER_CONST:
      *qual = SLANG_QUAL_CONST;
      break;
   case TYPE_QUALIFIER_ATTRIBUTE:
      *qual = SLANG_QUAL_ATTRIBUTE;
      break;
   case TYPE_QUALIFIER_VARYING:
      *qual = SLANG_QUAL_VARYING;
      break;
   case TYPE_QUALIFIER_UNIFORM:
      *qual = SLANG_QUAL_UNIFORM;
      break;
   case TYPE_QUALIFIER_FIXEDOUTPUT:
      *qual = SLANG_QUAL_FIXEDOUTPUT;
      break;
   case TYPE_QUALIFIER_FIXEDINPUT:
      *qual = SLANG_QUAL_FIXEDINPUT;
      break;
   default:
      RETURN0;
   }
   return 1;
}

/* type specifier */
#define TYPE_SPECIFIER_VOID 0
#define TYPE_SPECIFIER_BOOL 1
#define TYPE_SPECIFIER_BVEC2 2
#define TYPE_SPECIFIER_BVEC3 3
#define TYPE_SPECIFIER_BVEC4 4
#define TYPE_SPECIFIER_INT 5
#define TYPE_SPECIFIER_IVEC2 6
#define TYPE_SPECIFIER_IVEC3 7
#define TYPE_SPECIFIER_IVEC4 8
#define TYPE_SPECIFIER_FLOAT 9
#define TYPE_SPECIFIER_VEC2 10
#define TYPE_SPECIFIER_VEC3 11
#define TYPE_SPECIFIER_VEC4 12
#define TYPE_SPECIFIER_MAT2 13
#define TYPE_SPECIFIER_MAT3 14
#define TYPE_SPECIFIER_MAT4 15
#define TYPE_SPECIFIER_SAMPLER1D 16
#define TYPE_SPECIFIER_SAMPLER2D 17
#define TYPE_SPECIFIER_SAMPLER3D 18
#define TYPE_SPECIFIER_SAMPLERCUBE 19
#define TYPE_SPECIFIER_SAMPLER1DSHADOW 20
#define TYPE_SPECIFIER_SAMPLER2DSHADOW 21
#define TYPE_SPECIFIER_SAMPLER2DRECT 22
#define TYPE_SPECIFIER_SAMPLER2DRECTSHADOW 23
#define TYPE_SPECIFIER_STRUCT 24
#define TYPE_SPECIFIER_TYPENAME 25
#define TYPE_SPECIFIER_MAT23 26
#define TYPE_SPECIFIER_MAT32 27
#define TYPE_SPECIFIER_MAT24 28
#define TYPE_SPECIFIER_MAT42 29
#define TYPE_SPECIFIER_MAT34 30
#define TYPE_SPECIFIER_MAT43 31
#define TYPE_SPECIFIER_SAMPLER_1D_ARRAY 32
#define TYPE_SPECIFIER_SAMPLER_2D_ARRAY 33
#define TYPE_SPECIFIER_SAMPLER_1D_ARRAY_SHADOW 34
#define TYPE_SPECIFIER_SAMPLER_2D_ARRAY_SHADOW 35
#define TYPE_SPECIFIER_COUNT 36

static int
parse_type_specifier(slang_parse_ctx * C, slang_output_ctx * O,
                     slang_type_specifier * spec)
{
   int type = *C->I++;
   switch (type) {
   case TYPE_SPECIFIER_VOID:
      spec->type = SLANG_SPEC_VOID;
      break;
   case TYPE_SPECIFIER_BOOL:
      spec->type = SLANG_SPEC_BOOL;
      break;
   case TYPE_SPECIFIER_BVEC2:
      spec->type = SLANG_SPEC_BVEC2;
      break;
   case TYPE_SPECIFIER_BVEC3:
      spec->type = SLANG_SPEC_BVEC3;
      break;
   case TYPE_SPECIFIER_BVEC4:
      spec->type = SLANG_SPEC_BVEC4;
      break;
   case TYPE_SPECIFIER_INT:
      spec->type = SLANG_SPEC_INT;
      break;
   case TYPE_SPECIFIER_IVEC2:
      spec->type = SLANG_SPEC_IVEC2;
      break;
   case TYPE_SPECIFIER_IVEC3:
      spec->type = SLANG_SPEC_IVEC3;
      break;
   case TYPE_SPECIFIER_IVEC4:
      spec->type = SLANG_SPEC_IVEC4;
      break;
   case TYPE_SPECIFIER_FLOAT:
      spec->type = SLANG_SPEC_FLOAT;
      break;
   case TYPE_SPECIFIER_VEC2:
      spec->type = SLANG_SPEC_VEC2;
      break;
   case TYPE_SPECIFIER_VEC3:
      spec->type = SLANG_SPEC_VEC3;
      break;
   case TYPE_SPECIFIER_VEC4:
      spec->type = SLANG_SPEC_VEC4;
      break;
   case TYPE_SPECIFIER_MAT2:
      spec->type = SLANG_SPEC_MAT2;
      break;
   case TYPE_SPECIFIER_MAT3:
      spec->type = SLANG_SPEC_MAT3;
      break;
   case TYPE_SPECIFIER_MAT4:
      spec->type = SLANG_SPEC_MAT4;
      break;
   case TYPE_SPECIFIER_MAT23:
      spec->type = SLANG_SPEC_MAT23;
      break;
   case TYPE_SPECIFIER_MAT32:
      spec->type = SLANG_SPEC_MAT32;
      break;
   case TYPE_SPECIFIER_MAT24:
      spec->type = SLANG_SPEC_MAT24;
      break;
   case TYPE_SPECIFIER_MAT42:
      spec->type = SLANG_SPEC_MAT42;
      break;
   case TYPE_SPECIFIER_MAT34:
      spec->type = SLANG_SPEC_MAT34;
      break;
   case TYPE_SPECIFIER_MAT43:
      spec->type = SLANG_SPEC_MAT43;
      break;
   case TYPE_SPECIFIER_SAMPLER1D:
      spec->type = SLANG_SPEC_SAMPLER_1D;
      break;
   case TYPE_SPECIFIER_SAMPLER2D:
      spec->type = SLANG_SPEC_SAMPLER_2D;
      break;
   case TYPE_SPECIFIER_SAMPLER3D:
      spec->type = SLANG_SPEC_SAMPLER_3D;
      break;
   case TYPE_SPECIFIER_SAMPLERCUBE:
      spec->type = SLANG_SPEC_SAMPLER_CUBE;
      break;
   case TYPE_SPECIFIER_SAMPLER2DRECT:
      spec->type = SLANG_SPEC_SAMPLER_RECT;
      break;
   case TYPE_SPECIFIER_SAMPLER1DSHADOW:
      spec->type = SLANG_SPEC_SAMPLER_1D_SHADOW;
      break;
   case TYPE_SPECIFIER_SAMPLER2DSHADOW:
      spec->type = SLANG_SPEC_SAMPLER_2D_SHADOW;
      break;
   case TYPE_SPECIFIER_SAMPLER2DRECTSHADOW:
      spec->type = SLANG_SPEC_SAMPLER_RECT_SHADOW;
      break;
   case TYPE_SPECIFIER_SAMPLER_1D_ARRAY:
      spec->type = SLANG_SPEC_SAMPLER_1D_ARRAY;
      break;
   case TYPE_SPECIFIER_SAMPLER_2D_ARRAY:
      spec->type = SLANG_SPEC_SAMPLER_2D_ARRAY;
      break;
   case TYPE_SPECIFIER_SAMPLER_1D_ARRAY_SHADOW:
      spec->type = SLANG_SPEC_SAMPLER_1D_ARRAY_SHADOW;
      break;
   case TYPE_SPECIFIER_SAMPLER_2D_ARRAY_SHADOW:
      spec->type = SLANG_SPEC_SAMPLER_2D_ARRAY_SHADOW;
      break;
   case TYPE_SPECIFIER_STRUCT:
      spec->type = SLANG_SPEC_STRUCT;
      if (!parse_struct(C, O, &spec->_struct))
         RETURN0;
      break;
   case TYPE_SPECIFIER_TYPENAME:
      spec->type = SLANG_SPEC_STRUCT;
      {
         slang_atom a_name;
         slang_struct *stru;

         a_name = parse_identifier(C);
         if (a_name == NULL)
            RETURN0;

         stru = slang_struct_scope_find(O->structs, a_name, 1);
         if (stru == NULL) {
            slang_info_log_error(C->L, "undeclared type name '%s'",
                                 slang_atom_pool_id(C->atoms, a_name));
            RETURN0;
         }

         spec->_struct = (slang_struct *) _slang_alloc(sizeof(slang_struct));
         if (spec->_struct == NULL) {
            slang_info_log_memory(C->L);
            RETURN0;
         }
         if (!slang_struct_construct(spec->_struct)) {
            _slang_free(spec->_struct);
            spec->_struct = NULL;
            RETURN0;
         }
         if (!slang_struct_copy(spec->_struct, stru))
            RETURN0;
      }
      break;
   default:
      RETURN0;
   }
   return 1;
}

#define TYPE_SPECIFIER_NONARRAY 0
#define TYPE_SPECIFIER_ARRAY    1

static int
parse_type_array_size(slang_parse_ctx *C,
                      slang_output_ctx *O,
                      GLint *array_len)
{
   GLuint size;

   switch (*C->I++) {
   case TYPE_SPECIFIER_NONARRAY:
      *array_len = -1; /* -1 = not an array */
      break;
   case TYPE_SPECIFIER_ARRAY:
      if (!parse_array_len(C, O, &size))
         RETURN0;
      *array_len = (GLint) size;
      break;
   default:
      assert(0);
      RETURN0;
   }
   return 1;
}

#define PRECISION_DEFAULT 0
#define PRECISION_LOW     1
#define PRECISION_MEDIUM  2
#define PRECISION_HIGH    3

static int
parse_type_precision(slang_parse_ctx *C,
                     slang_type_precision *precision)
{
   GLint prec = *C->I++;
   switch (prec) {
   case PRECISION_DEFAULT:
      *precision = SLANG_PREC_DEFAULT;
      return 1;
   case PRECISION_LOW:
      *precision = SLANG_PREC_LOW;
      return 1;
   case PRECISION_MEDIUM:
      *precision = SLANG_PREC_MEDIUM;
      return 1;
   case PRECISION_HIGH:
      *precision = SLANG_PREC_HIGH;
      return 1;
   default:
      RETURN0;
   }
}

static int
parse_fully_specified_type(slang_parse_ctx * C, slang_output_ctx * O,
                           slang_fully_specified_type * type)
{
   if (!parse_layout_qualifiers(C, &type->layout))
      RETURN0;

   if (!parse_type_variant(C, &type->variant))
      RETURN0;

   if (!parse_type_centroid(C, &type->centroid))
      RETURN0;

   if (!parse_type_qualifier(C, &type->qualifier))
      RETURN0;

   if (!parse_type_precision(C, &type->precision))
      RETURN0;

   if (!parse_type_specifier(C, O, &type->specifier))
      RETURN0;

   if (!parse_type_array_size(C, O, &type->array_len))
      RETURN0;

   if (!O->allow_invariant && type->variant == SLANG_INVARIANT) {
      slang_info_log_error(C->L,
         "'invariant' keyword not allowed (perhaps set #version 120)");
      RETURN0;
   }

   if (!O->allow_centroid && type->centroid == SLANG_CENTROID) {
      slang_info_log_error(C->L,
         "'centroid' keyword not allowed (perhaps set #version 120)");
      RETURN0;
   }
   else if (type->centroid == SLANG_CENTROID &&
            type->qualifier != SLANG_QUAL_VARYING) {
      slang_info_log_error(C->L,
         "'centroid' keyword only allowed for varying vars");
      RETURN0;
   }


   /* need this?
   if (type->qualifier != SLANG_QUAL_VARYING &&
       type->variant == SLANG_INVARIANT) {
      slang_info_log_error(C->L,
                           "invariant qualifer only allowed for varying vars");
      RETURN0;
   }
   */

   if (O->allow_precision) {
      if (type->precision == SLANG_PREC_DEFAULT) {
         assert(type->specifier.type < TYPE_SPECIFIER_COUNT);
         /* use the default precision for this datatype */
         type->precision = O->default_precision[type->specifier.type];
      }
   }
   else {
      /* only default is allowed */
      if (type->precision != SLANG_PREC_DEFAULT) {
         slang_info_log_error(C->L, "precision qualifiers not allowed");
         RETURN0;
      }
   }

   if (!O->allow_array_types && type->array_len >= 0) {
      slang_info_log_error(C->L, "first-class array types not allowed");
      RETURN0;
   }

   if (type->array_len >= 0) {
      /* convert type to array type (ex: convert "int" to "array of int" */
      promote_type_to_array(C, type, type->array_len);
   }

   return 1;
}

/* operation */
#define OP_END 0
#define OP_BLOCK_BEGIN_NO_NEW_SCOPE 1
#define OP_BLOCK_BEGIN_NEW_SCOPE 2
#define OP_DECLARE 3
#define OP_ASM 4
#define OP_BREAK 5
#define OP_CONTINUE 6
#define OP_DISCARD 7
#define OP_RETURN 8
#define OP_EXPRESSION 9
#define OP_IF 10
#define OP_WHILE 11
#define OP_DO 12
#define OP_FOR 13
#define OP_PUSH_VOID 14
#define OP_PUSH_BOOL 15
#define OP_PUSH_INT 16
#define OP_PUSH_FLOAT 17
#define OP_PUSH_IDENTIFIER 18
#define OP_SEQUENCE 19
#define OP_ASSIGN 20
#define OP_ADDASSIGN 21
#define OP_SUBASSIGN 22
#define OP_MULASSIGN 23
#define OP_DIVASSIGN 24
/*#define OP_MODASSIGN 25*/
/*#define OP_LSHASSIGN 26*/
/*#define OP_RSHASSIGN 27*/
/*#define OP_ORASSIGN 28*/
/*#define OP_XORASSIGN 29*/
/*#define OP_ANDASSIGN 30*/
#define OP_SELECT 31
#define OP_LOGICALOR 32
#define OP_LOGICALXOR 33
#define OP_LOGICALAND 34
/*#define OP_BITOR 35*/
/*#define OP_BITXOR 36*/
/*#define OP_BITAND 37*/
#define OP_EQUAL 38
#define OP_NOTEQUAL 39
#define OP_LESS 40
#define OP_GREATER 41
#define OP_LESSEQUAL 42
#define OP_GREATEREQUAL 43
/*#define OP_LSHIFT 44*/
/*#define OP_RSHIFT 45*/
#define OP_ADD 46
#define OP_SUBTRACT 47
#define OP_MULTIPLY 48
#define OP_DIVIDE 49
/*#define OP_MODULUS 50*/
#define OP_PREINCREMENT 51
#define OP_PREDECREMENT 52
#define OP_PLUS 53
#define OP_MINUS 54
/*#define OP_COMPLEMENT 55*/
#define OP_NOT 56
#define OP_SUBSCRIPT 57
#define OP_CALL 58
#define OP_FIELD 59
#define OP_POSTINCREMENT 60
#define OP_POSTDECREMENT 61
#define OP_PRECISION 62
#define OP_METHOD 63


/**
 * When parsing a compound production, this function is used to parse the
 * children.
 * For example, a while-loop compound will have two children, the
 * while condition expression and the loop body.  So, this function will
 * be called twice to parse those two sub-expressions.
 * \param C  the parsing context
 * \param O  the output context
 * \param oper  the operation we're parsing
 * \param statement  indicates whether parsing a statement, or expression
 * \return 1 if success, 0 if error
 */
static int
parse_child_operation(slang_parse_ctx * C, slang_output_ctx * O,
                      slang_operation * oper, GLboolean statement)
{
   slang_operation *ch;

   /* grow child array */
   ch = slang_operation_grow(&oper->num_children, &oper->children);
   if (statement)
      return parse_statement(C, O, ch);
   return parse_expression(C, O, ch);
}

static int parse_declaration(slang_parse_ctx * C, slang_output_ctx * O);

static int
parse_statement(slang_parse_ctx * C, slang_output_ctx * O,
                slang_operation * oper)
{
   int op;

   oper->locals->outer_scope = O->vars;

   op = *C->I++;
   switch (op) {
   case OP_BLOCK_BEGIN_NO_NEW_SCOPE:
      /* parse child statements, do not create new variable scope */
      oper->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE;
      while (*C->I != OP_END)
         if (!parse_child_operation(C, O, oper, GL_TRUE))
            RETURN0;
      C->I++;
      break;
   case OP_BLOCK_BEGIN_NEW_SCOPE:
      /* parse child statements, create new variable scope */
      {
         slang_output_ctx o = *O;

         oper->type = SLANG_OPER_BLOCK_NEW_SCOPE;
         o.vars = oper->locals;
         while (*C->I != OP_END)
            if (!parse_child_operation(C, &o, oper, GL_TRUE))
               RETURN0;
         C->I++;
      }
      break;
   case OP_DECLARE:
      /* local variable declaration, individual declarators are stored as
       * children identifiers
       */
      oper->type = SLANG_OPER_BLOCK_NO_NEW_SCOPE;
      {
         const unsigned int first_var = O->vars->num_variables;

         /* parse the declaration, note that there can be zero or more
          * than one declarators
          */
         if (!parse_declaration(C, O))
            RETURN0;
         if (first_var < O->vars->num_variables) {
            const unsigned int num_vars = O->vars->num_variables - first_var;
            unsigned int i;
            assert(oper->num_children == 0);
            oper->num_children = num_vars;
            oper->children = slang_operation_new(num_vars);
            if (oper->children == NULL) {
               slang_info_log_memory(C->L);
               RETURN0;
            }
            for (i = first_var; i < O->vars->num_variables; i++) {
               slang_operation *o = &oper->children[i - first_var];
               slang_variable *var = O->vars->variables[i];
               o->type = SLANG_OPER_VARIABLE_DECL;
               o->locals->outer_scope = O->vars;
               o->a_id = var->a_name;

               /* new/someday...
               calculate_var_size(C, O, var);
               */

               if (!legal_identifier(o->a_id)) {
                  slang_info_log_error(C->L, "illegal variable name '%s'",
                                       (char *) o->a_id);
                  RETURN0;
               }
            }
         }
      }
      break;
   case OP_ASM:
      /* the __asm statement, parse the mnemonic and all its arguments
       * as expressions
       */
      oper->type = SLANG_OPER_ASM;
      oper->a_id = parse_identifier(C);
      if (oper->a_id == SLANG_ATOM_NULL)
         RETURN0;
      while (*C->I != OP_END) {
         if (!parse_child_operation(C, O, oper, GL_FALSE))
            RETURN0;
      }
      C->I++;
      break;
   case OP_BREAK:
      oper->type = SLANG_OPER_BREAK;
      break;
   case OP_CONTINUE:
      oper->type = SLANG_OPER_CONTINUE;
      break;
   case OP_DISCARD:
      oper->type = SLANG_OPER_DISCARD;
      break;
   case OP_RETURN:
      oper->type = SLANG_OPER_RETURN;
      if (!parse_child_operation(C, O, oper, GL_FALSE))
         RETURN0;
      break;
   case OP_EXPRESSION:
      oper->type = SLANG_OPER_EXPRESSION;
      if (!parse_child_operation(C, O, oper, GL_FALSE))
         RETURN0;
      break;
   case OP_IF:
      oper->type = SLANG_OPER_IF;
      if (!parse_child_operation(C, O, oper, GL_FALSE))
         RETURN0;
      if (!parse_child_operation(C, O, oper, GL_TRUE))
         RETURN0;
      if (!parse_child_operation(C, O, oper, GL_TRUE))
         RETURN0;
      break;
   case OP_WHILE:
      {
         slang_output_ctx o = *O;

         oper->type = SLANG_OPER_WHILE;
         o.vars = oper->locals;
         if (!parse_child_operation(C, &o, oper, GL_TRUE))
            RETURN0;
         if (!parse_child_operation(C, &o, oper, GL_TRUE))
            RETURN0;
      }
      break;
   case OP_DO:
      oper->type = SLANG_OPER_DO;
      if (!parse_child_operation(C, O, oper, GL_TRUE))
         RETURN0;
      if (!parse_child_operation(C, O, oper, GL_FALSE))
         RETURN0;
      break;
   case OP_FOR:
      {
         slang_output_ctx o = *O;

         oper->type = SLANG_OPER_FOR;
         o.vars = oper->locals;
         if (!parse_child_operation(C, &o, oper, GL_TRUE))
            RETURN0;
         if (!parse_child_operation(C, &o, oper, GL_TRUE))
            RETURN0;
         if (!parse_child_operation(C, &o, oper, GL_FALSE))
            RETURN0;
         if (!parse_child_operation(C, &o, oper, GL_TRUE))
            RETURN0;
      }
      break;
   case OP_PRECISION:
      {
         /* set default precision for a type in this scope */
         /* ignored at this time */
         int prec_qual = *C->I++;
         int datatype = *C->I++;
         (void) prec_qual;
         (void) datatype;
      }
      break;
   default:
      /*printf("Unexpected operation %d\n", op);*/
      RETURN0;
   }
   return 1;
}

static int
handle_nary_expression(slang_parse_ctx * C, slang_operation * op,
                       slang_operation ** ops, unsigned int *total_ops,
                       unsigned int n)
{
   unsigned int i;

   op->children = slang_operation_new(n);
   if (op->children == NULL) {
      slang_info_log_memory(C->L);
      RETURN0;
   }
   op->num_children = n;

   for (i = 0; i < n; i++) {
      slang_operation_destruct(&op->children[i]);
      op->children[i] = (*ops)[*total_ops - (n + 1 - i)];
   }

   (*ops)[*total_ops - (n + 1)] = (*ops)[*total_ops - 1];
   *total_ops -= n;

   *ops = (slang_operation *)
      _slang_realloc(*ops,
                     (*total_ops + n) * sizeof(slang_operation),
                     *total_ops * sizeof(slang_operation));
   if (*ops == NULL) {
      slang_info_log_memory(C->L);
      RETURN0;
   }
   return 1;
}

static int
is_constructor_name(const char *name, slang_atom a_name,
                    slang_struct_scope * structs)
{
   if (slang_type_specifier_type_from_string(name) != SLANG_SPEC_VOID)
      return 1;
   return slang_struct_scope_find(structs, a_name, 1) != NULL;
}

#define FUNCTION_CALL_NONARRAY 0
#define FUNCTION_CALL_ARRAY    1

static int
parse_expression(slang_parse_ctx * C, slang_output_ctx * O,
                 slang_operation * oper)
{
   slang_operation *ops = NULL;
   unsigned int num_ops = 0;
   int number;

   while (*C->I != OP_END) {
      slang_operation *op;
      const unsigned int op_code = *C->I++;

      /* allocate default operation, becomes a no-op if not used  */
      ops = (slang_operation *)
         _slang_realloc(ops,
                        num_ops * sizeof(slang_operation),
                        (num_ops + 1) * sizeof(slang_operation));
      if (ops == NULL) {
         slang_info_log_memory(C->L);
         RETURN0;
      }
      op = &ops[num_ops];
      if (!slang_operation_construct(op)) {
         slang_info_log_memory(C->L);
         RETURN0;
      }
      num_ops++;
      op->locals->outer_scope = O->vars;

      switch (op_code) {
      case OP_PUSH_VOID:
         op->type = SLANG_OPER_VOID;
         break;
      case OP_PUSH_BOOL:
         op->type = SLANG_OPER_LITERAL_BOOL;
         if (!parse_number(C, &number))
            RETURN0;
         op->literal[0] =
         op->literal[1] =
         op->literal[2] =
         op->literal[3] = (GLfloat) number;
         op->literal_size = 1;
         break;
      case OP_PUSH_INT:
         op->type = SLANG_OPER_LITERAL_INT;
         if (!parse_number(C, &number))
            RETURN0;
         op->literal[0] =
         op->literal[1] =
         op->literal[2] =
         op->literal[3] = (GLfloat) number;
         op->literal_size = 1;
         break;
      case OP_PUSH_FLOAT:
         op->type = SLANG_OPER_LITERAL_FLOAT;
         if (!parse_float(C, &op->literal[0]))
            RETURN0;
         op->literal[1] =
         op->literal[2] =
         op->literal[3] = op->literal[0];
         op->literal_size = 1;
         break;
      case OP_PUSH_IDENTIFIER:
         op->type = SLANG_OPER_IDENTIFIER;
         op->a_id = parse_identifier(C);
         if (op->a_id == SLANG_ATOM_NULL)
            RETURN0;
         break;
      case OP_SEQUENCE:
         op->type = SLANG_OPER_SEQUENCE;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_ASSIGN:
         op->type = SLANG_OPER_ASSIGN;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_ADDASSIGN:
         op->type = SLANG_OPER_ADDASSIGN;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_SUBASSIGN:
         op->type = SLANG_OPER_SUBASSIGN;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_MULASSIGN:
         op->type = SLANG_OPER_MULASSIGN;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_DIVASSIGN:
         op->type = SLANG_OPER_DIVASSIGN;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
         /*case OP_MODASSIGN: */
         /*case OP_LSHASSIGN: */
         /*case OP_RSHASSIGN: */
         /*case OP_ORASSIGN: */
         /*case OP_XORASSIGN: */
         /*case OP_ANDASSIGN: */
      case OP_SELECT:
         op->type = SLANG_OPER_SELECT;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 3))
            RETURN0;
         break;
      case OP_LOGICALOR:
         op->type = SLANG_OPER_LOGICALOR;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_LOGICALXOR:
         op->type = SLANG_OPER_LOGICALXOR;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_LOGICALAND:
         op->type = SLANG_OPER_LOGICALAND;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
         /*case OP_BITOR: */
         /*case OP_BITXOR: */
         /*case OP_BITAND: */
      case OP_EQUAL:
         op->type = SLANG_OPER_EQUAL;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_NOTEQUAL:
         op->type = SLANG_OPER_NOTEQUAL;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_LESS:
         op->type = SLANG_OPER_LESS;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_GREATER:
         op->type = SLANG_OPER_GREATER;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_LESSEQUAL:
         op->type = SLANG_OPER_LESSEQUAL;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_GREATEREQUAL:
         op->type = SLANG_OPER_GREATEREQUAL;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
         /*case OP_LSHIFT: */
         /*case OP_RSHIFT: */
      case OP_ADD:
         op->type = SLANG_OPER_ADD;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_SUBTRACT:
         op->type = SLANG_OPER_SUBTRACT;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_MULTIPLY:
         op->type = SLANG_OPER_MULTIPLY;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_DIVIDE:
         op->type = SLANG_OPER_DIVIDE;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
         /*case OP_MODULUS: */
      case OP_PREINCREMENT:
         op->type = SLANG_OPER_PREINCREMENT;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 1))
            RETURN0;
         break;
      case OP_PREDECREMENT:
         op->type = SLANG_OPER_PREDECREMENT;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 1))
            RETURN0;
         break;
      case OP_PLUS:
         op->type = SLANG_OPER_PLUS;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 1))
            RETURN0;
         break;
      case OP_MINUS:
         op->type = SLANG_OPER_MINUS;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 1))
            RETURN0;
         break;
      case OP_NOT:
         op->type = SLANG_OPER_NOT;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 1))
            RETURN0;
         break;
         /*case OP_COMPLEMENT: */
      case OP_SUBSCRIPT:
         op->type = SLANG_OPER_SUBSCRIPT;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 2))
            RETURN0;
         break;
      case OP_METHOD:
         op->type = SLANG_OPER_METHOD;
         op->a_obj = parse_identifier(C);
         if (op->a_obj == SLANG_ATOM_NULL)
            RETURN0;

         op->a_id = parse_identifier(C);
         if (op->a_id == SLANG_ATOM_NULL)
            RETURN0;

         assert(*C->I == OP_END);
         C->I++;

         while (*C->I != OP_END)
            if (!parse_child_operation(C, O, op, GL_FALSE))
               RETURN0;
         C->I++;
#if 0
         /* don't lookup the method (not yet anyway) */
         if (!C->parsing_builtin
             && !slang_function_scope_find_by_name(O->funs, op->a_id, 1)) {
            const char *id;

            id = slang_atom_pool_id(C->atoms, op->a_id);
            if (!is_constructor_name(id, op->a_id, O->structs)) {
               slang_info_log_error(C->L, "%s: undeclared function name.", id);
               RETURN0;
            }
         }
#endif
         break;
      case OP_CALL:
         {
            GLboolean array_constructor = GL_FALSE;
            GLint array_constructor_size = 0;

            op->type = SLANG_OPER_CALL;
            op->a_id = parse_identifier(C);
            if (op->a_id == SLANG_ATOM_NULL)
               RETURN0;
            switch (*C->I++) {
            case FUNCTION_CALL_NONARRAY:
               /* Nothing to do. */
               break;
            case FUNCTION_CALL_ARRAY:
               /* Calling an array constructor. For example:
                *   float[3](1.1, 2.2, 3.3);
                */
               if (!O->allow_array_types) {
                  slang_info_log_error(C->L,
                                       "array constructors not allowed "
                                       "in this GLSL version");
                  RETURN0;
               }
               else {
                  /* parse the array constructor size */
                  slang_operation array_size;
                  array_constructor = GL_TRUE;
                  slang_operation_construct(&array_size);
                  if (!parse_expression(C, O, &array_size)) {
                     slang_operation_destruct(&array_size);
                     return GL_FALSE;
                  }
                  if (array_size.type != SLANG_OPER_LITERAL_INT) {
                     slang_info_log_error(C->L,
                        "constructor array size is not an integer");
                     slang_operation_destruct(&array_size);
                     RETURN0;
                  }
                  array_constructor_size = (int) array_size.literal[0];
                  op->array_constructor = GL_TRUE;
                  slang_operation_destruct(&array_size);
               }
               break;
            default:
               assert(0);
               RETURN0;
            }
            while (*C->I != OP_END)
               if (!parse_child_operation(C, O, op, GL_FALSE))
                  RETURN0;
            C->I++;

            if (array_constructor &&
                array_constructor_size != op->num_children) {
               slang_info_log_error(C->L, "number of parameters to array"
                                    " constructor does not match array size");
               RETURN0;
            }

            if (!C->parsing_builtin
                && !slang_function_scope_find_by_name(O->funs, op->a_id, 1)) {
               const char *id;

               id = slang_atom_pool_id(C->atoms, op->a_id);
               if (!is_constructor_name(id, op->a_id, O->structs)) {
                  slang_info_log_error(C->L, "%s: undeclared function name.", id);
                  RETURN0;
               }
            }
         }
         break;
      case OP_FIELD:
         op->type = SLANG_OPER_FIELD;
         op->a_id = parse_identifier(C);
         if (op->a_id == SLANG_ATOM_NULL)
            RETURN0;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 1))
            RETURN0;
         break;
      case OP_POSTINCREMENT:
         op->type = SLANG_OPER_POSTINCREMENT;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 1))
            RETURN0;
         break;
      case OP_POSTDECREMENT:
         op->type = SLANG_OPER_POSTDECREMENT;
         if (!handle_nary_expression(C, op, &ops, &num_ops, 1))
            RETURN0;
         break;
      default:
         RETURN0;
      }
   }
   C->I++;

   slang_operation_destruct(oper);
   *oper = *ops; /* struct copy */
   _slang_free(ops);

   return 1;
}

/* parameter qualifier */
#define PARAM_QUALIFIER_IN 0
#define PARAM_QUALIFIER_OUT 1
#define PARAM_QUALIFIER_INOUT 2

/* function parameter array presence */
#define PARAMETER_ARRAY_NOT_PRESENT 0
#define PARAMETER_ARRAY_PRESENT 1

static int
parse_parameter_declaration(slang_parse_ctx * C, slang_output_ctx * O,
                            slang_variable * param)
{
   int param_qual, precision_qual;

   /* parse and validate the parameter's type qualifiers (there can be
    * two at most) because not all combinations are valid
    */
   if (!parse_type_qualifier(C, &param->type.qualifier))
      RETURN0;

   param_qual = *C->I++;
   switch (param_qual) {
   case PARAM_QUALIFIER_IN:
      if (param->type.qualifier != SLANG_QUAL_CONST
          && param->type.qualifier != SLANG_QUAL_NONE) {
         slang_info_log_error(C->L, "Invalid type qualifier.");
         RETURN0;
      }
      break;
   case PARAM_QUALIFIER_OUT:
      if (param->type.qualifier == SLANG_QUAL_NONE)
         param->type.qualifier = SLANG_QUAL_OUT;
      else {
         slang_info_log_error(C->L, "Invalid type qualifier.");
         RETURN0;
      }
      break;
   case PARAM_QUALIFIER_INOUT:
      if (param->type.qualifier == SLANG_QUAL_NONE)
         param->type.qualifier = SLANG_QUAL_INOUT;
      else {
         slang_info_log_error(C->L, "Invalid type qualifier.");
         RETURN0;
      }
      break;
   default:
      RETURN0;
   }

   /* parse precision qualifier (lowp, mediump, highp */
   precision_qual = *C->I++;
   /* ignored at this time */
   (void) precision_qual;

   /* parse parameter's type specifier and name */
   if (!parse_type_specifier(C, O, &param->type.specifier))
      RETURN0;
   if (!parse_type_array_size(C, O, &param->type.array_len))
      RETURN0;
   param->a_name = parse_identifier(C);
   if (param->a_name == SLANG_ATOM_NULL)
      RETURN0;

   /* first-class array
    */
   if (param->type.array_len >= 0) {
      slang_type_specifier p;

      slang_type_specifier_ctr(&p);
      if (!slang_type_specifier_copy(&p, &param->type.specifier)) {
         slang_type_specifier_dtr(&p);
         RETURN0;
      }
      if (!convert_to_array(C, param, &p)) {
         slang_type_specifier_dtr(&p);
         RETURN0;
      }
      slang_type_specifier_dtr(&p);
      param->array_len = param->type.array_len;
   }

   /* if the parameter is an array, parse its size (the size must be
    * explicitly defined
    */
   if (*C->I++ == PARAMETER_ARRAY_PRESENT) {
      slang_type_specifier p;

      if (param->type.array_len >= 0) {
         slang_info_log_error(C->L, "multi-dimensional arrays not allowed");
         RETURN0;
      }
      slang_type_specifier_ctr(&p);
      if (!slang_type_specifier_copy(&p, &param->type.specifier)) {
         slang_type_specifier_dtr(&p);
         RETURN0;
      }
      if (!convert_to_array(C, param, &p)) {
         slang_type_specifier_dtr(&p);
         RETURN0;
      }
      slang_type_specifier_dtr(&p);
      if (!parse_array_len(C, O, &param->array_len))
         RETURN0;
   }

#if 0
   /* calculate the parameter size */
   if (!calculate_var_size(C, O, param))
      RETURN0;
#endif
   /* TODO: allocate the local address here? */
   return 1;
}

/* function type */
#define FUNCTION_ORDINARY 0
#define FUNCTION_CONSTRUCTOR 1
#define FUNCTION_OPERATOR 2

/* function parameter */
#define PARAMETER_NONE 0
#define PARAMETER_NEXT 1

/* operator type */
#define OPERATOR_ADDASSIGN 1
#define OPERATOR_SUBASSIGN 2
#define OPERATOR_MULASSIGN 3
#define OPERATOR_DIVASSIGN 4
/*#define OPERATOR_MODASSIGN 5*/
/*#define OPERATOR_LSHASSIGN 6*/
/*#define OPERATOR_RSHASSIGN 7*/
/*#define OPERATOR_ANDASSIGN 8*/
/*#define OPERATOR_XORASSIGN 9*/
/*#define OPERATOR_ORASSIGN 10*/
#define OPERATOR_LOGICALXOR 11
/*#define OPERATOR_BITOR 12*/
/*#define OPERATOR_BITXOR 13*/
/*#define OPERATOR_BITAND 14*/
#define OPERATOR_LESS 15
#define OPERATOR_GREATER 16
#define OPERATOR_LESSEQUAL 17
#define OPERATOR_GREATEREQUAL 18
/*#define OPERATOR_LSHIFT 19*/
/*#define OPERATOR_RSHIFT 20*/
#define OPERATOR_MULTIPLY 21
#define OPERATOR_DIVIDE 22
/*#define OPERATOR_MODULUS 23*/
#define OPERATOR_INCREMENT 24
#define OPERATOR_DECREMENT 25
#define OPERATOR_PLUS 26
#define OPERATOR_MINUS 27
/*#define OPERATOR_COMPLEMENT 28*/
#define OPERATOR_NOT 29

static const struct
{
   unsigned int o_code;
   const char *o_name;
} operator_names[] = {
   {OPERATOR_INCREMENT, "++"},
   {OPERATOR_ADDASSIGN, "+="},
   {OPERATOR_PLUS, "+"},
   {OPERATOR_DECREMENT, "--"},
   {OPERATOR_SUBASSIGN, "-="},
   {OPERATOR_MINUS, "-"},
   {OPERATOR_NOT, "!"},
   {OPERATOR_MULASSIGN, "*="},
   {OPERATOR_MULTIPLY, "*"},
   {OPERATOR_DIVASSIGN, "/="},
   {OPERATOR_DIVIDE, "/"},
   {OPERATOR_LESSEQUAL, "<="},
   /*{ OPERATOR_LSHASSIGN, "<<=" }, */
   /*{ OPERATOR_LSHIFT, "<<" }, */
   {OPERATOR_LESS, "<"},
   {OPERATOR_GREATEREQUAL, ">="},
   /*{ OPERATOR_RSHASSIGN, ">>=" }, */
   /*{ OPERATOR_RSHIFT, ">>" }, */
   {OPERATOR_GREATER, ">"},
   /*{ OPERATOR_MODASSIGN, "%=" }, */
   /*{ OPERATOR_MODULUS, "%" }, */
   /*{ OPERATOR_ANDASSIGN, "&=" }, */
   /*{ OPERATOR_BITAND, "&" }, */
   /*{ OPERATOR_ORASSIGN, "|=" }, */
   /*{ OPERATOR_BITOR, "|" }, */
   /*{ OPERATOR_COMPLEMENT, "~" }, */
   /*{ OPERATOR_XORASSIGN, "^=" }, */
   {OPERATOR_LOGICALXOR, "^^"},
   /*{ OPERATOR_BITXOR, "^" } */
};

static slang_atom
parse_operator_name(slang_parse_ctx * C)
{
   unsigned int i;

   for (i = 0; i < sizeof(operator_names) / sizeof(*operator_names); i++) {
      if (operator_names[i].o_code == (unsigned int) (*C->I)) {
         slang_atom atom =
            slang_atom_pool_atom(C->atoms, operator_names[i].o_name);
         if (atom == SLANG_ATOM_NULL) {
            slang_info_log_memory(C->L);
            RETURN0;
         }
         C->I++;
         return atom;
      }
   }
   RETURN0;
}


static int
parse_function_prototype(slang_parse_ctx * C, slang_output_ctx * O,
                         slang_function * func)
{
   GLuint functype;
   /* parse function type and name */
   if (!parse_fully_specified_type(C, O, &func->header.type))
      RETURN0;

   functype = *C->I++;
   switch (functype) {
   case FUNCTION_ORDINARY:
      func->kind = SLANG_FUNC_ORDINARY;
      func->header.a_name = parse_identifier(C);
      if (func->header.a_name == SLANG_ATOM_NULL)
         RETURN0;
      break;
   case FUNCTION_CONSTRUCTOR:
      func->kind = SLANG_FUNC_CONSTRUCTOR;
      if (func->header.type.specifier.type == SLANG_SPEC_STRUCT)
         RETURN0;
      func->header.a_name =
         slang_atom_pool_atom(C->atoms,
                              slang_type_specifier_type_to_string
                              (func->header.type.specifier.type));
      if (func->header.a_name == SLANG_ATOM_NULL) {
         slang_info_log_memory(C->L);
         RETURN0;
      }
      break;
   case FUNCTION_OPERATOR:
      func->kind = SLANG_FUNC_OPERATOR;
      func->header.a_name = parse_operator_name(C);
      if (func->header.a_name == SLANG_ATOM_NULL)
         RETURN0;
      break;
   default:
      RETURN0;
   }

   if (!legal_identifier(func->header.a_name)) {
      slang_info_log_error(C->L, "illegal function name '%s'",
                           (char *) func->header.a_name);
      RETURN0;
   }

   /* parse function parameters */
   while (*C->I++ == PARAMETER_NEXT) {
      slang_variable *p = slang_variable_scope_grow(func->parameters);
      if (!p) {
         slang_info_log_memory(C->L);
         RETURN0;
      }
      if (!parse_parameter_declaration(C, O, p))
         RETURN0;
   }

   /* if the function returns a value, append a hidden __retVal 'out'
    * parameter that corresponds to the return value.
    */
   if (_slang_function_has_return_value(func)) {
      slang_variable *p = slang_variable_scope_grow(func->parameters);
      slang_atom a_retVal = slang_atom_pool_atom(C->atoms, "__retVal");
      assert(a_retVal);
      p->a_name = a_retVal;
      p->type = func->header.type;
      p->type.qualifier = SLANG_QUAL_OUT;
   }

   /* function formal parameters and local variables share the same
    * scope, so save the information about param count in a seperate
    * place also link the scope to the global variable scope so when a
    * given identifier is not found here, the search process continues
    * in the global space
    */
   func->param_count = func->parameters->num_variables;
   func->parameters->outer_scope = O->vars;

   return 1;
}

static int
parse_function_definition(slang_parse_ctx * C, slang_output_ctx * O,
                          slang_function * func)
{
   slang_output_ctx o = *O;

   if (!parse_function_prototype(C, O, func))
      RETURN0;

   /* create function's body operation */
   func->body = (slang_operation *) _slang_alloc(sizeof(slang_operation));
   if (func->body == NULL) {
      slang_info_log_memory(C->L);
      RETURN0;
   }
   if (!slang_operation_construct(func->body)) {
      _slang_free(func->body);
      func->body = NULL;
      slang_info_log_memory(C->L);
      RETURN0;
   }

   /* to parse the body the parse context is modified in order to
    * capture parsed variables into function's local variable scope
    */
   C->global_scope = GL_FALSE;
   o.vars = func->parameters;
   if (!parse_statement(C, &o, func->body))
      RETURN0;

   C->global_scope = GL_TRUE;
   return 1;
}

static GLboolean
initialize_global(slang_assemble_ctx * A, slang_variable * var)
{
   slang_operation op_id, op_assign;
   GLboolean result;

   /* construct the left side of assignment */
   if (!slang_operation_construct(&op_id))
      return GL_FALSE;
   op_id.type = SLANG_OPER_IDENTIFIER;
   op_id.a_id = var->a_name;

   /* put the variable into operation's scope */
   op_id.locals->variables =
      (slang_variable **) _slang_alloc(sizeof(slang_variable *));
   if (op_id.locals->variables == NULL) {
      slang_operation_destruct(&op_id);
      return GL_FALSE;
   }
   op_id.locals->num_variables = 1;
   op_id.locals->variables[0] = var;

   /* construct the assignment expression */
   if (!slang_operation_construct(&op_assign)) {
      op_id.locals->num_variables = 0;
      slang_operation_destruct(&op_id);
      return GL_FALSE;
   }
   op_assign.type = SLANG_OPER_ASSIGN;
   op_assign.children =
      (slang_operation *) _slang_alloc(2 * sizeof(slang_operation));
   if (op_assign.children == NULL) {
      slang_operation_destruct(&op_assign);
      op_id.locals->num_variables = 0;
      slang_operation_destruct(&op_id);
      return GL_FALSE;
   }
   op_assign.num_children = 2;
   op_assign.children[0] = op_id;
   op_assign.children[1] = *var->initializer;

   result = 1;

   /* carefully destroy the operations */
   op_assign.num_children = 0;
   _slang_free(op_assign.children);
   op_assign.children = NULL;
   slang_operation_destruct(&op_assign);
   op_id.locals->num_variables = 0;
   slang_operation_destruct(&op_id);

   if (!result)
      return GL_FALSE;

   return GL_TRUE;
}

/* init declarator list */
#define DECLARATOR_NONE 0
#define DECLARATOR_NEXT 1

/* variable declaration */
#define VARIABLE_NONE 0
#define VARIABLE_IDENTIFIER 1
#define VARIABLE_INITIALIZER 2
#define VARIABLE_ARRAY_EXPLICIT 3
#define VARIABLE_ARRAY_UNKNOWN 4


/**
 * Check if it's OK to re-declare a variable with the given new type.
 * This happens when applying layout qualifiers to gl_FragCoord or
 * (re)setting an array size.
 * If redeclaration is OK, return a pointer to the incoming variable
 * updated with new type info.  Else return NULL;
 */
static slang_variable *
redeclare_variable(slang_variable *var, 
                   const slang_fully_specified_type *type)
{
   if (slang_fully_specified_types_compatible(&var->type, type)) {
      /* replace orig var layout with new layout */
      var->type.layout = type->layout;

      /* XXX there may be other type updates in the future here */

      return var;
   }
   else
      return NULL;
}


/**
 * Parse the initializer for a variable declaration.
 */
static int
parse_init_declarator(slang_parse_ctx * C, slang_output_ctx * O,
                      const slang_fully_specified_type * type)
{
   GET_CURRENT_CONTEXT(ctx); /* a hack */
   slang_variable *var = NULL, *prevDecl;
   slang_atom a_name;

   /* empty init declatator (without name, e.g. "float ;") */
   if (*C->I++ == VARIABLE_NONE)
      return 1;

   a_name = parse_identifier(C);

   /* check if name is already in this scope */
   prevDecl = _slang_variable_locate(O->vars, a_name, C->global_scope);
   if (prevDecl) {
      /* A var with this name has already been declared.
       * Check if redeclaring the var with a different type/layout is legal.
       */
      if (C->global_scope) {
         var = redeclare_variable(prevDecl, type);
      }
      if (!var) {
         slang_info_log_error(C->L,
                   "declaration of '%s' conflicts with previous declaration",
                   (char *) a_name);
         RETURN0;
      }
   }

   if (!var) {
      /* make room for a new variable and initialize it */
      var = slang_variable_scope_grow(O->vars);
      if (!var) {
         slang_info_log_memory(C->L);
         RETURN0;
      }

      /* copy the declarator type qualifier/etc info, parse the identifier */
      var->type.qualifier = type->qualifier;
      var->type.centroid = type->centroid;
      var->type.precision = type->precision;
      var->type.specifier = type->specifier;/*new*/
      var->type.variant = type->variant;
      var->type.layout = type->layout;
      var->type.array_len = type->array_len;
      var->a_name = a_name;
      if (var->a_name == SLANG_ATOM_NULL)
         RETURN0;
   }

   switch (*C->I++) {
   case VARIABLE_NONE:
      /* simple variable declarator - just copy the specifier */
      if (!slang_type_specifier_copy(&var->type.specifier, &type->specifier))
         RETURN0;
      break;
   case VARIABLE_INITIALIZER:
      /* initialized variable - copy the specifier and parse the expression */
      if (0 && type->array_len >= 0) {
         /* The type was something like "float[4]" */
         convert_to_array(C, var, &type->specifier);
         var->array_len = type->array_len;
      }
      else {
         if (!slang_type_specifier_copy(&var->type.specifier, &type->specifier))
            RETURN0;
      }
      var->initializer =
         (slang_operation *) _slang_alloc(sizeof(slang_operation));
      if (var->initializer == NULL) {
         slang_info_log_memory(C->L);
         RETURN0;
      }
      if (!slang_operation_construct(var->initializer)) {
         _slang_free(var->initializer);
         var->initializer = NULL;
         slang_info_log_memory(C->L);
         RETURN0;
      }
      if (!parse_expression(C, O, var->initializer))
         RETURN0;
      break;
   case VARIABLE_ARRAY_UNKNOWN:
      /* unsized array - mark it as array and copy the specifier to
       * the array element
       */
      if (type->array_len >= 0) {
         slang_info_log_error(C->L, "multi-dimensional arrays not allowed");
         RETURN0;
      }
      if (!convert_to_array(C, var, &type->specifier))
         return GL_FALSE;
      break;
   case VARIABLE_ARRAY_EXPLICIT:
      if (type->array_len >= 0) {
         /* the user is trying to do something like: float[2] x[3]; */
         slang_info_log_error(C->L, "multi-dimensional arrays not allowed");
         RETURN0;
      }
      if (!convert_to_array(C, var, &type->specifier))
         return GL_FALSE;
      if (!parse_array_len(C, O, &var->array_len))
         return GL_FALSE;
      break;
   default:
      RETURN0;
   }

   /* allocate global address space for a variable with a known size */
   if (C->global_scope
       && !(var->type.specifier.type == SLANG_SPEC_ARRAY
            && var->array_len == 0)) {
      if (!calculate_var_size(C, O, var))
         return GL_FALSE;
   }

   /* emit code for global var decl */
   if (C->global_scope) {
      slang_assemble_ctx A;
      memset(&A, 0, sizeof(slang_assemble_ctx));
      A.allow_uniform_initializers = C->version > 110;
      A.atoms = C->atoms;
      A.space.funcs = O->funs;
      A.space.structs = O->structs;
      A.space.vars = O->vars;
      A.program = O->program;
      A.pragmas = O->pragmas;
      A.vartable = O->vartable;
      A.log = C->L;
      A.curFuncEndLabel = NULL;
      A.EmitContReturn = ctx->Shader.EmitContReturn;
      if (!_slang_codegen_global_variable(&A, var, C->type))
         RETURN0;
   }

   /* initialize global variable */
   if (C->global_scope) {
      if (var->initializer != NULL) {
         slang_assemble_ctx A;
         memset(&A, 0, sizeof(slang_assemble_ctx));
         A.allow_uniform_initializers = C->version > 110;
         A.atoms = C->atoms;
         A.space.funcs = O->funs;
         A.space.structs = O->structs;
         A.space.vars = O->vars;
         if (!initialize_global(&A, var))
            RETURN0;
      }
   }

   if (var->type.qualifier == SLANG_QUAL_FIXEDINPUT &&
       var->a_name == slang_atom_pool_atom(C->atoms, "gl_FragCoord")) {
      /* set the program's PixelCenterInteger, OriginUpperLeft fields */
      struct gl_fragment_program *fragProg =
         (struct gl_fragment_program *) O->program;

      if (var->type.layout & SLANG_LAYOUT_UPPER_LEFT_BIT) {
         fragProg->OriginUpperLeft = GL_TRUE;
      }
      if (var->type.layout & SLANG_LAYOUT_PIXEL_CENTER_INTEGER_BIT) {
         fragProg->PixelCenterInteger = GL_TRUE;
      }
   }

   return 1;
}

/**
 * Parse a list of variable declarations.  Each variable may have an
 * initializer.
 */
static int
parse_init_declarator_list(slang_parse_ctx * C, slang_output_ctx * O)
{
   slang_fully_specified_type type;

   /* parse the fully specified type, common to all declarators */
   if (!slang_fully_specified_type_construct(&type))
      RETURN0;
   if (!parse_fully_specified_type(C, O, &type)) {
      slang_fully_specified_type_destruct(&type);
      RETURN0;
   }

   /* parse declarators, pass-in the parsed type */
   do {
      if (!parse_init_declarator(C, O, &type)) {
         slang_fully_specified_type_destruct(&type);
         RETURN0;
      }
   }
   while (*C->I++ == DECLARATOR_NEXT);

   slang_fully_specified_type_destruct(&type);
   return 1;
}


/**
 * Parse a function definition or declaration.
 * \param C  parsing context
 * \param O  output context
 * \param definition if non-zero expect a definition, else a declaration
 * \param parsed_func_ret  returns the parsed function
 * \return GL_TRUE if success, GL_FALSE if failure
 */
static GLboolean
parse_function(slang_parse_ctx * C, slang_output_ctx * O, int definition,
               slang_function ** parsed_func_ret)
{
   slang_function parsed_func, *found_func;

   /* parse function definition/declaration */
   if (!slang_function_construct(&parsed_func))
      return GL_FALSE;
   if (definition) {
      if (!parse_function_definition(C, O, &parsed_func)) {
         slang_function_destruct(&parsed_func);
         return GL_FALSE;
      }
   }
   else {
      if (!parse_function_prototype(C, O, &parsed_func)) {
         slang_function_destruct(&parsed_func);
         return GL_FALSE;
      }
   }

   /* find a function with a prototype matching the parsed one - only
    * the current scope is being searched to allow built-in function
    * overriding
    */
   found_func = slang_function_scope_find(O->funs, &parsed_func, 0);
   if (found_func == NULL) {
      /* New function, add it to the function list */
      O->funs->functions =
         (slang_function *) _slang_realloc(O->funs->functions,
                                           O->funs->num_functions
                                           * sizeof(slang_function),
                                           (O->funs->num_functions + 1)
                                           * sizeof(slang_function));
      if (O->funs->functions == NULL) {
         /* Make sure that there are no functions marked, as the
          * allocation is currently NULL, in order to avoid
          * a potental segfault as we clean up later.
          */
         O->funs->num_functions = 0;

         slang_info_log_memory(C->L);
         slang_function_destruct(&parsed_func);
         return GL_FALSE;
      }
      O->funs->functions[O->funs->num_functions] = parsed_func;
      O->funs->num_functions++;

      /* return the newly parsed function */
      *parsed_func_ret = &O->funs->functions[O->funs->num_functions - 1];
   }
   else {
      /* previously defined or declared */
      /* TODO: check function return type qualifiers and specifiers */
      if (definition) {
         if (found_func->body != NULL) {
            slang_info_log_error(C->L, "%s: function already has a body.",
                                 slang_atom_pool_id(C->atoms,
                                                    parsed_func.header.
                                                    a_name));
            slang_function_destruct(&parsed_func);
            return GL_FALSE;
         }

         /* destroy the existing function declaration and replace it
          * with the new one
          */
         slang_function_destruct(found_func);
         *found_func = parsed_func;
      }
      else {
         /* another declaration of the same function prototype - ignore it */
         slang_function_destruct(&parsed_func);
      }

      /* return the found function */
      *parsed_func_ret = found_func;
   }

   return GL_TRUE;
}

/* declaration */
#define DECLARATION_FUNCTION_PROTOTYPE 1
#define DECLARATION_INIT_DECLARATOR_LIST 2

static int
parse_declaration(slang_parse_ctx * C, slang_output_ctx * O)
{
   switch (*C->I++) {
   case DECLARATION_INIT_DECLARATOR_LIST:
      if (!parse_init_declarator_list(C, O))
         RETURN0;
      break;
   case DECLARATION_FUNCTION_PROTOTYPE:
      {
         slang_function *dummy_func;

         if (!parse_function(C, O, 0, &dummy_func))
            RETURN0;
      }
      break;
   default:
      RETURN0;
   }
   return 1;
}

static int
parse_default_precision(slang_parse_ctx * C, slang_output_ctx * O)
{
   int precision, type;

   if (!O->allow_precision) {
      slang_info_log_error(C->L, "syntax error at \"precision\"");
      RETURN0;
   }

   precision = *C->I++;
   switch (precision) {
   case PRECISION_LOW:
   case PRECISION_MEDIUM:
   case PRECISION_HIGH:
      /* OK */
      break;
   default:
      _mesa_problem(NULL, "unexpected precision %d at %s:%d\n",
                    precision, __FILE__, __LINE__);
      RETURN0;
   }

   type = *C->I++;
   switch (type) {
   case TYPE_SPECIFIER_FLOAT:
   case TYPE_SPECIFIER_INT:
   case TYPE_SPECIFIER_SAMPLER1D:
   case TYPE_SPECIFIER_SAMPLER2D:
   case TYPE_SPECIFIER_SAMPLER3D:
   case TYPE_SPECIFIER_SAMPLERCUBE:
   case TYPE_SPECIFIER_SAMPLER1DSHADOW:
   case TYPE_SPECIFIER_SAMPLER2DSHADOW:
   case TYPE_SPECIFIER_SAMPLER2DRECT:
   case TYPE_SPECIFIER_SAMPLER2DRECTSHADOW:
   case TYPE_SPECIFIER_SAMPLER_1D_ARRAY:
   case TYPE_SPECIFIER_SAMPLER_2D_ARRAY:
   case TYPE_SPECIFIER_SAMPLER_1D_ARRAY_SHADOW:
   case TYPE_SPECIFIER_SAMPLER_2D_ARRAY_SHADOW:
      /* OK */
      break;
   default:
      _mesa_problem(NULL, "unexpected type %d at %s:%d\n",
                    type, __FILE__, __LINE__);
      RETURN0;
   }

   assert(type < TYPE_SPECIFIER_COUNT);
   O->default_precision[type] = precision;

   return 1;
}


/**
 * Initialize the default precision for all types.
 * XXX this info isn't used yet.
 */
static void
init_default_precision(slang_output_ctx *O, slang_unit_type type)
{
   GLuint i;
   for (i = 0; i < TYPE_SPECIFIER_COUNT; i++) {
#if FEATURE_es2_glsl
      O->default_precision[i] = PRECISION_LOW;
#else
      O->default_precision[i] = PRECISION_HIGH;
#endif
   }

   if (type == SLANG_UNIT_VERTEX_SHADER) {
      O->default_precision[TYPE_SPECIFIER_FLOAT] = PRECISION_HIGH;
      O->default_precision[TYPE_SPECIFIER_INT] = PRECISION_HIGH;
   }
   else {
      O->default_precision[TYPE_SPECIFIER_INT] = PRECISION_MEDIUM;
   }
}


static int
parse_invariant(slang_parse_ctx * C, slang_output_ctx * O)
{
   if (O->allow_invariant) {
      slang_atom *a = parse_identifier(C);
      /* XXX not doing anything with this var yet */
      /*printf("ID: %s\n", (char*) a);*/
      return a ? 1 : 0;
   }
   else {
      slang_info_log_error(C->L, "syntax error at \"invariant\"");
      RETURN0;
   }
}
      

/* external declaration or default precision specifier */
#define EXTERNAL_NULL 0
#define EXTERNAL_FUNCTION_DEFINITION 1
#define EXTERNAL_DECLARATION 2
#define DEFAULT_PRECISION 3
#define INVARIANT_STMT 4


static GLboolean
parse_code_unit(slang_parse_ctx * C, slang_code_unit * unit,
                struct gl_shader *shader)
{
   GET_CURRENT_CONTEXT(ctx);
   slang_output_ctx o;
   GLboolean success;
   GLuint maxRegs;
   slang_function *mainFunc = NULL;

   if (unit->type == SLANG_UNIT_FRAGMENT_BUILTIN ||
       unit->type == SLANG_UNIT_FRAGMENT_SHADER) {
      maxRegs = ctx->Const.FragmentProgram.MaxTemps;
   }
   else {
      assert(unit->type == SLANG_UNIT_VERTEX_BUILTIN ||
             unit->type == SLANG_UNIT_VERTEX_SHADER);
      maxRegs = ctx->Const.VertexProgram.MaxTemps;
   }

   /* setup output context */
   o.funs = &unit->funs;
   o.structs = &unit->structs;
   o.vars = &unit->vars;
   o.program = shader ? shader->Program : NULL;
   o.pragmas = shader ? &shader->Pragmas : NULL;
   o.vartable = _slang_new_var_table(maxRegs);
   _slang_push_var_table(o.vartable);

   /* allow 'invariant' keyword? */
#if FEATURE_es2_glsl
   o.allow_invariant = GL_TRUE;
#else
   o.allow_invariant = (C->version >= 120) ? GL_TRUE : GL_FALSE;
#endif

   /* allow 'centroid' keyword? */
   o.allow_centroid = (C->version >= 120) ? GL_TRUE : GL_FALSE;

   /* allow 'lowp/mediump/highp' keywords? */
#if FEATURE_es2_glsl
   o.allow_precision = GL_TRUE;
#else
   o.allow_precision = (C->version >= 120) ? GL_TRUE : GL_FALSE;
#endif
   init_default_precision(&o, unit->type);

   /* allow 'float[]' keyword? */
   o.allow_array_types = (C->version >= 120) ? GL_TRUE : GL_FALSE;

   /* parse individual functions and declarations */
   while (*C->I != EXTERNAL_NULL) {
      switch (*C->I++) {
      case EXTERNAL_FUNCTION_DEFINITION:
         {
            slang_function *func;
            success = parse_function(C, &o, 1, &func);
            if (success && strcmp((char *) func->header.a_name, "main") == 0) {
               /* found main() */
               mainFunc = func;
            }
         }
         break;
      case EXTERNAL_DECLARATION:
         success = parse_declaration(C, &o);
         break;
      case DEFAULT_PRECISION:
         success = parse_default_precision(C, &o);
         break;
      case INVARIANT_STMT:
         success = parse_invariant(C, &o);
         break;
      default:
         success = GL_FALSE;
      }

      if (!success) {
         /* xxx free codegen */
         _slang_pop_var_table(o.vartable);
         return GL_FALSE;
      }
   }
   C->I++;

   if (mainFunc) {
      /* assemble (generate code) for main() */
      slang_assemble_ctx A;
      memset(&A, 0, sizeof(slang_assemble_ctx));
      A.atoms = C->atoms;
      A.space.funcs = o.funs;
      A.space.structs = o.structs;
      A.space.vars = o.vars;
      A.program = o.program;
      A.pragmas = &shader->Pragmas;
      A.vartable = o.vartable;
      A.EmitContReturn = ctx->Shader.EmitContReturn;
      A.log = C->L;
      A.allow_uniform_initializers = C->version > 110;

      /* main() takes no parameters */
      if (mainFunc->param_count > 0) {
         slang_info_log_error(A.log, "main() takes no arguments");
         return GL_FALSE;
      }

      _slang_codegen_function(&A, mainFunc);

      shader->Main = GL_TRUE; /* this shader defines main() */

      shader->UnresolvedRefs = A.UnresolvedRefs;
   }

   _slang_pop_var_table(o.vartable);
   _slang_delete_var_table(o.vartable);

   return GL_TRUE;
}

static GLboolean
compile_binary(const unsigned char * prod, slang_code_unit * unit,
               GLuint version,
               slang_unit_type type, slang_info_log * infolog,
               slang_code_unit * builtin, slang_code_unit * downlink,
               struct gl_shader *shader)
{
   slang_parse_ctx C;

   unit->type = type;

   /* setup parse context */
   C.I = prod;
   C.L = infolog;
   C.parsing_builtin = (builtin == NULL);
   C.global_scope = GL_TRUE;
   C.atoms = &unit->object->atompool;
   C.type = type;
   C.version = version;

   if (!check_revision(&C))
      return GL_FALSE;

   if (downlink != NULL) {
      unit->vars.outer_scope = &downlink->vars;
      unit->funs.outer_scope = &downlink->funs;
      unit->structs.outer_scope = &downlink->structs;
   }

   /* parse translation unit */
   return parse_code_unit(&C, unit, shader);
}

static GLboolean
compile_with_grammar(const char *source,
                     slang_code_unit *unit,
                     slang_unit_type type,
                     slang_info_log *infolog,
                     slang_code_unit *builtin,
                     struct gl_shader *shader,
                     struct gl_sl_pragmas *pragmas,
                     unsigned int shader_type,
                     unsigned int parsing_builtin)
{
   struct sl_pp_purify_options options;
   struct sl_pp_context *context;
   unsigned char *prod;
   GLuint size;
   unsigned int version;
   unsigned int maxVersion;
   int result;
   char errmsg[200] = "";

   assert(shader_type == 1 || shader_type == 2);

   memset(&options, 0, sizeof(options));

   context = sl_pp_context_create(source, &options);
   if (!context) {
      slang_info_log_error(infolog, "out of memory");
      return GL_FALSE;
   }

   if (sl_pp_version(context, &version)) {
      slang_info_log_error(infolog, "%s", sl_pp_context_error_message(context));
      sl_pp_context_destroy(context);
      return GL_FALSE;
   }

   if (sl_pp_context_add_extension(context, "GL_ARB_draw_buffers") ||
       sl_pp_context_add_extension(context, "GL_ARB_texture_rectangle")) {
      slang_info_log_error(infolog, "%s", sl_pp_context_error_message(context));
      sl_pp_context_destroy(context);
      return GL_FALSE;
   }

   if (type == SLANG_UNIT_FRAGMENT_SHADER) {
      sl_pp_context_add_extension(context, "GL_ARB_fragment_coord_conventions");
   }


#if FEATURE_es2_glsl
   if (sl_pp_context_add_predefined(context, "GL_ES", "1") ||
       sl_pp_context_add_predefined(context, "GL_FRAGMENT_PRECISION_HIGH", "1")) {
      slang_info_log_error(infolog, "%s", sl_pp_context_error_message(context));
      sl_pp_context_destroy(context);
      return GL_FALSE;
   }
#endif

#if FEATURE_ARB_shading_language_120
   maxVersion = 120;
#elif FEATURE_es2_glsl
   maxVersion = 100;
#else
   maxVersion = 110;
#endif

   if (version > maxVersion ||
       (version != 100 && version != 110 && version != 120)) {
      slang_info_log_error(infolog,
                           "language version %.2f is not supported.",
                           version * 0.01);
      sl_pp_context_destroy(context);
      return GL_FALSE;
   }

   /* Finally check the syntax and generate its binary representation. */
   result = sl_cl_compile(context,
                          shader_type,
                          parsing_builtin,
                          &prod,
                          &size,
                          errmsg,
                          sizeof(errmsg));

   sl_pp_context_destroy(context);

   if (result) {
      /*GLint pos;*/

      slang_info_log_error(infolog, errmsg);
      /* syntax error (possibly in library code) */
#if 0
      {
         int line, col;
         char *s;
         s = (char *) _mesa_find_line_column((const GLubyte *) source,
                                             (const GLubyte *) source + pos,
                                             &line, &col);
         printf("Error on line %d, col %d: %s\n", line, col, s);
      }
#endif
      return GL_FALSE;
   }

   /* Syntax is okay - translate it to internal representation. */
   if (!compile_binary(prod, unit, version, type, infolog, builtin,
                       &builtin[SLANG_BUILTIN_TOTAL - 1],
                       shader)) {
      free(prod);
      return GL_FALSE;
   }
   free(prod);
   return GL_TRUE;
}

static const unsigned char slang_core_gc[] = {
#include "library/slang_core_gc.h"
};

static const unsigned char slang_120_core_gc[] = {
#include "library/slang_120_core_gc.h"
};

static const unsigned char slang_120_fragment_gc[] = {
#include "library/slang_builtin_120_fragment_gc.h"
};

static const unsigned char slang_common_builtin_gc[] = {
#include "library/slang_common_builtin_gc.h"
};

static const unsigned char slang_fragment_builtin_gc[] = {
#include "library/slang_fragment_builtin_gc.h"
};

static const unsigned char slang_vertex_builtin_gc[] = {
#include "library/slang_vertex_builtin_gc.h"
};

static GLboolean
compile_object(const char *source,
               slang_code_object *object,
               slang_unit_type type,
               slang_info_log *infolog,
               struct gl_shader *shader,
               struct gl_sl_pragmas *pragmas)
{
   slang_code_unit *builtins = NULL;
   GLuint base_version = 110;
   unsigned int shader_type;
   unsigned int parsing_builtin;

   /* set shader type - the syntax is slightly different for different shaders */
   if (type == SLANG_UNIT_FRAGMENT_SHADER || type == SLANG_UNIT_FRAGMENT_BUILTIN) {
      shader_type = 1;
   } else {
      shader_type = 2;
   }

   /* enable language extensions */
   parsing_builtin = 1;

   /* if parsing user-specified shader, load built-in library */
   if (type == SLANG_UNIT_FRAGMENT_SHADER || type == SLANG_UNIT_VERTEX_SHADER) {
      /* compile core functionality first */
      if (!compile_binary(slang_core_gc,
                          &object->builtin[SLANG_BUILTIN_CORE],
                          base_version,
                          SLANG_UNIT_FRAGMENT_BUILTIN, infolog,
                          NULL, NULL, NULL))
         return GL_FALSE;

#if FEATURE_ARB_shading_language_120
      if (!compile_binary(slang_120_core_gc,
                          &object->builtin[SLANG_BUILTIN_120_CORE],
                          120,
                          SLANG_UNIT_FRAGMENT_BUILTIN, infolog,
                          NULL, &object->builtin[SLANG_BUILTIN_CORE], NULL))
         return GL_FALSE;
#endif

      /* compile common functions and variables, link to core */
      if (!compile_binary(slang_common_builtin_gc,
                          &object->builtin[SLANG_BUILTIN_COMMON],
#if FEATURE_ARB_shading_language_120
                          120,
#else
                          base_version,
#endif
                          SLANG_UNIT_FRAGMENT_BUILTIN, infolog, NULL,
#if FEATURE_ARB_shading_language_120
                          &object->builtin[SLANG_BUILTIN_120_CORE],
#else
                          &object->builtin[SLANG_BUILTIN_CORE],
#endif
                          NULL))
         return GL_FALSE;

      /* compile target-specific functions and variables, link to common */
      if (type == SLANG_UNIT_FRAGMENT_SHADER) {
         if (!compile_binary(slang_fragment_builtin_gc,
                             &object->builtin[SLANG_BUILTIN_TARGET],
                             base_version,
                             SLANG_UNIT_FRAGMENT_BUILTIN, infolog, NULL,
                             &object->builtin[SLANG_BUILTIN_COMMON], NULL))
            return GL_FALSE;
#if FEATURE_ARB_shading_language_120
         if (!compile_binary(slang_120_fragment_gc,
                             &object->builtin[SLANG_BUILTIN_TARGET],
                             120,
                             SLANG_UNIT_FRAGMENT_BUILTIN, infolog, NULL,
                             &object->builtin[SLANG_BUILTIN_COMMON], NULL))
            return GL_FALSE;
#endif
      }
      else if (type == SLANG_UNIT_VERTEX_SHADER) {
         if (!compile_binary(slang_vertex_builtin_gc,
                             &object->builtin[SLANG_BUILTIN_TARGET],
                             base_version,
                             SLANG_UNIT_VERTEX_BUILTIN, infolog, NULL,
                             &object->builtin[SLANG_BUILTIN_COMMON], NULL))
            return GL_FALSE;
      }

      /* disable language extensions */
      parsing_builtin = 0;

      builtins = object->builtin;
   }

   /* compile the actual shader - pass-in built-in library for external shader */
   return compile_with_grammar(source,
                               &object->unit,
                               type,
                               infolog,
                               builtins,
                               shader,
                               pragmas,
                               shader_type,
                               parsing_builtin);
}


GLboolean
_slang_compile(GLcontext *ctx, struct gl_shader *shader)
{
   GLboolean success;
   slang_info_log info_log;
   slang_code_object obj;
   slang_unit_type type;
   GLenum progTarget;

   if (shader->Type == GL_VERTEX_SHADER) {
      type = SLANG_UNIT_VERTEX_SHADER;
   }
   else {
      assert(shader->Type == GL_FRAGMENT_SHADER);
      type = SLANG_UNIT_FRAGMENT_SHADER;
   }

   if (!shader->Source)
      return GL_FALSE;

   ctx->Shader.MemPool = _slang_new_mempool(1024*1024);

   shader->Main = GL_FALSE;

   /* free the shader's old instructions, etc */
   _mesa_reference_program(ctx, &shader->Program, NULL);

   /* allocate new GPU program, parameter lists, etc. */
   if (shader->Type == GL_VERTEX_SHADER)
      progTarget = GL_VERTEX_PROGRAM_ARB;
   else
      progTarget = GL_FRAGMENT_PROGRAM_ARB;
   shader->Program = ctx->Driver.NewProgram(ctx, progTarget, 1);
   shader->Program->Parameters = _mesa_new_parameter_list();
   shader->Program->Varying = _mesa_new_parameter_list();
   shader->Program->Attributes = _mesa_new_parameter_list();

   slang_info_log_construct(&info_log);
   _slang_code_object_ctr(&obj);

   success = compile_object(shader->Source,
                            &obj,
                            type,
                            &info_log,
                            shader,
                            &shader->Pragmas);

   /* free shader's prev info log */
   if (shader->InfoLog) {
      free(shader->InfoLog);
      shader->InfoLog = NULL;
   }

   if (info_log.text) {
      /* copy info-log string to shader object */
      shader->InfoLog = _mesa_strdup(info_log.text);
   }

   if (info_log.error_flag) {
      success = GL_FALSE;
   }

   slang_info_log_destruct(&info_log);
   _slang_code_object_dtr(&obj);

   _slang_delete_mempool((slang_mempool *) ctx->Shader.MemPool);
   ctx->Shader.MemPool = NULL;

   /* remove any reads of output registers */
#if 0
   printf("Pre-remove output reads:\n");
   _mesa_print_program(shader->Program);
#endif
   _mesa_remove_output_reads(shader->Program, PROGRAM_OUTPUT);
   if (shader->Type == GL_VERTEX_SHADER) {
      /* and remove writes to varying vars in vertex programs */
      _mesa_remove_output_reads(shader->Program, PROGRAM_VARYING);
   }
#if 0
   printf("Post-remove output reads:\n");
   _mesa_print_program(shader->Program);
#endif

   shader->CompileStatus = success;

   if (success) {
      if (shader->Pragmas.Optimize &&
          (ctx->Shader.Flags & GLSL_NO_OPT) == 0) {
         _mesa_optimize_program(ctx, shader->Program);
      }
      if ((ctx->Shader.Flags & GLSL_NOP_VERT) &&
          shader->Program->Target == GL_VERTEX_PROGRAM_ARB) {
         _mesa_nop_vertex_program(ctx,
                                  (struct gl_vertex_program *) shader->Program);
      }
      if ((ctx->Shader.Flags & GLSL_NOP_FRAG) &&
          shader->Program->Target == GL_FRAGMENT_PROGRAM_ARB) {
         _mesa_nop_fragment_program(ctx,
                                (struct gl_fragment_program *) shader->Program);
      }
   }

   if (ctx->Shader.Flags & GLSL_LOG) {
      _mesa_write_shader_to_file(shader);
   }

   return success;
}