File: Css3.g

package info (click to toggle)
libnb-platform18-java 12.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 729,624 kB
  • sloc: java: 5,058,967; xml: 574,432; php: 78,788; javascript: 29,039; ansic: 10,278; sh: 6,386; cpp: 4,612; jsp: 3,643; sql: 1,097; makefile: 540; objc: 288; perl: 277; haskell: 93
file content (1963 lines) | stat: -rw-r--r-- 56,606 bytes parent folder | download
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
// A complete lexer and grammar for CSS 2.1 as defined by the
// W3 specification.
//
// This grammar is free to use providing you retain everyhting in this header comment
// section.
//
// Author      : Jim Idle, Temporal Wave LLC.
// Contact     : jimi@temporal-wave.com
// Website     : http://www.temporal-wave.com
// License     : ANTLR Free BSD License
//
// Please visit our Web site at http://www.temporal-wave.com and try our commercial
// parsers for SQL, C#, VB.Net and more.
//
// This grammar is free to use providing you retain everything in this header comment
// section.
//

//Modifications to the original css21 source file by Jim Idle have been done to fulfill the
//css3 parsing rules and making the parser more error prone.
//1) incorporated the grammar changes from selectors module: http://www.w3.org/TR/css3-selectors/#grammar
//      a. There's no 'universal' selector node, 'typeSelector' is used instead where instead of the identifier there's the star token.
//         This solves the too long (==3) lookahead problem in the simpleSelectorSequence rule
//2) implemented custom error recovery
//3) removed whitespaces from the alpha token fragments
//
//Please be aware that the grammar doesn't properly and fully reflect the whole css3 specification!!!

// The original CSS 2.1 grammar was downloaded from the antlr 3 grammars:
// https://raw.githubusercontent.com/antlr/grammars-v3/62555b5befd6f89af05bf918b79fa98f5391e12f/css21/css21.g

// Rebuild the lexer and parser:
// 1. Update Css3.g
// 2. Update the lexer/parser sources by running
//    ant -Dantlr.jar=<PATH_TO_ANTLR3_JAR> generate-antlr-parser
//    from the module directory (ide/css.lib)
// 3. Rerun unittests
// 4. Commit Css3.g together with generated Css3Lexer.java and Css3Parser.java

grammar Css3;

//options {
//	k='*';
//}

@header {
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

// DO NOT EDIT THIS FILE MANUALLY!
// SEE Css3.g FOR INSTRUCTIONS

package org.netbeans.modules.css.lib;

}

@lexer::members {
    protected boolean isLessSource() {
        return false;
    }

    protected boolean isScssSource() {
        return false;
    }

    private boolean isCssPreprocessorSource() {
        return isLessSource() || isScssSource();
    }
}

@members {

    protected boolean isLessSource() {
        return false;
    }

    protected boolean isScssSource() {
        return false;
    }

    private boolean isCssPreprocessorSource() {
        return isLessSource() || isScssSource();
    }

    private boolean tokenNameEquals(String tokenImage) {
        return tokenImage.equalsIgnoreCase(input.LT(1).getText());
    }

    private boolean tokenNameIs(String[] tokens) {
        for(String tokenImage : tokens) {
            if(tokenImage.equalsIgnoreCase(input.LT(1).getText())) {
                return true;
            }
        }
        return false;
    }

    private boolean tokenNameStartsWith(String prefix) {
        return input.LT(1).getText() != null
            && input.LT(1).getText().startsWith(prefix);
    }

/**
     * Use the current stacked followset to work out the valid tokens that
     * can follow on from the current point in the parse, then recover by
     * eating tokens that are not a member of the follow set we compute.
     *
     * This method is used whenever we wish to force a sync, even though
     * the parser has not yet checked LA(1) for alt selection. This is useful
     * in situations where only a subset of tokens can begin a new construct
     * (such as the start of a new statement in a block) and we want to
     * proactively detect garbage so that the current rule does not exit on
     * on an exception.
     *
     * We could override recover() to make this the default behavior but that
     * is too much like using a sledge hammer to crack a nut. We want finer
     * grained control of the recovery and error mechanisms.
     */
    protected void syncToSet()
    {
        // Compute the followset that is in context wherever we are in the
        // rule chain/stack
        //
         BitSet follow = state.following[state._fsp]; //computeContextSensitiveRuleFOLLOW();

         syncToSet(follow);
    }

    protected void syncToSet(BitSet follow)
    {
        int mark = -1;

        //create error-recovery node
        dbg.enterRule(getGrammarFileName(), "recovery");

        try {

            mark = input.mark();

            // Consume all tokens in the stream until we find a member of the follow
            // set, which means the next production should be guaranteed to be happy.
            //
            while (! follow.member(input.LA(1)) ) {

                if  (input.LA(1) == Token.EOF) {

                    // Looks like we didn't find anything at all that can help us here
                    // so we need to rewind to where we were and let normal error handling
                    // bail out.
                    //
                    input.rewind();
                    mark = -1;
                    return;
                }
                input.consume();

                // Now here, because you are consuming some tokens, yu will probably want
                // to raise an error message such as "Spurious elements after the class member were discarded"
                // using whatever your override of displayRecognitionError() routine does to record
                // error messages. The exact error my depend on context etc.
                //
            }
        } catch (Exception e) {

          // Just ignore any errors here, we will just let the recognizer
          // try to resync as normal - something must be very screwed.
          //
        }
        finally {
            dbg.exitRule(getGrammarFileName(), "recovery");

            // Always release the mark we took
            //
            if  (mark != -1) {
                input.release(mark);
            }
        }
    }

    /**
         * synces to next RBRACE "}" taking nesting into account
         */
        protected void syncToRBRACE(int nest)
            {

                int mark = -1;
                //create error-recovery node
                //dbg.enterRule(getGrammarFileName(), "recovery");

                try {
                    mark = input.mark();
                    for(;;) {
                        //read char
                        int c = input.LA(1);

                        switch(c) {
                            case Token.EOF:
                                input.rewind();
                                mark = -1;
                                return ;
                            case Css3Lexer.LBRACE:
                                nest++;
                                break;
                            case Css3Lexer.RBRACE:
                                nest--;
                                if(nest == 0) {
                                    //do not eat the final RBRACE
                                    return ;
                                }
                        }

                        input.consume();

                    }

                } catch (Exception e) {

                  // Just ignore any errors here, we will just let the recognizer
                  // try to resync as normal - something must be very screwed.
                  //
                }
                finally {
                    if  (mark != -1) {
                        input.release(mark);
                    }
                    //dbg.exitRule(getGrammarFileName(), "recovery");
                }
            }

}

@lexer::header {
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.netbeans.modules.css.lib;
}

// -------------
// Main rule.   This is the main entry rule for the parser, the top level
//              grammar rule.
//
// A style sheet consists of an optional character set specification, an optional series
// of imports, and then the main body of style rules.
//
styleSheet
    :
    	ws?
    	( charSet ws? )?
        imports?
        namespaces?
        body?
     EOF
    ;

namespaces
	:
	( namespace ws? )+
	;

namespace
  : NAMESPACE_SYM ws? (namespacePrefixName ws?)? resourceIdentifier ws? SEMI
  ;

namespacePrefixName
  : IDENT
  ;

resourceIdentifier
  : STRING | URI
  ;

charSet
    :   CHARSET_SYM ws? charSetValue ws? SEMI
    ;

charSetValue
	: STRING
	;

imports
	:
	( importItem ws? SEMI ws? )+
	;

