• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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(glcpp_parser_t *parser);
53 
54 static void
55 _string_list_append_item(glcpp_parser_t *parser, string_list_t *list,
56                          const char *str);
57 
58 static int
59 _string_list_contains(string_list_t *list, const char *member, int *index);
60 
61 static const char *
62 _string_list_has_duplicate(string_list_t *list);
63 
64 static int
65 _string_list_length(string_list_t *list);
66 
67 static int
68 _string_list_equal(string_list_t *a, string_list_t *b);
69 
70 static argument_list_t *
71 _argument_list_create(glcpp_parser_t *parser);
72 
73 static void
74 _argument_list_append(glcpp_parser_t *parser, argument_list_t *list,
75                       token_list_t *argument);
76 
77 static int
78 _argument_list_length(argument_list_t *list);
79 
80 static token_list_t *
81 _argument_list_member_at(argument_list_t *list, int index);
82 
83 static token_t *
84 _token_create_str(glcpp_parser_t *parser, int type, char *str);
85 
86 static token_t *
87 _token_create_ival(glcpp_parser_t *parser, int type, int ival);
88 
89 static token_list_t *
90 _token_list_create(glcpp_parser_t *parser);
91 
92 static void
93 _token_list_append(glcpp_parser_t *parser, token_list_t *list, token_t *token);
94 
95 static void
96 _token_list_append_list(token_list_t *list, token_list_t *tail);
97 
98 static int
99 _token_list_equal_ignoring_space(token_list_t *a, token_list_t *b);
100 
101 static void
102 _parser_active_list_push(glcpp_parser_t *parser, const char *identifier,
103                          token_node_t *marker);
104 
105 static void
106 _parser_active_list_pop(glcpp_parser_t *parser);
107 
108 static int
109 _parser_active_list_contains(glcpp_parser_t *parser, const char *identifier);
110 
111 typedef enum {
112    EXPANSION_MODE_IGNORE_DEFINED,
113    EXPANSION_MODE_EVALUATE_DEFINED
114 } expansion_mode_t;
115 
116 /* Expand list, and begin lexing from the result (after first
117  * prefixing a token of type 'head_token_type').
118  */
119 static void
120 _glcpp_parser_expand_and_lex_from(glcpp_parser_t *parser, int head_token_type,
121                                   token_list_t *list, expansion_mode_t mode);
122 
123 /* Perform macro expansion in-place on the given list. */
124 static void
125 _glcpp_parser_expand_token_list(glcpp_parser_t *parser, token_list_t *list,
126                                 expansion_mode_t mode);
127 
128 static void
129 _glcpp_parser_print_expanded_token_list(glcpp_parser_t *parser,
130                                         token_list_t *list);
131 
132 static void
133 _glcpp_parser_skip_stack_push_if(glcpp_parser_t *parser, YYLTYPE *loc,
134                                  int condition);
135 
136 static void
137 _glcpp_parser_skip_stack_change_if(glcpp_parser_t *parser, YYLTYPE *loc,
138                                    const char *type, int condition);
139 
140 static void
141 _glcpp_parser_skip_stack_pop(glcpp_parser_t *parser, YYLTYPE *loc);
142 
143 static void
144 _glcpp_parser_handle_version_declaration(glcpp_parser_t *parser, intmax_t version,
145                                          const char *ident, bool explicitly_set);
146 
147 static int
148 glcpp_parser_lex(YYSTYPE *yylval, YYLTYPE *yylloc, glcpp_parser_t *parser);
149 
150 static void
151 glcpp_parser_lex_from(glcpp_parser_t *parser, token_list_t *list);
152 
153 static void
154 add_builtin_define(glcpp_parser_t *parser, const char *name, int value);
155 
156 %}
157 
158 %pure-parser
159 %error-verbose
160 
161 %locations
162 %initial-action {
163    @$.first_line = 1;
164    @$.first_column = 1;
165    @$.last_line = 1;
166    @$.last_column = 1;
167    @$.source = 0;
168 }
169 
170 %parse-param {glcpp_parser_t *parser}
171 %lex-param {glcpp_parser_t *parser}
172 
173 %expect 0
174 
175         /* We use HASH_TOKEN, DEFINE_TOKEN and VERSION_TOKEN (as opposed to
176          * HASH, DEFINE, and VERSION) to avoid conflicts with other symbols,
177          * (such as the <HASH> and <DEFINE> start conditions in the lexer). */
178 %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
179 %token PASTE
180 %type <ival> INTEGER operator SPACE integer_constant version_constant
181 %type <expression_value> expression
182 %type <str> IDENTIFIER FUNC_IDENTIFIER OBJ_IDENTIFIER INTEGER_STRING OTHER ERROR_TOKEN PRAGMA
183 %type <string_list> identifier_list
184 %type <token> preprocessing_token
185 %type <token_list> pp_tokens replacement_list text_line
186 %left OR
187 %left AND
188 %left '|'
189 %left '^'
190 %left '&'
191 %left EQUAL NOT_EQUAL
192 %left '<' '>' LESS_OR_EQUAL GREATER_OR_EQUAL
193 %left LEFT_SHIFT RIGHT_SHIFT
194 %left '+' '-'
195 %left '*' '/' '%'
196 %right UNARY
197 
198 %debug
199 
200 %%
201 
202 input:
203 	/* empty */
204 |	input line
205 ;
206 
207 line:
208 	control_line
209 |	SPACE control_line
210 |	text_line {
211 		_glcpp_parser_print_expanded_token_list (parser, $1);
212 		ralloc_asprintf_rewrite_tail (&parser->output, &parser->output_length, "\n");
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 		struct hash_entry *entry;
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 		entry = _mesa_hash_table_search (parser->defines, $3);
313 		if (entry) {
314 			_mesa_hash_table_remove (parser->defines, entry);
315 		}
316 	}
317 |	HASH_TOKEN IF pp_tokens NEWLINE {
318 		/* Be careful to only evaluate the 'if' expression if
319 		 * we are not skipping. When we are skipping, we
320 		 * simply push a new 0-valued 'if' onto the skip
321 		 * stack.
322 		 *
323 		 * This avoids generating diagnostics for invalid
324 		 * expressions that are being skipped. */
325 		if (parser->skip_stack == NULL ||
326 		    parser->skip_stack->type == SKIP_NO_SKIP)
327 		{
328 			_glcpp_parser_expand_and_lex_from (parser,
329 							   IF_EXPANDED, $3,
330 							   EXPANSION_MODE_EVALUATE_DEFINED);
331 		}
332 		else
333 		{
334 			_glcpp_parser_skip_stack_push_if (parser, & @1, 0);
335 			parser->skip_stack->type = SKIP_TO_ENDIF;
336 		}
337 	}
338 |	HASH_TOKEN IF NEWLINE {
339 		/* #if without an expression is only an error if we
340 		 *  are not skipping */
341 		if (parser->skip_stack == NULL ||
342 		    parser->skip_stack->type == SKIP_NO_SKIP)
343 		{
344 			glcpp_error(& @1, parser, "#if with no expression");
345 		}
346 		_glcpp_parser_skip_stack_push_if (parser, & @1, 0);
347 	}
348 |	HASH_TOKEN IFDEF IDENTIFIER junk NEWLINE {
349 		struct hash_entry *entry =
350 				_mesa_hash_table_search(parser->defines, $3);
351 		macro_t *macro = entry ? entry->data : NULL;
352 		_glcpp_parser_skip_stack_push_if (parser, & @1, macro != NULL);
353 	}
354 |	HASH_TOKEN IFNDEF IDENTIFIER junk NEWLINE {
355 		struct hash_entry *entry =
356 				_mesa_hash_table_search(parser->defines, $3);
357 		macro_t *macro = entry ? entry->data : NULL;
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 version_constant NEWLINE {
423 		if (parser->version_set) {
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 version_constant IDENTIFIER NEWLINE {
429 		if (parser->version_set) {
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 version_constant:
469 	INTEGER_STRING {
470 	   /* Both octal and hexadecimal constants begin with 0. */
471 	   if ($1[0] == '0' && $1[1] != '\0') {
472 		glcpp_error(&@1, parser, "invalid #version \"%s\" (not a decimal constant)", $1);
473 		$$ = 0;
474 	   } else {
475 		$$ = strtoll($1, NULL, 10);
476 	   }
477 	}
478 
479 expression:
480 	integer_constant {
481 		$$.value = $1;
482 		$$.undefined_macro = NULL;
483 	}
484 |	IDENTIFIER {
485 		$$.value = 0;
486 		if (parser->is_gles)
487 			$$.undefined_macro = linear_strdup(parser->linalloc, $1);
488 		else
489 			$$.undefined_macro = NULL;
490 	}
491 |	expression OR expression {
492 		$$.value = $1.value || $3.value;
493 
494 		/* Short-circuit: Only flag undefined from right side
495 		 * if left side evaluates to false.
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 AND expression {
503 		$$.value = $1.value && $3.value;
504 
505 		/* Short-circuit: Only flag undefined from right-side
506 		 * if left side evaluates to true.
507 		 */
508 		if ($1.undefined_macro)
509 			$$.undefined_macro = $1.undefined_macro;
510                 else if ($1.value)
511 			$$.undefined_macro = $3.undefined_macro;
512 	}
513 |	expression '|' expression {
514 		$$.value = $1.value | $3.value;
515 		if ($1.undefined_macro)
516 			$$.undefined_macro = $1.undefined_macro;
517                 else
518 			$$.undefined_macro = $3.undefined_macro;
519 	}
520 |	expression '^' expression {
521 		$$.value = $1.value ^ $3.value;
522 		if ($1.undefined_macro)
523 			$$.undefined_macro = $1.undefined_macro;
524                 else
525 			$$.undefined_macro = $3.undefined_macro;
526 	}
527 |	expression '&' expression {
528 		$$.value = $1.value & $3.value;
529 		if ($1.undefined_macro)
530 			$$.undefined_macro = $1.undefined_macro;
531                 else
532 			$$.undefined_macro = $3.undefined_macro;
533 	}
534 |	expression NOT_EQUAL expression {
535 		$$.value = $1.value != $3.value;
536 		if ($1.undefined_macro)
537 			$$.undefined_macro = $1.undefined_macro;
538                 else
539 			$$.undefined_macro = $3.undefined_macro;
540 	}
541 |	expression EQUAL expression {
542 		$$.value = $1.value == $3.value;
543 		if ($1.undefined_macro)
544 			$$.undefined_macro = $1.undefined_macro;
545                 else
546 			$$.undefined_macro = $3.undefined_macro;
547 	}
548 |	expression GREATER_OR_EQUAL expression {
549 		$$.value = $1.value >= $3.value;
550 		if ($1.undefined_macro)
551 			$$.undefined_macro = $1.undefined_macro;
552                 else
553 			$$.undefined_macro = $3.undefined_macro;
554 	}
555 |	expression LESS_OR_EQUAL expression {
556 		$$.value = $1.value <= $3.value;
557 		if ($1.undefined_macro)
558 			$$.undefined_macro = $1.undefined_macro;
559                 else
560 			$$.undefined_macro = $3.undefined_macro;
561 	}
562 |	expression '>' expression {
563 		$$.value = $1.value > $3.value;
564 		if ($1.undefined_macro)
565 			$$.undefined_macro = $1.undefined_macro;
566                 else
567 			$$.undefined_macro = $3.undefined_macro;
568 	}
569 |	expression '<' expression {
570 		$$.value = $1.value < $3.value;
571 		if ($1.undefined_macro)
572 			$$.undefined_macro = $1.undefined_macro;
573                 else
574 			$$.undefined_macro = $3.undefined_macro;
575 	}
576 |	expression RIGHT_SHIFT expression {
577 		$$.value = $1.value >> $3.value;
578 		if ($1.undefined_macro)
579 			$$.undefined_macro = $1.undefined_macro;
580                 else
581 			$$.undefined_macro = $3.undefined_macro;
582 	}
583 |	expression LEFT_SHIFT expression {
584 		$$.value = $1.value << $3.value;
585 		if ($1.undefined_macro)
586 			$$.undefined_macro = $1.undefined_macro;
587                 else
588 			$$.undefined_macro = $3.undefined_macro;
589 	}
590 |	expression '-' expression {
591 		$$.value = $1.value - $3.value;
592 		if ($1.undefined_macro)
593 			$$.undefined_macro = $1.undefined_macro;
594                 else
595 			$$.undefined_macro = $3.undefined_macro;
596 	}
597 |	expression '+' expression {
598 		$$.value = $1.value + $3.value;
599 		if ($1.undefined_macro)
600 			$$.undefined_macro = $1.undefined_macro;
601                 else
602 			$$.undefined_macro = $3.undefined_macro;
603 	}
604 |	expression '%' expression {
605 		if ($3.value == 0) {
606 			yyerror (& @1, parser,
607 				 "zero modulus in preprocessor directive");
608 		} else {
609 			$$.value = $1.value % $3.value;
610 		}
611 		if ($1.undefined_macro)
612 			$$.undefined_macro = $1.undefined_macro;
613                 else
614 			$$.undefined_macro = $3.undefined_macro;
615 	}
616 |	expression '/' expression {
617 		if ($3.value == 0) {
618 			yyerror (& @1, parser,
619 				 "division by 0 in preprocessor directive");
620 		} else {
621 			$$.value = $1.value / $3.value;
622 		}
623 		if ($1.undefined_macro)
624 			$$.undefined_macro = $1.undefined_macro;
625                 else
626 			$$.undefined_macro = $3.undefined_macro;
627 	}
628 |	expression '*' expression {
629 		$$.value = $1.value * $3.value;
630 		if ($1.undefined_macro)
631 			$$.undefined_macro = $1.undefined_macro;
632                 else
633 			$$.undefined_macro = $3.undefined_macro;
634 	}
635 |	'!' expression %prec UNARY {
636 		$$.value = ! $2.value;
637 		$$.undefined_macro = $2.undefined_macro;
638 	}
639 |	'~' expression %prec UNARY {
640 		$$.value = ~ $2.value;
641 		$$.undefined_macro = $2.undefined_macro;
642 	}
643 |	'-' expression %prec UNARY {
644 		$$.value = - $2.value;
645 		$$.undefined_macro = $2.undefined_macro;
646 	}
647 |	'+' expression %prec UNARY {
648 		$$.value = + $2.value;
649 		$$.undefined_macro = $2.undefined_macro;
650 	}
651 |	'(' expression ')' {
652 		$$ = $2;
653 	}
654 ;
655 
656 identifier_list:
657 	IDENTIFIER {
658 		$$ = _string_list_create (parser);
659 		_string_list_append_item (parser, $$, $1);
660 	}
661 |	identifier_list ',' IDENTIFIER {
662 		$$ = $1;
663 		_string_list_append_item (parser, $$, $3);
664 	}
665 ;
666 
667 text_line:
668 	NEWLINE { $$ = NULL; }
669 |	pp_tokens NEWLINE
670 ;
671 
672 replacement_list:
673 	/* empty */ { $$ = NULL; }
674 |	pp_tokens
675 ;
676 
677 junk:
678 	/* empty */
679 |	pp_tokens {
680 		glcpp_error(&@1, parser, "extra tokens at end of directive");
681 	}
682 ;
683 
684 pp_tokens:
685 	preprocessing_token {
686 		parser->space_tokens = 1;
687 		$$ = _token_list_create (parser);
688 		_token_list_append (parser, $$, $1);
689 	}
690 |	pp_tokens preprocessing_token {
691 		$$ = $1;
692 		_token_list_append (parser, $$, $2);
693 	}
694 ;
695 
696 preprocessing_token:
697 	IDENTIFIER {
698 		$$ = _token_create_str (parser, IDENTIFIER, $1);
699 		$$->location = yylloc;
700 	}
701 |	INTEGER_STRING {
702 		$$ = _token_create_str (parser, INTEGER_STRING, $1);
703 		$$->location = yylloc;
704 	}
705 |	operator {
706 		$$ = _token_create_ival (parser, $1, $1);
707 		$$->location = yylloc;
708 	}
709 |	DEFINED {
710 		$$ = _token_create_ival (parser, DEFINED, DEFINED);
711 		$$->location = yylloc;
712 	}
713 |	OTHER {
714 		$$ = _token_create_str (parser, OTHER, $1);
715 		$$->location = yylloc;
716 	}
717 |	SPACE {
718 		$$ = _token_create_ival (parser, SPACE, SPACE);
719 		$$->location = yylloc;
720 	}
721 ;
722 
723 operator:
724 	'['			{ $$ = '['; }
725 |	']'			{ $$ = ']'; }
726 |	'('			{ $$ = '('; }
727 |	')'			{ $$ = ')'; }
728 |	'{'			{ $$ = '{'; }
729 |	'}'			{ $$ = '}'; }
730 |	'.'			{ $$ = '.'; }
731 |	'&'			{ $$ = '&'; }
732 |	'*'			{ $$ = '*'; }
733 |	'+'			{ $$ = '+'; }
734 |	'-'			{ $$ = '-'; }
735 |	'~'			{ $$ = '~'; }
736 |	'!'			{ $$ = '!'; }
737 |	'/'			{ $$ = '/'; }
738 |	'%'			{ $$ = '%'; }
739 |	LEFT_SHIFT		{ $$ = LEFT_SHIFT; }
740 |	RIGHT_SHIFT		{ $$ = RIGHT_SHIFT; }
741 |	'<'			{ $$ = '<'; }
742 |	'>'			{ $$ = '>'; }
743 |	LESS_OR_EQUAL		{ $$ = LESS_OR_EQUAL; }
744 |	GREATER_OR_EQUAL	{ $$ = GREATER_OR_EQUAL; }
745 |	EQUAL			{ $$ = EQUAL; }
746 |	NOT_EQUAL		{ $$ = NOT_EQUAL; }
747 |	'^'			{ $$ = '^'; }
748 |	'|'			{ $$ = '|'; }
749 |	AND			{ $$ = AND; }
750 |	OR			{ $$ = OR; }
751 |	';'			{ $$ = ';'; }
752 |	','			{ $$ = ','; }
753 |	'='			{ $$ = '='; }
754 |	PASTE			{ $$ = PASTE; }
755 |	PLUS_PLUS		{ $$ = PLUS_PLUS; }
756 |	MINUS_MINUS		{ $$ = MINUS_MINUS; }
757 ;
758 
759 %%
760 
761 string_list_t *
762 _string_list_create(glcpp_parser_t *parser)
763 {
764    string_list_t *list;
765 
766    list = linear_alloc_child(parser->linalloc, sizeof(string_list_t));
767    list->head = NULL;
768    list->tail = NULL;
769 
770    return list;
771 }
772 
773 void
_string_list_append_item(glcpp_parser_t * parser,string_list_t * list,const char * str)774 _string_list_append_item(glcpp_parser_t *parser, string_list_t *list,
775                          const char *str)
776 {
777    string_node_t *node;
778 
779    node = linear_alloc_child(parser->linalloc, sizeof(string_node_t));
780    node->str = linear_strdup(parser->linalloc, str);
781 
782    node->next = NULL;
783 
784    if (list->head == NULL) {
785       list->head = node;
786    } else {
787       list->tail->next = node;
788    }
789 
790    list->tail = node;
791 }
792 
793 int
_string_list_contains(string_list_t * list,const char * member,int * index)794 _string_list_contains(string_list_t *list, const char *member, int *index)
795 {
796    string_node_t *node;
797    int i;
798 
799    if (list == NULL)
800       return 0;
801 
802    for (i = 0, node = list->head; node; i++, node = node->next) {
803       if (strcmp (node->str, member) == 0) {
804          if (index)
805             *index = i;
806          return 1;
807       }
808    }
809 
810    return 0;
811 }
812 
813 /* Return duplicate string in list (if any), NULL otherwise. */
814 const char *
_string_list_has_duplicate(string_list_t * list)815 _string_list_has_duplicate(string_list_t *list)
816 {
817    string_node_t *node, *dup;
818 
819    if (list == NULL)
820       return NULL;
821 
822    for (node = list->head; node; node = node->next) {
823       for (dup = node->next; dup; dup = dup->next) {
824          if (strcmp (node->str, dup->str) == 0)
825             return node->str;
826       }
827    }
828 
829    return NULL;
830 }
831 
832 int
_string_list_length(string_list_t * list)833 _string_list_length(string_list_t *list)
834 {
835    int length = 0;
836    string_node_t *node;
837 
838    if (list == NULL)
839       return 0;
840 
841    for (node = list->head; node; node = node->next)
842       length++;
843 
844    return length;
845 }
846 
847 int
_string_list_equal(string_list_t * a,string_list_t * b)848 _string_list_equal(string_list_t *a, string_list_t *b)
849 {
850    string_node_t *node_a, *node_b;
851 
852    if (a == NULL && b == NULL)
853       return 1;
854 
855    if (a == NULL || b == NULL)
856       return 0;
857 
858    for (node_a = a->head, node_b = b->head;
859         node_a && node_b;
860         node_a = node_a->next, node_b = node_b->next)
861    {
862       if (strcmp (node_a->str, node_b->str))
863          return 0;
864    }
865 
866    /* Catch the case of lists being different lengths, (which
867     * would cause the loop above to terminate after the shorter
868     * list). */
869    return node_a == node_b;
870 }
871 
872 argument_list_t *
_argument_list_create(glcpp_parser_t * parser)873 _argument_list_create(glcpp_parser_t *parser)
874 {
875    argument_list_t *list;
876 
877    list = linear_alloc_child(parser->linalloc, sizeof(argument_list_t));
878    list->head = NULL;
879    list->tail = NULL;
880 
881    return list;
882 }
883 
884 void
_argument_list_append(glcpp_parser_t * parser,argument_list_t * list,token_list_t * argument)885 _argument_list_append(glcpp_parser_t *parser,
886                       argument_list_t *list, token_list_t *argument)
887 {
888    argument_node_t *node;
889 
890    node = linear_alloc_child(parser->linalloc, sizeof(argument_node_t));
891    node->argument = argument;
892 
893    node->next = NULL;
894 
895    if (list->head == NULL) {
896       list->head = node;
897    } else {
898       list->tail->next = node;
899    }
900 
901    list->tail = node;
902 }
903 
904 int
_argument_list_length(argument_list_t * list)905 _argument_list_length(argument_list_t *list)
906 {
907    int length = 0;
908    argument_node_t *node;
909 
910    if (list == NULL)
911       return 0;
912 
913    for (node = list->head; node; node = node->next)
914       length++;
915 
916    return length;
917 }
918 
919 token_list_t *
_argument_list_member_at(argument_list_t * list,int index)920 _argument_list_member_at(argument_list_t *list, int index)
921 {
922    argument_node_t *node;
923    int i;
924 
925    if (list == NULL)
926       return NULL;
927 
928    node = list->head;
929    for (i = 0; i < index; i++) {
930       node = node->next;
931       if (node == NULL)
932          break;
933    }
934 
935    if (node)
936       return node->argument;
937 
938    return NULL;
939 }
940 
941 token_t *
_token_create_str(glcpp_parser_t * parser,int type,char * str)942 _token_create_str(glcpp_parser_t *parser, int type, char *str)
943 {
944    token_t *token;
945 
946    token = linear_alloc_child(parser->linalloc, sizeof(token_t));
947    token->type = type;
948    token->value.str = str;
949 
950    return token;
951 }
952 
953 token_t *
_token_create_ival(glcpp_parser_t * parser,int type,int ival)954 _token_create_ival(glcpp_parser_t *parser, int type, int ival)
955 {
956    token_t *token;
957 
958    token = linear_alloc_child(parser->linalloc, sizeof(token_t));
959    token->type = type;
960    token->value.ival = ival;
961 
962    return token;
963 }
964 
965 token_list_t *
_token_list_create(glcpp_parser_t * parser)966 _token_list_create(glcpp_parser_t *parser)
967 {
968    token_list_t *list;
969 
970    list = linear_alloc_child(parser->linalloc, sizeof(token_list_t));
971    list->head = NULL;
972    list->tail = NULL;
973    list->non_space_tail = NULL;
974 
975    return list;
976 }
977 
978 void
_token_list_append(glcpp_parser_t * parser,token_list_t * list,token_t * token)979 _token_list_append(glcpp_parser_t *parser, token_list_t *list, token_t *token)
980 {
981    token_node_t *node;
982 
983    node = linear_alloc_child(parser->linalloc, sizeof(token_node_t));
984    node->token = token;
985    node->next = NULL;
986 
987    if (list->head == NULL) {
988       list->head = node;
989    } else {
990       list->tail->next = node;
991    }
992 
993    list->tail = node;
994    if (token->type != SPACE)
995       list->non_space_tail = node;
996 }
997 
998 void
_token_list_append_list(token_list_t * list,token_list_t * tail)999 _token_list_append_list(token_list_t *list, token_list_t *tail)
1000 {
1001    if (tail == NULL || tail->head == NULL)
1002       return;
1003 
1004    if (list->head == NULL) {
1005       list->head = tail->head;
1006    } else {
1007       list->tail->next = tail->head;
1008    }
1009 
1010    list->tail = tail->tail;
1011    list->non_space_tail = tail->non_space_tail;
1012 }
1013 
1014 static token_list_t *
_token_list_copy(glcpp_parser_t * parser,token_list_t * other)1015 _token_list_copy(glcpp_parser_t *parser, token_list_t *other)
1016 {
1017    token_list_t *copy;
1018    token_node_t *node;
1019 
1020    if (other == NULL)
1021       return NULL;
1022 
1023    copy = _token_list_create (parser);
1024    for (node = other->head; node; node = node->next) {
1025       token_t *new_token = linear_alloc_child(parser->linalloc, sizeof(token_t));
1026       *new_token = *node->token;
1027       _token_list_append (parser, copy, new_token);
1028    }
1029 
1030    return copy;
1031 }
1032 
1033 static void
_token_list_trim_trailing_space(token_list_t * list)1034 _token_list_trim_trailing_space(token_list_t *list)
1035 {
1036    if (list->non_space_tail) {
1037       list->non_space_tail->next = NULL;
1038       list->tail = list->non_space_tail;
1039    }
1040 }
1041 
1042 static int
_token_list_is_empty_ignoring_space(token_list_t * l)1043 _token_list_is_empty_ignoring_space(token_list_t *l)
1044 {
1045    token_node_t *n;
1046 
1047    if (l == NULL)
1048       return 1;
1049 
1050    n = l->head;
1051    while (n != NULL && n->token->type == SPACE)
1052       n = n->next;
1053 
1054    return n == NULL;
1055 }
1056 
1057 int
_token_list_equal_ignoring_space(token_list_t * a,token_list_t * b)1058 _token_list_equal_ignoring_space(token_list_t *a, token_list_t *b)
1059 {
1060    token_node_t *node_a, *node_b;
1061 
1062    if (a == NULL || b == NULL) {
1063       int a_empty = _token_list_is_empty_ignoring_space(a);
1064       int b_empty = _token_list_is_empty_ignoring_space(b);
1065       return a_empty == b_empty;
1066    }
1067 
1068    node_a = a->head;
1069    node_b = b->head;
1070 
1071    while (1)
1072    {
1073       if (node_a == NULL && node_b == NULL)
1074          break;
1075 
1076       if (node_a == NULL || node_b == NULL)
1077          return 0;
1078       /* Make sure whitespace appears in the same places in both.
1079        * It need not be exactly the same amount of whitespace,
1080        * though.
1081        */
1082       if (node_a->token->type == SPACE && node_b->token->type == SPACE) {
1083          while (node_a && node_a->token->type == SPACE)
1084             node_a = node_a->next;
1085          while (node_b && node_b->token->type == SPACE)
1086             node_b = node_b->next;
1087          continue;
1088       }
1089 
1090       if (node_a->token->type != node_b->token->type)
1091          return 0;
1092 
1093       switch (node_a->token->type) {
1094       case INTEGER:
1095          if (node_a->token->value.ival !=  node_b->token->value.ival) {
1096             return 0;
1097          }
1098          break;
1099       case IDENTIFIER:
1100       case INTEGER_STRING:
1101       case OTHER:
1102          if (strcmp(node_a->token->value.str, node_b->token->value.str)) {
1103             return 0;
1104          }
1105          break;
1106       }
1107 
1108       node_a = node_a->next;
1109       node_b = node_b->next;
1110    }
1111 
1112    return 1;
1113 }
1114 
1115 static void
_token_print(char ** out,size_t * len,token_t * token)1116 _token_print(char **out, size_t *len, token_t *token)
1117 {
1118    if (token->type < 256) {
1119       ralloc_asprintf_rewrite_tail (out, len, "%c", token->type);
1120       return;
1121    }
1122 
1123    switch (token->type) {
1124    case INTEGER:
1125       ralloc_asprintf_rewrite_tail (out, len, "%" PRIiMAX, token->value.ival);
1126       break;
1127    case IDENTIFIER:
1128    case INTEGER_STRING:
1129    case OTHER:
1130       ralloc_asprintf_rewrite_tail (out, len, "%s", token->value.str);
1131       break;
1132    case SPACE:
1133       ralloc_asprintf_rewrite_tail (out, len, " ");
1134       break;
1135    case LEFT_SHIFT:
1136       ralloc_asprintf_rewrite_tail (out, len, "<<");
1137       break;
1138    case RIGHT_SHIFT:
1139       ralloc_asprintf_rewrite_tail (out, len, ">>");
1140       break;
1141    case LESS_OR_EQUAL:
1142       ralloc_asprintf_rewrite_tail (out, len, "<=");
1143       break;
1144    case GREATER_OR_EQUAL:
1145       ralloc_asprintf_rewrite_tail (out, len, ">=");
1146       break;
1147    case EQUAL:
1148       ralloc_asprintf_rewrite_tail (out, len, "==");
1149       break;
1150    case NOT_EQUAL:
1151       ralloc_asprintf_rewrite_tail (out, len, "!=");
1152       break;
1153    case AND:
1154       ralloc_asprintf_rewrite_tail (out, len, "&&");
1155       break;
1156    case OR:
1157       ralloc_asprintf_rewrite_tail (out, len, "||");
1158       break;
1159    case PASTE:
1160       ralloc_asprintf_rewrite_tail (out, len, "##");
1161       break;
1162    case PLUS_PLUS:
1163       ralloc_asprintf_rewrite_tail (out, len, "++");
1164       break;
1165    case MINUS_MINUS:
1166       ralloc_asprintf_rewrite_tail (out, len, "--");
1167       break;
1168    case DEFINED:
1169       ralloc_asprintf_rewrite_tail (out, len, "defined");
1170       break;
1171    case PLACEHOLDER:
1172       /* Nothing to print. */
1173       break;
1174    default:
1175       assert(!"Error: Don't know how to print token.");
1176 
1177       break;
1178    }
1179 }
1180 
1181 /* Return a new token formed by pasting 'token' and 'other'. Note that this
1182  * function may return 'token' or 'other' directly rather than allocating
1183  * anything new.
1184  *
1185  * Caution: Only very cursory error-checking is performed to see if
1186  * the final result is a valid single token. */
1187 static token_t *
_token_paste(glcpp_parser_t * parser,token_t * token,token_t * other)1188 _token_paste(glcpp_parser_t *parser, token_t *token, token_t *other)
1189 {
1190    token_t *combined = NULL;
1191 
1192    /* Pasting a placeholder onto anything makes no change. */
1193    if (other->type == PLACEHOLDER)
1194       return token;
1195 
1196    /* When 'token' is a placeholder, just return 'other'. */
1197    if (token->type == PLACEHOLDER)
1198       return other;
1199 
1200    /* A very few single-character punctuators can be combined
1201     * with another to form a multi-character punctuator. */
1202    switch (token->type) {
1203    case '<':
1204       if (other->type == '<')
1205          combined = _token_create_ival (parser, LEFT_SHIFT, LEFT_SHIFT);
1206       else if (other->type == '=')
1207          combined = _token_create_ival (parser, LESS_OR_EQUAL, LESS_OR_EQUAL);
1208       break;
1209    case '>':
1210       if (other->type == '>')
1211          combined = _token_create_ival (parser, RIGHT_SHIFT, RIGHT_SHIFT);
1212       else if (other->type == '=')
1213          combined = _token_create_ival (parser, GREATER_OR_EQUAL, GREATER_OR_EQUAL);
1214       break;
1215    case '=':
1216       if (other->type == '=')
1217          combined = _token_create_ival (parser, EQUAL, EQUAL);
1218       break;
1219    case '!':
1220       if (other->type == '=')
1221          combined = _token_create_ival (parser, NOT_EQUAL, NOT_EQUAL);
1222       break;
1223    case '&':
1224       if (other->type == '&')
1225          combined = _token_create_ival (parser, AND, AND);
1226       break;
1227    case '|':
1228       if (other->type == '|')
1229          combined = _token_create_ival (parser, OR, OR);
1230       break;
1231    }
1232 
1233    if (combined != NULL) {
1234       /* Inherit the location from the first token */
1235       combined->location = token->location;
1236       return combined;
1237    }
1238 
1239    /* Two string-valued (or integer) tokens can usually just be
1240     * mashed together. (We also handle a string followed by an
1241     * integer here as well.)
1242     *
1243     * There are some exceptions here. Notably, if the first token
1244     * is an integer (or a string representing an integer), then
1245     * the second token must also be an integer or must be a
1246     * string representing an integer that begins with a digit.
1247     */
1248    if ((token->type == IDENTIFIER || token->type == OTHER || token->type == INTEGER_STRING || token->type == INTEGER) &&
1249        (other->type == IDENTIFIER || other->type == OTHER || other->type == INTEGER_STRING || other->type == INTEGER))
1250    {
1251       char *str;
1252       int combined_type;
1253 
1254       /* Check that pasting onto an integer doesn't create a
1255        * non-integer, (that is, only digits can be
1256        * pasted. */
1257       if (token->type == INTEGER_STRING || token->type == INTEGER) {
1258          switch (other->type) {
1259          case INTEGER_STRING:
1260             if (other->value.str[0] < '0' || other->value.str[0] > '9')
1261                goto FAIL;
1262             break;
1263          case INTEGER:
1264             if (other->value.ival < 0)
1265                goto FAIL;
1266             break;
1267          default:
1268             goto FAIL;
1269          }
1270       }
1271 
1272       if (token->type == INTEGER)
1273          str = linear_asprintf(parser->linalloc, "%" PRIiMAX, token->value.ival);
1274       else
1275          str = linear_strdup(parser->linalloc, token->value.str);
1276 
1277       if (other->type == INTEGER)
1278          linear_asprintf_append(parser->linalloc, &str, "%" PRIiMAX, other->value.ival);
1279       else
1280          linear_strcat(parser->linalloc, &str, other->value.str);
1281 
1282       /* New token is same type as original token, unless we
1283        * started with an integer, in which case we will be
1284        * creating an integer-string. */
1285       combined_type = token->type;
1286       if (combined_type == INTEGER)
1287          combined_type = INTEGER_STRING;
1288 
1289       combined = _token_create_str (parser, combined_type, str);
1290       combined->location = token->location;
1291       return combined;
1292    }
1293 
1294     FAIL:
1295    glcpp_error (&token->location, parser, "");
1296    ralloc_asprintf_rewrite_tail (&parser->info_log, &parser->info_log_length, "Pasting \"");
1297    _token_print (&parser->info_log, &parser->info_log_length, token);
1298    ralloc_asprintf_rewrite_tail (&parser->info_log, &parser->info_log_length, "\" and \"");
1299    _token_print (&parser->info_log, &parser->info_log_length, other);
1300    ralloc_asprintf_rewrite_tail (&parser->info_log, &parser->info_log_length, "\" does not give a valid preprocessing token.\n");
1301 
1302    return token;
1303 }
1304 
1305 static void
_token_list_print(glcpp_parser_t * parser,token_list_t * list)1306 _token_list_print(glcpp_parser_t *parser, token_list_t *list)
1307 {
1308    token_node_t *node;
1309 
1310    if (list == NULL)
1311       return;
1312 
1313    for (node = list->head; node; node = node->next)
1314       _token_print (&parser->output, &parser->output_length, node->token);
1315 }
1316 
1317 void
yyerror(YYLTYPE * locp,glcpp_parser_t * parser,const char * error)1318 yyerror(YYLTYPE *locp, glcpp_parser_t *parser, const char *error)
1319 {
1320    glcpp_error(locp, parser, "%s", error);
1321 }
1322 
1323 static void
add_builtin_define(glcpp_parser_t * parser,const char * name,int value)1324 add_builtin_define(glcpp_parser_t *parser, const char *name, int value)
1325 {
1326    token_t *tok;
1327    token_list_t *list;
1328 
1329    tok = _token_create_ival (parser, INTEGER, value);
1330 
1331    list = _token_list_create(parser);
1332    _token_list_append(parser, list, tok);
1333    _define_object_macro(parser, NULL, name, list);
1334 }
1335 
1336 glcpp_parser_t *
glcpp_parser_create(glcpp_extension_iterator extensions,void * state,gl_api api)1337 glcpp_parser_create(glcpp_extension_iterator extensions, void *state, gl_api api)
1338 {
1339    glcpp_parser_t *parser;
1340 
1341    parser = ralloc (NULL, glcpp_parser_t);
1342 
1343    glcpp_lex_init_extra (parser, &parser->scanner);
1344    parser->defines = _mesa_hash_table_create(NULL, _mesa_key_hash_string,
1345                                              _mesa_key_string_equal);
1346    parser->linalloc = linear_alloc_parent(parser, 0);
1347    parser->active = NULL;
1348    parser->lexing_directive = 0;
1349    parser->lexing_version_directive = 0;
1350    parser->space_tokens = 1;
1351    parser->last_token_was_newline = 0;
1352    parser->last_token_was_space = 0;
1353    parser->first_non_space_token_this_line = 1;
1354    parser->newline_as_space = 0;
1355    parser->in_control_line = 0;
1356    parser->paren_count = 0;
1357    parser->commented_newlines = 0;
1358 
1359    parser->skip_stack = NULL;
1360    parser->skipping = 0;
1361 
1362    parser->lex_from_list = NULL;
1363    parser->lex_from_node = NULL;
1364 
1365    parser->output = ralloc_strdup(parser, "");
1366    parser->output_length = 0;
1367    parser->info_log = ralloc_strdup(parser, "");
1368    parser->info_log_length = 0;
1369    parser->error = 0;
1370 
1371    parser->extensions = extensions;
1372    parser->state = state;
1373    parser->api = api;
1374    parser->version = 0;
1375    parser->version_set = false;
1376 
1377    parser->has_new_line_number = 0;
1378    parser->new_line_number = 1;
1379    parser->has_new_source_number = 0;
1380    parser->new_source_number = 0;
1381 
1382    parser->is_gles = false;
1383 
1384    return parser;
1385 }
1386 
1387 void
glcpp_parser_destroy(glcpp_parser_t * parser)1388 glcpp_parser_destroy(glcpp_parser_t *parser)
1389 {
1390    glcpp_lex_destroy (parser->scanner);
1391    _mesa_hash_table_destroy(parser->defines, NULL);
1392    ralloc_free (parser);
1393 }
1394 
1395 typedef enum function_status
1396 {
1397    FUNCTION_STATUS_SUCCESS,
1398    FUNCTION_NOT_A_FUNCTION,
1399    FUNCTION_UNBALANCED_PARENTHESES
1400 } function_status_t;
1401 
1402 /* Find a set of function-like macro arguments by looking for a
1403  * balanced set of parentheses.
1404  *
1405  * When called, 'node' should be the opening-parenthesis token, (or
1406  * perhaps preceeding SPACE tokens). Upon successful return *last will
1407  * be the last consumed node, (corresponding to the closing right
1408  * parenthesis).
1409  *
1410  * Return values:
1411  *
1412  *   FUNCTION_STATUS_SUCCESS:
1413  *
1414  *      Successfully parsed a set of function arguments.
1415  *
1416  *   FUNCTION_NOT_A_FUNCTION:
1417  *
1418  *      Macro name not followed by a '('. This is not an error, but
1419  *      simply that the macro name should be treated as a non-macro.
1420  *
1421  *   FUNCTION_UNBALANCED_PARENTHESES
1422  *
1423  *      Macro name is not followed by a balanced set of parentheses.
1424  */
1425 static function_status_t
_arguments_parse(glcpp_parser_t * parser,argument_list_t * arguments,token_node_t * node,token_node_t ** last)1426 _arguments_parse(glcpp_parser_t *parser,
1427                  argument_list_t *arguments, token_node_t *node,
1428                  token_node_t **last)
1429 {
1430    token_list_t *argument;
1431    int paren_count;
1432 
1433    node = node->next;
1434 
1435    /* Ignore whitespace before first parenthesis. */
1436    while (node && node->token->type == SPACE)
1437       node = node->next;
1438 
1439    if (node == NULL || node->token->type != '(')
1440       return FUNCTION_NOT_A_FUNCTION;
1441 
1442    node = node->next;
1443 
1444    argument = _token_list_create (parser);
1445    _argument_list_append (parser, arguments, argument);
1446 
1447    for (paren_count = 1; node; node = node->next) {
1448       if (node->token->type == '(') {
1449          paren_count++;
1450       } else if (node->token->type == ')') {
1451          paren_count--;
1452          if (paren_count == 0)
1453             break;
1454       }
1455 
1456       if (node->token->type == ',' && paren_count == 1) {
1457          _token_list_trim_trailing_space (argument);
1458          argument = _token_list_create (parser);
1459          _argument_list_append (parser, arguments, argument);
1460       } else {
1461          if (argument->head == NULL) {
1462             /* Don't treat initial whitespace as part of the argument. */
1463             if (node->token->type == SPACE)
1464                continue;
1465          }
1466          _token_list_append(parser, argument, node->token);
1467       }
1468    }
1469 
1470    if (paren_count)
1471       return FUNCTION_UNBALANCED_PARENTHESES;
1472 
1473    *last = node;
1474 
1475    return FUNCTION_STATUS_SUCCESS;
1476 }
1477 
1478 static token_list_t *
_token_list_create_with_one_ival(glcpp_parser_t * parser,int type,int ival)1479 _token_list_create_with_one_ival(glcpp_parser_t *parser, int type, int ival)
1480 {
1481    token_list_t *list;
1482    token_t *node;
1483 
1484    list = _token_list_create(parser);
1485    node = _token_create_ival(parser, type, ival);
1486    _token_list_append(parser, list, node);
1487 
1488    return list;
1489 }
1490 
1491 static token_list_t *
_token_list_create_with_one_space(glcpp_parser_t * parser)1492 _token_list_create_with_one_space(glcpp_parser_t *parser)
1493 {
1494    return _token_list_create_with_one_ival(parser, SPACE, SPACE);
1495 }
1496 
1497 static token_list_t *
_token_list_create_with_one_integer(glcpp_parser_t * parser,int ival)1498 _token_list_create_with_one_integer(glcpp_parser_t *parser, int ival)
1499 {
1500    return _token_list_create_with_one_ival(parser, INTEGER, ival);
1501 }
1502 
1503 /* Evaluate a DEFINED token node (based on subsequent tokens in the list).
1504  *
1505  * Note: This function must only be called when "node" is a DEFINED token,
1506  * (and will abort with an assertion failure otherwise).
1507  *
1508  * If "node" is followed, (ignoring any SPACE tokens), by an IDENTIFIER token
1509  * (optionally preceded and followed by '(' and ')' tokens) then the following
1510  * occurs:
1511  *
1512  *   If the identifier is a defined macro, this function returns 1.
1513  *
1514  *   If the identifier is not a defined macro, this function returns 0.
1515  *
1516  *   In either case, *last will be updated to the last node in the list
1517  *   consumed by the evaluation, (either the token of the identifier or the
1518  *   token of the closing parenthesis).
1519  *
1520  * In all other cases, (such as "node is the final node of the list", or
1521  * "missing closing parenthesis", etc.), this function generates a
1522  * preprocessor error, returns -1 and *last will not be set.
1523  */
1524 static int
_glcpp_parser_evaluate_defined(glcpp_parser_t * parser,token_node_t * node,token_node_t ** last)1525 _glcpp_parser_evaluate_defined(glcpp_parser_t *parser, token_node_t *node,
1526                                token_node_t **last)
1527 {
1528    token_node_t *argument, *defined = node;
1529 
1530    assert(node->token->type == DEFINED);
1531 
1532    node = node->next;
1533 
1534    /* Ignore whitespace after DEFINED token. */
1535    while (node && node->token->type == SPACE)
1536       node = node->next;
1537 
1538    if (node == NULL)
1539       goto FAIL;
1540 
1541    if (node->token->type == IDENTIFIER || node->token->type == OTHER) {
1542       argument = node;
1543    } else if (node->token->type == '(') {
1544       node = node->next;
1545 
1546       /* Ignore whitespace after '(' token. */
1547       while (node && node->token->type == SPACE)
1548          node = node->next;
1549 
1550       if (node == NULL || (node->token->type != IDENTIFIER &&
1551                            node->token->type != OTHER)) {
1552          goto FAIL;
1553       }
1554 
1555       argument = node;
1556 
1557       node = node->next;
1558 
1559       /* Ignore whitespace after identifier, before ')' token. */
1560       while (node && node->token->type == SPACE)
1561          node = node->next;
1562 
1563       if (node == NULL || node->token->type != ')')
1564          goto FAIL;
1565    } else {
1566       goto FAIL;
1567    }
1568 
1569    *last = node;
1570 
1571    return _mesa_hash_table_search(parser->defines,
1572                                   argument->token->value.str) ? 1 : 0;
1573 
1574 FAIL:
1575    glcpp_error (&defined->token->location, parser,
1576                 "\"defined\" not followed by an identifier");
1577    return -1;
1578 }
1579 
1580 /* Evaluate all DEFINED nodes in a given list, modifying the list in place.
1581  */
1582 static void
_glcpp_parser_evaluate_defined_in_list(glcpp_parser_t * parser,token_list_t * list)1583 _glcpp_parser_evaluate_defined_in_list(glcpp_parser_t *parser,
1584                                        token_list_t *list)
1585 {
1586    token_node_t *node, *node_prev, *replacement, *last = NULL;
1587    int value;
1588 
1589    if (list == NULL)
1590       return;
1591 
1592    node_prev = NULL;
1593    node = list->head;
1594 
1595    while (node) {
1596 
1597       if (node->token->type != DEFINED)
1598          goto NEXT;
1599 
1600       value = _glcpp_parser_evaluate_defined (parser, node, &last);
1601       if (value == -1)
1602          goto NEXT;
1603 
1604       replacement = linear_alloc_child(parser->linalloc, sizeof(token_node_t));
1605       replacement->token = _token_create_ival (parser, INTEGER, value);
1606 
1607       /* Splice replacement node into list, replacing from "node"
1608        * through "last". */
1609       if (node_prev)
1610          node_prev->next = replacement;
1611       else
1612          list->head = replacement;
1613       replacement->next = last->next;
1614       if (last == list->tail)
1615          list->tail = replacement;
1616 
1617       node = replacement;
1618 
1619    NEXT:
1620       node_prev = node;
1621       node = node->next;
1622    }
1623 }
1624 
1625 /* Perform macro expansion on 'list', placing the resulting tokens
1626  * into a new list which is initialized with a first token of type
1627  * 'head_token_type'. Then begin lexing from the resulting list,
1628  * (return to the current lexing source when this list is exhausted).
1629  *
1630  * See the documentation of _glcpp_parser_expand_token_list for a description
1631  * of the "mode" parameter.
1632  */
1633 static void
_glcpp_parser_expand_and_lex_from(glcpp_parser_t * parser,int head_token_type,token_list_t * list,expansion_mode_t mode)1634 _glcpp_parser_expand_and_lex_from(glcpp_parser_t *parser, int head_token_type,
1635                                   token_list_t *list, expansion_mode_t mode)
1636 {
1637    token_list_t *expanded;
1638    token_t *token;
1639 
1640    expanded = _token_list_create (parser);
1641    token = _token_create_ival (parser, head_token_type, head_token_type);
1642    _token_list_append (parser, expanded, token);
1643    _glcpp_parser_expand_token_list (parser, list, mode);
1644    _token_list_append_list (expanded, list);
1645    glcpp_parser_lex_from (parser, expanded);
1646 }
1647 
1648 static void
_glcpp_parser_apply_pastes(glcpp_parser_t * parser,token_list_t * list)1649 _glcpp_parser_apply_pastes(glcpp_parser_t *parser, token_list_t *list)
1650 {
1651    token_node_t *node;
1652 
1653    node = list->head;
1654    while (node) {
1655       token_node_t *next_non_space;
1656 
1657       /* Look ahead for a PASTE token, skipping space. */
1658       next_non_space = node->next;
1659       while (next_non_space && next_non_space->token->type == SPACE)
1660          next_non_space = next_non_space->next;
1661 
1662       if (next_non_space == NULL)
1663          break;
1664 
1665       if (next_non_space->token->type != PASTE) {
1666          node = next_non_space;
1667          continue;
1668       }
1669 
1670       /* Now find the next non-space token after the PASTE. */
1671       next_non_space = next_non_space->next;
1672       while (next_non_space && next_non_space->token->type == SPACE)
1673          next_non_space = next_non_space->next;
1674 
1675       if (next_non_space == NULL) {
1676          yyerror(&node->token->location, parser, "'##' cannot appear at either end of a macro expansion\n");
1677          return;
1678       }
1679 
1680       node->token = _token_paste(parser, node->token, next_non_space->token);
1681       node->next = next_non_space->next;
1682       if (next_non_space == list->tail)
1683          list->tail = node;
1684    }
1685 
1686    list->non_space_tail = list->tail;
1687 }
1688 
1689 /* This is a helper function that's essentially part of the
1690  * implementation of _glcpp_parser_expand_node. It shouldn't be called
1691  * except for by that function.
1692  *
1693  * Returns NULL if node is a simple token with no expansion, (that is,
1694  * although 'node' corresponds to an identifier defined as a
1695  * function-like macro, it is not followed with a parenthesized
1696  * argument list).
1697  *
1698  * Compute the complete expansion of node (which is a function-like
1699  * macro) and subsequent nodes which are arguments.
1700  *
1701  * Returns the token list that results from the expansion and sets
1702  * *last to the last node in the list that was consumed by the
1703  * expansion. Specifically, *last will be set as follows: as the
1704  * token of the closing right parenthesis.
1705  *
1706  * See the documentation of _glcpp_parser_expand_token_list for a description
1707  * of the "mode" parameter.
1708  */
1709 static token_list_t *
_glcpp_parser_expand_function(glcpp_parser_t * parser,token_node_t * node,token_node_t ** last,expansion_mode_t mode)1710 _glcpp_parser_expand_function(glcpp_parser_t *parser, token_node_t *node,
1711                               token_node_t **last, expansion_mode_t mode)
1712 {
1713    struct hash_entry *entry;
1714    macro_t *macro;
1715    const char *identifier;
1716    argument_list_t *arguments;
1717    function_status_t status;
1718    token_list_t *substituted;
1719    int parameter_index;
1720 
1721    identifier = node->token->value.str;
1722 
1723    entry = _mesa_hash_table_search(parser->defines, identifier);
1724    macro = entry ? entry->data : NULL;
1725 
1726    assert(macro->is_function);
1727 
1728    arguments = _argument_list_create(parser);
1729    status = _arguments_parse(parser, arguments, node, last);
1730 
1731    switch (status) {
1732    case FUNCTION_STATUS_SUCCESS:
1733       break;
1734    case FUNCTION_NOT_A_FUNCTION:
1735       return NULL;
1736    case FUNCTION_UNBALANCED_PARENTHESES:
1737       glcpp_error(&node->token->location, parser, "Macro %s call has unbalanced parentheses\n", identifier);
1738       return NULL;
1739    }
1740 
1741    /* Replace a macro defined as empty with a SPACE token. */
1742    if (macro->replacements == NULL) {
1743       return _token_list_create_with_one_space(parser);
1744    }
1745 
1746    if (!((_argument_list_length (arguments) ==
1747           _string_list_length (macro->parameters)) ||
1748          (_string_list_length (macro->parameters) == 0 &&
1749           _argument_list_length (arguments) == 1 &&
1750           arguments->head->argument->head == NULL))) {
1751       glcpp_error(&node->token->location, parser,
1752                   "Error: macro %s invoked with %d arguments (expected %d)\n",
1753                   identifier, _argument_list_length (arguments),
1754                   _string_list_length(macro->parameters));
1755       return NULL;
1756    }
1757 
1758    /* Perform argument substitution on the replacement list. */
1759    substituted = _token_list_create(parser);
1760 
1761    for (node = macro->replacements->head; node; node = node->next) {
1762       if (node->token->type == IDENTIFIER &&
1763           _string_list_contains(macro->parameters, node->token->value.str,
1764                                 &parameter_index)) {
1765          token_list_t *argument;
1766          argument = _argument_list_member_at(arguments, parameter_index);
1767          /* Before substituting, we expand the argument tokens, or append a
1768           * placeholder token for an empty argument. */
1769          if (argument->head) {
1770             token_list_t *expanded_argument;
1771             expanded_argument = _token_list_copy(parser, argument);
1772             _glcpp_parser_expand_token_list(parser, expanded_argument, mode);
1773             _token_list_append_list(substituted, expanded_argument);
1774          } else {
1775             token_t *new_token;
1776 
1777             new_token = _token_create_ival(parser, PLACEHOLDER,
1778                                            PLACEHOLDER);
1779             _token_list_append(parser, substituted, new_token);
1780          }
1781       } else {
1782          _token_list_append(parser, substituted, node->token);
1783       }
1784    }
1785 
1786    /* After argument substitution, and before further expansion
1787     * below, implement token pasting. */
1788 
1789    _token_list_trim_trailing_space(substituted);
1790 
1791    _glcpp_parser_apply_pastes(parser, substituted);
1792 
1793    return substituted;
1794 }
1795 
1796 /* Compute the complete expansion of node, (and subsequent nodes after
1797  * 'node' in the case that 'node' is a function-like macro and
1798  * subsequent nodes are arguments).
1799  *
1800  * Returns NULL if node is a simple token with no expansion.
1801  *
1802  * Otherwise, returns the token list that results from the expansion
1803  * and sets *last to the last node in the list that was consumed by
1804  * the expansion. Specifically, *last will be set as follows:
1805  *
1806  *   As 'node' in the case of object-like macro expansion.
1807  *
1808  *   As the token of the closing right parenthesis in the case of
1809  *   function-like macro expansion.
1810  *
1811  * See the documentation of _glcpp_parser_expand_token_list for a description
1812  * of the "mode" parameter.
1813  */
1814 static token_list_t *
_glcpp_parser_expand_node(glcpp_parser_t * parser,token_node_t * node,token_node_t ** last,expansion_mode_t mode)1815 _glcpp_parser_expand_node(glcpp_parser_t *parser, token_node_t *node,
1816                           token_node_t **last, expansion_mode_t mode)
1817 {
1818    token_t *token = node->token;
1819    const char *identifier;
1820    struct hash_entry *entry;
1821    macro_t *macro;
1822 
1823    /* We only expand identifiers */
1824    if (token->type != IDENTIFIER) {
1825       return NULL;
1826    }
1827 
1828    *last = node;
1829    identifier = token->value.str;
1830 
1831    /* Special handling for __LINE__ and __FILE__, (not through
1832     * the hash table). */
1833    if (strcmp(identifier, "__LINE__") == 0)
1834       return _token_list_create_with_one_integer(parser, node->token->location.first_line);
1835 
1836    if (strcmp(identifier, "__FILE__") == 0)
1837       return _token_list_create_with_one_integer(parser, node->token->location.source);
1838 
1839    /* Look up this identifier in the hash table. */
1840    entry = _mesa_hash_table_search(parser->defines, identifier);
1841    macro = entry ? entry->data : NULL;
1842 
1843    /* Not a macro, so no expansion needed. */
1844    if (macro == NULL)
1845       return NULL;
1846 
1847    /* Finally, don't expand this macro if we're already actively
1848     * expanding it, (to avoid infinite recursion). */
1849    if (_parser_active_list_contains (parser, identifier)) {
1850       /* We change the token type here from IDENTIFIER to OTHER to prevent any
1851        * future expansion of this unexpanded token. */
1852       char *str;
1853       token_list_t *expansion;
1854       token_t *final;
1855 
1856       str = linear_strdup(parser->linalloc, token->value.str);
1857       final = _token_create_str(parser, OTHER, str);
1858       expansion = _token_list_create(parser);
1859       _token_list_append(parser, expansion, final);
1860       return expansion;
1861    }
1862 
1863    if (! macro->is_function) {
1864       token_list_t *replacement;
1865 
1866       /* Replace a macro defined as empty with a SPACE token. */
1867       if (macro->replacements == NULL)
1868          return _token_list_create_with_one_space(parser);
1869 
1870       replacement = _token_list_copy(parser, macro->replacements);
1871       _glcpp_parser_apply_pastes(parser, replacement);
1872       return replacement;
1873    }
1874 
1875    return _glcpp_parser_expand_function(parser, node, last, mode);
1876 }
1877 
1878 /* Push a new identifier onto the parser's active list.
1879  *
1880  * Here, 'marker' is the token node that appears in the list after the
1881  * expansion of 'identifier'. That is, when the list iterator begins
1882  * examining 'marker', then it is time to pop this node from the
1883  * active stack.
1884  */
1885 static void
_parser_active_list_push(glcpp_parser_t * parser,const char * identifier,token_node_t * marker)1886 _parser_active_list_push(glcpp_parser_t *parser, const char *identifier,
1887                          token_node_t *marker)
1888 {
1889    active_list_t *node;
1890 
1891    node = linear_alloc_child(parser->linalloc, sizeof(active_list_t));
1892    node->identifier = linear_strdup(parser->linalloc, identifier);
1893    node->marker = marker;
1894    node->next = parser->active;
1895 
1896    parser->active = node;
1897 }
1898 
1899 static void
_parser_active_list_pop(glcpp_parser_t * parser)1900 _parser_active_list_pop(glcpp_parser_t *parser)
1901 {
1902    active_list_t *node = parser->active;
1903 
1904    if (node == NULL) {
1905       parser->active = NULL;
1906       return;
1907    }
1908 
1909    node = parser->active->next;
1910    parser->active = node;
1911 }
1912 
1913 static int
_parser_active_list_contains(glcpp_parser_t * parser,const char * identifier)1914 _parser_active_list_contains(glcpp_parser_t *parser, const char *identifier)
1915 {
1916    active_list_t *node;
1917 
1918    if (parser->active == NULL)
1919       return 0;
1920 
1921    for (node = parser->active; node; node = node->next)
1922       if (strcmp(node->identifier, identifier) == 0)
1923          return 1;
1924 
1925    return 0;
1926 }
1927 
1928 /* Walk over the token list replacing nodes with their expansion.
1929  * Whenever nodes are expanded the walking will walk over the new
1930  * nodes, continuing to expand as necessary. The results are placed in
1931  * 'list' itself.
1932  *
1933  * The "mode" argument controls the handling of any DEFINED tokens that
1934  * result from expansion as follows:
1935  *
1936  *   EXPANSION_MODE_IGNORE_DEFINED: Any resulting DEFINED tokens will be
1937  *      left in the final list, unevaluated. This is the correct mode
1938  *      for expanding any list in any context other than a
1939  *      preprocessor conditional, (#if or #elif).
1940  *
1941  *   EXPANSION_MODE_EVALUATE_DEFINED: Any resulting DEFINED tokens will be
1942  *      evaluated to 0 or 1 tokens depending on whether the following
1943  *      token is the name of a defined macro. If the DEFINED token is
1944  *      not followed by an (optionally parenthesized) identifier, then
1945  *      an error will be generated. This the correct mode for
1946  *      expanding any list in the context of a preprocessor
1947  *      conditional, (#if or #elif).
1948  */
1949 static void
_glcpp_parser_expand_token_list(glcpp_parser_t * parser,token_list_t * list,expansion_mode_t mode)1950 _glcpp_parser_expand_token_list(glcpp_parser_t *parser, token_list_t *list,
1951                                 expansion_mode_t mode)
1952 {
1953    token_node_t *node_prev;
1954    token_node_t *node, *last = NULL;
1955    token_list_t *expansion;
1956    active_list_t *active_initial = parser->active;
1957 
1958    if (list == NULL)
1959       return;
1960 
1961    _token_list_trim_trailing_space (list);
1962 
1963    node_prev = NULL;
1964    node = list->head;
1965 
1966    if (mode == EXPANSION_MODE_EVALUATE_DEFINED)
1967       _glcpp_parser_evaluate_defined_in_list (parser, list);
1968 
1969    while (node) {
1970 
1971       while (parser->active && parser->active->marker == node)
1972          _parser_active_list_pop (parser);
1973 
1974       expansion = _glcpp_parser_expand_node (parser, node, &last, mode);
1975       if (expansion) {
1976          token_node_t *n;
1977 
1978          if (mode == EXPANSION_MODE_EVALUATE_DEFINED) {
1979             _glcpp_parser_evaluate_defined_in_list (parser, expansion);
1980          }
1981 
1982          for (n = node; n != last->next; n = n->next)
1983             while (parser->active && parser->active->marker == n) {
1984                _parser_active_list_pop (parser);
1985             }
1986 
1987          _parser_active_list_push(parser, node->token->value.str, last->next);
1988 
1989          /* Splice expansion into list, supporting a simple deletion if the
1990           * expansion is empty.
1991           */
1992          if (expansion->head) {
1993             if (node_prev)
1994                node_prev->next = expansion->head;
1995             else
1996                list->head = expansion->head;
1997             expansion->tail->next = last->next;
1998             if (last == list->tail)
1999                list->tail = expansion->tail;
2000          } else {
2001             if (node_prev)
2002                node_prev->next = last->next;
2003             else
2004                list->head = last->next;
2005             if (last == list->tail)
2006                list->tail = NULL;
2007          }
2008       } else {
2009          node_prev = node;
2010       }
2011       node = node_prev ? node_prev->next : list->head;
2012    }
2013 
2014    /* Remove any lingering effects of this invocation on the
2015     * active list. That is, pop until the list looks like it did
2016     * at the beginning of this function. */
2017    while (parser->active && parser->active != active_initial)
2018       _parser_active_list_pop (parser);
2019 
2020    list->non_space_tail = list->tail;
2021 }
2022 
2023 void
_glcpp_parser_print_expanded_token_list(glcpp_parser_t * parser,token_list_t * list)2024 _glcpp_parser_print_expanded_token_list(glcpp_parser_t *parser,
2025                                         token_list_t *list)
2026 {
2027    if (list == NULL)
2028       return;
2029 
2030    _glcpp_parser_expand_token_list (parser, list, EXPANSION_MODE_IGNORE_DEFINED);
2031 
2032    _token_list_trim_trailing_space (list);
2033 
2034    _token_list_print (parser, list);
2035 }
2036 
2037 static void
_check_for_reserved_macro_name(glcpp_parser_t * parser,YYLTYPE * loc,const char * identifier)2038 _check_for_reserved_macro_name(glcpp_parser_t *parser, YYLTYPE *loc,
2039                                const char *identifier)
2040 {
2041    /* Section 3.3 (Preprocessor) of the GLSL 1.30 spec (and later) and
2042     * the GLSL ES spec (all versions) say:
2043     *
2044     *     "All macro names containing two consecutive underscores ( __ )
2045     *     are reserved for future use as predefined macro names. All
2046     *     macro names prefixed with "GL_" ("GL" followed by a single
2047     *     underscore) are also reserved."
2048     *
2049     * The intention is that names containing __ are reserved for internal
2050     * use by the implementation, and names prefixed with GL_ are reserved
2051     * for use by Khronos.  Since every extension adds a name prefixed
2052     * with GL_ (i.e., the name of the extension), that should be an
2053     * error.  Names simply containing __ are dangerous to use, but should
2054     * be allowed.
2055     *
2056     * A future version of the GLSL specification will clarify this.
2057     */
2058    if (strstr(identifier, "__")) {
2059       glcpp_warning(loc, parser, "Macro names containing \"__\" are reserved "
2060                     "for use by the implementation.\n");
2061    }
2062    if (strncmp(identifier, "GL_", 3) == 0) {
2063       glcpp_error (loc, parser, "Macro names starting with \"GL_\" are reserved.\n");
2064    }
2065    if (strcmp(identifier, "defined") == 0) {
2066       glcpp_error (loc, parser, "\"defined\" cannot be used as a macro name");
2067    }
2068 }
2069 
2070 static int
_macro_equal(macro_t * a,macro_t * b)2071 _macro_equal(macro_t *a, macro_t *b)
2072 {
2073    if (a->is_function != b->is_function)
2074       return 0;
2075 
2076    if (a->is_function) {
2077       if (! _string_list_equal (a->parameters, b->parameters))
2078          return 0;
2079    }
2080 
2081    return _token_list_equal_ignoring_space(a->replacements, b->replacements);
2082 }
2083 
2084 void
_define_object_macro(glcpp_parser_t * parser,YYLTYPE * loc,const char * identifier,token_list_t * replacements)2085 _define_object_macro(glcpp_parser_t *parser, YYLTYPE *loc,
2086                      const char *identifier, token_list_t *replacements)
2087 {
2088    macro_t *macro, *previous;
2089    struct hash_entry *entry;
2090 
2091    /* We define pre-defined macros before we've started parsing the actual
2092     * file. So if there's no location defined yet, that's what were doing and
2093     * we don't want to generate an error for using the reserved names. */
2094    if (loc != NULL)
2095       _check_for_reserved_macro_name(parser, loc, identifier);
2096 
2097    macro = linear_alloc_child(parser->linalloc, sizeof(macro_t));
2098 
2099    macro->is_function = 0;
2100    macro->parameters = NULL;
2101    macro->identifier = linear_strdup(parser->linalloc, identifier);
2102    macro->replacements = replacements;
2103 
2104    entry = _mesa_hash_table_search(parser->defines, identifier);
2105    previous = entry ? entry->data : NULL;
2106    if (previous) {
2107       if (_macro_equal (macro, previous)) {
2108          return;
2109       }
2110       glcpp_error (loc, parser, "Redefinition of macro %s\n",  identifier);
2111    }
2112 
2113    _mesa_hash_table_insert (parser->defines, identifier, macro);
2114 }
2115 
2116 void
_define_function_macro(glcpp_parser_t * parser,YYLTYPE * loc,const char * identifier,string_list_t * parameters,token_list_t * replacements)2117 _define_function_macro(glcpp_parser_t *parser, YYLTYPE *loc,
2118                        const char *identifier, string_list_t *parameters,
2119                        token_list_t *replacements)
2120 {
2121    macro_t *macro, *previous;
2122    struct hash_entry *entry;
2123    const char *dup;
2124 
2125    _check_for_reserved_macro_name(parser, loc, identifier);
2126 
2127         /* Check for any duplicate parameter names. */
2128    if ((dup = _string_list_has_duplicate (parameters)) != NULL) {
2129       glcpp_error (loc, parser, "Duplicate macro parameter \"%s\"", dup);
2130    }
2131 
2132    macro = linear_alloc_child(parser->linalloc, sizeof(macro_t));
2133 
2134    macro->is_function = 1;
2135    macro->parameters = parameters;
2136    macro->identifier = linear_strdup(parser->linalloc, identifier);
2137    macro->replacements = replacements;
2138 
2139    entry = _mesa_hash_table_search(parser->defines, identifier);
2140    previous = entry ? entry->data : NULL;
2141    if (previous) {
2142       if (_macro_equal (macro, previous)) {
2143          return;
2144       }
2145       glcpp_error (loc, parser, "Redefinition of macro %s\n", identifier);
2146    }
2147 
2148    _mesa_hash_table_insert(parser->defines, identifier, macro);
2149 }
2150 
2151 static int
glcpp_parser_lex(YYSTYPE * yylval,YYLTYPE * yylloc,glcpp_parser_t * parser)2152 glcpp_parser_lex(YYSTYPE *yylval, YYLTYPE *yylloc, glcpp_parser_t *parser)
2153 {
2154    token_node_t *node;
2155    int ret;
2156 
2157    if (parser->lex_from_list == NULL) {
2158       ret = glcpp_lex(yylval, yylloc, parser->scanner);
2159 
2160       /* XXX: This ugly block of code exists for the sole
2161        * purpose of converting a NEWLINE token into a SPACE
2162        * token, but only in the case where we have seen a
2163        * function-like macro name, but have not yet seen its
2164        * closing parenthesis.
2165        *
2166        * There's perhaps a more compact way to do this with
2167        * mid-rule actions in the grammar.
2168        *
2169        * I'm definitely not pleased with the complexity of
2170        * this code here.
2171        */
2172       if (parser->newline_as_space) {
2173          if (ret == '(') {
2174             parser->paren_count++;
2175          } else if (ret == ')') {
2176             parser->paren_count--;
2177             if (parser->paren_count == 0)
2178                parser->newline_as_space = 0;
2179          } else if (ret == NEWLINE) {
2180             ret = SPACE;
2181          } else if (ret != SPACE) {
2182             if (parser->paren_count == 0)
2183                parser->newline_as_space = 0;
2184          }
2185       } else if (parser->in_control_line) {
2186          if (ret == NEWLINE)
2187             parser->in_control_line = 0;
2188       }
2189       else if (ret == DEFINE_TOKEN || ret == UNDEF || ret == IF ||
2190                ret == IFDEF || ret == IFNDEF || ret == ELIF || ret == ELSE ||
2191                ret == ENDIF || ret == HASH_TOKEN) {
2192          parser->in_control_line = 1;
2193       } else if (ret == IDENTIFIER) {
2194          struct hash_entry *entry = _mesa_hash_table_search(parser->defines,
2195                                                             yylval->str);
2196          macro_t *macro = entry ? entry->data : NULL;
2197          if (macro && macro->is_function) {
2198             parser->newline_as_space = 1;
2199             parser->paren_count = 0;
2200          }
2201       }
2202 
2203       return ret;
2204    }
2205 
2206    node = parser->lex_from_node;
2207 
2208    if (node == NULL) {
2209       parser->lex_from_list = NULL;
2210       return NEWLINE;
2211    }
2212 
2213    *yylval = node->token->value;
2214    ret = node->token->type;
2215 
2216    parser->lex_from_node = node->next;
2217 
2218    return ret;
2219 }
2220 
2221 static void
glcpp_parser_lex_from(glcpp_parser_t * parser,token_list_t * list)2222 glcpp_parser_lex_from(glcpp_parser_t *parser, token_list_t *list)
2223 {
2224    token_node_t *node;
2225 
2226    assert (parser->lex_from_list == NULL);
2227 
2228    /* Copy list, eliminating any space tokens. */
2229    parser->lex_from_list = _token_list_create (parser);
2230 
2231    for (node = list->head; node; node = node->next) {
2232       if (node->token->type == SPACE)
2233          continue;
2234       _token_list_append (parser,  parser->lex_from_list, node->token);
2235    }
2236 
2237    parser->lex_from_node = parser->lex_from_list->head;
2238 
2239    /* It's possible the list consisted of nothing but whitespace. */
2240    if (parser->lex_from_node == NULL) {
2241       parser->lex_from_list = NULL;
2242    }
2243 }
2244 
2245 static void
_glcpp_parser_skip_stack_push_if(glcpp_parser_t * parser,YYLTYPE * loc,int condition)2246 _glcpp_parser_skip_stack_push_if(glcpp_parser_t *parser, YYLTYPE *loc,
2247                                  int condition)
2248 {
2249    skip_type_t current = SKIP_NO_SKIP;
2250    skip_node_t *node;
2251 
2252    if (parser->skip_stack)
2253       current = parser->skip_stack->type;
2254 
2255    node = linear_alloc_child(parser->linalloc, sizeof(skip_node_t));
2256    node->loc = *loc;
2257 
2258    if (current == SKIP_NO_SKIP) {
2259       if (condition)
2260          node->type = SKIP_NO_SKIP;
2261       else
2262          node->type = SKIP_TO_ELSE;
2263    } else {
2264       node->type = SKIP_TO_ENDIF;
2265    }
2266 
2267    node->has_else = false;
2268    node->next = parser->skip_stack;
2269    parser->skip_stack = node;
2270 }
2271 
2272 static void
_glcpp_parser_skip_stack_change_if(glcpp_parser_t * parser,YYLTYPE * loc,const char * type,int condition)2273 _glcpp_parser_skip_stack_change_if(glcpp_parser_t *parser, YYLTYPE *loc,
2274                                    const char *type, int condition)
2275 {
2276    if (parser->skip_stack == NULL) {
2277       glcpp_error (loc, parser, "#%s without #if\n", type);
2278       return;
2279    }
2280 
2281    if (parser->skip_stack->type == SKIP_TO_ELSE) {
2282       if (condition)
2283          parser->skip_stack->type = SKIP_NO_SKIP;
2284    } else {
2285       parser->skip_stack->type = SKIP_TO_ENDIF;
2286    }
2287 }
2288 
2289 static void
_glcpp_parser_skip_stack_pop(glcpp_parser_t * parser,YYLTYPE * loc)2290 _glcpp_parser_skip_stack_pop(glcpp_parser_t *parser, YYLTYPE *loc)
2291 {
2292    skip_node_t *node;
2293 
2294    if (parser->skip_stack == NULL) {
2295       glcpp_error (loc, parser, "#endif without #if\n");
2296       return;
2297    }
2298 
2299    node = parser->skip_stack;
2300    parser->skip_stack = node->next;
2301 }
2302 
2303 static void
_glcpp_parser_handle_version_declaration(glcpp_parser_t * parser,intmax_t version,const char * es_identifier,bool explicitly_set)2304 _glcpp_parser_handle_version_declaration(glcpp_parser_t *parser, intmax_t version,
2305                                          const char *es_identifier,
2306                                          bool explicitly_set)
2307 {
2308    if (parser->version_set)
2309       return;
2310 
2311    parser->version = version;
2312    parser->version_set = true;
2313 
2314    add_builtin_define (parser, "__VERSION__", version);
2315 
2316    parser->is_gles = (version == 100) ||
2317                      (es_identifier && (strcmp(es_identifier, "es") == 0));
2318 
2319    /* Add pre-defined macros. */
2320    if (parser->is_gles)
2321       add_builtin_define(parser, "GL_ES", 1);
2322    else if (version >= 150)
2323       add_builtin_define(parser, "GL_core_profile", 1);
2324 
2325    /* Currently, all ES2/ES3 implementations support highp in the
2326     * fragment shader, so we always define this macro in ES2/ES3.
2327     * If we ever get a driver that doesn't support highp, we'll
2328     * need to add a flag to the gl_context and check that here.
2329     */
2330    if (version >= 130 || parser->is_gles)
2331       add_builtin_define (parser, "GL_FRAGMENT_PRECISION_HIGH", 1);
2332 
2333    /* Add all the extension macros available in this context */
2334    if (parser->extensions)
2335       parser->extensions(parser->state, add_builtin_define, parser,
2336                          version, parser->is_gles);
2337 
2338    if (explicitly_set) {
2339       ralloc_asprintf_rewrite_tail(&parser->output, &parser->output_length,
2340                                    "#version %" PRIiMAX "%s%s", version,
2341                                    es_identifier ? " " : "",
2342                                    es_identifier ? es_identifier : "");
2343    }
2344 }
2345 
2346 /* GLSL version if no version is explicitly specified. */
2347 #define IMPLICIT_GLSL_VERSION 110
2348 
2349 /* GLSL ES version if no version is explicitly specified. */
2350 #define IMPLICIT_GLSL_ES_VERSION 100
2351 
2352 void
glcpp_parser_resolve_implicit_version(glcpp_parser_t * parser)2353 glcpp_parser_resolve_implicit_version(glcpp_parser_t *parser)
2354 {
2355    int language_version = parser->api == API_OPENGLES2 ?
2356                           IMPLICIT_GLSL_ES_VERSION : IMPLICIT_GLSL_VERSION;
2357 
2358    _glcpp_parser_handle_version_declaration(parser, language_version,
2359                                             NULL, false);
2360 }
2361