OSDN Git Service

glcpp: Only disallow #undef of pre-defined macros on GLSL ES >= 3.00 shaders
[android-x86/external-mesa.git] / src / compiler / glsl / glcpp / glcpp-parse.y
1 %{
2 /*
3  * Copyright © 2010 Intel Corporation
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  */
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <assert.h>
29 #include <inttypes.h>
30
31 #include "glcpp.h"
32 #include "main/core.h" /* for struct gl_extensions */
33 #include "main/mtypes.h" /* for gl_api enum */
34
35 static void
36 yyerror(YYLTYPE *locp, glcpp_parser_t *parser, const char *error);
37
38 static void
39 _define_object_macro(glcpp_parser_t *parser,
40                      YYLTYPE *loc,
41                      const char *macro,
42                      token_list_t *replacements);
43
44 static void
45 _define_function_macro(glcpp_parser_t *parser,
46                        YYLTYPE *loc,
47                        const char *macro,
48                        string_list_t *parameters,
49                        token_list_t *replacements);
50
51 static string_list_t *
52 _string_list_create(void *ctx);
53
54 static void
55 _string_list_append_item(string_list_t *list, const char *str);
56
57 static int
58 _string_list_contains(string_list_t *list, const char *member, int *index);
59
60 static const char *
61 _string_list_has_duplicate(string_list_t *list);
62
63 static int
64 _string_list_length(string_list_t *list);
65
66 static int
67 _string_list_equal(string_list_t *a, string_list_t *b);
68
69 static argument_list_t *
70 _argument_list_create(void *ctx);
71
72 static void
73 _argument_list_append(argument_list_t *list, token_list_t *argument);
74
75 static int
76 _argument_list_length(argument_list_t *list);
77
78 static token_list_t *
79 _argument_list_member_at(argument_list_t *list, int index);
80
81 /* Note: This function ralloc_steal()s the str pointer. */
82 static token_t *
83 _token_create_str(void *ctx, int type, char *str);
84
85 static token_t *
86 _token_create_ival(void *ctx, int type, int ival);
87
88 static token_list_t *
89 _token_list_create(void *ctx);
90
91 static void
92 _token_list_append(token_list_t *list, token_t *token);
93
94 static void
95 _token_list_append_list(token_list_t *list, token_list_t *tail);
96
97 static int
98 _token_list_equal_ignoring_space(token_list_t *a, token_list_t *b);
99
100 static void
101 _parser_active_list_push(glcpp_parser_t *parser, const char *identifier,
102                          token_node_t *marker);
103
104 static void
105 _parser_active_list_pop(glcpp_parser_t *parser);
106
107 static int
108 _parser_active_list_contains(glcpp_parser_t *parser, const char *identifier);
109
110 typedef enum {
111    EXPANSION_MODE_IGNORE_DEFINED,
112    EXPANSION_MODE_EVALUATE_DEFINED
113 } expansion_mode_t;
114
115 /* Expand list, and begin lexing from the result (after first
116  * prefixing a token of type 'head_token_type').
117  */
118 static void
119 _glcpp_parser_expand_and_lex_from(glcpp_parser_t *parser, int head_token_type,
120                                   token_list_t *list, expansion_mode_t mode);
121
122 /* Perform macro expansion in-place on the given list. */
123 static void
124 _glcpp_parser_expand_token_list(glcpp_parser_t *parser, token_list_t *list,
125                                 expansion_mode_t mode);
126
127 static void
128 _glcpp_parser_print_expanded_token_list(glcpp_parser_t *parser,
129                                         token_list_t *list);
130
131 static void
132 _glcpp_parser_skip_stack_push_if(glcpp_parser_t *parser, YYLTYPE *loc,
133                                  int condition);
134
135 static void
136 _glcpp_parser_skip_stack_change_if(glcpp_parser_t *parser, YYLTYPE *loc,
137                                    const char *type, int condition);
138
139 static void
140 _glcpp_parser_skip_stack_pop(glcpp_parser_t *parser, YYLTYPE *loc);
141
142 static void
143 _glcpp_parser_handle_version_declaration(glcpp_parser_t *parser, intmax_t version,
144                                          const char *ident, bool explicitly_set);
145
146 static int
147 glcpp_parser_lex(YYSTYPE *yylval, YYLTYPE *yylloc, glcpp_parser_t *parser);
148
149 static void
150 glcpp_parser_lex_from(glcpp_parser_t *parser, token_list_t *list);
151
152 static void
153 add_builtin_define(glcpp_parser_t *parser, const char *name, int value);
154
155 %}
156
157 %pure-parser
158 %error-verbose
159
160 %locations
161 %initial-action {
162    @$.first_line = 1;
163    @$.first_column = 1;
164    @$.last_line = 1;
165    @$.last_column = 1;
166    @$.source = 0;
167 }
168
169 %parse-param {glcpp_parser_t *parser}
170 %lex-param {glcpp_parser_t *parser}
171
172 %expect 0
173
174         /* We use HASH_TOKEN, DEFINE_TOKEN and VERSION_TOKEN (as opposed to
175          * HASH, DEFINE, and VERSION) to avoid conflicts with other symbols,
176          * (such as the <HASH> and <DEFINE> start conditions in the lexer). */
177 %token DEFINED ELIF_EXPANDED HASH_TOKEN DEFINE_TOKEN FUNC_IDENTIFIER OBJ_IDENTIFIER ELIF ELSE ENDIF ERROR_TOKEN IF IFDEF IFNDEF LINE PRAGMA UNDEF VERSION_TOKEN GARBAGE IDENTIFIER IF_EXPANDED INTEGER INTEGER_STRING LINE_EXPANDED NEWLINE OTHER PLACEHOLDER SPACE PLUS_PLUS MINUS_MINUS
178 %token PASTE
179 %type <ival> INTEGER operator SPACE integer_constant
180 %type <expression_value> expression
181 %type <str> IDENTIFIER FUNC_IDENTIFIER OBJ_IDENTIFIER INTEGER_STRING OTHER ERROR_TOKEN PRAGMA
182 %type <string_list> identifier_list
183 %type <token> preprocessing_token
184 %type <token_list> pp_tokens replacement_list text_line
185 %left OR
186 %left AND
187 %left '|'
188 %left '^'
189 %left '&'
190 %left EQUAL NOT_EQUAL
191 %left '<' '>' LESS_OR_EQUAL GREATER_OR_EQUAL
192 %left LEFT_SHIFT RIGHT_SHIFT
193 %left '+' '-'
194 %left '*' '/' '%'
195 %right UNARY
196
197 %debug
198
199 %%
200
201 input:
202         /* empty */
203 |       input line
204 ;
205
206 line:
207         control_line
208 |       SPACE control_line
209 |       text_line {
210                 _glcpp_parser_print_expanded_token_list (parser, $1);
211                 ralloc_asprintf_rewrite_tail (&parser->output, &parser->output_length, "\n");
212                 ralloc_free ($1);
213         }
214 |       expanded_line
215 ;
216
217 expanded_line:
218         IF_EXPANDED expression NEWLINE {
219                 if (parser->is_gles && $2.undefined_macro)
220                         glcpp_error(& @1, parser, "undefined macro %s in expression (illegal in GLES)", $2.undefined_macro);
221                 _glcpp_parser_skip_stack_push_if (parser, & @1, $2.value);
222         }
223 |       ELIF_EXPANDED expression NEWLINE {
224                 if (parser->is_gles && $2.undefined_macro)
225                         glcpp_error(& @1, parser, "undefined macro %s in expression (illegal in GLES)", $2.undefined_macro);
226                 _glcpp_parser_skip_stack_change_if (parser, & @1, "elif", $2.value);
227         }
228 |       LINE_EXPANDED integer_constant NEWLINE {
229                 parser->has_new_line_number = 1;
230                 parser->new_line_number = $2;
231                 ralloc_asprintf_rewrite_tail (&parser->output,
232                                               &parser->output_length,
233                                               "#line %" PRIiMAX "\n",
234                                               $2);
235         }
236 |       LINE_EXPANDED integer_constant integer_constant NEWLINE {
237                 parser->has_new_line_number = 1;
238                 parser->new_line_number = $2;
239                 parser->has_new_source_number = 1;
240                 parser->new_source_number = $3;
241                 ralloc_asprintf_rewrite_tail (&parser->output,
242                                               &parser->output_length,
243                                               "#line %" PRIiMAX " %" PRIiMAX "\n",
244                                               $2, $3);
245         }
246 ;
247
248 define:
249         OBJ_IDENTIFIER replacement_list NEWLINE {
250                 _define_object_macro (parser, & @1, $1, $2);
251         }
252 |       FUNC_IDENTIFIER '(' ')' replacement_list NEWLINE {
253                 _define_function_macro (parser, & @1, $1, NULL, $4);
254         }
255 |       FUNC_IDENTIFIER '(' identifier_list ')' replacement_list NEWLINE {
256                 _define_function_macro (parser, & @1, $1, $3, $5);
257         }
258 ;
259
260 control_line:
261         control_line_success {
262                 ralloc_asprintf_rewrite_tail (&parser->output, &parser->output_length, "\n");
263         }
264 |       control_line_error
265 |       HASH_TOKEN LINE pp_tokens NEWLINE {
266
267                 if (parser->skip_stack == NULL ||
268                     parser->skip_stack->type == SKIP_NO_SKIP)
269                 {
270                         _glcpp_parser_expand_and_lex_from (parser,
271                                                            LINE_EXPANDED, $3,
272                                                            EXPANSION_MODE_IGNORE_DEFINED);
273                 }
274         }
275 ;
276
277 control_line_success:
278         HASH_TOKEN DEFINE_TOKEN define
279 |       HASH_TOKEN UNDEF IDENTIFIER NEWLINE {
280                 macro_t *macro;
281
282                 /* Section 3.4 (Preprocessor) of the GLSL ES 3.00 spec says:
283                  *
284                  *    It is an error to undefine or to redefine a built-in
285                  *    (pre-defined) macro name.
286                  *
287                  * The GLSL ES 1.00 spec does not contain this text.
288                  *
289                  * Section 3.3 (Preprocessor) of the GLSL 1.30 spec says:
290                  *
291                  *    #define and #undef functionality are defined as is
292                  *    standard for C++ preprocessors for macro definitions
293                  *    both with and without macro parameters.
294                  *
295                  * At least as far as I can tell GCC allow '#undef __FILE__'.
296                  * Furthermore, there are desktop OpenGL conformance tests
297                  * that expect '#undef __VERSION__' and '#undef
298                  * GL_core_profile' to work.
299                  *
300                  * Only disallow #undef of pre-defined macros on GLSL ES >=
301                  * 3.00 shaders.
302                  */
303                 if (parser->is_gles &&
304                     parser->version >= 300 &&
305                     (strcmp("__LINE__", $3) == 0
306                      || strcmp("__FILE__", $3) == 0
307                      || strcmp("__VERSION__", $3) == 0
308                      || strncmp("GL_", $3, 3) == 0))
309                         glcpp_error(& @1, parser, "Built-in (pre-defined)"
310                                     " macro names cannot be undefined.");
311
312                 macro = hash_table_find (parser->defines, $3);
313                 if (macro) {
314                         hash_table_remove (parser->defines, $3);
315                         ralloc_free (macro);
316                 }
317                 ralloc_free ($3);
318         }
319 |       HASH_TOKEN IF pp_tokens NEWLINE {
320                 /* Be careful to only evaluate the 'if' expression if
321                  * we are not skipping. When we are skipping, we
322                  * simply push a new 0-valued 'if' onto the skip
323                  * stack.
324                  *
325                  * This avoids generating diagnostics for invalid
326                  * expressions that are being skipped. */
327                 if (parser->skip_stack == NULL ||
328                     parser->skip_stack->type == SKIP_NO_SKIP)
329                 {
330                         _glcpp_parser_expand_and_lex_from (parser,
331                                                            IF_EXPANDED, $3,
332                                                            EXPANSION_MODE_EVALUATE_DEFINED);
333                 }       
334                 else
335                 {
336                         _glcpp_parser_skip_stack_push_if (parser, & @1, 0);
337                         parser->skip_stack->type = SKIP_TO_ENDIF;
338                 }
339         }
340 |       HASH_TOKEN IF NEWLINE {
341                 /* #if without an expression is only an error if we
342                  *  are not skipping */
343                 if (parser->skip_stack == NULL ||
344                     parser->skip_stack->type == SKIP_NO_SKIP)
345                 {
346                         glcpp_error(& @1, parser, "#if with no expression");
347                 }       
348                 _glcpp_parser_skip_stack_push_if (parser, & @1, 0);
349         }
350 |       HASH_TOKEN IFDEF IDENTIFIER junk NEWLINE {
351                 macro_t *macro = hash_table_find (parser->defines, $3);
352                 ralloc_free ($3);
353                 _glcpp_parser_skip_stack_push_if (parser, & @1, macro != NULL);
354         }
355 |       HASH_TOKEN IFNDEF IDENTIFIER junk NEWLINE {
356                 macro_t *macro = hash_table_find (parser->defines, $3);
357                 ralloc_free ($3);
358                 _glcpp_parser_skip_stack_push_if (parser, & @3, macro == NULL);
359         }
360 |       HASH_TOKEN ELIF pp_tokens NEWLINE {
361                 /* Be careful to only evaluate the 'elif' expression
362                  * if we are not skipping. When we are skipping, we
363                  * simply change to a 0-valued 'elif' on the skip
364                  * stack.
365                  *
366                  * This avoids generating diagnostics for invalid
367                  * expressions that are being skipped. */
368                 if (parser->skip_stack &&
369                     parser->skip_stack->type == SKIP_TO_ELSE)
370                 {
371                         _glcpp_parser_expand_and_lex_from (parser,
372                                                            ELIF_EXPANDED, $3,
373                                                            EXPANSION_MODE_EVALUATE_DEFINED);
374                 }
375                 else if (parser->skip_stack &&
376                     parser->skip_stack->has_else)
377                 {
378                         glcpp_error(& @1, parser, "#elif after #else");
379                 }
380                 else
381                 {
382                         _glcpp_parser_skip_stack_change_if (parser, & @1,
383                                                             "elif", 0);
384                 }
385         }
386 |       HASH_TOKEN ELIF NEWLINE {
387                 /* #elif without an expression is an error unless we
388                  * are skipping. */
389                 if (parser->skip_stack &&
390                     parser->skip_stack->type == SKIP_TO_ELSE)
391                 {
392                         glcpp_error(& @1, parser, "#elif with no expression");
393                 }
394                 else if (parser->skip_stack &&
395                     parser->skip_stack->has_else)
396                 {
397                         glcpp_error(& @1, parser, "#elif after #else");
398                 }
399                 else
400                 {
401                         _glcpp_parser_skip_stack_change_if (parser, & @1,
402                                                             "elif", 0);
403                         glcpp_warning(& @1, parser, "ignoring illegal #elif without expression");
404                 }
405         }
406 |       HASH_TOKEN ELSE { parser->lexing_directive = 1; } NEWLINE {
407                 if (parser->skip_stack &&
408                     parser->skip_stack->has_else)
409                 {
410                         glcpp_error(& @1, parser, "multiple #else");
411                 }
412                 else
413                 {
414                         _glcpp_parser_skip_stack_change_if (parser, & @1, "else", 1);
415                         if (parser->skip_stack)
416                                 parser->skip_stack->has_else = true;
417                 }
418         }
419 |       HASH_TOKEN ENDIF {
420                 _glcpp_parser_skip_stack_pop (parser, & @1);
421         } NEWLINE
422 |       HASH_TOKEN VERSION_TOKEN integer_constant NEWLINE {
423                 if (parser->version != 0) {
424                         glcpp_error(& @1, parser, "#version must appear on the first line");
425                 }
426                 _glcpp_parser_handle_version_declaration(parser, $3, NULL, true);
427         }
428 |       HASH_TOKEN VERSION_TOKEN integer_constant IDENTIFIER NEWLINE {
429                 if (parser->version != 0) {
430                         glcpp_error(& @1, parser, "#version must appear on the first line");
431                 }
432                 _glcpp_parser_handle_version_declaration(parser, $3, $4, true);
433         }
434 |       HASH_TOKEN NEWLINE {
435                 glcpp_parser_resolve_implicit_version(parser);
436         }
437 |       HASH_TOKEN PRAGMA NEWLINE {
438                 ralloc_asprintf_rewrite_tail (&parser->output, &parser->output_length, "#%s", $2);
439         }
440 ;
441
442 control_line_error:
443         HASH_TOKEN ERROR_TOKEN NEWLINE {
444                 glcpp_error(& @1, parser, "#%s", $2);
445         }
446 |       HASH_TOKEN DEFINE_TOKEN NEWLINE {
447                 glcpp_error (& @1, parser, "#define without macro name");
448         }
449 |       HASH_TOKEN GARBAGE pp_tokens NEWLINE  {
450                 glcpp_error (& @1, parser, "Illegal non-directive after #");
451         }
452 ;
453
454 integer_constant:
455         INTEGER_STRING {
456                 if (strlen ($1) >= 3 && strncmp ($1, "0x", 2) == 0) {
457                         $$ = strtoll ($1 + 2, NULL, 16);
458                 } else if ($1[0] == '0') {
459                         $$ = strtoll ($1, NULL, 8);
460                 } else {
461                         $$ = strtoll ($1, NULL, 10);
462                 }
463         }
464 |       INTEGER {
465                 $$ = $1;
466         }
467
468 expression:
469         integer_constant {
470                 $$.value = $1;
471                 $$.undefined_macro = NULL;
472         }
473 |       IDENTIFIER {
474                 $$.value = 0;
475                 if (parser->is_gles)
476                         $$.undefined_macro = ralloc_strdup (parser, $1);
477                 else
478                         $$.undefined_macro = NULL;
479         }
480 |       expression OR expression {
481                 $$.value = $1.value || $3.value;
482
483                 /* Short-circuit: Only flag undefined from right side
484                  * if left side evaluates to false.
485                  */
486                 if ($1.undefined_macro)
487                         $$.undefined_macro = $1.undefined_macro;
488                 else if (! $1.value)
489                         $$.undefined_macro = $3.undefined_macro;
490         }
491 |       expression AND expression {
492                 $$.value = $1.value && $3.value;
493
494                 /* Short-circuit: Only flag undefined from right-side
495                  * if left side evaluates to true.
496                  */
497                 if ($1.undefined_macro)
498                         $$.undefined_macro = $1.undefined_macro;
499                 else if ($1.value)
500                         $$.undefined_macro = $3.undefined_macro;
501         }
502 |       expression '|' expression {
503                 $$.value = $1.value | $3.value;
504                 if ($1.undefined_macro)
505                         $$.undefined_macro = $1.undefined_macro;
506                 else
507                         $$.undefined_macro = $3.undefined_macro;
508         }
509 |       expression '^' expression {
510                 $$.value = $1.value ^ $3.value;
511                 if ($1.undefined_macro)
512                         $$.undefined_macro = $1.undefined_macro;
513                 else
514                         $$.undefined_macro = $3.undefined_macro;
515         }
516 |       expression '&' expression {
517                 $$.value = $1.value & $3.value;
518                 if ($1.undefined_macro)
519                         $$.undefined_macro = $1.undefined_macro;
520                 else
521                         $$.undefined_macro = $3.undefined_macro;
522         }
523 |       expression NOT_EQUAL expression {
524                 $$.value = $1.value != $3.value;
525                 if ($1.undefined_macro)
526                         $$.undefined_macro = $1.undefined_macro;
527                 else
528                         $$.undefined_macro = $3.undefined_macro;
529         }
530 |       expression EQUAL expression {
531                 $$.value = $1.value == $3.value;
532                 if ($1.undefined_macro)
533                         $$.undefined_macro = $1.undefined_macro;
534                 else
535                         $$.undefined_macro = $3.undefined_macro;
536         }
537 |       expression GREATER_OR_EQUAL expression {
538                 $$.value = $1.value >= $3.value;
539                 if ($1.undefined_macro)
540                         $$.undefined_macro = $1.undefined_macro;
541                 else
542                         $$.undefined_macro = $3.undefined_macro;
543         }
544 |       expression LESS_OR_EQUAL expression {
545                 $$.value = $1.value <= $3.value;
546                 if ($1.undefined_macro)
547                         $$.undefined_macro = $1.undefined_macro;
548                 else
549                         $$.undefined_macro = $3.undefined_macro;
550         }
551 |       expression '>' expression {
552                 $$.value = $1.value > $3.value;
553                 if ($1.undefined_macro)
554                         $$.undefined_macro = $1.undefined_macro;
555                 else
556                         $$.undefined_macro = $3.undefined_macro;
557         }
558 |       expression '<' expression {
559                 $$.value = $1.value < $3.value;
560                 if ($1.undefined_macro)
561                         $$.undefined_macro = $1.undefined_macro;
562                 else
563                         $$.undefined_macro = $3.undefined_macro;
564         }
565 |       expression RIGHT_SHIFT expression {
566                 $$.value = $1.value >> $3.value;
567                 if ($1.undefined_macro)
568                         $$.undefined_macro = $1.undefined_macro;
569                 else
570                         $$.undefined_macro = $3.undefined_macro;
571         }
572 |       expression LEFT_SHIFT expression {
573                 $$.value = $1.value << $3.value;
574                 if ($1.undefined_macro)
575                         $$.undefined_macro = $1.undefined_macro;
576                 else
577                         $$.undefined_macro = $3.undefined_macro;
578         }
579 |       expression '-' expression {
580                 $$.value = $1.value - $3.value;
581                 if ($1.undefined_macro)
582                         $$.undefined_macro = $1.undefined_macro;
583                 else
584                         $$.undefined_macro = $3.undefined_macro;
585         }
586 |       expression '+' expression {
587                 $$.value = $1.value + $3.value;
588                 if ($1.undefined_macro)
589                         $$.undefined_macro = $1.undefined_macro;
590                 else
591                         $$.undefined_macro = $3.undefined_macro;
592         }
593 |       expression '%' expression {
594                 if ($3.value == 0) {
595                         yyerror (& @1, parser,
596                                  "zero modulus in preprocessor directive");
597                 } else {
598                         $$.value = $1.value % $3.value;
599                 }
600                 if ($1.undefined_macro)
601                         $$.undefined_macro = $1.undefined_macro;
602                 else
603                         $$.undefined_macro = $3.undefined_macro;
604         }
605 |       expression '/' expression {
606                 if ($3.value == 0) {
607                         yyerror (& @1, parser,
608                                  "division by 0 in preprocessor directive");
609                 } else {
610                         $$.value = $1.value / $3.value;
611                 }
612                 if ($1.undefined_macro)
613                         $$.undefined_macro = $1.undefined_macro;
614                 else
615                         $$.undefined_macro = $3.undefined_macro;
616         }
617 |       expression '*' expression {
618                 $$.value = $1.value * $3.value;
619                 if ($1.undefined_macro)
620                         $$.undefined_macro = $1.undefined_macro;
621                 else
622                         $$.undefined_macro = $3.undefined_macro;
623         }
624 |       '!' expression %prec UNARY {
625                 $$.value = ! $2.value;
626                 $$.undefined_macro = $2.undefined_macro;
627         }
628 |       '~' expression %prec UNARY {
629                 $$.value = ~ $2.value;
630                 $$.undefined_macro = $2.undefined_macro;
631         }
632 |       '-' expression %prec UNARY {
633                 $$.value = - $2.value;
634                 $$.undefined_macro = $2.undefined_macro;
635         }
636 |       '+' expression %prec UNARY {
637                 $$.value = + $2.value;
638                 $$.undefined_macro = $2.undefined_macro;
639         }
640 |       '(' expression ')' {
641                 $$ = $2;
642         }
643 ;
644
645 identifier_list:
646         IDENTIFIER {
647                 $$ = _string_list_create (parser);
648                 _string_list_append_item ($$, $1);
649                 ralloc_steal ($$, $1);
650         }
651 |       identifier_list ',' IDENTIFIER {
652                 $$ = $1;        
653                 _string_list_append_item ($$, $3);
654                 ralloc_steal ($$, $3);
655         }
656 ;
657
658 text_line:
659         NEWLINE { $$ = NULL; }
660 |       pp_tokens NEWLINE
661 ;
662
663 replacement_list:
664         /* empty */ { $$ = NULL; }
665 |       pp_tokens
666 ;
667
668 junk:
669         /* empty */
670 |       pp_tokens {
671                 glcpp_error(&@1, parser, "extra tokens at end of directive");
672         }
673 ;
674
675 pp_tokens:
676         preprocessing_token {
677                 parser->space_tokens = 1;
678                 $$ = _token_list_create (parser);
679                 _token_list_append ($$, $1);
680         }
681 |       pp_tokens preprocessing_token {
682                 $$ = $1;
683                 _token_list_append ($$, $2);
684         }
685 ;
686
687 preprocessing_token:
688         IDENTIFIER {
689                 $$ = _token_create_str (parser, IDENTIFIER, $1);
690                 $$->location = yylloc;
691         }
692 |       INTEGER_STRING {
693                 $$ = _token_create_str (parser, INTEGER_STRING, $1);
694                 $$->location = yylloc;
695         }
696 |       operator {
697                 $$ = _token_create_ival (parser, $1, $1);
698                 $$->location = yylloc;
699         }
700 |       DEFINED {
701                 $$ = _token_create_ival (parser, DEFINED, DEFINED);
702                 $$->location = yylloc;
703         }
704 |       OTHER {
705                 $$ = _token_create_str (parser, OTHER, $1);
706                 $$->location = yylloc;
707         }
708 |       SPACE {
709                 $$ = _token_create_ival (parser, SPACE, SPACE);
710                 $$->location = yylloc;
711         }
712 ;
713
714 operator:
715         '['                     { $$ = '['; }
716 |       ']'                     { $$ = ']'; }
717 |       '('                     { $$ = '('; }
718 |       ')'                     { $$ = ')'; }
719 |       '{'                     { $$ = '{'; }
720 |       '}'                     { $$ = '}'; }
721 |       '.'                     { $$ = '.'; }
722 |       '&'                     { $$ = '&'; }
723 |       '*'                     { $$ = '*'; }
724 |       '+'                     { $$ = '+'; }
725 |       '-'                     { $$ = '-'; }
726 |       '~'                     { $$ = '~'; }
727 |       '!'                     { $$ = '!'; }
728 |       '/'                     { $$ = '/'; }
729 |       '%'                     { $$ = '%'; }
730 |       LEFT_SHIFT              { $$ = LEFT_SHIFT; }
731 |       RIGHT_SHIFT             { $$ = RIGHT_SHIFT; }
732 |       '<'                     { $$ = '<'; }
733 |       '>'                     { $$ = '>'; }
734 |       LESS_OR_EQUAL           { $$ = LESS_OR_EQUAL; }
735 |       GREATER_OR_EQUAL        { $$ = GREATER_OR_EQUAL; }
736 |       EQUAL                   { $$ = EQUAL; }
737 |       NOT_EQUAL               { $$ = NOT_EQUAL; }
738 |       '^'                     { $$ = '^'; }
739 |       '|'                     { $$ = '|'; }
740 |       AND                     { $$ = AND; }
741 |       OR                      { $$ = OR; }
742 |       ';'                     { $$ = ';'; }
743 |       ','                     { $$ = ','; }
744 |       '='                     { $$ = '='; }
745 |       PASTE                   { $$ = PASTE; }
746 |       PLUS_PLUS               { $$ = PLUS_PLUS; }
747 |       MINUS_MINUS             { $$ = MINUS_MINUS; }
748 ;
749
750 %%
751
752 string_list_t *
753 _string_list_create(void *ctx)
754 {
755    string_list_t *list;
756
757    list = ralloc (ctx, string_list_t);
758    list->head = NULL;
759    list->tail = NULL;
760
761    return list;
762 }
763
764 void
765 _string_list_append_item(string_list_t *list, const char *str)
766 {
767    string_node_t *node;
768
769    node = ralloc (list, string_node_t);
770    node->str = ralloc_strdup (node, str);
771
772    node->next = NULL;
773
774    if (list->head == NULL) {
775       list->head = node;
776    } else {
777       list->tail->next = node;
778    }
779
780    list->tail = node;
781 }
782
783 int
784 _string_list_contains(string_list_t *list, const char *member, int *index)
785 {
786    string_node_t *node;
787    int i;
788
789    if (list == NULL)
790       return 0;
791
792    for (i = 0, node = list->head; node; i++, node = node->next) {
793       if (strcmp (node->str, member) == 0) {
794          if (index)
795             *index = i;
796          return 1;
797       }
798    }
799
800    return 0;
801 }
802
803 /* Return duplicate string in list (if any), NULL otherwise. */
804 const char *
805 _string_list_has_duplicate(string_list_t *list)
806 {
807    string_node_t *node, *dup;
808
809    if (list == NULL)
810       return NULL;
811
812    for (node = list->head; node; node = node->next) {
813       for (dup = node->next; dup; dup = dup->next) {
814          if (strcmp (node->str, dup->str) == 0)
815             return node->str;
816       }
817    }
818
819    return NULL;
820 }
821
822 int
823 _string_list_length(string_list_t *list)
824 {
825    int length = 0;
826    string_node_t *node;
827
828    if (list == NULL)
829       return 0;
830
831    for (node = list->head; node; node = node->next)
832       length++;
833
834    return length;
835 }
836
837 int
838 _string_list_equal(string_list_t *a, string_list_t *b)
839 {
840    string_node_t *node_a, *node_b;
841
842    if (a == NULL && b == NULL)
843       return 1;
844
845    if (a == NULL || b == NULL)
846       return 0;
847
848    for (node_a = a->head, node_b = b->head;
849         node_a && node_b;
850         node_a = node_a->next, node_b = node_b->next)
851    {
852       if (strcmp (node_a->str, node_b->str))
853          return 0;
854    }
855
856    /* Catch the case of lists being different lengths, (which
857     * would cause the loop above to terminate after the shorter
858     * list). */
859    return node_a == node_b;
860 }
861
862 argument_list_t *
863 _argument_list_create(void *ctx)
864 {
865    argument_list_t *list;
866
867    list = ralloc (ctx, argument_list_t);
868    list->head = NULL;
869    list->tail = NULL;
870
871    return list;
872 }
873
874 void
875 _argument_list_append(argument_list_t *list, token_list_t *argument)
876 {
877    argument_node_t *node;
878
879    node = ralloc (list, argument_node_t);
880    node->argument = argument;
881
882    node->next = NULL;
883
884    if (list->head == NULL) {
885       list->head = node;
886    } else {
887       list->tail->next = node;
888    }
889
890    list->tail = node;
891 }
892
893 int
894 _argument_list_length(argument_list_t *list)
895 {
896    int length = 0;
897    argument_node_t *node;
898
899    if (list == NULL)
900       return 0;
901
902    for (node = list->head; node; node = node->next)
903       length++;
904
905    return length;
906 }
907
908 token_list_t *
909 _argument_list_member_at(argument_list_t *list, int index)
910 {
911    argument_node_t *node;
912    int i;
913
914    if (list == NULL)
915       return NULL;
916
917    node = list->head;
918    for (i = 0; i < index; i++) {
919       node = node->next;
920       if (node == NULL)
921          break;
922    }
923
924    if (node)
925       return node->argument;
926
927    return NULL;
928 }
929
930 /* Note: This function ralloc_steal()s the str pointer. */
931 token_t *
932 _token_create_str(void *ctx, int type, char *str)
933 {
934    token_t *token;
935
936    token = ralloc (ctx, token_t);
937    token->type = type;
938    token->value.str = str;
939
940    ralloc_steal (token, str);
941
942    return token;
943 }
944
945 token_t *
946 _token_create_ival(void *ctx, int type, int ival)
947 {
948    token_t *token;
949
950    token = ralloc (ctx, token_t);
951    token->type = type;
952    token->value.ival = ival;
953
954    return token;
955 }
956
957 token_list_t *
958 _token_list_create(void *ctx)
959 {
960    token_list_t *list;
961
962    list = ralloc (ctx, token_list_t);
963    list->head = NULL;
964    list->tail = NULL;
965    list->non_space_tail = NULL;
966
967    return list;
968 }
969
970 void
971 _token_list_append(token_list_t *list, token_t *token)
972 {
973    token_node_t *node;
974
975    node = ralloc (list, token_node_t);
976    node->token = token;
977    node->next = NULL;
978
979    if (list->head == NULL) {
980       list->head = node;
981    } else {
982       list->tail->next = node;
983    }
984
985    list->tail = node;
986    if (token->type != SPACE)
987       list->non_space_tail = node;
988 }
989
990 void
991 _token_list_append_list(token_list_t *list, token_list_t *tail)
992 {
993    if (tail == NULL || tail->head == NULL)
994       return;
995
996    if (list->head == NULL) {
997       list->head = tail->head;
998    } else {
999       list->tail->next = tail->head;
1000    }
1001
1002    list->tail = tail->tail;
1003    list->non_space_tail = tail->non_space_tail;
1004 }
1005
1006 static token_list_t *
1007 _token_list_copy(void *ctx, token_list_t *other)
1008 {
1009    token_list_t *copy;
1010    token_node_t *node;
1011
1012    if (other == NULL)
1013       return NULL;
1014
1015    copy = _token_list_create (ctx);
1016    for (node = other->head; node; node = node->next) {
1017       token_t *new_token = ralloc (copy, token_t);
1018       *new_token = *node->token;
1019       _token_list_append (copy, new_token);
1020    }
1021
1022    return copy;
1023 }
1024
1025 static void
1026 _token_list_trim_trailing_space(token_list_t *list)
1027 {
1028    token_node_t *tail, *next;
1029
1030    if (list->non_space_tail) {
1031       tail = list->non_space_tail->next;
1032       list->non_space_tail->next = NULL;
1033       list->tail = list->non_space_tail;
1034
1035       while (tail) {
1036          next = tail->next;
1037          ralloc_free (tail);
1038          tail = next;
1039       }
1040    }
1041 }
1042
1043 static int
1044 _token_list_is_empty_ignoring_space(token_list_t *l)
1045 {
1046    token_node_t *n;
1047
1048    if (l == NULL)
1049       return 1;
1050
1051    n = l->head;
1052    while (n != NULL && n->token->type == SPACE)
1053       n = n->next;
1054
1055    return n == NULL;
1056 }
1057
1058 int
1059 _token_list_equal_ignoring_space(token_list_t *a, token_list_t *b)
1060 {
1061    token_node_t *node_a, *node_b;
1062
1063    if (a == NULL || b == NULL) {
1064       int a_empty = _token_list_is_empty_ignoring_space(a);
1065       int b_empty = _token_list_is_empty_ignoring_space(b);
1066       return a_empty == b_empty;
1067    }
1068
1069    node_a = a->head;
1070    node_b = b->head;
1071
1072    while (1)
1073    {
1074       if (node_a == NULL && node_b == NULL)
1075          break;
1076
1077       if (node_a == NULL || node_b == NULL)
1078          return 0;
1079       /* Make sure whitespace appears in the same places in both.
1080        * It need not be exactly the same amount of whitespace,
1081        * though.
1082        */
1083       if (node_a->token->type == SPACE && node_b->token->type == SPACE) {
1084          while (node_a && node_a->token->type == SPACE)
1085             node_a = node_a->next;
1086          while (node_b && node_b->token->type == SPACE)
1087             node_b = node_b->next;
1088          continue;
1089       }
1090
1091       if (node_a->token->type != node_b->token->type)
1092          return 0;
1093
1094       switch (node_a->token->type) {
1095       case INTEGER:
1096          if (node_a->token->value.ival !=  node_b->token->value.ival) {
1097             return 0;
1098          }
1099          break;
1100       case IDENTIFIER:
1101       case INTEGER_STRING:
1102       case OTHER:
1103          if (strcmp(node_a->token->value.str, node_b->token->value.str)) {
1104             return 0;
1105          }
1106          break;
1107       }
1108
1109       node_a = node_a->next;
1110       node_b = node_b->next;
1111    }
1112
1113    return 1;
1114 }
1115
1116 static void
1117 _token_print(char **out, size_t *len, token_t *token)
1118 {
1119    if (token->type < 256) {
1120       ralloc_asprintf_rewrite_tail (out, len, "%c", token->type);
1121       return;
1122    }
1123
1124    switch (token->type) {
1125    case INTEGER:
1126       ralloc_asprintf_rewrite_tail (out, len, "%" PRIiMAX, token->value.ival);
1127       break;
1128    case IDENTIFIER:
1129    case INTEGER_STRING:
1130    case OTHER:
1131       ralloc_asprintf_rewrite_tail (out, len, "%s", token->value.str);
1132       break;
1133    case SPACE:
1134       ralloc_asprintf_rewrite_tail (out, len, " ");
1135       break;
1136    case LEFT_SHIFT:
1137       ralloc_asprintf_rewrite_tail (out, len, "<<");
1138       break;
1139    case RIGHT_SHIFT:
1140       ralloc_asprintf_rewrite_tail (out, len, ">>");
1141       break;
1142    case LESS_OR_EQUAL:
1143       ralloc_asprintf_rewrite_tail (out, len, "<=");
1144       break;
1145    case GREATER_OR_EQUAL:
1146       ralloc_asprintf_rewrite_tail (out, len, ">=");
1147       break;
1148    case EQUAL:
1149       ralloc_asprintf_rewrite_tail (out, len, "==");
1150       break;
1151    case NOT_EQUAL:
1152       ralloc_asprintf_rewrite_tail (out, len, "!=");
1153       break;
1154    case AND:
1155       ralloc_asprintf_rewrite_tail (out, len, "&&");
1156       break;
1157    case OR:
1158       ralloc_asprintf_rewrite_tail (out, len, "||");
1159       break;
1160    case PASTE:
1161       ralloc_asprintf_rewrite_tail (out, len, "##");
1162       break;
1163    case PLUS_PLUS:
1164       ralloc_asprintf_rewrite_tail (out, len, "++");
1165       break;
1166    case MINUS_MINUS:
1167       ralloc_asprintf_rewrite_tail (out, len, "--");
1168       break;
1169    case DEFINED:
1170       ralloc_asprintf_rewrite_tail (out, len, "defined");
1171       break;
1172    case PLACEHOLDER:
1173       /* Nothing to print. */
1174       break;
1175    default:
1176       assert(!"Error: Don't know how to print token.");
1177
1178       break;
1179    }
1180 }
1181
1182 /* Return a new token (ralloc()ed off of 'token') formed by pasting
1183  * 'token' and 'other'. Note that this function may return 'token' or
1184  * 'other' directly rather than allocating anything new.
1185  *
1186  * Caution: Only very cursory error-checking is performed to see if
1187  * the final result is a valid single token. */
1188 static token_t *
1189 _token_paste(glcpp_parser_t *parser, token_t *token, token_t *other)
1190 {
1191    token_t *combined = NULL;
1192
1193    /* Pasting a placeholder onto anything makes no change. */
1194    if (other->type == PLACEHOLDER)
1195       return token;
1196
1197    /* When 'token' is a placeholder, just return 'other'. */
1198    if (token->type == PLACEHOLDER)
1199       return other;
1200
1201    /* A very few single-character punctuators can be combined
1202     * with another to form a multi-character punctuator. */
1203    switch (token->type) {
1204    case '<':
1205       if (other->type == '<')
1206          combined = _token_create_ival (token, LEFT_SHIFT, LEFT_SHIFT);
1207       else if (other->type == '=')
1208          combined = _token_create_ival (token, LESS_OR_EQUAL, LESS_OR_EQUAL);
1209       break;
1210    case '>':
1211       if (other->type == '>')
1212          combined = _token_create_ival (token, RIGHT_SHIFT, RIGHT_SHIFT);
1213       else if (other->type == '=')
1214          combined = _token_create_ival (token, GREATER_OR_EQUAL, GREATER_OR_EQUAL);
1215       break;
1216    case '=':
1217       if (other->type == '=')
1218          combined = _token_create_ival (token, EQUAL, EQUAL);
1219       break;
1220    case '!':
1221       if (other->type == '=')
1222          combined = _token_create_ival (token, NOT_EQUAL, NOT_EQUAL);
1223       break;
1224    case '&':
1225       if (other->type == '&')
1226          combined = _token_create_ival (token, AND, AND);
1227       break;
1228    case '|':
1229       if (other->type == '|')
1230          combined = _token_create_ival (token, OR, OR);
1231       break;
1232    }
1233
1234    if (combined != NULL) {
1235       /* Inherit the location from the first token */
1236       combined->location = token->location;
1237       return combined;
1238    }
1239
1240    /* Two string-valued (or integer) tokens can usually just be
1241     * mashed together. (We also handle a string followed by an
1242     * integer here as well.)
1243     *
1244     * There are some exceptions here. Notably, if the first token
1245     * is an integer (or a string representing an integer), then
1246     * the second token must also be an integer or must be a
1247     * string representing an integer that begins with a digit.
1248     */
1249    if ((token->type == IDENTIFIER || token->type == OTHER || token->type == INTEGER_STRING || token->type == INTEGER) &&
1250        (other->type == IDENTIFIER || other->type == OTHER || other->type == INTEGER_STRING || other->type == INTEGER))
1251    {
1252       char *str;
1253       int combined_type;
1254
1255       /* Check that pasting onto an integer doesn't create a
1256        * non-integer, (that is, only digits can be
1257        * pasted. */
1258       if (token->type == INTEGER_STRING || token->type == INTEGER) {
1259          switch (other->type) {
1260          case INTEGER_STRING:
1261             if (other->value.str[0] < '0' || other->value.str[0] > '9')
1262                goto FAIL;
1263             break;
1264          case INTEGER:
1265             if (other->value.ival < 0)
1266                goto FAIL;
1267             break;
1268          default:
1269             goto FAIL;
1270          }
1271       }
1272
1273       if (token->type == INTEGER)
1274          str = ralloc_asprintf (token, "%" PRIiMAX, token->value.ival);
1275       else
1276          str = ralloc_strdup (token, token->value.str);
1277
1278       if (other->type == INTEGER)
1279          ralloc_asprintf_append (&str, "%" PRIiMAX, other->value.ival);
1280       else
1281          ralloc_strcat (&str, other->value.str);
1282
1283       /* New token is same type as original token, unless we
1284        * started with an integer, in which case we will be
1285        * creating an integer-string. */
1286       combined_type = token->type;
1287       if (combined_type == INTEGER)
1288          combined_type = INTEGER_STRING;
1289
1290       combined = _token_create_str (token, combined_type, str);
1291       combined->location = token->location;
1292       return combined;
1293    }
1294
1295     FAIL:
1296    glcpp_error (&token->location, parser, "");
1297    ralloc_asprintf_rewrite_tail (&parser->info_log, &parser->info_log_length, "Pasting \"");
1298    _token_print (&parser->info_log, &parser->info_log_length, token);
1299    ralloc_asprintf_rewrite_tail (&parser->info_log, &parser->info_log_length, "\" and \"");
1300    _token_print (&parser->info_log, &parser->info_log_length, other);
1301    ralloc_asprintf_rewrite_tail (&parser->info_log, &parser->info_log_length, "\" does not give a valid preprocessing token.\n");
1302
1303    return token;
1304 }
1305
1306 static void
1307 _token_list_print(glcpp_parser_t *parser, token_list_t *list)
1308 {
1309    token_node_t *node;
1310
1311    if (list == NULL)
1312       return;
1313
1314    for (node = list->head; node; node = node->next)
1315       _token_print (&parser->output, &parser->output_length, node->token);
1316 }
1317
1318 void
1319 yyerror(YYLTYPE *locp, glcpp_parser_t *parser, const char *error)
1320 {
1321    glcpp_error(locp, parser, "%s", error);
1322 }
1323
1324 static void
1325 add_builtin_define(glcpp_parser_t *parser, const char *name, int value)
1326 {
1327    token_t *tok;
1328    token_list_t *list;
1329
1330    tok = _token_create_ival (parser, INTEGER, value);
1331
1332    list = _token_list_create(parser);
1333    _token_list_append(list, tok);
1334    _define_object_macro(parser, NULL, name, list);
1335 }
1336
1337 glcpp_parser_t *
1338 glcpp_parser_create(const struct gl_extensions *extensions, gl_api api)
1339 {
1340    glcpp_parser_t *parser;
1341
1342    parser = ralloc (NULL, glcpp_parser_t);
1343
1344    glcpp_lex_init_extra (parser, &parser->scanner);
1345    parser->defines = hash_table_ctor(32, hash_table_string_hash,
1346                                      hash_table_string_compare);
1347    parser->active = NULL;
1348    parser->lexing_directive = 0;
1349    parser->space_tokens = 1;
1350    parser->last_token_was_newline = 0;
1351    parser->last_token_was_space = 0;
1352    parser->first_non_space_token_this_line = 1;
1353    parser->newline_as_space = 0;
1354    parser->in_control_line = 0;
1355    parser->paren_count = 0;
1356    parser->commented_newlines = 0;
1357
1358    parser->skip_stack = NULL;
1359    parser->skipping = 0;
1360
1361    parser->lex_from_list = NULL;
1362    parser->lex_from_node = NULL;
1363
1364    parser->output = ralloc_strdup(parser, "");
1365    parser->output_length = 0;
1366    parser->info_log = ralloc_strdup(parser, "");
1367    parser->info_log_length = 0;
1368    parser->error = 0;
1369
1370    parser->extensions = extensions;
1371    parser->api = api;
1372    parser->version = 0;
1373
1374    parser->has_new_line_number = 0;
1375    parser->new_line_number = 1;
1376    parser->has_new_source_number = 0;
1377    parser->new_source_number = 0;
1378
1379    return parser;
1380 }
1381
1382 void
1383 glcpp_parser_destroy(glcpp_parser_t *parser)
1384 {
1385    glcpp_lex_destroy (parser->scanner);
1386    hash_table_dtor (parser->defines);
1387    ralloc_free (parser);
1388 }
1389
1390 typedef enum function_status
1391 {
1392    FUNCTION_STATUS_SUCCESS,
1393    FUNCTION_NOT_A_FUNCTION,
1394    FUNCTION_UNBALANCED_PARENTHESES
1395 } function_status_t;
1396
1397 /* Find a set of function-like macro arguments by looking for a
1398  * balanced set of parentheses.
1399  *
1400  * When called, 'node' should be the opening-parenthesis token, (or
1401  * perhaps preceeding SPACE tokens). Upon successful return *last will
1402  * be the last consumed node, (corresponding to the closing right
1403  * parenthesis).
1404  *
1405  * Return values:
1406  *
1407  *   FUNCTION_STATUS_SUCCESS:
1408  *
1409  *      Successfully parsed a set of function arguments.
1410  *
1411  *   FUNCTION_NOT_A_FUNCTION:
1412  *
1413  *      Macro name not followed by a '('. This is not an error, but
1414  *      simply that the macro name should be treated as a non-macro.
1415  *
1416  *   FUNCTION_UNBALANCED_PARENTHESES
1417  *
1418  *      Macro name is not followed by a balanced set of parentheses.
1419  */
1420 static function_status_t
1421 _arguments_parse(argument_list_t *arguments, token_node_t *node,
1422                  token_node_t **last)
1423 {
1424    token_list_t *argument;
1425    int paren_count;
1426
1427    node = node->next;
1428
1429    /* Ignore whitespace before first parenthesis. */
1430    while (node && node->token->type == SPACE)
1431       node = node->next;
1432
1433    if (node == NULL || node->token->type != '(')
1434       return FUNCTION_NOT_A_FUNCTION;
1435
1436    node = node->next;
1437
1438    argument = _token_list_create (arguments);
1439    _argument_list_append (arguments, argument);
1440
1441    for (paren_count = 1; node; node = node->next) {
1442       if (node->token->type == '(') {
1443          paren_count++;
1444       } else if (node->token->type == ')') {
1445          paren_count--;
1446          if (paren_count == 0)
1447             break;
1448       }
1449
1450       if (node->token->type == ',' && paren_count == 1) {
1451          _token_list_trim_trailing_space (argument);
1452          argument = _token_list_create (arguments);
1453          _argument_list_append (arguments, argument);
1454       } else {
1455          if (argument->head == NULL) {
1456             /* Don't treat initial whitespace as part of the argument. */
1457             if (node->token->type == SPACE)
1458                continue;
1459          }
1460          _token_list_append (argument, node->token);
1461       }
1462    }
1463
1464    if (paren_count)
1465       return FUNCTION_UNBALANCED_PARENTHESES;
1466
1467    *last = node;
1468
1469    return FUNCTION_STATUS_SUCCESS;
1470 }
1471
1472 static token_list_t *
1473 _token_list_create_with_one_ival(void *ctx, int type, int ival)
1474 {
1475    token_list_t *list;
1476    token_t *node;
1477
1478    list = _token_list_create(ctx);
1479    node = _token_create_ival(list, type, ival);
1480    _token_list_append(list, node);
1481
1482    return list;
1483 }
1484
1485 static token_list_t *
1486 _token_list_create_with_one_space(void *ctx)
1487 {
1488    return _token_list_create_with_one_ival(ctx, SPACE, SPACE);
1489 }
1490
1491 static token_list_t *
1492 _token_list_create_with_one_integer(void *ctx, int ival)
1493 {
1494    return _token_list_create_with_one_ival(ctx, INTEGER, ival);
1495 }
1496
1497 /* Evaluate a DEFINED token node (based on subsequent tokens in the list).
1498  *
1499  * Note: This function must only be called when "node" is a DEFINED token,
1500  * (and will abort with an assertion failure otherwise).
1501  *
1502  * If "node" is followed, (ignoring any SPACE tokens), by an IDENTIFIER token
1503  * (optionally preceded and followed by '(' and ')' tokens) then the following
1504  * occurs:
1505  *
1506  *   If the identifier is a defined macro, this function returns 1.
1507  *
1508  *   If the identifier is not a defined macro, this function returns 0.
1509  *
1510  *   In either case, *last will be updated to the last node in the list
1511  *   consumed by the evaluation, (either the token of the identifier or the
1512  *   token of the closing parenthesis).
1513  *
1514  * In all other cases, (such as "node is the final node of the list", or
1515  * "missing closing parenthesis", etc.), this function generates a
1516  * preprocessor error, returns -1 and *last will not be set.
1517  */
1518 static int
1519 _glcpp_parser_evaluate_defined(glcpp_parser_t *parser, token_node_t *node,
1520                                token_node_t **last)
1521 {
1522    token_node_t *argument, *defined = node;
1523
1524    assert(node->token->type == DEFINED);
1525
1526    node = node->next;
1527
1528    /* Ignore whitespace after DEFINED token. */
1529    while (node && node->token->type == SPACE)
1530       node = node->next;
1531
1532    if (node == NULL)
1533       goto FAIL;
1534
1535    if (node->token->type == IDENTIFIER || node->token->type == OTHER) {
1536       argument = node;
1537    } else if (node->token->type == '(') {
1538       node = node->next;
1539
1540       /* Ignore whitespace after '(' token. */
1541       while (node && node->token->type == SPACE)
1542          node = node->next;
1543
1544       if (node == NULL || (node->token->type != IDENTIFIER &&
1545                            node->token->type != OTHER)) {
1546          goto FAIL;
1547       }
1548
1549       argument = node;
1550
1551       node = node->next;
1552
1553       /* Ignore whitespace after identifier, before ')' token. */
1554       while (node && node->token->type == SPACE)
1555          node = node->next;
1556
1557       if (node == NULL || node->token->type != ')')
1558          goto FAIL;
1559    } else {
1560       goto FAIL;
1561    }
1562
1563    *last = node;
1564
1565    return hash_table_find(parser->defines,
1566                           argument->token->value.str) ? 1 : 0;
1567
1568 FAIL:
1569    glcpp_error (&defined->token->location, parser,
1570                 "\"defined\" not followed by an identifier");
1571    return -1;
1572 }
1573
1574 /* Evaluate all DEFINED nodes in a given list, modifying the list in place.
1575  */
1576 static void
1577 _glcpp_parser_evaluate_defined_in_list(glcpp_parser_t *parser,
1578                                        token_list_t *list)
1579 {
1580    token_node_t *node, *node_prev, *replacement, *last = NULL;
1581    int value;
1582
1583    if (list == NULL)
1584       return;
1585
1586    node_prev = NULL;
1587    node = list->head;
1588
1589    while (node) {
1590
1591       if (node->token->type != DEFINED)
1592          goto NEXT;
1593
1594       value = _glcpp_parser_evaluate_defined (parser, node, &last);
1595       if (value == -1)
1596          goto NEXT;
1597
1598       replacement = ralloc (list, token_node_t);
1599       replacement->token = _token_create_ival (list, INTEGER, value);
1600
1601       /* Splice replacement node into list, replacing from "node"
1602        * through "last". */
1603       if (node_prev)
1604          node_prev->next = replacement;
1605       else
1606          list->head = replacement;
1607       replacement->next = last->next;
1608       if (last == list->tail)
1609          list->tail = replacement;
1610
1611       node = replacement;
1612
1613    NEXT:
1614       node_prev = node;
1615       node = node->next;
1616    }
1617 }
1618
1619 /* Perform macro expansion on 'list', placing the resulting tokens
1620  * into a new list which is initialized with a first token of type
1621  * 'head_token_type'. Then begin lexing from the resulting list,
1622  * (return to the current lexing source when this list is exhausted).
1623  *
1624  * See the documentation of _glcpp_parser_expand_token_list for a description
1625  * of the "mode" parameter.
1626  */
1627 static void
1628 _glcpp_parser_expand_and_lex_from(glcpp_parser_t *parser, int head_token_type,
1629                                   token_list_t *list, expansion_mode_t mode)
1630 {
1631    token_list_t *expanded;
1632    token_t *token;
1633
1634    expanded = _token_list_create (parser);
1635    token = _token_create_ival (parser, head_token_type, head_token_type);
1636    _token_list_append (expanded, token);
1637    _glcpp_parser_expand_token_list (parser, list, mode);
1638    _token_list_append_list (expanded, list);
1639    glcpp_parser_lex_from (parser, expanded);
1640 }
1641
1642 static void
1643 _glcpp_parser_apply_pastes(glcpp_parser_t *parser, token_list_t *list)
1644 {
1645    token_node_t *node;
1646
1647    node = list->head;
1648    while (node) {
1649       token_node_t *next_non_space;
1650
1651       /* Look ahead for a PASTE token, skipping space. */
1652       next_non_space = node->next;
1653       while (next_non_space && next_non_space->token->type == SPACE)
1654          next_non_space = next_non_space->next;
1655
1656       if (next_non_space == NULL)
1657          break;
1658
1659       if (next_non_space->token->type != PASTE) {
1660          node = next_non_space;
1661          continue;
1662       }
1663
1664       /* Now find the next non-space token after the PASTE. */
1665       next_non_space = next_non_space->next;
1666       while (next_non_space && next_non_space->token->type == SPACE)
1667          next_non_space = next_non_space->next;
1668
1669       if (next_non_space == NULL) {
1670          yyerror(&node->token->location, parser, "'##' cannot appear at either end of a macro expansion\n");
1671          return;
1672       }
1673
1674       node->token = _token_paste(parser, node->token, next_non_space->token);
1675       node->next = next_non_space->next;
1676       if (next_non_space == list->tail)
1677          list->tail = node;
1678    }
1679
1680    list->non_space_tail = list->tail;
1681 }
1682
1683 /* This is a helper function that's essentially part of the
1684  * implementation of _glcpp_parser_expand_node. It shouldn't be called
1685  * except for by that function.
1686  *
1687  * Returns NULL if node is a simple token with no expansion, (that is,
1688  * although 'node' corresponds to an identifier defined as a
1689  * function-like macro, it is not followed with a parenthesized
1690  * argument list).
1691  *
1692  * Compute the complete expansion of node (which is a function-like
1693  * macro) and subsequent nodes which are arguments.
1694  *
1695  * Returns the token list that results from the expansion and sets
1696  * *last to the last node in the list that was consumed by the
1697  * expansion. Specifically, *last will be set as follows: as the
1698  * token of the closing right parenthesis.
1699  *
1700  * See the documentation of _glcpp_parser_expand_token_list for a description
1701  * of the "mode" parameter.
1702  */
1703 static token_list_t *
1704 _glcpp_parser_expand_function(glcpp_parser_t *parser, token_node_t *node,
1705                               token_node_t **last, expansion_mode_t mode)
1706 {
1707    macro_t *macro;
1708    const char *identifier;
1709    argument_list_t *arguments;
1710    function_status_t status;
1711    token_list_t *substituted;
1712    int parameter_index;
1713
1714    identifier = node->token->value.str;
1715
1716    macro = hash_table_find(parser->defines, identifier);
1717
1718    assert(macro->is_function);
1719
1720    arguments = _argument_list_create(parser);
1721    status = _arguments_parse(arguments, node, last);
1722
1723    switch (status) {
1724    case FUNCTION_STATUS_SUCCESS:
1725       break;
1726    case FUNCTION_NOT_A_FUNCTION:
1727       return NULL;
1728    case FUNCTION_UNBALANCED_PARENTHESES:
1729       glcpp_error(&node->token->location, parser, "Macro %s call has unbalanced parentheses\n", identifier);
1730       return NULL;
1731    }
1732
1733    /* Replace a macro defined as empty with a SPACE token. */
1734    if (macro->replacements == NULL) {
1735       ralloc_free(arguments);
1736       return _token_list_create_with_one_space(parser);
1737    }
1738
1739    if (!((_argument_list_length (arguments) ==
1740           _string_list_length (macro->parameters)) ||
1741          (_string_list_length (macro->parameters) == 0 &&
1742           _argument_list_length (arguments) == 1 &&
1743           arguments->head->argument->head == NULL))) {
1744       glcpp_error(&node->token->location, parser,
1745                   "Error: macro %s invoked with %d arguments (expected %d)\n",
1746                   identifier, _argument_list_length (arguments),
1747                   _string_list_length(macro->parameters));
1748       return NULL;
1749    }
1750
1751    /* Perform argument substitution on the replacement list. */
1752    substituted = _token_list_create(arguments);
1753
1754    for (node = macro->replacements->head; node; node = node->next) {
1755       if (node->token->type == IDENTIFIER &&
1756           _string_list_contains(macro->parameters, node->token->value.str,
1757                                 &parameter_index)) {
1758          token_list_t *argument;
1759          argument = _argument_list_member_at(arguments, parameter_index);
1760          /* Before substituting, we expand the argument tokens, or append a
1761           * placeholder token for an empty argument. */
1762          if (argument->head) {
1763             token_list_t *expanded_argument;
1764             expanded_argument = _token_list_copy(parser, argument);
1765             _glcpp_parser_expand_token_list(parser, expanded_argument, mode);
1766             _token_list_append_list(substituted, expanded_argument);
1767          } else {
1768             token_t *new_token;
1769
1770             new_token = _token_create_ival(substituted, PLACEHOLDER,
1771                                            PLACEHOLDER);
1772             _token_list_append(substituted, new_token);
1773          }
1774       } else {
1775          _token_list_append(substituted, node->token);
1776       }
1777    }
1778
1779    /* After argument substitution, and before further expansion
1780     * below, implement token pasting. */
1781
1782    _token_list_trim_trailing_space(substituted);
1783
1784    _glcpp_parser_apply_pastes(parser, substituted);
1785
1786    return substituted;
1787 }
1788
1789 /* Compute the complete expansion of node, (and subsequent nodes after
1790  * 'node' in the case that 'node' is a function-like macro and
1791  * subsequent nodes are arguments).
1792  *
1793  * Returns NULL if node is a simple token with no expansion.
1794  *
1795  * Otherwise, returns the token list that results from the expansion
1796  * and sets *last to the last node in the list that was consumed by
1797  * the expansion. Specifically, *last will be set as follows:
1798  *
1799  *   As 'node' in the case of object-like macro expansion.
1800  *
1801  *   As the token of the closing right parenthesis in the case of
1802  *   function-like macro expansion.
1803  *
1804  * See the documentation of _glcpp_parser_expand_token_list for a description
1805  * of the "mode" parameter.
1806  */
1807 static token_list_t *
1808 _glcpp_parser_expand_node(glcpp_parser_t *parser, token_node_t *node,
1809                           token_node_t **last, expansion_mode_t mode)
1810 {
1811    token_t *token = node->token;
1812    const char *identifier;
1813    macro_t *macro;
1814
1815    /* We only expand identifiers */
1816    if (token->type != IDENTIFIER) {
1817       return NULL;
1818    }
1819
1820    *last = node;
1821    identifier = token->value.str;
1822
1823    /* Special handling for __LINE__ and __FILE__, (not through
1824     * the hash table). */
1825    if (strcmp(identifier, "__LINE__") == 0)
1826       return _token_list_create_with_one_integer(parser, node->token->location.first_line);
1827
1828    if (strcmp(identifier, "__FILE__") == 0)
1829       return _token_list_create_with_one_integer(parser, node->token->location.source);
1830
1831    /* Look up this identifier in the hash table. */
1832    macro = hash_table_find(parser->defines, identifier);
1833
1834    /* Not a macro, so no expansion needed. */
1835    if (macro == NULL)
1836       return NULL;
1837
1838    /* Finally, don't expand this macro if we're already actively
1839     * expanding it, (to avoid infinite recursion). */
1840    if (_parser_active_list_contains (parser, identifier)) {
1841       /* We change the token type here from IDENTIFIER to OTHER to prevent any
1842        * future expansion of this unexpanded token. */
1843       char *str;
1844       token_list_t *expansion;
1845       token_t *final;
1846
1847       str = ralloc_strdup(parser, token->value.str);
1848       final = _token_create_str(parser, OTHER, str);
1849       expansion = _token_list_create(parser);
1850       _token_list_append(expansion, final);
1851       return expansion;
1852    }
1853
1854    if (! macro->is_function) {
1855       token_list_t *replacement;
1856
1857       /* Replace a macro defined as empty with a SPACE token. */
1858       if (macro->replacements == NULL)
1859          return _token_list_create_with_one_space(parser);
1860
1861       replacement = _token_list_copy(parser, macro->replacements);
1862       _glcpp_parser_apply_pastes(parser, replacement);
1863       return replacement;
1864    }
1865
1866    return _glcpp_parser_expand_function(parser, node, last, mode);
1867 }
1868
1869 /* Push a new identifier onto the parser's active list.
1870  *
1871  * Here, 'marker' is the token node that appears in the list after the
1872  * expansion of 'identifier'. That is, when the list iterator begins
1873  * examining 'marker', then it is time to pop this node from the
1874  * active stack.
1875  */
1876 static void
1877 _parser_active_list_push(glcpp_parser_t *parser, const char *identifier,
1878                          token_node_t *marker)
1879 {
1880    active_list_t *node;
1881
1882    node = ralloc(parser->active, active_list_t);
1883    node->identifier = ralloc_strdup(node, identifier);
1884    node->marker = marker;
1885    node->next = parser->active;
1886
1887    parser->active = node;
1888 }
1889
1890 static void
1891 _parser_active_list_pop(glcpp_parser_t *parser)
1892 {
1893    active_list_t *node = parser->active;
1894
1895    if (node == NULL) {
1896       parser->active = NULL;
1897       return;
1898    }
1899
1900    node = parser->active->next;
1901    ralloc_free (parser->active);
1902
1903    parser->active = node;
1904 }
1905
1906 static int
1907 _parser_active_list_contains(glcpp_parser_t *parser, const char *identifier)
1908 {
1909    active_list_t *node;
1910
1911    if (parser->active == NULL)
1912       return 0;
1913
1914    for (node = parser->active; node; node = node->next)
1915       if (strcmp(node->identifier, identifier) == 0)
1916          return 1;
1917
1918    return 0;
1919 }
1920
1921 /* Walk over the token list replacing nodes with their expansion.
1922  * Whenever nodes are expanded the walking will walk over the new
1923  * nodes, continuing to expand as necessary. The results are placed in
1924  * 'list' itself.
1925  *
1926  * The "mode" argument controls the handling of any DEFINED tokens that
1927  * result from expansion as follows:
1928  *
1929  *   EXPANSION_MODE_IGNORE_DEFINED: Any resulting DEFINED tokens will be
1930  *      left in the final list, unevaluated. This is the correct mode
1931  *      for expanding any list in any context other than a
1932  *      preprocessor conditional, (#if or #elif).
1933  *
1934  *   EXPANSION_MODE_EVALUATE_DEFINED: Any resulting DEFINED tokens will be
1935  *      evaluated to 0 or 1 tokens depending on whether the following
1936  *      token is the name of a defined macro. If the DEFINED token is
1937  *      not followed by an (optionally parenthesized) identifier, then
1938  *      an error will be generated. This the correct mode for
1939  *      expanding any list in the context of a preprocessor
1940  *      conditional, (#if or #elif).
1941  */
1942 static void
1943 _glcpp_parser_expand_token_list(glcpp_parser_t *parser, token_list_t *list,
1944                                 expansion_mode_t mode)
1945 {
1946    token_node_t *node_prev;
1947    token_node_t *node, *last = NULL;
1948    token_list_t *expansion;
1949    active_list_t *active_initial = parser->active;
1950
1951    if (list == NULL)
1952       return;
1953
1954    _token_list_trim_trailing_space (list);
1955
1956    node_prev = NULL;
1957    node = list->head;
1958
1959    if (mode == EXPANSION_MODE_EVALUATE_DEFINED)
1960       _glcpp_parser_evaluate_defined_in_list (parser, list);
1961
1962    while (node) {
1963
1964       while (parser->active && parser->active->marker == node)
1965          _parser_active_list_pop (parser);
1966
1967       expansion = _glcpp_parser_expand_node (parser, node, &last, mode);
1968       if (expansion) {
1969          token_node_t *n;
1970
1971          if (mode == EXPANSION_MODE_EVALUATE_DEFINED) {
1972             _glcpp_parser_evaluate_defined_in_list (parser, expansion);
1973          }
1974
1975          for (n = node; n != last->next; n = n->next)
1976             while (parser->active && parser->active->marker == n) {
1977                _parser_active_list_pop (parser);
1978             }
1979
1980          _parser_active_list_push(parser, node->token->value.str, last->next);
1981
1982          /* Splice expansion into list, supporting a simple deletion if the
1983           * expansion is empty.
1984           */
1985          if (expansion->head) {
1986             if (node_prev)
1987                node_prev->next = expansion->head;
1988             else
1989                list->head = expansion->head;
1990             expansion->tail->next = last->next;
1991             if (last == list->tail)
1992                list->tail = expansion->tail;
1993          } else {
1994             if (node_prev)
1995                node_prev->next = last->next;
1996             else
1997                list->head = last->next;
1998             if (last == list->tail)
1999                list->tail = NULL;
2000          }
2001       } else {
2002          node_prev = node;
2003       }
2004       node = node_prev ? node_prev->next : list->head;
2005    }
2006
2007    /* Remove any lingering effects of this invocation on the
2008     * active list. That is, pop until the list looks like it did
2009     * at the beginning of this function. */
2010    while (parser->active && parser->active != active_initial)
2011       _parser_active_list_pop (parser);
2012
2013    list->non_space_tail = list->tail;
2014 }
2015
2016 void
2017 _glcpp_parser_print_expanded_token_list(glcpp_parser_t *parser,
2018                                         token_list_t *list)
2019 {
2020    if (list == NULL)
2021       return;
2022
2023    _glcpp_parser_expand_token_list (parser, list, EXPANSION_MODE_IGNORE_DEFINED);
2024
2025    _token_list_trim_trailing_space (list);
2026
2027    _token_list_print (parser, list);
2028 }
2029
2030 static void
2031 _check_for_reserved_macro_name(glcpp_parser_t *parser, YYLTYPE *loc,
2032                                const char *identifier)
2033 {
2034    /* Section 3.3 (Preprocessor) of the GLSL 1.30 spec (and later) and
2035     * the GLSL ES spec (all versions) say:
2036     *
2037     *     "All macro names containing two consecutive underscores ( __ )
2038     *     are reserved for future use as predefined macro names. All
2039     *     macro names prefixed with "GL_" ("GL" followed by a single
2040     *     underscore) are also reserved."
2041     *
2042     * The intention is that names containing __ are reserved for internal
2043     * use by the implementation, and names prefixed with GL_ are reserved
2044     * for use by Khronos.  Since every extension adds a name prefixed
2045     * with GL_ (i.e., the name of the extension), that should be an
2046     * error.  Names simply containing __ are dangerous to use, but should
2047     * be allowed.
2048     *
2049     * A future version of the GLSL specification will clarify this.
2050     */
2051    if (strstr(identifier, "__")) {
2052       glcpp_warning(loc, parser, "Macro names containing \"__\" are reserved "
2053                     "for use by the implementation.\n");
2054    }
2055    if (strncmp(identifier, "GL_", 3) == 0) {
2056       glcpp_error (loc, parser, "Macro names starting with \"GL_\" are reserved.\n");
2057    }
2058    if (strcmp(identifier, "defined") == 0) {
2059       glcpp_error (loc, parser, "\"defined\" cannot be used as a macro name");
2060    }
2061 }
2062
2063 static int
2064 _macro_equal(macro_t *a, macro_t *b)
2065 {
2066    if (a->is_function != b->is_function)
2067       return 0;
2068
2069    if (a->is_function) {
2070       if (! _string_list_equal (a->parameters, b->parameters))
2071          return 0;
2072    }
2073
2074    return _token_list_equal_ignoring_space(a->replacements, b->replacements);
2075 }
2076
2077 void
2078 _define_object_macro(glcpp_parser_t *parser, YYLTYPE *loc,
2079                      const char *identifier, token_list_t *replacements)
2080 {
2081    macro_t *macro, *previous;
2082
2083    /* We define pre-defined macros before we've started parsing the actual
2084     * file. So if there's no location defined yet, that's what were doing and
2085     * we don't want to generate an error for using the reserved names. */
2086    if (loc != NULL)
2087       _check_for_reserved_macro_name(parser, loc, identifier);
2088
2089    macro = ralloc (parser, macro_t);
2090
2091    macro->is_function = 0;
2092    macro->parameters = NULL;
2093    macro->identifier = ralloc_strdup (macro, identifier);
2094    macro->replacements = replacements;
2095    ralloc_steal (macro, replacements);
2096
2097    previous = hash_table_find (parser->defines, identifier);
2098    if (previous) {
2099       if (_macro_equal (macro, previous)) {
2100          ralloc_free (macro);
2101          return;
2102       }
2103       glcpp_error (loc, parser, "Redefinition of macro %s\n",  identifier);
2104    }
2105
2106    hash_table_insert (parser->defines, macro, identifier);
2107 }
2108
2109 void
2110 _define_function_macro(glcpp_parser_t *parser, YYLTYPE *loc,
2111                        const char *identifier, string_list_t *parameters,
2112                        token_list_t *replacements)
2113 {
2114    macro_t *macro, *previous;
2115    const char *dup;
2116
2117    _check_for_reserved_macro_name(parser, loc, identifier);
2118
2119         /* Check for any duplicate parameter names. */
2120    if ((dup = _string_list_has_duplicate (parameters)) != NULL) {
2121       glcpp_error (loc, parser, "Duplicate macro parameter \"%s\"", dup);
2122    }
2123
2124    macro = ralloc (parser, macro_t);
2125    ralloc_steal (macro, parameters);
2126    ralloc_steal (macro, replacements);
2127
2128    macro->is_function = 1;
2129    macro->parameters = parameters;
2130    macro->identifier = ralloc_strdup (macro, identifier);
2131    macro->replacements = replacements;
2132    previous = hash_table_find (parser->defines, identifier);
2133    if (previous) {
2134       if (_macro_equal (macro, previous)) {
2135          ralloc_free (macro);
2136          return;
2137       }
2138       glcpp_error (loc, parser, "Redefinition of macro %s\n", identifier);
2139    }
2140
2141    hash_table_insert(parser->defines, macro, identifier);
2142 }
2143
2144 static int
2145 glcpp_parser_lex(YYSTYPE *yylval, YYLTYPE *yylloc, glcpp_parser_t *parser)
2146 {
2147    token_node_t *node;
2148    int ret;
2149
2150    if (parser->lex_from_list == NULL) {
2151       ret = glcpp_lex(yylval, yylloc, parser->scanner);
2152
2153       /* XXX: This ugly block of code exists for the sole
2154        * purpose of converting a NEWLINE token into a SPACE
2155        * token, but only in the case where we have seen a
2156        * function-like macro name, but have not yet seen its
2157        * closing parenthesis.
2158        *
2159        * There's perhaps a more compact way to do this with
2160        * mid-rule actions in the grammar.
2161        *
2162        * I'm definitely not pleased with the complexity of
2163        * this code here.
2164        */
2165       if (parser->newline_as_space) {
2166          if (ret == '(') {
2167             parser->paren_count++;
2168          } else if (ret == ')') {
2169             parser->paren_count--;
2170             if (parser->paren_count == 0)
2171                parser->newline_as_space = 0;
2172          } else if (ret == NEWLINE) {
2173             ret = SPACE;
2174          } else if (ret != SPACE) {
2175             if (parser->paren_count == 0)
2176                parser->newline_as_space = 0;
2177          }
2178       } else if (parser->in_control_line) {
2179          if (ret == NEWLINE)
2180             parser->in_control_line = 0;
2181       }
2182       else if (ret == DEFINE_TOKEN || ret == UNDEF || ret == IF ||
2183                ret == IFDEF || ret == IFNDEF || ret == ELIF || ret == ELSE ||
2184                ret == ENDIF || ret == HASH_TOKEN) {
2185          parser->in_control_line = 1;
2186       } else if (ret == IDENTIFIER) {
2187          macro_t *macro;
2188          macro = hash_table_find (parser->defines,
2189                    yylval->str);
2190          if (macro && macro->is_function) {
2191             parser->newline_as_space = 1;
2192             parser->paren_count = 0;
2193          }
2194       }
2195
2196       return ret;
2197    }
2198
2199    node = parser->lex_from_node;
2200
2201    if (node == NULL) {
2202       ralloc_free (parser->lex_from_list);
2203       parser->lex_from_list = NULL;
2204       return NEWLINE;
2205    }
2206
2207    *yylval = node->token->value;
2208    ret = node->token->type;
2209
2210    parser->lex_from_node = node->next;
2211
2212    return ret;
2213 }
2214
2215 static void
2216 glcpp_parser_lex_from(glcpp_parser_t *parser, token_list_t *list)
2217 {
2218    token_node_t *node;
2219
2220    assert (parser->lex_from_list == NULL);
2221
2222    /* Copy list, eliminating any space tokens. */
2223    parser->lex_from_list = _token_list_create (parser);
2224
2225    for (node = list->head; node; node = node->next) {
2226       if (node->token->type == SPACE)
2227          continue;
2228       _token_list_append (parser->lex_from_list, node->token);
2229    }
2230
2231    ralloc_free (list);
2232
2233    parser->lex_from_node = parser->lex_from_list->head;
2234
2235    /* It's possible the list consisted of nothing but whitespace. */
2236    if (parser->lex_from_node == NULL) {
2237       ralloc_free (parser->lex_from_list);
2238       parser->lex_from_list = NULL;
2239    }
2240 }
2241
2242 static void
2243 _glcpp_parser_skip_stack_push_if(glcpp_parser_t *parser, YYLTYPE *loc,
2244                                  int condition)
2245 {
2246    skip_type_t current = SKIP_NO_SKIP;
2247    skip_node_t *node;
2248
2249    if (parser->skip_stack)
2250       current = parser->skip_stack->type;
2251
2252    node = ralloc (parser, skip_node_t);
2253    node->loc = *loc;
2254
2255    if (current == SKIP_NO_SKIP) {
2256       if (condition)
2257          node->type = SKIP_NO_SKIP;
2258       else
2259          node->type = SKIP_TO_ELSE;
2260    } else {
2261       node->type = SKIP_TO_ENDIF;
2262    }
2263
2264    node->has_else = false;
2265    node->next = parser->skip_stack;
2266    parser->skip_stack = node;
2267 }
2268
2269 static void
2270 _glcpp_parser_skip_stack_change_if(glcpp_parser_t *parser, YYLTYPE *loc,
2271                                    const char *type, int condition)
2272 {
2273    if (parser->skip_stack == NULL) {
2274       glcpp_error (loc, parser, "#%s without #if\n", type);
2275       return;
2276    }
2277
2278    if (parser->skip_stack->type == SKIP_TO_ELSE) {
2279       if (condition)
2280          parser->skip_stack->type = SKIP_NO_SKIP;
2281    } else {
2282       parser->skip_stack->type = SKIP_TO_ENDIF;
2283    }
2284 }
2285
2286 static void
2287 _glcpp_parser_skip_stack_pop(glcpp_parser_t *parser, YYLTYPE *loc)
2288 {
2289    skip_node_t *node;
2290
2291    if (parser->skip_stack == NULL) {
2292       glcpp_error (loc, parser, "#endif without #if\n");
2293       return;
2294    }
2295
2296    node = parser->skip_stack;
2297    parser->skip_stack = node->next;
2298    ralloc_free (node);
2299 }
2300
2301 static void
2302 _glcpp_parser_handle_version_declaration(glcpp_parser_t *parser, intmax_t version,
2303                                          const char *es_identifier,
2304                                          bool explicitly_set)
2305 {
2306    const struct gl_extensions *extensions = parser->extensions;
2307
2308    if (parser->version != 0)
2309       return;
2310
2311    parser->version = version;
2312
2313    add_builtin_define (parser, "__VERSION__", version);
2314
2315    parser->is_gles = (version == 100) ||
2316                      (es_identifier && (strcmp(es_identifier, "es") == 0));
2317
2318    /* Add pre-defined macros. */
2319    if (parser->is_gles) {
2320       add_builtin_define(parser, "GL_ES", 1);
2321       add_builtin_define(parser, "GL_EXT_separate_shader_objects", 1);
2322       add_builtin_define(parser, "GL_EXT_draw_buffers", 1);
2323
2324       if (extensions != NULL) {
2325          if (extensions->OES_EGL_image_external)
2326             add_builtin_define(parser, "GL_OES_EGL_image_external", 1);
2327          if (extensions->OES_sample_variables) {
2328             add_builtin_define(parser, "GL_OES_sample_variables", 1);
2329             add_builtin_define(parser, "GL_OES_shader_multisample_interpolation", 1);
2330          }
2331          if (extensions->OES_standard_derivatives)
2332             add_builtin_define(parser, "GL_OES_standard_derivatives", 1);
2333          if (extensions->ARB_texture_multisample)
2334             add_builtin_define(parser, "GL_OES_texture_storage_multisample_2d_array", 1);
2335          if (extensions->ARB_blend_func_extended)
2336             add_builtin_define(parser, "GL_EXT_blend_func_extended", 1);
2337          if (extensions->ARB_cull_distance)
2338             add_builtin_define(parser, "GL_EXT_clip_cull_distance", 1);
2339
2340          if (version >= 310) {
2341             if (extensions->ARB_shader_image_load_store)
2342                add_builtin_define(parser, "GL_OES_shader_image_atomic", 1);
2343
2344             if (extensions->OES_geometry_shader) {
2345                add_builtin_define(parser, "GL_OES_geometry_point_size", 1);
2346                add_builtin_define(parser, "GL_OES_geometry_shader", 1);
2347             }
2348             if (extensions->ARB_gpu_shader5) {
2349                add_builtin_define(parser, "GL_EXT_gpu_shader5", 1);
2350                add_builtin_define(parser, "GL_OES_gpu_shader5", 1);
2351             }
2352             if (extensions->OES_texture_buffer) {
2353                add_builtin_define(parser, "GL_EXT_texture_buffer", 1);
2354                add_builtin_define(parser, "GL_OES_texture_buffer", 1);
2355             }
2356
2357             if (extensions->OES_shader_io_blocks) {
2358                add_builtin_define(parser, "GL_EXT_shader_io_blocks", 1);
2359                add_builtin_define(parser, "GL_OES_shader_io_blocks", 1);
2360             }
2361          }
2362       }
2363    } else {
2364       add_builtin_define(parser, "GL_ARB_draw_buffers", 1);
2365       add_builtin_define(parser, "GL_ARB_enhanced_layouts", 1);
2366       add_builtin_define(parser, "GL_ARB_separate_shader_objects", 1);
2367       add_builtin_define(parser, "GL_ARB_texture_rectangle", 1);
2368       add_builtin_define(parser, "GL_AMD_shader_trinary_minmax", 1);
2369
2370       if (extensions != NULL) {
2371          if (extensions->EXT_texture_array)
2372             add_builtin_define(parser, "GL_EXT_texture_array", 1);
2373
2374          if (extensions->ARB_ES3_1_compatibility)
2375             add_builtin_define(parser, "GL_ARB_ES3_1_compatibility", 1);
2376
2377          if (extensions->ARB_arrays_of_arrays)
2378              add_builtin_define(parser, "GL_ARB_arrays_of_arrays", 1);
2379
2380          if (extensions->ARB_fragment_coord_conventions) {
2381             add_builtin_define(parser, "GL_ARB_fragment_coord_conventions",
2382                                1);
2383          }
2384
2385          if (extensions->ARB_fragment_layer_viewport)
2386             add_builtin_define(parser, "GL_ARB_fragment_layer_viewport", 1);
2387
2388          if (extensions->ARB_explicit_attrib_location)
2389             add_builtin_define(parser, "GL_ARB_explicit_attrib_location", 1);
2390
2391          if (extensions->ARB_explicit_uniform_location)
2392             add_builtin_define(parser, "GL_ARB_explicit_uniform_location", 1);
2393
2394          if (extensions->ARB_shader_texture_lod)
2395             add_builtin_define(parser, "GL_ARB_shader_texture_lod", 1);
2396
2397          if (extensions->ARB_draw_instanced)
2398             add_builtin_define(parser, "GL_ARB_draw_instanced", 1);
2399
2400          if (extensions->ARB_conservative_depth) {
2401             add_builtin_define(parser, "GL_AMD_conservative_depth", 1);
2402             add_builtin_define(parser, "GL_ARB_conservative_depth", 1);
2403          }
2404
2405          if (extensions->ARB_shader_bit_encoding)
2406             add_builtin_define(parser, "GL_ARB_shader_bit_encoding", 1);
2407
2408          if (extensions->ARB_shader_clock)
2409             add_builtin_define(parser, "GL_ARB_shader_clock", 1);
2410
2411          if (extensions->ARB_uniform_buffer_object)
2412             add_builtin_define(parser, "GL_ARB_uniform_buffer_object", 1);
2413
2414          if (extensions->ARB_texture_cube_map_array)
2415             add_builtin_define(parser, "GL_ARB_texture_cube_map_array", 1);
2416
2417          if (extensions->ARB_shading_language_packing)
2418             add_builtin_define(parser, "GL_ARB_shading_language_packing", 1);
2419
2420          if (extensions->ARB_texture_multisample)
2421             add_builtin_define(parser, "GL_ARB_texture_multisample", 1);
2422
2423          if (extensions->ARB_texture_query_levels)
2424             add_builtin_define(parser, "GL_ARB_texture_query_levels", 1);
2425
2426          if (extensions->ARB_texture_query_lod)
2427             add_builtin_define(parser, "GL_ARB_texture_query_lod", 1);
2428
2429          if (extensions->ARB_gpu_shader5)
2430             add_builtin_define(parser, "GL_ARB_gpu_shader5", 1);
2431
2432          if (extensions->ARB_gpu_shader_fp64)
2433             add_builtin_define(parser, "GL_ARB_gpu_shader_fp64", 1);
2434
2435          if (extensions->ARB_vertex_attrib_64bit)
2436             add_builtin_define(parser, "GL_ARB_vertex_attrib_64bit", 1);
2437
2438          if (extensions->AMD_vertex_shader_layer)
2439             add_builtin_define(parser, "GL_AMD_vertex_shader_layer", 1);
2440
2441          if (extensions->AMD_vertex_shader_viewport_index)
2442             add_builtin_define(parser, "GL_AMD_vertex_shader_viewport_index", 1);
2443
2444          if (extensions->ARB_shading_language_420pack)
2445             add_builtin_define(parser, "GL_ARB_shading_language_420pack", 1);
2446
2447          if (extensions->ARB_sample_shading)
2448             add_builtin_define(parser, "GL_ARB_sample_shading", 1);
2449
2450          if (extensions->ARB_texture_gather)
2451             add_builtin_define(parser, "GL_ARB_texture_gather", 1);
2452
2453          if (extensions->ARB_shader_atomic_counters)
2454             add_builtin_define(parser, "GL_ARB_shader_atomic_counters", 1);
2455
2456          if (extensions->ARB_shader_atomic_counter_ops)
2457             add_builtin_define(parser, "GL_ARB_shader_atomic_counter_ops", 1);
2458
2459          if (extensions->ARB_viewport_array)
2460             add_builtin_define(parser, "GL_ARB_viewport_array", 1);
2461
2462          if (extensions->ARB_compute_shader)
2463             add_builtin_define(parser, "GL_ARB_compute_shader", 1);
2464
2465          if (extensions->ARB_shader_image_load_store)
2466             add_builtin_define(parser, "GL_ARB_shader_image_load_store", 1);
2467
2468          if (extensions->ARB_shader_image_size)
2469             add_builtin_define(parser, "GL_ARB_shader_image_size", 1);
2470
2471          if (extensions->ARB_shader_texture_image_samples)
2472             add_builtin_define(parser, "GL_ARB_shader_texture_image_samples", 1);
2473
2474          if (extensions->ARB_derivative_control)
2475             add_builtin_define(parser, "GL_ARB_derivative_control", 1);
2476
2477          if (extensions->ARB_shader_precision)
2478             add_builtin_define(parser, "GL_ARB_shader_precision", 1);
2479
2480          if (extensions->ARB_shader_storage_buffer_object)
2481             add_builtin_define(parser, "GL_ARB_shader_storage_buffer_object", 1);
2482
2483          if (extensions->ARB_tessellation_shader)
2484             add_builtin_define(parser, "GL_ARB_tessellation_shader", 1);
2485
2486          if (extensions->ARB_shader_subroutine)
2487             add_builtin_define(parser, "GL_ARB_shader_subroutine", 1);
2488
2489          if (extensions->ARB_shader_draw_parameters)
2490             add_builtin_define(parser, "GL_ARB_shader_draw_parameters", 1);
2491
2492          if (extensions->ARB_cull_distance)
2493             add_builtin_define(parser, "GL_ARB_cull_distance", 1);
2494       }
2495    }
2496
2497    if (extensions != NULL) {
2498       if (extensions->EXT_shader_integer_mix)
2499          add_builtin_define(parser, "GL_EXT_shader_integer_mix", 1);
2500
2501       if (extensions->EXT_shader_samples_identical)
2502          add_builtin_define(parser, "GL_EXT_shader_samples_identical", 1);
2503    }
2504
2505    if (version >= 150)
2506       add_builtin_define(parser, "GL_core_profile", 1);
2507
2508    /* Currently, all ES2/ES3 implementations support highp in the
2509     * fragment shader, so we always define this macro in ES2/ES3.
2510     * If we ever get a driver that doesn't support highp, we'll
2511     * need to add a flag to the gl_context and check that here.
2512     */
2513    if (version >= 130 || parser->is_gles)
2514       add_builtin_define (parser, "GL_FRAGMENT_PRECISION_HIGH", 1);
2515
2516    if (explicitly_set) {
2517       ralloc_asprintf_rewrite_tail(&parser->output, &parser->output_length,
2518                                    "#version %" PRIiMAX "%s%s", version,
2519                                    es_identifier ? " " : "",
2520                                    es_identifier ? es_identifier : "");
2521    }
2522 }
2523
2524 /* GLSL version if no version is explicitly specified. */
2525 #define IMPLICIT_GLSL_VERSION 110
2526
2527 /* GLSL ES version if no version is explicitly specified. */
2528 #define IMPLICIT_GLSL_ES_VERSION 100
2529
2530 void
2531 glcpp_parser_resolve_implicit_version(glcpp_parser_t *parser)
2532 {
2533    int language_version = parser->api == API_OPENGLES2 ?
2534                           IMPLICIT_GLSL_ES_VERSION : IMPLICIT_GLSL_VERSION;
2535
2536    _glcpp_parser_handle_version_declaration(parser, language_version,
2537                                             NULL, false);
2538 }