importItem
    :
        IMPORT_SYM ws? resourceIdentifier ((ws? mediaQueryList)=>ws? mediaQueryList)?
        |
        //multiple imports in one directive
        {isScssSource()}? IMPORT_SYM ws? resourceIdentifier (ws? COMMA ws? resourceIdentifier)* ((ws? mediaQueryList)=>ws? mediaQueryList)?
        |
        {isLessSource()}? IMPORT_SYM ws? (LPAREN less_import_types RPAREN ws?)? resourceIdentifier ((ws? mediaQueryList)=>ws? mediaQueryList)?
    ;
media
    : MEDIA_SYM ws?
    (
         mediaQueryList
    ) ws?
    LBRACE ws? syncToFollow
        mediaBody?
    RBRACE
    ;

mediaBody
    :
    (
         ( mediaBodyItem ((ws? SEMI)=>ws? SEMI)? ws? )
         |
         ( SEMI ws? )
         | ({isScssSource()}? sass_extend (ws | (SEMI)))
    )+
    ;

mediaBodyItem
    :
    (SASS_MIXIN | (((DOT IDENT) | HASH) ws? LPAREN (~RPAREN)* RPAREN ~(LBRACE|SEMI)* LBRACE))=>cp_mixin_declaration
    //https://netbeans.org/bugzilla/show_bug.cgi?id=227510#c12 -- class selector in selector group recognized as mixin call -- workarounded by adding the ws? SEMI to the predicate
    | (cp_mixin_call (ws? IMPORTANT_SYM)? ws? SEMI)=> {isLessSource()}? cp_mixin_call (ws? IMPORTANT_SYM)?
    | (cp_mixin_call)=> {isScssSource()}? cp_mixin_call (ws? IMPORTANT_SYM)?
    | (((SASS_AT_ROOT (ws selectorsGroup)? ) | (SASS_AT_ROOT ws LPAREN ws? IDENT ws? COLON ws? IDENT ws? RPAREN) | selectorsGroup) ws? LBRACE)=>rule
    | (propertyDeclaration)=>propertyDeclaration
    | {isScssSource()}? sass_debug
    | {isScssSource()}? sass_control
    | {isScssSource()}? sass_content
    | {isCssPreprocessorSource()}? importItem
    | rule
    | page
    | fontFace
    | vendorAtRule
    //Just a partial hotfix for nested MQ: complete grammar is defined in: http://www.w3.org/TR/css3-conditional/#processing
    | media
    | supportsAtRule
    ;

mediaQueryList
 : mediaQuery ( (ws? COMMA)=> ws? COMMA ws? mediaQuery )*
 ;

mediaQuery
 :
    (mediaQueryOperator ws? )?  mediaType ((ws? key_and)=> ws? key_and ws? mediaExpression )*
    | mediaExpression ((ws? key_and)=> ws? key_and ws? mediaExpression )*
    | {isLessSource()}? cp_variable
 ;

mediaQueryOperator
 	: key_only | NOT
 	;

mediaType
 : IDENT | GEN | {isCssPreprocessorSource()}? sass_interpolation_expression_var
 ;

mediaExpression
    :
    (LPAREN) => (LPAREN ws? mediaFeature mediaFeatureValue? ws? RPAREN)
    | (HASH) => {isCssPreprocessorSource()}? sass_interpolation_expression_var
    ;

mediaFeatureValue
    :
    ws? COLON ws?
    (
        {isCssPreprocessorSource()}? cp_expression
        |
        expression
    )
    ;

mediaFeature
 : IDENT | GEN | {isCssPreprocessorSource()}? ( cp_variable | sass_interpolation_expression_var )
 ;

 body
    :
    (
         ( bodyItem ((ws? SEMI)=>ws? SEMI)? ws? )
         |
         ( SEMI ws? )
    )+
    ;

bodyItem
    :
        (SASS_MIXIN | (((DOT IDENT) | HASH) ws? LPAREN (~RPAREN)* RPAREN ~(LBRACE|RBRACE|SEMI)* LBRACE))=>cp_mixin_declaration
        //https://netbeans.org/bugzilla/show_bug.cgi?id=227510#c12 -- class selector in selector group recognized as mixin call -- workarounded by adding the ws? SEMI to the predicate
        | (cp_mixin_call ws? SEMI)=> {isLessSource()}? cp_mixin_call
        | (cp_mixin_call)=> {isScssSource()}? cp_mixin_call
    	| rule
        | (cp_variable ws? COLON)=> cp_variable_declaration
        | (sass_map)=> sass_map
        | at_rule
        //not exactly acc. to the spec, since just CP stuff can preceede, but is IMO satisfactory
        | {isCssPreprocessorSource()}? importItem
        | {isScssSource()}? sass_debug
        | {isScssSource()}? sass_control
        | {isScssSource()}? sass_function_declaration
    ; catch[ RecognitionException rce] {
        reportError(rce);
        consumeUntil(input, BitSet.of(NL));
    }

supportsAtRule
	:
	SUPPORTS_SYM ws? supportsCondition ws? LBRACE ws? syncToFollow mediaBody? RBRACE
	;


supportsCondition
	:
	NOT ws supportsInParens
	| supportsInParens (ws supportsWithOperator)?
	;

supportsWithOperator
        :
        supportsConjunction (ws supportsConjunction)*
        | supportsDisjunction (ws supportsDisjunction)*
        ;

supportsConjunction
        : (key_and ws supportsInParens)
        ;

supportsDisjunction
        : (key_or ws supportsInParens)
        ;

supportsInParens
	:
	LPAREN ws? (supportsCondition | supportsFeature) ws? RPAREN
	;
	
supportsFeature
	:
	supportsDecl
	;
	
supportsDecl
	:
	declaration
	;

at_rule
    :
    media
    | page
    | counterStyle
    | fontFace
    | supportsAtRule
    | vendorAtRule
    ;

vendorAtRule
: moz_document | webkitKeyframes | generic_at_rule;

atRuleId
	:
	IDENT | STRING | {isCssPreprocessorSource()}? ( cp_variable | sass_interpolation_expression_var )
	;

generic_at_rule
    : AT_IDENT ws? ( atRuleId ws? )?
        LBRACE
        	syncTo_RBRACE
        RBRACE
	;
moz_document
	:
	MOZ_DOCUMENT_SYM ws? ( moz_document_function ws?) ( COMMA ws? moz_document_function ws? )*
	LBRACE ws?
		body? //can be empty
	RBRACE
	;

moz_document_function
	:
	URI | MOZ_URL_PREFIX | MOZ_DOMAIN | MOZ_REGEXP
	;

//http://developer.apple.com/library/safari/#documentation/appleapplications/reference/SafariCSSRef/Articles/OtherStandardCSS3Features.html#//apple_ref/doc/uid/TP40007601-SW1
webkitKeyframes
	:
	WEBKIT_KEYFRAMES_SYM ws? atRuleId ws?
	LBRACE ws?
		( webkitKeyframesBlock ws? )*
	RBRACE
	;

webkitKeyframesBlock
	:
	webkitKeyframeSelectors ws?
	LBRACE  ws? syncToFollow
		declarations?
	RBRACE
        | {isScssSource()}?  {isScssSource()}? sass_content SEMI?
	;

webkitKeyframeSelectors
	:
	( {tokenNameEquals("from")}? IDENT | {tokenNameEquals("to")}? IDENT | PERCENTAGE ) ( ws? COMMA ws? ( {tokenNameEquals("from")}? IDENT | {tokenNameEquals("to")}? IDENT | PERCENTAGE ) )*
	;

