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