Implement write-only semantic checking, the non-r32f/i/u readonly/writeonly check...
[platform/upstream/glslang.git] / glslang / MachineIndependent / Scan.cpp
1 //
2 //Copyright (C) 2002-2005  3Dlabs Inc. Ltd.
3 //Copyright (C) 2013 LunarG, Inc.
4 //
5 //All rights reserved.
6 //
7 //Redistribution and use in source and binary forms, with or without
8 //modification, are permitted provided that the following conditions
9 //are met:
10 //
11 //    Redistributions of source code must retain the above copyright
12 //    notice, this list of conditions and the following disclaimer.
13 //
14 //    Redistributions in binary form must reproduce the above
15 //    copyright notice, this list of conditions and the following
16 //    disclaimer in the documentation and/or other materials provided
17 //    with the distribution.
18 //
19 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20 //    contributors may be used to endorse or promote products derived
21 //    from this software without specific prior written permission.
22 //
23 //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 //"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 //LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 //FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 //COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 //BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 //CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33 //ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 //POSSIBILITY OF SUCH DAMAGE.
35 //
36
37 //
38 // GLSL scanning, leveraging the scanning done by the preprocessor.
39 //
40
41 #include <string.h>
42
43 #include "../Include/Types.h"
44 #include "SymbolTable.h"
45 #include "ParseHelper.h"
46 #include "glslang_tab.cpp.h"
47 #include "ScanContext.h"
48 #include "Scan.h"
49
50 // preprocessor includes
51 #include "preprocessor/PpContext.h"
52 #include "preprocessor/PpTokens.h"
53
54 namespace glslang {
55     
56 // read past any white space
57 void TInputScanner::consumeWhiteSpace(bool& foundNonSpaceTab)
58 {
59     int c = peek();  // don't accidentally consume anything other than whitespace
60     while (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
61         if (c == '\r' || c == '\n')
62             foundNonSpaceTab = true;
63         get();
64         c = peek();
65     }
66 }
67
68 // return true if a comment was actually consumed
69 bool TInputScanner::consumeComment()
70 {
71     if (peek() != '/')
72         return false;
73
74     get();  // consume the '/'
75     int c = peek();
76     if (c == '/') {
77
78         // a '//' style comment
79         get();  // consume the second '/'
80         c = get();
81         do {
82             while (c > 0 && c != '\\' && c != '\r' && c != '\n')
83                 c = get();
84
85             if (c <= 0 || c == '\r' || c == '\n') {
86                 while (c == '\r' || c == '\n')
87                     c = get();
88
89                 // we reached the end of the comment
90                 break;
91             } else {
92                 // it's a '\', so we need to keep going, after skipping what's escaped
93
94                 // read the skipped character
95                 c = get();
96
97                 // if it's a two-character newline, skip both characters
98                 if (c == '\r' && peek() == '\n')
99                     get();
100                 c = get();
101             }
102         } while (true);
103
104         // put back the last non-comment character
105         if (c > 0)
106             unget();
107
108         return true;
109     } else if (c == '*') {
110
111         // a '/*' style comment
112         get();  // consume the '*'
113         c = get();
114         do {
115             while (c > 0 && c != '*')
116                 c = get();
117             if (c == '*') {
118                 c = get();
119                 if (c == '/')
120                     break;  // end of comment
121                 // not end of comment
122             } else // end of input
123                 break;
124         } while (true);
125
126         return true;
127     } else {
128         // it's not a comment, put the '/' back
129         unget();
130
131         return false;
132     }
133 }
134
135 // skip whitespace, then skip a comment, rinse, repeat
136 void TInputScanner::consumeWhitespaceComment(bool& foundNonSpaceTab)
137 {
138     do {
139         consumeWhiteSpace(foundNonSpaceTab);
140  
141         // if not starting a comment now, then done
142         int c = peek();
143         if (c != '/' || c < 0)
144             return;
145
146         // skip potential comment 
147         foundNonSpaceTab = true;
148         if (! consumeComment())
149             return;
150
151     } while (true);
152 }
153
154 // Returns true if there was non-white space (e.g., a comment, newline) before the #version
155 // or no #version was found; otherwise, returns false.  There is no error case, it always
156 // succeeds, but will leave version == 0 if no #version was found.
157 //
158 // Sets versionNotFirstToken based on whether tokens (beyond white space and comments)
159 // appeared before the #version.
160 //
161 // N.B. does not attempt to leave input in any particular known state.  The assumption
162 // is that scanning will start anew, following the rules for the chosen version/profile,
163 // and with a corresponding parsing context.
164 //
165 bool TInputScanner::scanVersion(int& version, EProfile& profile, bool& notFirstToken)
166 {
167     // This function doesn't have to get all the semantics correct,
168     // just find the #version if there is a correct one present.
169     // The preprocessor will have the responsibility of getting all the semantics right.
170
171     bool versionNotFirst = false;  // means not first WRT comments and white space, nothing more
172     notFirstToken = false;         // means not first WRT to real tokens
173     version = 0;  // means not found
174     profile = ENoProfile;
175
176     bool foundNonSpaceTab = false;
177     bool lookingInMiddle = false;
178     int c;
179     do {
180         if (lookingInMiddle) {
181             notFirstToken = true;
182             // make forward progress by finishing off the current line plus extra new lines
183             if (peek() == '\n' || peek() == '\r') {
184                 while (peek() == '\n' || peek() == '\r')
185                     get();
186             } else
187                 do {
188                     c = get();
189                 } while (c > 0 && c != '\n' && c != '\r');
190                 while (peek() == '\n' || peek() == '\r')
191                     get();
192                 if (peek() < 0)
193                     return true;
194         }
195         lookingInMiddle = true;
196
197         // Nominal start, skipping the desktop allowed comments and white space, but tracking if 
198         // something else was found for ES:
199         consumeWhitespaceComment(foundNonSpaceTab);
200         if (foundNonSpaceTab) 
201             versionNotFirst = true;
202
203         // "#"
204         if (get() != '#') {
205             versionNotFirst = true;
206             continue;
207         }
208
209         // whitespace
210         do {
211             c = get();
212         } while (c == ' ' || c == '\t');
213
214         // "version"
215         if (    c != 'v' ||
216             get() != 'e' ||
217             get() != 'r' ||
218             get() != 's' ||
219             get() != 'i' ||
220             get() != 'o' ||
221             get() != 'n') {
222             versionNotFirst = true;
223             continue;
224         }
225
226         // whitespace
227         do {
228             c = get();
229         } while (c == ' ' || c == '\t');
230
231         // version number
232         while (c >= '0' && c <= '9') {
233             version = 10 * version + (c - '0');
234             c = get();
235         }
236         if (version == 0) {
237             versionNotFirst = true;
238             continue;
239         }
240
241         // whitespace
242         while (c == ' ' || c == '\t')
243             c = get();
244
245         // profile
246         const int maxProfileLength = 13;  // not including any 0
247         char profileString[maxProfileLength];
248         int profileLength;
249         for (profileLength = 0; profileLength < maxProfileLength; ++profileLength) {
250             if (c < 0 || c == ' ' || c == '\t' || c == '\n' || c == '\r')
251                 break;
252             profileString[profileLength] = c;
253             c = get();
254         }
255         if (c > 0 && c != ' ' && c != '\t' && c != '\n' && c != '\r') {
256             versionNotFirst = true;
257             continue;
258         }
259
260         if (profileLength == 2 && strncmp(profileString, "es", profileLength) == 0)
261             profile = EEsProfile;
262         else if (profileLength == 4 && strncmp(profileString, "core", profileLength) == 0)
263             profile = ECoreProfile;
264         else if (profileLength == 13 && strncmp(profileString, "compatibility", profileLength) == 0)
265             profile = ECompatibilityProfile;
266
267         return versionNotFirst;
268     } while (true);
269 }
270
271 // Fill this in when doing glslang-level scanning, to hand back to the parser.
272 class TParserToken {
273 public:
274     explicit TParserToken(YYSTYPE& b) : sType(b) { }
275
276     YYSTYPE& sType;
277 };
278
279 } // end namespace glslang
280
281 // This is the function the glslang parser (i.e., bison) calls to get its next token
282 int yylex(YYSTYPE* glslangTokenDesc, glslang::TParseContext& parseContext)
283 {
284     glslang::TParserToken token(*glslangTokenDesc);
285
286     return parseContext.getScanContext()->tokenize(parseContext.getPpContext(), token);
287 }
288
289 namespace {
290
291 // A single global usable by all threads, by all versions, by all languages.
292 // After a single process-level initialization, this is read only and thread safe
293 std::map<std::string, int>* KeywordMap = 0;
294 std::set<std::string>* ReservedSet = 0;
295
296 };
297
298 namespace glslang {
299
300 void TScanContext::fillInKeywordMap()
301 {
302     if (KeywordMap != 0) {
303         // this is really an error, as this should called only once per process
304         // but, the only risk is if two threads called simultaneously
305         return;
306     }
307     KeywordMap = new std::map<std::string, int>;
308
309     (*KeywordMap)["const"] =                   CONST;
310     (*KeywordMap)["uniform"] =                 UNIFORM;
311     (*KeywordMap)["in"] =                      IN;
312     (*KeywordMap)["out"] =                     OUT;
313     (*KeywordMap)["inout"] =                   INOUT;
314     (*KeywordMap)["struct"] =                  STRUCT;
315     (*KeywordMap)["break"] =                   BREAK;
316     (*KeywordMap)["continue"] =                CONTINUE;
317     (*KeywordMap)["do"] =                      DO;
318     (*KeywordMap)["for"] =                     FOR;
319     (*KeywordMap)["while"] =                   WHILE;
320     (*KeywordMap)["switch"] =                  SWITCH;
321     (*KeywordMap)["case"] =                    CASE;
322     (*KeywordMap)["default"] =                 DEFAULT;
323     (*KeywordMap)["if"] =                      IF;
324     (*KeywordMap)["else"] =                    ELSE;
325     (*KeywordMap)["discard"] =                 DISCARD;
326     (*KeywordMap)["return"] =                  RETURN;
327     (*KeywordMap)["void"] =                    VOID;
328     (*KeywordMap)["bool"] =                    BOOL;
329     (*KeywordMap)["float"] =                   FLOAT;
330     (*KeywordMap)["int"] =                     INT;
331     (*KeywordMap)["bvec2"] =                   BVEC2;
332     (*KeywordMap)["bvec3"] =                   BVEC3;
333     (*KeywordMap)["bvec4"] =                   BVEC4;
334     (*KeywordMap)["vec2"] =                    VEC2;
335     (*KeywordMap)["vec3"] =                    VEC3;
336     (*KeywordMap)["vec4"] =                    VEC4;
337     (*KeywordMap)["ivec2"] =                   IVEC2;
338     (*KeywordMap)["ivec3"] =                   IVEC3;
339     (*KeywordMap)["ivec4"] =                   IVEC4;
340     (*KeywordMap)["mat2"] =                    MAT2;
341     (*KeywordMap)["mat3"] =                    MAT3;
342     (*KeywordMap)["mat4"] =                    MAT4;
343     (*KeywordMap)["sampler2D"] =               SAMPLER2D;
344     (*KeywordMap)["samplerCube"] =             SAMPLERCUBE;
345     (*KeywordMap)["true"] =                    BOOLCONSTANT;
346     (*KeywordMap)["false"] =                   BOOLCONSTANT;
347     (*KeywordMap)["attribute"] =               ATTRIBUTE;
348     (*KeywordMap)["varying"] =                 VARYING;
349     (*KeywordMap)["buffer"] =                  BUFFER;
350     (*KeywordMap)["coherent"] =                COHERENT;
351     (*KeywordMap)["restrict"] =                RESTRICT;
352     (*KeywordMap)["readonly"] =                READONLY;
353     (*KeywordMap)["writeonly"] =               WRITEONLY;
354     (*KeywordMap)["atomic_uint"] =             ATOMIC_UINT;
355     (*KeywordMap)["volatile"] =                VOLATILE;
356     (*KeywordMap)["layout"] =                  LAYOUT;
357     (*KeywordMap)["shared"] =                  SHARED;
358     (*KeywordMap)["patch"] =                   PATCH;
359     (*KeywordMap)["sample"] =                  SAMPLE;
360     (*KeywordMap)["subroutine"] =              SUBROUTINE;
361     (*KeywordMap)["highp"] =                   HIGH_PRECISION;
362     (*KeywordMap)["mediump"] =                 MEDIUM_PRECISION;
363     (*KeywordMap)["lowp"] =                    LOW_PRECISION;
364     (*KeywordMap)["precision"] =               PRECISION;
365     (*KeywordMap)["mat2x2"] =                  MAT2X2;
366     (*KeywordMap)["mat2x3"] =                  MAT2X3;
367     (*KeywordMap)["mat2x4"] =                  MAT2X4;
368     (*KeywordMap)["mat3x2"] =                  MAT3X2;
369     (*KeywordMap)["mat3x3"] =                  MAT3X3;
370     (*KeywordMap)["mat3x4"] =                  MAT3X4;
371     (*KeywordMap)["mat4x2"] =                  MAT4X2;
372     (*KeywordMap)["mat4x3"] =                  MAT4X3;
373     (*KeywordMap)["mat4x4"] =                  MAT4X4;
374     (*KeywordMap)["dmat2"] =                   DMAT2;
375     (*KeywordMap)["dmat3"] =                   DMAT3;
376     (*KeywordMap)["dmat4"] =                   DMAT4;
377     (*KeywordMap)["dmat2x2"] =                 DMAT2X2;
378     (*KeywordMap)["dmat2x3"] =                 DMAT2X3;
379     (*KeywordMap)["dmat2x4"] =                 DMAT2X4;
380     (*KeywordMap)["dmat3x2"] =                 DMAT3X2;
381     (*KeywordMap)["dmat3x3"] =                 DMAT3X3;
382     (*KeywordMap)["dmat3x4"] =                 DMAT3X4;
383     (*KeywordMap)["dmat4x2"] =                 DMAT4X2;
384     (*KeywordMap)["dmat4x3"] =                 DMAT4X3;
385     (*KeywordMap)["dmat4x4"] =                 DMAT4X4;
386     (*KeywordMap)["image1D"] =                 IMAGE1D;
387     (*KeywordMap)["iimage1D"] =                IIMAGE1D;
388     (*KeywordMap)["uimage1D"] =                UIMAGE1D;
389     (*KeywordMap)["image2D"] =                 IMAGE2D;
390     (*KeywordMap)["iimage2D"] =                IIMAGE2D;
391     (*KeywordMap)["uimage2D"] =                UIMAGE2D;
392     (*KeywordMap)["image3D"] =                 IMAGE3D;
393     (*KeywordMap)["iimage3D"] =                IIMAGE3D;
394     (*KeywordMap)["uimage3D"] =                UIMAGE3D;
395     (*KeywordMap)["image2DRect"] =             IMAGE2DRECT;
396     (*KeywordMap)["iimage2DRect"] =            IIMAGE2DRECT;
397     (*KeywordMap)["uimage2DRect"] =            UIMAGE2DRECT;
398     (*KeywordMap)["imageCube"] =               IMAGECUBE;
399     (*KeywordMap)["iimageCube"] =              IIMAGECUBE;
400     (*KeywordMap)["uimageCube"] =              UIMAGECUBE;
401     (*KeywordMap)["imageBuffer"] =             IMAGEBUFFER;
402     (*KeywordMap)["iimageBuffer"] =            IIMAGEBUFFER;
403     (*KeywordMap)["uimageBuffer"] =            UIMAGEBUFFER;
404     (*KeywordMap)["image1DArray"] =            IMAGE1DARRAY;
405     (*KeywordMap)["iimage1DArray"] =           IIMAGE1DARRAY;
406     (*KeywordMap)["uimage1DArray"] =           UIMAGE1DARRAY;
407     (*KeywordMap)["image2DArray"] =            IMAGE2DARRAY;
408     (*KeywordMap)["iimage2DArray"] =           IIMAGE2DARRAY;
409     (*KeywordMap)["uimage2DArray"] =           UIMAGE2DARRAY;
410     (*KeywordMap)["imageCubeArray"] =          IMAGECUBEARRAY;
411     (*KeywordMap)["iimageCubeArray"] =         IIMAGECUBEARRAY;
412     (*KeywordMap)["uimageCubeArray"] =         UIMAGECUBEARRAY;
413     (*KeywordMap)["image2DMS"] =               IMAGE2DMS;
414     (*KeywordMap)["iimage2DMS"] =              IIMAGE2DMS;
415     (*KeywordMap)["uimage2DMS"] =              UIMAGE2DMS;
416     (*KeywordMap)["image2DMSArray"] =          IMAGE2DMSARRAY;
417     (*KeywordMap)["iimage2DMSArray"] =         IIMAGE2DMSARRAY;
418     (*KeywordMap)["uimage2DMSArray"] =         UIMAGE2DMSARRAY;
419     (*KeywordMap)["double"] =                  DOUBLE;
420     (*KeywordMap)["dvec2"] =                   DVEC2;
421     (*KeywordMap)["dvec3"] =                   DVEC3;
422     (*KeywordMap)["dvec4"] =                   DVEC4;
423     (*KeywordMap)["samplerCubeArray"] =        SAMPLERCUBEARRAY;
424     (*KeywordMap)["samplerCubeArrayShadow"] =  SAMPLERCUBEARRAYSHADOW;
425     (*KeywordMap)["isamplerCubeArray"] =       ISAMPLERCUBEARRAY;
426     (*KeywordMap)["usamplerCubeArray"] =       USAMPLERCUBEARRAY;
427     (*KeywordMap)["sampler1DArrayShadow"] =    SAMPLER1DARRAYSHADOW;
428     (*KeywordMap)["isampler1DArray"] =         ISAMPLER1DARRAY;
429     (*KeywordMap)["usampler1D"] =              USAMPLER1D;
430     (*KeywordMap)["isampler1D"] =              ISAMPLER1D;
431     (*KeywordMap)["usampler1DArray"] =         USAMPLER1DARRAY;
432     (*KeywordMap)["samplerBuffer"] =           SAMPLERBUFFER;
433     (*KeywordMap)["uint"] =                    UINT;
434     (*KeywordMap)["uvec2"] =                   UVEC2;
435     (*KeywordMap)["uvec3"] =                   UVEC3;
436     (*KeywordMap)["uvec4"] =                   UVEC4;
437     (*KeywordMap)["samplerCubeShadow"] =       SAMPLERCUBESHADOW;
438     (*KeywordMap)["sampler2DArray"] =          SAMPLER2DARRAY;
439     (*KeywordMap)["sampler2DArrayShadow"] =    SAMPLER2DARRAYSHADOW;
440     (*KeywordMap)["isampler2D"] =              ISAMPLER2D;
441     (*KeywordMap)["isampler3D"] =              ISAMPLER3D;
442     (*KeywordMap)["isamplerCube"] =            ISAMPLERCUBE;
443     (*KeywordMap)["isampler2DArray"] =         ISAMPLER2DARRAY;
444     (*KeywordMap)["usampler2D"] =              USAMPLER2D;
445     (*KeywordMap)["usampler3D"] =              USAMPLER3D;
446     (*KeywordMap)["usamplerCube"] =            USAMPLERCUBE;
447     (*KeywordMap)["usampler2DArray"] =         USAMPLER2DARRAY;
448     (*KeywordMap)["isampler2DRect"] =          ISAMPLER2DRECT;
449     (*KeywordMap)["usampler2DRect"] =          USAMPLER2DRECT;
450     (*KeywordMap)["isamplerBuffer"] =          ISAMPLERBUFFER;
451     (*KeywordMap)["usamplerBuffer"] =          USAMPLERBUFFER;
452     (*KeywordMap)["sampler2DMS"] =             SAMPLER2DMS;
453     (*KeywordMap)["isampler2DMS"] =            ISAMPLER2DMS;
454     (*KeywordMap)["usampler2DMS"] =            USAMPLER2DMS;
455     (*KeywordMap)["sampler2DMSArray"] =        SAMPLER2DMSARRAY;
456     (*KeywordMap)["isampler2DMSArray"] =       ISAMPLER2DMSARRAY;
457     (*KeywordMap)["usampler2DMSArray"] =       USAMPLER2DMSARRAY;
458     (*KeywordMap)["sampler1D"] =               SAMPLER1D;
459     (*KeywordMap)["sampler1DShadow"] =         SAMPLER1DSHADOW;
460     (*KeywordMap)["sampler3D"] =               SAMPLER3D;
461     (*KeywordMap)["sampler2DShadow"] =         SAMPLER2DSHADOW;
462     (*KeywordMap)["sampler2DRect"] =           SAMPLER2DRECT;
463     (*KeywordMap)["sampler2DRectShadow"] =     SAMPLER2DRECTSHADOW;
464     (*KeywordMap)["sampler1DArray"] =          SAMPLER1DARRAY;
465     (*KeywordMap)["samplerExternalOES"] =      SAMPLEREXTERNALOES; // GL_OES_EGL_image_external
466     (*KeywordMap)["noperspective"] =           NOPERSPECTIVE;
467     (*KeywordMap)["smooth"] =                  SMOOTH;
468     (*KeywordMap)["flat"] =                    FLAT;
469     (*KeywordMap)["centroid"] =                CENTROID;
470     (*KeywordMap)["precise"] =                 PRECISE;
471     (*KeywordMap)["invariant"] =               INVARIANT;
472     (*KeywordMap)["packed"] =                  PACKED;
473     (*KeywordMap)["resource"] =                RESOURCE;
474     (*KeywordMap)["superp"] =                  SUPERP;
475
476     ReservedSet = new std::set<std::string>;
477     
478     ReservedSet->insert("common");
479     ReservedSet->insert("partition");
480     ReservedSet->insert("active");
481     ReservedSet->insert("asm");
482     ReservedSet->insert("class");
483     ReservedSet->insert("union");
484     ReservedSet->insert("enum");
485     ReservedSet->insert("typedef");
486     ReservedSet->insert("template");
487     ReservedSet->insert("this");
488     ReservedSet->insert("goto");
489     ReservedSet->insert("inline");
490     ReservedSet->insert("noinline");
491     ReservedSet->insert("public");
492     ReservedSet->insert("static");
493     ReservedSet->insert("extern");
494     ReservedSet->insert("external");
495     ReservedSet->insert("interface");
496     ReservedSet->insert("long");
497     ReservedSet->insert("short");
498     ReservedSet->insert("half");
499     ReservedSet->insert("fixed");
500     ReservedSet->insert("unsigned");
501     ReservedSet->insert("input");
502     ReservedSet->insert("output");
503     ReservedSet->insert("hvec2");
504     ReservedSet->insert("hvec3");
505     ReservedSet->insert("hvec4");
506     ReservedSet->insert("fvec2");
507     ReservedSet->insert("fvec3");
508     ReservedSet->insert("fvec4");
509     ReservedSet->insert("sampler3DRect");
510     ReservedSet->insert("filter");
511     ReservedSet->insert("sizeof");
512     ReservedSet->insert("cast");
513     ReservedSet->insert("namespace");
514     ReservedSet->insert("using");
515 }
516
517 int TScanContext::tokenize(TPpContext* pp, TParserToken& token)
518 {
519     do {
520         parserToken = &token;
521         TPpToken ppToken;
522         tokenText = pp->tokenize(&ppToken);
523         if (tokenText == 0)
524             return 0;
525
526         loc = ppToken.loc;
527         parserToken->sType.lex.loc = loc;
528         switch (ppToken.token) {
529         case ';':  afterType = false;   return SEMICOLON;
530         case ',':  afterType = false;   return COMMA;
531         case ':':                       return COLON;
532         case '=':  afterType = false;   return EQUAL;
533         case '(':  afterType = false;   return LEFT_PAREN;
534         case ')':  afterType = false;   return RIGHT_PAREN;
535         case '.':  field = true;        return DOT;
536         case '!':                       return BANG;
537         case '-':                       return DASH;
538         case '~':                       return TILDE;
539         case '+':                       return PLUS;
540         case '*':                       return STAR;
541         case '/':                       return SLASH;
542         case '%':                       return PERCENT;
543         case '<':                       return LEFT_ANGLE;
544         case '>':                       return RIGHT_ANGLE;
545         case '|':                       return VERTICAL_BAR;
546         case '^':                       return CARET;
547         case '&':                       return AMPERSAND;
548         case '?':                       return QUESTION;
549         case '[':                       return LEFT_BRACKET;
550         case ']':                       return RIGHT_BRACKET;
551         case '{':                       return LEFT_BRACE;
552         case '}':                       return RIGHT_BRACE;
553         case '\\':
554             parseContext.error(loc, "illegal use of escape character", "\\", "");
555             break;
556
557         case CPP_AND_OP:                return AND_OP;
558         case CPP_SUB_ASSIGN:            return SUB_ASSIGN;
559         case CPP_MOD_ASSIGN:            return MOD_ASSIGN;
560         case CPP_ADD_ASSIGN:            return ADD_ASSIGN;
561         case CPP_DIV_ASSIGN:            return DIV_ASSIGN;
562         case CPP_MUL_ASSIGN:            return MUL_ASSIGN;
563         case CPP_EQ_OP:                 return EQ_OP;
564         case CPP_XOR_OP:                return XOR_OP;
565         case CPP_GE_OP:                 return GE_OP;
566         case CPP_RIGHT_OP:              return RIGHT_OP;
567         case CPP_LE_OP:                 return LE_OP;
568         case CPP_LEFT_OP:               return LEFT_OP;
569         case CPP_DEC_OP:                return DEC_OP;
570         case CPP_NE_OP:                 return NE_OP;
571         case CPP_OR_OP:                 return OR_OP;
572         case CPP_INC_OP:                return INC_OP;
573         case CPP_RIGHT_ASSIGN:          return RIGHT_ASSIGN;
574         case CPP_LEFT_ASSIGN:           return LEFT_ASSIGN;
575         case CPP_AND_ASSIGN:            return AND_ASSIGN;
576         case CPP_OR_ASSIGN:             return OR_ASSIGN;
577         case CPP_XOR_ASSIGN:            return XOR_ASSIGN;
578                                    
579         case CPP_INTCONSTANT:           parserToken->sType.lex.i = ppToken.ival;       return INTCONSTANT;
580         case CPP_UINTCONSTANT:          parserToken->sType.lex.i = ppToken.ival;       return UINTCONSTANT;
581         case CPP_FLOATCONSTANT:         parserToken->sType.lex.d = ppToken.dval;       return FLOATCONSTANT;
582         case CPP_DOUBLECONSTANT:        parserToken->sType.lex.d = ppToken.dval;       return DOUBLECONSTANT;
583         case CPP_IDENTIFIER:            return tokenizeIdentifier();
584
585         case EOF:                       return 0;
586                                    
587         default:
588             char buf[2];
589             buf[0] = ppToken.token;
590             buf[1] = 0;
591             parseContext.error(loc, "unexpected token", buf, "");
592             break;
593         }
594     } while (true);
595 }
596
597 int TScanContext::tokenizeIdentifier()
598 {
599     if (ReservedSet->find(tokenText) != ReservedSet->end())
600         return reservedWord();
601
602     std::map<std::string, int>::const_iterator it = KeywordMap->find(tokenText);
603     if (it == KeywordMap->end()) {
604         // Should have an identifier of some sort
605         return identifierOrType();
606     }
607     keyword = it->second;
608     field = false;
609
610     switch (keyword) {
611     case CONST:
612     case UNIFORM:
613     case IN:
614     case OUT:
615     case INOUT:
616     case STRUCT:
617     case BREAK:
618     case CONTINUE:
619     case DO:
620     case FOR:
621     case WHILE:
622     case IF:
623     case ELSE:
624     case DISCARD:
625     case RETURN:
626     case CASE:
627         return keyword;
628
629     case SWITCH:
630     case DEFAULT:
631         if ((parseContext.profile == EEsProfile && parseContext.version < 300) ||
632             (parseContext.profile != EEsProfile && parseContext.version < 130))
633             reservedWord();
634         return keyword;
635
636     case VOID:
637     case BOOL:
638     case FLOAT:
639     case INT:
640     case BVEC2:
641     case BVEC3:
642     case BVEC4:
643     case VEC2:
644     case VEC3:
645     case VEC4:
646     case IVEC2:
647     case IVEC3:
648     case IVEC4:
649     case MAT2:
650     case MAT3:
651     case MAT4:
652     case SAMPLER2D:
653     case SAMPLERCUBE:
654         afterType = true;
655         return keyword;
656
657     case BOOLCONSTANT:
658         if (strcmp("true", tokenText) == 0)
659             parserToken->sType.lex.b = true;
660         else
661             parserToken->sType.lex.b = false;
662         return keyword;
663
664     case ATTRIBUTE:
665     case VARYING:
666         if (parseContext.profile == EEsProfile && parseContext.version >= 300)
667             reservedWord();
668         return keyword;
669
670     case BUFFER:
671         if ((parseContext.profile == EEsProfile && parseContext.version < 310) || 
672             (parseContext.profile != EEsProfile && parseContext.version < 430))
673             return identifierOrType();
674         return keyword;
675
676     case ATOMIC_UINT:
677         if (parseContext.profile == EEsProfile && parseContext.version >= 310 ||
678             parseContext.extensionsTurnedOn(1, &GL_ARB_shader_atomic_counters))
679             return keyword;
680         return es30ReservedFromGLSL(420);
681
682     case COHERENT:
683     case RESTRICT:
684     case READONLY:
685     case WRITEONLY:
686         if (parseContext.profile == EEsProfile && parseContext.version >= 310)
687             return keyword;
688         return es30ReservedFromGLSL(parseContext.extensionsTurnedOn(1, &GL_ARB_shader_image_load_store) ? 130 : 420);
689
690     case VOLATILE:
691         if (parseContext.profile == EEsProfile && parseContext.version >= 310)
692             return keyword;
693         if (! parseContext.symbolTable.atBuiltInLevel() && (parseContext.profile == EEsProfile || (parseContext.version < 420 && ! parseContext.extensionsTurnedOn(1, &GL_ARB_shader_image_load_store))))
694             reservedWord();
695         return keyword;
696
697     case LAYOUT:
698         if ((parseContext.profile == EEsProfile && parseContext.version < 300) ||
699             (parseContext.profile != EEsProfile && parseContext.version < 140 &&
700             ! parseContext.extensionsTurnedOn(1, &GL_ARB_shading_language_420pack)))
701             return identifierOrType();
702         return keyword;
703
704     case SHARED:
705         if ((parseContext.profile == EEsProfile && parseContext.version < 300) ||
706             (parseContext.profile != EEsProfile && parseContext.version < 140))
707             return identifierOrType();
708         return keyword;
709
710     case PATCH:
711         if (parseContext.symbolTable.atBuiltInLevel() || parseContext.extensionsTurnedOn(1, &GL_ARB_tessellation_shader))
712             return es30ReservedFromGLSL(150);
713         else
714             return es30ReservedFromGLSL(400);
715
716     case SAMPLE:
717     case SUBROUTINE:
718         return es30ReservedFromGLSL(400);
719
720     case HIGH_PRECISION:
721     case MEDIUM_PRECISION:
722     case LOW_PRECISION:
723     case PRECISION:
724         return precisionKeyword();
725
726     case MAT2X2:
727     case MAT2X3:
728     case MAT2X4:
729     case MAT3X2:
730     case MAT3X3:
731     case MAT3X4:
732     case MAT4X2:
733     case MAT4X3:
734     case MAT4X4:        
735         return matNxM();
736
737     case DMAT2:
738     case DMAT3:
739     case DMAT4:
740     case DMAT2X2:
741     case DMAT2X3:
742     case DMAT2X4:
743     case DMAT3X2:
744     case DMAT3X3:
745     case DMAT3X4:
746     case DMAT4X2:
747     case DMAT4X3:
748     case DMAT4X4:
749         return dMat();
750
751     case IMAGE1D:
752     case IIMAGE1D:
753     case UIMAGE1D:
754     case IMAGE1DARRAY:
755     case IIMAGE1DARRAY:
756     case UIMAGE1DARRAY:
757     case IMAGE2DRECT:
758     case IIMAGE2DRECT:
759     case UIMAGE2DRECT:
760     case IMAGEBUFFER:
761     case IIMAGEBUFFER:
762     case UIMAGEBUFFER:
763         return firstGenerationImage(false);
764
765     case IMAGE2D:
766     case IIMAGE2D:
767     case UIMAGE2D:
768     case IMAGE3D:
769     case IIMAGE3D:
770     case UIMAGE3D:
771     case IMAGECUBE:
772     case IIMAGECUBE:
773     case UIMAGECUBE:
774     case IMAGE2DARRAY:
775     case IIMAGE2DARRAY:
776     case UIMAGE2DARRAY:
777         return firstGenerationImage(true);
778
779     case IMAGECUBEARRAY:
780     case IIMAGECUBEARRAY:
781     case UIMAGECUBEARRAY:        
782     case IMAGE2DMS:
783     case IIMAGE2DMS:
784     case UIMAGE2DMS:
785     case IMAGE2DMSARRAY:
786     case IIMAGE2DMSARRAY:
787     case UIMAGE2DMSARRAY:
788         return secondGenerationImage();
789
790     case DOUBLE:
791     case DVEC2:
792     case DVEC3:
793     case DVEC4:
794         afterType = true;
795         if (parseContext.profile == EEsProfile || parseContext.version < 400)
796             reservedWord();
797         return keyword;
798
799     case SAMPLERCUBEARRAY:
800     case SAMPLERCUBEARRAYSHADOW:
801     case ISAMPLERCUBEARRAY:
802     case USAMPLERCUBEARRAY:
803         afterType = true;
804         if (parseContext.profile == EEsProfile || (parseContext.version < 400 && ! parseContext.extensionsTurnedOn(1, &GL_ARB_texture_cube_map_array)))
805             reservedWord();
806         return keyword;
807
808     case ISAMPLER1D:
809     case ISAMPLER1DARRAY:
810     case SAMPLER1DARRAYSHADOW:
811     case USAMPLER1D:
812     case USAMPLER1DARRAY:
813     case SAMPLERBUFFER:
814         afterType = true;
815         return es30ReservedFromGLSL(130);
816
817     case UINT:
818     case UVEC2:
819     case UVEC3:
820     case UVEC4:
821     case SAMPLERCUBESHADOW:
822     case SAMPLER2DARRAY:
823     case SAMPLER2DARRAYSHADOW:
824     case ISAMPLER2D:
825     case ISAMPLER3D:
826     case ISAMPLERCUBE:
827     case ISAMPLER2DARRAY:
828     case USAMPLER2D:
829     case USAMPLER3D:
830     case USAMPLERCUBE:
831     case USAMPLER2DARRAY:
832         afterType = true;
833         return nonreservedKeyword(300, 130);
834         
835     case ISAMPLER2DRECT:
836     case USAMPLER2DRECT:
837     case ISAMPLERBUFFER:
838     case USAMPLERBUFFER:
839         afterType = true;
840         return es30ReservedFromGLSL(140);
841         
842     case SAMPLER2DMS:
843     case ISAMPLER2DMS:
844     case USAMPLER2DMS:
845         afterType = true;
846         if (parseContext.profile == EEsProfile && parseContext.version >= 310)
847             return keyword;
848         return es30ReservedFromGLSL(150);
849
850     case SAMPLER2DMSARRAY:
851     case ISAMPLER2DMSARRAY:
852     case USAMPLER2DMSARRAY:
853         afterType = true;
854         return es30ReservedFromGLSL(150);
855
856     case SAMPLER1D:
857     case SAMPLER1DSHADOW:
858         afterType = true;
859         if (parseContext.profile == EEsProfile)
860             reservedWord();
861         return keyword;
862
863     case SAMPLER3D:
864         afterType = true;
865         if (parseContext.profile == EEsProfile && parseContext.version < 300) {
866             if (! parseContext.extensionsTurnedOn(1, &GL_OES_texture_3D))
867                 reservedWord();
868         }
869         return keyword;
870
871     case SAMPLER2DSHADOW:
872         afterType = true;
873         if (parseContext.profile == EEsProfile && parseContext.version < 300)
874             reservedWord();
875         return keyword;
876
877     case SAMPLER2DRECT:
878     case SAMPLER2DRECTSHADOW:
879         afterType = true;
880         if (parseContext.profile == EEsProfile)
881             reservedWord();
882         else if (parseContext.version < 140 && ! parseContext.symbolTable.atBuiltInLevel() && ! parseContext.extensionsTurnedOn(1, &GL_ARB_texture_rectangle)) {
883             if (parseContext.messages & EShMsgRelaxedErrors)
884                 parseContext.requireExtensions(loc, 1, &GL_ARB_texture_rectangle, "texture-rectangle sampler keyword");
885             else
886                 reservedWord();
887         }
888         return keyword;
889
890     case SAMPLER1DARRAY:
891         afterType = true;
892         if (parseContext.profile == EEsProfile && parseContext.version == 300)
893             reservedWord();
894         else if ((parseContext.profile == EEsProfile && parseContext.version < 300) ||
895                  (parseContext.profile != EEsProfile && parseContext.version < 130))
896             return identifierOrType();
897         return keyword;
898
899     case SAMPLEREXTERNALOES:
900         afterType = true;
901         if (parseContext.symbolTable.atBuiltInLevel() || parseContext.extensionsTurnedOn(1, &GL_OES_EGL_image_external))
902             return keyword;
903         return identifierOrType();
904
905     case NOPERSPECTIVE:
906         return es30ReservedFromGLSL(130);
907         
908     case SMOOTH:
909         if ((parseContext.profile == EEsProfile && parseContext.version < 300) ||
910             (parseContext.profile != EEsProfile && parseContext.version < 130))
911             return identifierOrType();
912         return keyword;
913
914     case FLAT:
915         if (parseContext.profile == EEsProfile && parseContext.version < 300)
916             reservedWord();
917         else if (parseContext.profile != EEsProfile && parseContext.version < 130)
918             return identifierOrType();
919         return keyword;
920
921     case CENTROID:
922         if (parseContext.version < 120)
923             return identifierOrType();
924         return keyword;
925
926     case PRECISE:
927         if (parseContext.profile == EEsProfile && parseContext.version >= 310)
928             reservedWord();
929         else if (parseContext.profile == EEsProfile ||
930             (parseContext.profile != EEsProfile && parseContext.version < 400))
931             return identifierOrType();
932         return keyword;
933
934     case INVARIANT:
935         if (parseContext.profile != EEsProfile && parseContext.version < 120)
936             return identifierOrType();
937         return keyword;
938
939     case PACKED:
940         if ((parseContext.profile == EEsProfile && parseContext.version < 300) ||
941             (parseContext.profile != EEsProfile && parseContext.version < 330))
942             return reservedWord();
943         return identifierOrType();
944
945     case RESOURCE:
946     {
947         bool reserved = (parseContext.profile == EEsProfile && parseContext.version >= 300) ||
948                         (parseContext.profile != EEsProfile && parseContext.version >= 420);
949         return identifierOrReserved(reserved);
950     }
951     case SUPERP:
952     {
953         bool reserved = parseContext.profile == EEsProfile || parseContext.version >= 130;
954         return identifierOrReserved(reserved);
955     }
956     
957     default:
958         parseContext.infoSink.info.message(EPrefixInternalError, "Unknown glslang keyword", loc);
959         return 0;
960     }
961 }
962
963 int TScanContext::identifierOrType()
964 {
965     parserToken->sType.lex.string = NewPoolTString(tokenText);
966     if (field) {
967         field = false;
968  
969         return FIELD_SELECTION;
970     }
971
972     parserToken->sType.lex.symbol = parseContext.symbolTable.find(*parserToken->sType.lex.string);
973     if (afterType == false && parserToken->sType.lex.symbol) {
974         if (const TVariable* variable = parserToken->sType.lex.symbol->getAsVariable()) {
975             if (variable->isUserType()) {
976                 afterType = true;
977
978                 return TYPE_NAME;
979             }
980         }
981     }
982
983     return IDENTIFIER;
984 }
985
986 // Give an error for use of a reserved symbol.
987 // However, allow built-in declarations to use reserved words, to allow
988 // extension support before the extension is enabled.
989 int TScanContext::reservedWord()
990 {
991     if (! parseContext.symbolTable.atBuiltInLevel())
992         parseContext.error(loc, "Reserved word.", tokenText, "", "");
993
994     return 0;
995 }
996
997 int TScanContext::identifierOrReserved(bool reserved)
998 {
999     if (reserved) {
1000         reservedWord();
1001
1002         return 0;
1003     }
1004
1005     if (parseContext.forwardCompatible)
1006         parseContext.warn(loc, "using future reserved keyword", tokenText, "");
1007
1008     return identifierOrType();
1009 }
1010
1011 // For keywords that suddenly showed up on non-ES (not previously reserved)
1012 // but then got reserved by ES 3.0.
1013 int TScanContext::es30ReservedFromGLSL(int version)
1014 {
1015     if (parseContext.symbolTable.atBuiltInLevel())
1016         return keyword;
1017
1018     if ((parseContext.profile == EEsProfile && parseContext.version < 300) ||
1019         (parseContext.profile != EEsProfile && parseContext.version < version)) {
1020             if (parseContext.forwardCompatible)
1021                 parseContext.warn(loc, "future reserved word in ES 300 and keyword in GLSL", tokenText, "");
1022
1023             return identifierOrType();
1024     } else if (parseContext.profile == EEsProfile && parseContext.version >= 300)
1025         reservedWord();
1026
1027     return keyword;
1028 }
1029
1030 // For a keyword that was never reserved, until it suddenly
1031 // showed up, both in an es version and a non-ES version.
1032 int TScanContext::nonreservedKeyword(int esVersion, int nonEsVersion)
1033 {
1034     if ((parseContext.profile == EEsProfile && parseContext.version < esVersion) ||
1035         (parseContext.profile != EEsProfile && parseContext.version < nonEsVersion)) {
1036         if (parseContext.forwardCompatible)
1037             parseContext.warn(loc, "using future keyword", tokenText, "");
1038
1039         return identifierOrType();
1040     }
1041
1042     return keyword;
1043 }
1044
1045 int TScanContext::precisionKeyword()
1046 {
1047     if (parseContext.profile == EEsProfile || parseContext.version >= 130)
1048         return keyword;
1049
1050     if (parseContext.forwardCompatible)
1051         parseContext.warn(loc, "using ES precision qualifier keyword", tokenText, "");
1052
1053     return identifierOrType();
1054 }
1055
1056 int TScanContext::matNxM()
1057 {
1058     afterType = true;
1059
1060     if (parseContext.version > 110)
1061         return keyword;
1062
1063     if (parseContext.forwardCompatible)
1064         parseContext.warn(loc, "using future non-square matrix type keyword", tokenText, "");
1065
1066     return identifierOrType();
1067 }
1068
1069 int TScanContext::dMat()
1070 {
1071     afterType = true;
1072
1073     if (parseContext.profile == EEsProfile && parseContext.version >= 300) {
1074         reservedWord();
1075
1076         return keyword;
1077     }
1078
1079     if (parseContext.profile != EEsProfile && parseContext.version >= 400)
1080         return keyword;
1081
1082     if (parseContext.forwardCompatible)
1083         parseContext.warn(loc, "using future type keyword", tokenText, "");
1084
1085     return identifierOrType();
1086 }
1087
1088 int TScanContext::firstGenerationImage(bool inEs310)
1089 {
1090     afterType = true;
1091
1092     if (parseContext.symbolTable.atBuiltInLevel() || 
1093         (parseContext.profile != EEsProfile && (parseContext.version >= 420 || parseContext.extensionsTurnedOn(1, &GL_ARB_shader_image_load_store))) ||                                                     
1094         (inEs310 && parseContext.profile == EEsProfile && parseContext.version >= 310))
1095         return keyword;
1096
1097     if ((parseContext.profile == EEsProfile && parseContext.version >= 300) ||
1098         (parseContext.profile != EEsProfile && parseContext.version >= 130)) {
1099         reservedWord();
1100
1101         return keyword;
1102     }
1103
1104     if (parseContext.forwardCompatible)
1105         parseContext.warn(loc, "using future type keyword", tokenText, "");
1106
1107     return identifierOrType();
1108 }
1109
1110 int TScanContext::secondGenerationImage()
1111 {
1112     afterType = true;
1113
1114     if (parseContext.profile == EEsProfile && parseContext.version >= 310) {
1115         reservedWord();
1116         return keyword;
1117     }
1118
1119     if (parseContext.symbolTable.atBuiltInLevel() || parseContext.profile != EEsProfile && (parseContext.version >= 420 || parseContext.extensionsTurnedOn(1, &GL_ARB_shader_image_load_store)))
1120         return keyword;
1121
1122     if (parseContext.forwardCompatible)
1123         parseContext.warn(loc, "using future type keyword", tokenText, "");
1124
1125     return identifierOrType();
1126 }
1127
1128 } // end namespace glslang