page
    : PAGE_SYM ws? ( IDENT ws? )? (pseudoPage ws?)?
        LBRACE ws?
            //the grammar in the http://www.w3.org/TR/css3-page/ says the declaration/margins should be delimited by the semicolon,
            //but there's no such char in the examples => making it arbitrary
            ((propertyDeclaration|margin) ws?)? (SEMI ws? ((propertyDeclaration|margin) ws?)?)*
        RBRACE
    ;

counterStyle
    : COUNTER_STYLE_SYM ws? IDENT ws?
        LBRACE ws? syncToDeclarationsRule
		declarations?
        RBRACE
    ;

fontFace
    : FONT_FACE_SYM ws?
        LBRACE ws? syncToDeclarationsRule
		declarations?
        RBRACE
    ;

margin
	: margin_sym ws? LBRACE ws? syncToDeclarationsRule declarations? RBRACE
       ;

margin_sym
	:
       TOPLEFTCORNER_SYM |
       TOPLEFT_SYM |
       TOPCENTER_SYM |
       TOPRIGHT_SYM |
       TOPRIGHTCORNER_SYM |
       BOTTOMLEFTCORNER_SYM |
       BOTTOMLEFT_SYM |
       BOTTOMCENTER_SYM |
       BOTTOMRIGHT_SYM |
       BOTTOMRIGHTCORNER_SYM |
       LEFTTOP_SYM |
       LEFTMIDDLE_SYM |
       LEFTBOTTOM_SYM |
       RIGHTTOP_SYM |
       RIGHTMIDDLE_SYM |
       RIGHTBOTTOM_SYM
       ;

pseudoPage
    : COLON IDENT
    ;

operator
    : SOLIDUS
    | COMMA
    ;

unaryOperator
    : MINUS
    | PLUS
    ;

property
    :

    //parse as scss_declaration_interpolation_expression only if it really contains some #{} content
    //(the IE allows also just ident as its content)
    {isScssSource()}? sass_selector_interpolation_exp
    | {isLessSource()}? less_selector_interpolation_exp
    | VARIABLE
    | IDENT
    | GEN
    | {isCssPreprocessorSource()}? cp_variable

    ; catch[ RecognitionException rce] {
        reportError(rce);
        consumeUntil(input, BitSet.of(COLON));
    }

sass_map
    :
    sass_map_name COLON ws? LPAREN ws? syncToFollow
        //what can be in the map? --- just properties? 
        sass_map_pairs?
    RPAREN ((ws? SASS_DEFAULT) | (ws? SASS_GLOBAL))*
    ;

sass_map_name
    :
    cp_variable
    ;

sass_map_pairs
    :
    (
         ( sass_map_pair ((ws? COMMA)=>ws? COMMA)? ws? )
         |
         ( COMMA ws? )
    )+
    ;

sass_map_pair
    :
        (NUMBER|(STRING (ws? STRING)*)|((function)=>function)|property|sass_map) ws? COLON ws? cp_expression (ws? prio)?
    ;

rule
    :
        (
            (SASS_AT_ROOT (ws selectorsGroup)?) 
            | (SASS_AT_ROOT ws LPAREN ws? {tokenNameEquals("without") || tokenNameEquals("with")}? IDENT /* with || without */ ws? COLON ws? IDENT ws? RPAREN) 
            | selectorsGroup
        ) ws?
    LBRACE ws? syncToFollow
        declarations?
    RBRACE
    ;
    catch[ RecognitionException rce] {
        reportError(rce);
        consumeUntil(input, BitSet.of(RBRACE));
        input.consume(); //consume the RBRACE as well
    }

declarations
    :
       (SEMI ws?)*  declaration (((ws? (SEMI ws?)+)|ws) declaration)* ((ws? (SEMI ws?)+)|ws)?
    |  (SEMI ws?)+ 
    ;

declaration
    :
    (cp_variable_declaration)=>cp_variable_declaration
    | (sass_map)=> sass_map
    | (sass_nested_properties)=>sass_nested_properties
    | (((SASS_AT_ROOT (ws selectorsGroup)? ) | (SASS_AT_ROOT ws LPAREN ws? IDENT ws? COLON ws? IDENT ws? RPAREN) | selectorsGroup) ws? LBRACE)=>rule
    | (propertyDeclaration)=>propertyDeclaration
    //for the error recovery - if the previous synt. predicate fails (an error in the declaration we'll still able to recover INSIDE the declaration
    | (property ws? COLON ~(LBRACE|SEMI|RBRACE)* (RBRACE|SEMI) )=>propertyDeclaration
    | (cp_mixin_declaration)=>cp_mixin_declaration
    | (cp_mixin_call)=> cp_mixin_call (ws? IMPORTANT_SYM)?
    | (cp_mixin_call)=> {isScssSource()}? cp_mixin_call (ws? IMPORTANT_SYM)?    
    | {isCssPreprocessorSource()}? at_rule
    | {isScssSource()}? sass_control
    | {isScssSource()}? sass_extend
    | {isScssSource()}? sass_debug
    | {isScssSource()}? sass_content
    | {isScssSource()}? sass_function_return
    | {isScssSource()}? sass_error
    | {isScssSource()}? importItem
    | GEN
    ;
    catch[ RecognitionException rce] {
        reportError(rce);
        consumeUntil(input, BitSet.of(SEMI));
    }

selectorsGroup
    :
        selector (ws? COMMA ws? selector)* ({isCssPreprocessorSource()}? COMMA)?
    ;

selector
    :  (combinator ws?)? simpleSelectorSequence ( ((ws? combinator ws?)|ws) simpleSelectorSequence)*
       | {isScssSource()}? combinator
    ;

combinator
    :
    PLUS | GREATER | TILDE
    ;

simpleSelectorSequence
	:
        (elementSubsequent | {isScssSource()}? sass_selector_interpolation_exp
        | {isLessSource()}? less_selector_interpolation_exp  ) ((ws? esPred)=>((ws? elementSubsequent) |(ws ({isScssSource()}? sass_selector_interpolation_exp | {isLessSource()}? less_selector_interpolation_exp))))*
	| (typeSelector)=>typeSelector ((ws? esPred)=>((ws? elementSubsequent) | {isScssSource()}? ws sass_selector_interpolation_exp))* 
	;
	catch[ RecognitionException rce] {
            reportError(rce);
            consumeUntil(input, BitSet.of(LBRACE));
        }

//predicate
esPred
    : HASH_SYMBOL | HASH | DOT | LBRACKET | COLON | DCOLON | SASS_EXTEND_ONLY_SELECTOR | {isCssPreprocessorSource()}? LESS_AND
    ;

typeSelector
	options { k = 2; }
 	:  (((IDENT | STAR)? PIPE)=>namespacePrefix)? elementName
 	;

namespacePrefix
  : ( namespacePrefixName | STAR)? PIPE
  ;


elementSubsequent
    :
    (
        {isScssSource()}? sass_extend_only_selector
        | {isCssPreprocessorSource()}? LESS_AND (IDENT | NUMBER)*
        | {isLessSource()}? LESS_AND less_selector_interpolation_exp
    	| cssId
    	| cssClass
        | slAttribute
        | pseudo
    )
    ;

//Error Recovery: Allow the parser to enter the cssId rule even if there's just hash char.
cssId
    : HASH ({isScssSource()}? sass_selector_interpolation_exp)?
      |
        ( HASH_SYMBOL
            ( NAME
              | {isLessSource()}? less_selector_interpolation_exp // #@{var} { ... }
            )
        )
    ;
    catch[ RecognitionException rce] {
        reportError(rce);
        consumeUntil(input, BitSet.of(WS, IDENT, LBRACE));
    }

cssClass
    : (DOT
        (
             {isScssSource()}?  sass_selector_interpolation_exp
            | {isLessSource()}? less_selector_interpolation_exp
            | IDENT
            | NOT
            | GEN
        )
      ) | {tokenNameStartsWith(".")}? DIMENSION
    ;
    catch[ RecognitionException rce] {
        reportError(rce);
        consumeUntil(input, BitSet.of(WS, IDENT, LBRACE));
    }

//using typeSelector even for the universal selector since the lookahead would have to be 3 (IDENT PIPE (IDENT|STAR) :-(
elementName
    : IDENT | GEN | LESS_AND | STAR
    ;

slAttribute
    : LBRACKET
    	namespacePrefix? ws?
        slAttributeName ws?

            (
                (
                      OPEQ
                    | INCLUDES
                    | DASHMATCH
                    | BEGINS
                    | ENDS
                    | CONTAINS
                )
                ws?
                slAttributeValue
                ws?
            )?

      RBRACKET
;
catch[ RecognitionException rce] {
        reportError(rce);
        consumeUntil(input, BitSet.of(IDENT, LBRACE));
    }

//bit similar naming to attrvalue, attrname - but these are different - for functions
slAttributeName
	: IDENT
	;

slAttributeValue
	:
	(
  	      IDENT
              | STRING
        )
        ;

pseudo
    : ( COLON | DCOLON )
             (
                (
                    ( IDENT | GEN )
                    ( // Function
                        ws? LPAREN ws? ( (expression ws?) | STAR )? RPAREN
                    )?
                )
                | {isScssSource()}? sass_interpolation_expression_var
                |
                ( NOT ws? LPAREN ws? (simpleSelectorSequence ws?)? RPAREN )
                | 
                ({isLessSource()}? {tokenNameEquals("extend")}? IDENT ws? LPAREN ws? selectorsGroup? RPAREN)
             ) 
    ;

propertyDeclaration
    :
{isCssPreprocessorSource()}? STAR? property ws? COLON ws? cp_propertyValue //cp_expression may contain the IMPORT_SYM
    | STAR? property ws? COLON ws? propertyValue (ws? prio)?
    
    ;
    catch[ RecognitionException rce] {
        reportError(rce);
        //recovery: if an mismatched token occures inside a declaration is found,
        //then skip all tokens until an end of the rule is found represented by right curly brace
        consumeUntil(input, BitSet.of(SEMI, RBRACE));
    }

//XXX this is a hack for the IMPORT_SYM inside cp_expression
cp_propertyValue
    :
    {isCssPreprocessorSource()}? cp_expression_list
    | propertyValue
    ;

propertyValue
	:
        expression
	;

//an expression wich doesn't contain cp expression operators
expressionPredicate
    options { k = 1; }
    :
    ( ~ (AT_IDENT | STAR | SOLIDUS | LBRACE | SEMI | RBRACE | SASS_VAR) )+ ( SEMI | RBRACE )
    ;

//recovery: syncs the parser to the first identifier in the token input stream or the closing curly bracket
//since the rule matches epsilon it will always be entered
syncToDeclarationsRule
    @init {
        //why sync to DOT? - LESS allows class rules nested
        syncToSet(BitSet.of(IDENT, RBRACE, STAR, DOT));
    }
    	:
    	;

syncTo_RBRACE
    @init {
        syncToRBRACE(1); //initial nest == 1
    }
    	:
    	;

syncTo_SEMI
    @init {
        syncToSet(BitSet.of(SEMI));
    }
    	:
            SEMI
    	;

//synct to computed follow set in the rule
syncToFollow
    @init {
        syncToSet();
    }
    	:
    	;

prio
    : IMPORTANT_SYM
    ;

expression
    : term ( (( ws | (ws? operator ws?) | /* nothing */) term)=> ( ws | (ws? operator ws?) | /* nothing */) term)*
    ;

term
    :
    ( unaryOperator ws? )?
    (
        (functionName ws? LPAREN)=>function //"myfunction(" as predicate
        | VARIABLE
        | IDENT
        | NUMBER
        | URANGE
        | PERCENTAGE
        | LENGTH
        | EMS
        | REM
        | EXS
        | ANGLE
        | TIME
        | FREQ
        | RESOLUTION
        | DIMENSION     //so we can match expression like a:nth-child(3n+1) -- the "3n" is lexed as dimension
        | STRING
        | TILDE ( STRING | LESS_JS_STRING ) //less escaped string/js string
        | LESS_JS_STRING   //less js string
        | GEN
        | URI
        | hexColor
        | {isCssPreprocessorSource()}? cp_variable
        | {isScssSource()}? LESS_AND
        | {isScssSource()}? sass_interpolation_expression_var
        | {isLessSource()}? less_selector_interpolation
        | {isCssPreprocessorSource()}? cp_term_symbol //accept any garbage in preprocessors
    )
    ;

//SASS/LESS expressions workaround
//Bug 233359 - false error in SASS editor
//https://netbeans.org/bugzilla/show_bug.cgi?id=233359
cp_term_symbol
    : PERCENTAGE_SYMBOL //what else?
    ;

function
	: 	functionName ws?
		LPAREN ws?
		(
                    fnAttributes
                    | //empty
		)
		RPAREN
	;
catch[ RecognitionException rce] {
        reportError(rce);
        consumeUntil(input, BitSet.of(RPAREN, SEMI, RBRACE));
}

functionName
        //css spec allows? here just IDENT,
        //but due to some nonstandart MS extension like progid:DXImageTransform.Microsoft.gradien
        //the function name can be a bit more complicated
	:
        (IDENT COLON)? IDENT (DOT IDENT)*
    	;

fnAttributes
    :
    fnAttribute (ws? (COMMA | {isLessSource()}? SEMI) ws? fnAttribute)* ws?
    ;

fnAttribute
	:
        (fnAttributeName ws? (OPEQ|COLON) )=>fnAttributeName ws? (OPEQ|COLON) ws? fnAttributeValue
        | (cp_expression)=> cp_expression
        | expression
	;

fnAttributeName
	:
            IDENT (DOT IDENT)*
            | {isCssPreprocessorSource()}? cp_variable
	;

fnAttributeValue
	:
            term ( (( ws | (ws? SOLIDUS ws?) | /* nothing */) term)=> ( ws | (ws? SOLIDUS ws?) | /* nothing */) term)* //== expression w/o COMMAs
            | {isCssPreprocessorSource()}? cp_math_expression
	;

hexColor
    : HASH
    ;

ws
    : ( WS | NL | COMMENT )+
    ;

//*** LESS SYNTAX ***
//Some additional modifications to the standard syntax rules has also been done.
//ENTRY POINT FROM CSS GRAMMAR
cp_variable_declaration
    :
        {isLessSource()}? cp_variable ws? COLON ws? cp_expression_list
        |
        {isScssSource()}? cp_variable ws? COLON ws? cp_expression_list ((ws? SASS_DEFAULT) | (ws? SASS_GLOBAL))*
    ;

//ENTRY POINT FROM CSS GRAMMAR
cp_variable
    :
        //every token which might possibly begin with the at sign
        {isLessSource()}? ( AT_IDENT | IMPORT_SYM | PAGE_SYM | MEDIA_SYM | NAMESPACE_SYM | CHARSET_SYM | COUNTER_STYLE_SYM | FONT_FACE_SYM | TOPLEFTCORNER_SYM | TOPLEFT_SYM | TOPCENTER_SYM | TOPRIGHT_SYM | TOPRIGHTCORNER_SYM | BOTTOMLEFTCORNER_SYM | BOTTOMLEFT_SYM | BOTTOMCENTER_SYM | BOTTOMRIGHT_SYM | BOTTOMRIGHTCORNER_SYM | LEFTTOP_SYM | LEFTMIDDLE_SYM | LEFTBOTTOM_SYM | RIGHTTOP_SYM | RIGHTMIDDLE_SYM | RIGHTBOTTOM_SYM | MOZ_DOCUMENT_SYM | WEBKIT_KEYFRAMES_SYM | SASS_CONTENT | SASS_MIXIN | SASS_INCLUDE | SASS_EXTEND | SASS_DEBUG | SASS_WARN | SASS_IF | SASS_ELSE | SASS_FOR | SASS_FUNCTION | SASS_RETURN | SASS_EACH | SASS_WHILE | SASS_AT_ROOT )
        |
        {isScssSource()}? ( SASS_VAR )
    ;

//comma separated list of cp_expression-s
cp_expression_list
    :
    (cp_expression) => cp_expression
    ((ws? COMMA ws? cp_expression)=>ws? COMMA ws? cp_expression)*
    ;

//expression:
//-----------
//
//allowed content:
//- boolean expression binary operators: and, or, <, >, <=, ==, ...
//- boolean expression unary operator: not
//- mathematical expression as term: cp_math_expression
//- whitespace separated list of expression-s
//- comma separted list of expressions-s in parenthesis
//
cp_expression
    :
    {isLessSource()}? (LBRACE ws? syncToFollow declarations? RBRACE)
    | (cp_expression_atom) => (cp_expression_atom
    (
        (ws? cp_expression_operator)=>(ws? cp_expression_operator ws?) cp_expression_atom
        | (ws? cp_expression_atom)=>ws? cp_expression_atom
    )*)
    | {isScssSource()}? LPAREN ws? syncToFollow sass_map_pairs? RPAREN
    ;

cp_expression_operator
    :
    key_or | key_and  | CP_EQ | CP_NOT_EQ | LESS | LESS_OR_EQ | GREATER | GREATER_OR_EQ
    ;

cp_expression_atom
    :
        (NOT ws?)?
        (
            (cp_math_expression)=>cp_math_expression
            | LPAREN ws? (cp_expression_list ws?)? RPAREN
        )
    ;

//WS separated list of cp_math_expression-s
cp_math_expressions
    :
    cp_math_expression
    (ws cp_math_expression)*
    ;
//mathematical expression:
//-------------------------
//allowed content:
//- parens: ()
//- binary oparators: +,-,*
//- unary operators: +,-
//- terms
//- SASS interpolation expression where the term is allowed
//
//NOT ALLOWED:
//- COMMAS
//- terms separated just by whitespace - e.g. "one two"
//
cp_math_expression
    :    cp_math_expression_atom
         (
            (ws? (PLUS|MINUS|STAR|SOLIDUS) )=> ws? (PLUS|MINUS|STAR|SOLIDUS) ws? cp_math_expression_atom
         )*
    ;

cp_math_expression_atom
    :
    term
    | IMPORTANT_SYM //cp property value may contain any gargabe - TODO - possibly add other garbage tokens
    | ( unaryOperator ws? )? LPAREN ws? cp_math_expression ws? RPAREN
    ;

//parametric mixins:
//    .border-radius (@radius)
//    .box-shadow (@x: 0, @y: 0, @blur: 1px, @color: #000)
//
//normal mixin has common css syntax: .mixin so cannot be distinguished from a css class
//ENTRY POINT FROM CSS GRAMMAR
cp_mixin_declaration
    :
    (
        {isLessSource()}? (LESS_AND | (((DOT cp_mixin_name) | HASH) ws? LPAREN ws? cp_args_list? RPAREN)) (ws? less_mixin_guarded)?
        |
        {isScssSource()}? SASS_MIXIN ws cp_mixin_name (ws? LPAREN ws? cp_args_list? RPAREN)?
    )
    ws? cp_mixin_block
    ;

//allow: .mixin; .mixin(); .mixin(@param, #77aa00);
//ENTRY POINT FROM CSS GRAMMAR
cp_mixin_call
    :
    (
        {isLessSource()}? (DOT cp_mixin_name | HASH | AT_IDENT | LESS_AND) ((ws? combinator ws?) => ws? combinator ws? (DOT cp_mixin_name | HASH | AT_IDENT | LESS_AND))* ((pseudo)=>pseudo | (ws? LPAREN)=>(ws? LPAREN ws? cp_mixin_call_args? RPAREN))?
        |
        {isScssSource()}? SASS_INCLUDE ws cp_mixin_name (ws? LPAREN ws? cp_mixin_call_args? RPAREN)? (ws? cp_mixin_block)?
    )
    ;

cp_mixin_block
    :
    LBRACE ws? syncToFollow
        (declarations | (webkitKeyframeSelectors) => 
		( webkitKeyframesBlock ws? )*)?
    RBRACE
    ;

cp_mixin_name
    :
    IDENT
    ;

cp_mixin_call_args
    :
    //the term separatos is supposed to be just COMMA, but in some weird old? samples
    //I found semicolon used as a delimiter between arguments
    cp_mixin_call_arg ( (COMMA | SEMI) ws? cp_mixin_call_arg)*  (CP_DOTS ws?)? SEMI?
    ;

cp_mixin_call_arg
    :
    (
        cp_variable ws? COLON ws? cp_expression
        | cp_expression
    ) ws?
    ;

//.box-shadow ("@x: 0, @y: 0, @blur: 1px, @color: #000")
cp_args_list
    :
    //the term separatos is supposed to be just COMMA, but in some weird old? samples
    //I found semicolon used as a delimiter between arguments

    //sass varargs:
    //@mixin box-shadow($shadows...) {} -- note that now also LESS parser allows this incorrectly (minor issue)

    ( cp_arg ( ( COMMA | SEMI ) ws? cp_arg)*  ( (COMMA | SEMI) ws? )? ( (CP_DOTS | LESS_REST) ws? )?)
    |
    (CP_DOTS | LESS_REST) ws?
    ;

//.box-shadow ("@x: 0", @y: 0, @blur: 1px, @color: #000)
cp_arg
    :
    cp_variable ws? ( COLON ws? cp_expression ws?)?
    | {isLessSource()}? IDENT
    ;

//.mixin (@a) "when (lightness(@a) >= 50%)" {
//.mixin (@a) "when (@a > 10), (@a < -10)" { ... }
less_mixin_guarded
    :
    less_when ws? less_condition (ws? (COMMA | key_and) ws? less_condition)*
    ;

//.truth (@a) when (@a) { ... }
//.truth (@a) when (@a = true) { ... }
less_condition
    :
    (NOT ws?)?
    LPAREN ws?
        (
             (cp_variable | less_function_in_condition) ws? (less_condition_operator ws? cp_math_expression)?
        )
    RPAREN
    ;

//.mixin (@a, @b: 0) when ("isnumber(@b)") { ... }
less_function_in_condition
    :
    less_fn_name ws? LPAREN ws? cp_variable ws? RPAREN
    ;

//.mixin (@a, @b: 0) when ("isnumber"(@b)) { ... }
less_fn_name
    :
    IDENT
    ;

less_condition_operator
    :
    GREATER | GREATER_OR_EQ | OPEQ | LESS | LESS_OR_EQ
    ;

less_selector_interpolation_exp :
    (IDENT | MINUS)? less_selector_interpolation (less_selector_interpolation_exp | ( IDENT | MINUS | DIMENSION | LENGTH)+)?
    ;

less_selector_interpolation
    :
    AT_SIGN LBRACE ws? IDENT ws? RBRACE
    ;

//SCSS interpolation expression
sass_selector_interpolation_exp :
    (IDENT | MINUS)? sass_interpolation_expression_var (sass_selector_interpolation_exp | ( IDENT | MINUS | DIMENSION | LENGTH)+)?
    ;

sass_interpolation_expression_var
    :
        HASH_SYMBOL LBRACE WS? cp_expression WS? RBRACE //XXX possibly allow cp_expression inside
    ;

//SASS nested properties:
//.funky {
//  font: 2px/3px {
//    family: fantasy;
//    size: 30em;
//    weight: bold;
//  }
//}
//
//or just:
//
//.funky {
//  font: {
//    family: fantasy;
//    size: 30em;
//    weight: bold;
//  }
//}
sass_nested_properties
    :
    property ws? COLON ws? (propertyValue ws?)? LBRACE ws? syncToFollow declarations? RBRACE
    ;

sass_extend
    :
    SASS_EXTEND ws simpleSelectorSequence (ws SASS_OPTIONAL)?
    ;

sass_extend_only_selector
    :
    SASS_EXTEND_ONLY_SELECTOR sass_selector_interpolation_exp?
    ;

sass_debug
    :
    ( SASS_DEBUG | SASS_WARN ) ws cp_expression
    ;

sass_error
    :
    SASS_ERROR ws STRING
    ;

sass_control
    :
    sass_if | sass_for | sass_each | sass_while
    ;

sass_if
    :
    SASS_IF ws? sass_control_expression ws? sass_control_block (ws? sass_else)?
    ;

sass_else
    :
    SASS_ELSE ws? sass_control_block
    |
    ((SASS_ELSE ws? {tokenNameEquals("if")}? IDENT /* if */) | SASS_ELSEIF) ws? sass_control_expression ws? sass_control_block (ws? sass_else)?
    ;

sass_control_expression
    :
    cp_expression
    ;

sass_for
    :
    SASS_FOR ws cp_variable ws {tokenNameEquals("from")}? IDENT /*from*/ ws cp_math_expression ws {tokenNameEquals("to")|tokenNameEquals("through")}? IDENT /*to, through*/ ws cp_math_expression ws? sass_control_block
    ;

sass_each
    :
    SASS_EACH ws sass_each_variables ws {tokenNameEquals("in")}? IDENT /*in*/ ws (cp_expression_list (ws? COMMA)? ws?)+  sass_control_block
    ;

sass_each_variables
    :
    cp_variable ( (ws? COMMA)=> ws? COMMA ws? cp_variable )*
    ;
 
sass_while
    :
    SASS_WHILE ws sass_control_expression ws? sass_control_block
    ;

sass_control_block
    :
    LBRACE ws? declarations? RBRACE //likely not enough!
    ;

sass_function_declaration
    :
    //I assume there can be not only the return statement in the function block,
    //but so far haven't found any such example so I put the declarations rule inside
    //and added the sass_function_return into the declarations rule itself (not fully correct)
    //as the return should be allowed only from the sass function declaration
    SASS_FUNCTION ws sass_function_name ws? LPAREN ws? cp_args_list? RPAREN ws? LBRACE ws? declarations? RBRACE
    ;

sass_function_name
    :
    IDENT
    ;

sass_function_return
    :
    SASS_RETURN ws cp_expression
    ;

sass_content
    :
    SASS_CONTENT
    ;

less_import_types: 
    {tokenNameIs(new String[]{"LESS", "CSS", "REFERENCE", "INLINE", "ONCE", "MULTIPLE"})}? IDENT
    ; catch[ RecognitionException rce] {
        reportError(rce);
        input.consume();
    }

less_when:
    {tokenNameEquals("when")}? IDENT
    ;

key_and: 
    {tokenNameEquals("and")}? IDENT
    ;

key_or:
    {tokenNameEquals("or")}? IDENT
    ;

key_only:
    {tokenNameEquals("only")}? IDENT
    ;


    
//*** END OF LESS SYNTAX ***

// ==============================================================
// LEXER
//
// The lexer follows the normative section of WWW standard as closely
// as it can. For instance, where the ANTLR lexer returns a token that
// is unambiguous for both ANTLR and lex (the standard defines tokens
// in lex notation), then the token names are equivalent.
//
// Note however that lex has a match order defined as top to bottom
// with longest match first. This results in a fairly inefficent, match,
// REJECT, match REJECT set of operations. ANTLR lexer grammars are actaully
// LL grammars (and hence LL recognizers), which means that we must
// specifically disambiguate longest matches and so on, when the lex
// like normative grammar results in ambiguities as far as ANTLR is concerned.
//
// This means that some tokens will either be combined compared to the
// normative spec, and the paresr will recognize them for what they are.
// In this case, the token will named as XXX_YYY where XXX and YYY are the
// token names used in the specification.
//
// Lex style macro names used in the spec may sometimes be used (in upper case
// version) as fragment rules in this grammar. However ANTLR fragment rules
// are not quite the same as lex macros, in that they generate actual
// methods in the recognizer class, and so may not be as effecient. In
// some cases then, the macro contents are embedded. Annotation indicate when
// this is the case.
//
// See comments in the rules for specific details.
// --------------------------------------------------------------
//
// N.B. CSS 2.1 is defined as case insensitive, but because each character
//      is allowed to be written as in escaped form we basically define each
//      character as a fragment and reuse it in all other rules.
// ==============================================================


// --------------------------------------------------------------
// Define all the fragments of the lexer. These rules neither recognize
// nor create tokens, but must be called from non-fragment rules, which
// do create tokens, using these fragments to either purely define the
// token number, or by calling them to match a certain portion of
// the token string.
//

GEN                     : '@@@';

fragment    HEXCHAR     : ('a'..'f'|'A'..'F'|'0'..'9')  ;

fragment    NONASCII    : '\u0080'..'\uFFFF'            ;   // NB: Upper bound should be \u4177777

fragment    UNICODE     : '\\' HEXCHAR
                                (HEXCHAR
                                    (HEXCHAR
                                        (HEXCHAR
                                            (HEXCHAR HEXCHAR?)?
                                        )?
                                    )?
                                )?
                                ('\r'|'\n'|'\t'|'\f'|' ')*  ;

fragment    ESCAPE      : UNICODE | '\\' ~('\r'|'\n'|'\f'|HEXCHAR)  ;

fragment    NMSTART     : '_'
                        | 'a'..'z'
                        | 'A'..'Z'
                        | NONASCII
                        | ESCAPE
                        ;

fragment    NMCHAR      : '_'
                        | 'a'..'z'
                        | 'A'..'Z'
                        | '0'..'9'
                        | '-'
                        | NONASCII
                        | ESCAPE
                        ;

fragment    NAME        : NMCHAR+   ;

fragment    URL         : ((
                              '['|'!'|'#'|'$'|'%'|'&'|'*'|'~'|'.'|':'|'/'|'?'|'='|';'|','|'+'|'@'|'|' | '{' | '}'
                            | NMCHAR
                          )
                          (
                              '['|'!'|'#'|'$'|'%'|'&'|'*'|'~'|'.'|':'|'/'|'?'|'='|';'|','|'+'|'@'|'|' | WS  | '\"' | '{' | '}'
                            | NMCHAR
                          )*)?
                        ;


// Basic Alpha characters in upper, lower and escaped form.

fragment    A   :   ('a'|'A')
                |   '\\' ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')'1'
                ;
fragment    B   :   ('b'|'B')
                |   '\\' ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')'2'
                ;
fragment    C   :   ('c'|'C')
                |   '\\' ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')'3'
                ;
fragment    D   :   ('d'|'D')
                |   '\\' ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')'4'
                ;
fragment    E   :   ('e'|'E')
                |   '\\' ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')'5'
                ;
fragment    F   :   ('f'|'F')
                |   '\\' ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')'6'
                ;
fragment    G   :   ('g'|'G')
                |   '\\'
                        (
                              'g'
                            | 'G'
                            | ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')'7'
                        )
                ;
fragment    H   :   ('h'|'H')
                | '\\'
                        (
                              'h'
                            | 'H'
                            | ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')'8'
                        )
                ;
fragment    I   :   ('i'|'I')
                | '\\'
                        (
                              'i'
                            | 'I'
                            | ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')'9'
                        )
                ;
fragment    J   :   ('j'|'J')
                | '\\'
                        (
                              'j'
                            | 'J'
                            | ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')('A'|'a')
                        )
                ;
fragment    K   :   ('k'|'K')
                | '\\'
                        (
                              'k'
                            | 'K'
                            | ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')('B'|'b')
                        )
                ;
fragment    L   :   ('l'|'L')
                | '\\'
                        (
                              'l'
                            | 'L'
                            | ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')('C'|'c')
                        )
                ;
fragment    M   :   ('m'|'M')
                | '\\'
                        (
                              'm'
                            | 'M'
                            | ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')('D'|'d')
                        )
                ;
fragment    N   :   ('n'|'N')
                | '\\'
                        (
                              'n'
                            | 'N'
                            | ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')('E'|'e')
                        )
                ;
fragment    O   :   ('o'|'O')
                | '\\'
                        (
                              'o'
                            | 'O'
                            | ('0' ('0' ('0' '0'?)?)?)? ('4'|'6')('F'|'f')
                        )
                ;
fragment    P   :   ('p'|'P')
                | '\\'
                        (
                              'p'
                            | 'P'
                            | ('0' ('0' ('0' '0'?)?)?)? ('5'|'7')('0')
                        )
                ;
fragment    Q   :   ('q'|'Q')
                | '\\'
                        (
                              'q'
                            | 'Q'
                            | ('0' ('0' ('0' '0'?)?)?)? ('5'|'7')('1')
                        )
                ;
fragment    R   :   ('r'|'R')
                | '\\'
                        (
                              'r'
                            | 'R'
                            | ('0' ('0' ('0' '0'?)?)?)? ('5'|'7')('2')
                        )
                ;
fragment    S   :   ('s'|'S')
                | '\\'
                        (
                              's'
                            | 'S'
                            | ('0' ('0' ('0' '0'?)?)?)? ('5'|'7')('3')
                        )
                ;
fragment    T   :   ('t'|'T')
                | '\\'
                        (
                              't'
                            | 'T'
                            | ('0' ('0' ('0' '0'?)?)?)? ('5'|'7')('4')
                        )
                ;
fragment    U   :   ('u'|'U')
                | '\\'
                        (
                              'u'
                            | 'U'
                            | ('0' ('0' ('0' '0'?)?)?)? ('5'|'7')('5')
                        )
                ;
fragment    V   :   ('v'|'V')
                | '\\'
                        (     'v'
                            | 'V'
                            | ('0' ('0' ('0' '0'?)?)?)? ('5'|'7')('6')
                        )
                ;
fragment    W   :   ('w'|'W')
                | '\\'
                        (
                              'w'
                            | 'W'
                            | ('0' ('0' ('0' '0'?)?)?)? ('5'|'7')('7')
                        )
                ;
fragment    X   :   ('x'|'X')
                | '\\'
                        (
                              'x'
                            | 'X'
                            | ('0' ('0' ('0' '0'?)?)?)? ('5'|'7')('8')
                        )
                ;
fragment    Y   :   ('y'|'Y')
                | '\\'
                        (
                              'y'
                            | 'Y'
                            | ('0' ('0' ('0' '0'?)?)?)? ('5'|'7')('9')
                        )
                ;
fragment    Z   :   ('z'|'Z')
                | '\\'
                        (
                              'z'
                            | 'Z'
                            | ('0' ('0' ('0' '0'?)?)?)? ('5'|'7')('A'|'a')
                        )
                ;



// ---------------------
// HTML comment open.   HTML/XML comments may be placed around style sheets so that they
//                      are hidden from higher scope parsing engines such as HTML parsers.
//                      They comment open is therfore ignored by the CSS parser and we hide
//                      it from the ANLTR parser.
//
CDO             : '<!--'

                    {
                        $channel = 3;   // CDO on channel 3 in case we want it later
                    }
                ;

// ---------------------
// HTML comment close.  HTML/XML comments may be placed around style sheets so that they
//                      are hidden from higher scope parsing engines such as HTML parsers.
//                      They comment close is therfore ignored by the CSS parser and we hide
//                      it from the ANLTR parser.
//
CDC             : '-->'

                    {
                        $channel = 4;   // CDC on channel 4 in case we want it later
                    }
                ;

INCLUDES        : '~='      ;
DASHMATCH       : '|='      ;
BEGINS          : '^='      ;
ENDS            : '$='      ;
CONTAINS        : '*='      ;

GREATER         : '>'       ;
LBRACE          : '{'       ;
RBRACE          : '}'       ;
LBRACKET        : '['       ;
RBRACKET        : ']'       ;
OPEQ            : '='       ;
SEMI            : ';'       ;
COLON           : ':'       ;
DCOLON          : '::'       ;
SOLIDUS         : '/'       ;
MINUS           : '-'       ;
PLUS            : '+'       ;
STAR            : '*'       ;
LPAREN          : '('       ;
RPAREN          : ')'       ;
COMMA           : ','       ;
DOT             : '.'       ;
TILDE		: '~'       ;
PIPE            : '|'       ;
PERCENTAGE_SYMBOL
                : '%'       ;
EXCLAMATION_MARK: '!'       ;

CP_EQ           : '=='       ;
CP_NOT_EQ       : '!='       ;
LESS            : '<'       ;
GREATER_OR_EQ   : '>=' | '=>'; //a weird operator variant supported by SASS
LESS_OR_EQ      : '=<' | '<='; //a weird operator variant supported by SASS
LESS_AND        : '&' '-'*    ;
CP_DOTS         : '...';
LESS_REST       : '@rest...';

// -----------------
// Literal strings. Delimited by either ' or "
//
fragment    INVALID :;
STRING          : '\'' ( ~('\r'|'\f'|'\'') )*
                    (
                          '\''
                        | { $type = INVALID; }
                    )

                | '"'  ( ('\\\"') => '\\\"' | ('\\\\') => '\\\\' | ~ ('\r'|'\f'|'"') )*
                    (
                          '"'
                        | { $type = INVALID; }
                    )
                ;

LESS_JS_STRING  : '`' ( ~('\r'|'\f'|'`') )*
                    (
                          '`'
                        | { $type = INVALID; }
                    )
                    ;

NOT		: 'NOT';

// Variable. Used to define properties, that can be used in the grammar by the
//           var function (https://www.w3.org/TR/css-variables-1/)
VARIABLE        : '--' NMSTART NMCHAR*  ;

// -------------
// Identifier.  Identifier tokens pick up properties names and values
//
IDENT           : '-'? NMSTART NMCHAR*  ;

// -------------
// Reference.   Reference to an element in the body we are styling, such as <XXXX id="reference">
//
HASH_SYMBOL     : '#';
HASH            : HASH_SYMBOL NAME;

IMPORTANT_SYM   : EXCLAMATION_MARK (WS|COMMENT)* 'IMPORTANT'   ;

IMPORT_SYM          : '@IMPORT';
PAGE_SYM            : '@PAGE';
MEDIA_SYM           : '@MEDIA';
NAMESPACE_SYM       : '@NAMESPACE' ;
CHARSET_SYM         : '@CHARSET';
COUNTER_STYLE_SYM   : '@COUNTER-STYLE';
FONT_FACE_SYM       : '@FONT-FACE';
SUPPORTS_SYM        : '@SUPPORTS';

TOPLEFTCORNER_SYM     :'@TOP-LEFT-CORNER';
TOPLEFT_SYM           :'@TOP-LEFT';
TOPCENTER_SYM         :'@TOP-CENTER';
TOPRIGHT_SYM          :'@TOP-RIGHT';
TOPRIGHTCORNER_SYM    :'@TOP-RIGHT-CORNER';
BOTTOMLEFTCORNER_SYM  :'@BOTTOM-LEFT-CORNER';
BOTTOMLEFT_SYM        :'@BOTTOM-LEFT';
BOTTOMCENTER_SYM      :'@BOTTOM-CENTER';
BOTTOMRIGHT_SYM       :'@BOTTOM-RIGHT';
BOTTOMRIGHTCORNER_SYM :'@BOTTOM-RIGHT-CORNER';
LEFTTOP_SYM           :'@LEFT-TOP';
LEFTMIDDLE_SYM        :'@LEFT-MIDDLE';
LEFTBOTTOM_SYM        :'@LEFT-BOTTOM';
RIGHTTOP_SYM          :'@RIGHT-TOP';
RIGHTMIDDLE_SYM       :'@RIGHT-MIDDLE';
RIGHTBOTTOM_SYM       :'@RIGHT-BOTTOM';

MOZ_DOCUMENT_SYM      : '@-MOZ-DOCUMENT';
WEBKIT_KEYFRAMES_SYM  :	'@-WEBKIT-KEYFRAMES';

//this generic at rule must be after the last of the specific at rule tokens
SASS_CONTENT        : '@CONTENT';
SASS_MIXIN          : '@MIXIN';
SASS_INCLUDE        : '@INCLUDE';
SASS_EXTEND         : '@EXTEND';
SASS_DEBUG          : '@DEBUG';
SASS_ERROR          : '@ERROR';
SASS_WARN           : '@WARN';
SASS_IF             : '@IF';
SASS_ELSE           : '@ELSE';
SASS_ELSEIF         : '@ELSEIF'; //@elseif
SASS_FOR            : '@FOR';
SASS_FUNCTION       : '@FUNCTION';
SASS_RETURN         : '@RETURN';

SASS_EACH           : '@EACH';
SASS_WHILE          : '@WHILE';
SASS_AT_ROOT        : '@AT-ROOT';

AT_SIGN             : '@';
AT_IDENT	    : (AT_SIGN | (AT_SIGN AT_SIGN)) NMCHAR+;

SASS_VAR            : '$' NMCHAR+;
SASS_DEFAULT        : '!DEFAULT';
SASS_OPTIONAL       : '!OPTIONAL';
SASS_GLOBAL         : '!GLOBAL';

SASS_EXTEND_ONLY_SELECTOR
                    : PERCENTAGE_SYMBOL NMCHAR+;

// ---------
// Numbers. Numbers can be followed by pre-known units or unknown units
//          as well as '%' it is a precentage. Whitespace cannot be between
//          the numebr and teh unit or percent. Hence we scan any numeric, then
//          if we detect one of the lexical sequences for unit tokens, we change
//          the lexical type dynamically.
//
//          Here we first define the various tokens, then we implement the
//          number parsing rule.
//
fragment    EMS         :;  // 'em'
fragment    EXS         :;  // 'ex'
fragment    LENGTH      :;  // 'px'. 'cm', 'mm', 'in'. 'pt', 'pc'
fragment    REM		:;  // 'rem'
fragment    ANGLE       :;  // 'deg', 'rad', 'grad'
fragment    TIME        :;  // 'ms', 's'
fragment    FREQ        :;  // 'khz', 'hz'
fragment    DIMENSION   :;  // nnn'Somethingnotyetinvented'
fragment    PERCENTAGE  :;  // '%'
fragment    RESOLUTION  :;  //dpi,dpcm

NUMBER
    :   (
              '0'..'9'+ ('.' '0'..'9'+)?
            | '.' '0'..'9'+
        )
        (
              (D P (I|C))=>
                D P
                (
                     I | C M
                )
                { $type = RESOLUTION; }

            | (E (M|X))=>
                E
                (
                      M     { $type = EMS;          }
                    | X     { $type = EXS;          }
                )
            | (P(X|T|C))=>
                P
                (
                      X
                    | T
                    | C
                )
                            { $type = LENGTH;       }
            | (C M)=>
                C M         { $type = LENGTH;       }
            | (M (M|S))=>
                M
                (
                      M     { $type = LENGTH;       }

                    | S     { $type = TIME;         }
                )
            | (I N)=>
                I N         { $type = LENGTH;       }

            | (D E G)=>
                D E G       { $type = ANGLE;        }
//            | (R A D)=>
//                R A D       { $type = ANGLE;        }

            | (R (A|E))=>
                R
                (
                   A D       {$type = ANGLE;         }
                 | E M       {$type = REM;           }
                )

            | (S)=>S        { $type = TIME;         }

            | (K? H Z)=>
                K? H    Z   { $type = FREQ;         }

            | IDENT         { $type = DIMENSION;    }

            | PERCENTAGE_SYMBOL { $type = PERCENTAGE;   }

            | // Just a number
        )
    ;

// ------------
// url and uri.
//
URI :   U R L
        '('
            ((WS)=>WS)? (URL|STRING) WS?
        ')'
    ;

fragment HEXCHAR_WILDCARD: '?' | HEXCHAR;

URANGE: ('u'|'U') PLUS HEXCHAR_WILDCARD+ (MINUS HEXCHAR_WILDCARD+)?;

MOZ_URL_PREFIX
	:
	'URL-PREFIX('
            ((WS)=>WS)? (URL|STRING) WS?
        ')'

    	;

MOZ_DOMAIN
	:
	'DOMAIN('
            ((WS)=>WS)? (URL|STRING) WS?
        ')'

    	;

MOZ_REGEXP
	:
	'REGEXP('
            ((WS)=>WS)? STRING WS?
        ')'

        	;

// -------------
// Whitespace.  Though the W3 standard shows a Yacc/Lex style parser and lexer
//              that process the whitespace within the parser, ANTLR does not
//              need to deal with the whitespace directly in the parser.
//
WS
    :
    (' '|'\t')+
    ;

NL
    :
//    ('\r' '\n'? | '\n')
    ('\r' | '\n')+
    ;

// Comments.    Comments may not be nested, may be multilined and are delimited
//              like C comments: /* ..... */
COMMENT
    :
    '/*' ( options { greedy=false; } : .*) '*/'
    ;

LINE_COMMENT
    :
    '//'( options { greedy=false; } : ~('\r' | '\n')* ) {
	if (isCssPreprocessorSource()) {$channel = HIDDEN;}
    }
    ;

// -------------
//  Illegal.    Any other character shoudl not be allowed.
//