Merge remote branch 'main/master' into radeon-rewrite
[mesa.git] / src / mesa / shader / slang / slang_preprocess.c
1 /*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 2005-2008 Brian Paul All Rights Reserved.
5 * Copyright (C) 2009 VMware, Inc. All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included
15 * in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
21 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25 /**
26 * \file slang_preprocess.c
27 * slang preprocessor
28 * \author Michal Krol
29 */
30
31 #include "main/imports.h"
32 #include "shader/grammar/grammar_mesa.h"
33 #include "slang_preprocess.h"
34
35 LONGSTRING static const char *slang_pp_directives_syn =
36 #include "library/slang_pp_directives_syn.h"
37 ;
38
39 LONGSTRING static const char *slang_pp_expression_syn =
40 #include "library/slang_pp_expression_syn.h"
41 ;
42
43 LONGSTRING static const char *slang_pp_version_syn =
44 #include "library/slang_pp_version_syn.h"
45 ;
46
47 static GLvoid
48 grammar_error_to_log (slang_info_log *log)
49 {
50 char buf[1024];
51 GLint pos;
52
53 grammar_get_last_error ((byte *) (buf), sizeof (buf), &pos);
54 if (buf[0] == 0) {
55 _mesa_snprintf(buf, sizeof(buf), "Preprocessor error");
56 }
57 slang_info_log_error (log, buf);
58 }
59
60 GLboolean
61 _slang_preprocess_version (const char *text, GLuint *version, GLuint *eaten, slang_info_log *log)
62 {
63 grammar id;
64 byte *prod, *I;
65 unsigned int size;
66
67 id = grammar_load_from_text ((const byte *) (slang_pp_version_syn));
68 if (id == 0) {
69 grammar_error_to_log (log);
70 return GL_FALSE;
71 }
72
73 if (!grammar_fast_check (id, (const byte *) (text), &prod, &size, 8)) {
74 grammar_error_to_log (log);
75 grammar_destroy (id);
76 return GL_FALSE;
77 }
78
79 /* there can be multiple #version directives - grab the last one */
80 I = &prod[size - 6];
81 *version = (GLuint) (I[0]) + (GLuint) (I[1]) * 100;
82 *eaten = (GLuint) (I[2]) + ((GLuint) (I[3]) << 8) + ((GLuint) (I[4]) << 16) + ((GLuint) (I[5]) << 24);
83
84 grammar_destroy (id);
85 grammar_alloc_free (prod);
86 return GL_TRUE;
87 }
88
89 /*
90 * The preprocessor does the following work.
91 * 1. Remove comments. Each comment block is replaced with a single space and if the
92 * block contains new-lines, they are preserved. This ensures that line numbers
93 * stay the same and if a comment block delimits two tokens, the are delitmited
94 * by the space after comment removal.
95 * 2. Remove preprocessor directives from the source string, checking their syntax and
96 * executing them if appropriate. Again, new-lines are preserved.
97 * 3. Expand macros.
98 * 4. Tokenize the source string by ensuring there is at least one space between every
99 * two adjacent tokens.
100 */
101
102 #define PP_ANNOTATE 0
103
104 static GLvoid
105 pp_annotate (slang_string *output, const char *fmt, ...)
106 {
107 #if PP_ANNOTATE
108 va_list va;
109 char buffer[1024];
110
111 va_start (va, fmt);
112 _mesa_vsprintf (buffer, fmt, va);
113 va_end (va);
114 slang_string_pushs (output, buffer, _mesa_strlen (buffer));
115 #else
116 (GLvoid) (output);
117 (GLvoid) (fmt);
118 #endif
119 }
120
121 /*
122 * The expression is executed on a fixed-sized stack. The PUSH macro makes a runtime
123 * check if the stack is not overflown by too complex expressions. In that situation the
124 * GLSL preprocessor should report internal compiler error.
125 * The BINARYDIV makes a runtime check if the divider is not 0. If it is, it reports
126 * compilation error.
127 */
128
129 #define EXECUTION_STACK_SIZE 1024
130
131 #define PUSH(x)\
132 do {\
133 if (sp == 0) {\
134 slang_info_log_error (elog, "internal compiler error: preprocessor execution stack overflow.");\
135 return GL_FALSE;\
136 }\
137 stack[--sp] = x;\
138 } while (GL_FALSE)
139
140 #define POP(x)\
141 do {\
142 assert (sp < EXECUTION_STACK_SIZE);\
143 x = stack[sp++];\
144 } while (GL_FALSE)
145
146 #define BINARY(op)\
147 do {\
148 GLint a, b;\
149 POP(b);\
150 POP(a);\
151 PUSH(a op b);\
152 } while (GL_FALSE)
153
154 #define BINARYDIV(op)\
155 do {\
156 GLint a, b;\
157 POP(b);\
158 POP(a);\
159 if (b == 0) {\
160 slang_info_log_error (elog, "division by zero in preprocessor expression.");\
161 return GL_FALSE;\
162 }\
163 PUSH(a op b);\
164 } while (GL_FALSE)
165
166 #define UNARY(op)\
167 do {\
168 GLint a;\
169 POP(a);\
170 PUSH(op a);\
171 } while (GL_FALSE)
172
173 #define OP_END 0
174 #define OP_PUSHINT 1
175 #define OP_LOGICALOR 2
176 #define OP_LOGICALAND 3
177 #define OP_OR 4
178 #define OP_XOR 5
179 #define OP_AND 6
180 #define OP_EQUAL 7
181 #define OP_NOTEQUAL 8
182 #define OP_LESSEQUAL 9
183 #define OP_GREATEREQUAL 10
184 #define OP_LESS 11
185 #define OP_GREATER 12
186 #define OP_LEFTSHIFT 13
187 #define OP_RIGHTSHIFT 14
188 #define OP_ADD 15
189 #define OP_SUBTRACT 16
190 #define OP_MULTIPLY 17
191 #define OP_DIVIDE 18
192 #define OP_MODULUS 19
193 #define OP_PLUS 20
194 #define OP_MINUS 21
195 #define OP_NEGATE 22
196 #define OP_COMPLEMENT 23
197
198 static GLboolean
199 execute_expression (slang_string *output, const byte *code, GLuint *pi, GLint *result,
200 slang_info_log *elog)
201 {
202 GLuint i = *pi;
203 GLint stack[EXECUTION_STACK_SIZE];
204 GLuint sp = EXECUTION_STACK_SIZE;
205
206 while (code[i] != OP_END) {
207 switch (code[i++]) {
208 case OP_PUSHINT:
209 i++;
210 PUSH(_mesa_atoi ((const char *) (&code[i])));
211 i += _mesa_strlen ((const char *) (&code[i])) + 1;
212 break;
213 case OP_LOGICALOR:
214 BINARY(||);
215 break;
216 case OP_LOGICALAND:
217 BINARY(&&);
218 break;
219 case OP_OR:
220 BINARY(|);
221 break;
222 case OP_XOR:
223 BINARY(^);
224 break;
225 case OP_AND:
226 BINARY(&);
227 break;
228 case OP_EQUAL:
229 BINARY(==);
230 break;
231 case OP_NOTEQUAL:
232 BINARY(!=);
233 break;
234 case OP_LESSEQUAL:
235 BINARY(<=);
236 break;
237 case OP_GREATEREQUAL:
238 BINARY(>=);
239 break;
240 case OP_LESS:
241 BINARY(<);
242 break;
243 case OP_GREATER:
244 BINARY(>);
245 break;
246 case OP_LEFTSHIFT:
247 BINARY(<<);
248 break;
249 case OP_RIGHTSHIFT:
250 BINARY(>>);
251 break;
252 case OP_ADD:
253 BINARY(+);
254 break;
255 case OP_SUBTRACT:
256 BINARY(-);
257 break;
258 case OP_MULTIPLY:
259 BINARY(*);
260 break;
261 case OP_DIVIDE:
262 BINARYDIV(/);
263 break;
264 case OP_MODULUS:
265 BINARYDIV(%);
266 break;
267 case OP_PLUS:
268 UNARY(+);
269 break;
270 case OP_MINUS:
271 UNARY(-);
272 break;
273 case OP_NEGATE:
274 UNARY(!);
275 break;
276 case OP_COMPLEMENT:
277 UNARY(~);
278 break;
279 default:
280 assert (0);
281 }
282 }
283
284 /* Write-back the index skipping the OP_END. */
285 *pi = i + 1;
286
287 /* There should be exactly one value left on the stack. This is our result. */
288 POP(*result);
289 pp_annotate (output, "%d ", *result);
290 assert (sp == EXECUTION_STACK_SIZE);
291 return GL_TRUE;
292 }
293
294 /*
295 * Function execute_expressions() executes up to 2 expressions. The second expression is there
296 * for the #line directive which takes 1 or 2 expressions that indicate line and file numbers.
297 * If it fails, it returns 0. If it succeeds, it returns the number of executed expressions.
298 */
299
300 #define EXP_END 0
301 #define EXP_EXPRESSION 1
302
303 static GLuint
304 execute_expressions (slang_string *output, grammar eid, const byte *expr, GLint results[2],
305 slang_info_log *elog)
306 {
307 GLint success;
308 byte *code;
309 GLuint size, count = 0;
310
311 success = grammar_fast_check (eid, expr, &code, &size, 64);
312 if (success) {
313 GLuint i = 0;
314
315 while (code[i++] == EXP_EXPRESSION) {
316 assert (count < 2);
317
318 if (!execute_expression (output, code, &i, &results[count], elog)) {
319 count = 0;
320 break;
321 }
322 count++;
323 }
324 grammar_alloc_free (code);
325 }
326 else {
327 slang_info_log_error (elog, "syntax error in preprocessor expression.");\
328 }
329 return count;
330 }
331
332 /*
333 * The pp_symbol structure is used to hold macro definitions and macro formal parameters. The
334 * pp_symbols strcture is a collection of pp_symbol. It is used both for storing macro formal
335 * parameters and all global macro definitions. Making this unification wastes some memory,
336 * becuse macro formal parameters don't need further lists of symbols. We lose 8 bytes per
337 * formal parameter here, but making this we can use the same code to substitute macro parameters
338 * as well as macros in the source string.
339 */
340
341 typedef struct
342 {
343 struct pp_symbol_ *symbols;
344 GLuint count;
345 } pp_symbols;
346
347 static GLvoid
348 pp_symbols_init (pp_symbols *self)
349 {
350 self->symbols = NULL;
351 self->count = 0;
352 }
353
354 static GLvoid
355 pp_symbols_free (pp_symbols *);
356
357 typedef struct pp_symbol_
358 {
359 slang_string name;
360 slang_string replacement;
361 pp_symbols parameters;
362 } pp_symbol;
363
364 static GLvoid
365 pp_symbol_init (pp_symbol *self)
366 {
367 slang_string_init (&self->name);
368 slang_string_init (&self->replacement);
369 pp_symbols_init (&self->parameters);
370 }
371
372 static GLvoid
373 pp_symbol_free (pp_symbol *self)
374 {
375 slang_string_free (&self->name);
376 slang_string_free (&self->replacement);
377 pp_symbols_free (&self->parameters);
378 }
379
380 static GLvoid
381 pp_symbol_reset (pp_symbol *self)
382 {
383 /* Leave symbol name intact. */
384 slang_string_reset (&self->replacement);
385 pp_symbols_free (&self->parameters);
386 pp_symbols_init (&self->parameters);
387 }
388
389 static GLvoid
390 pp_symbols_free (pp_symbols *self)
391 {
392 GLuint i;
393
394 for (i = 0; i < self->count; i++)
395 pp_symbol_free (&self->symbols[i]);
396 _mesa_free (self->symbols);
397 }
398
399 static pp_symbol *
400 pp_symbols_push (pp_symbols *self)
401 {
402 self->symbols = (pp_symbol *) (_mesa_realloc (self->symbols, self->count * sizeof (pp_symbol),
403 (self->count + 1) * sizeof (pp_symbol)));
404 if (self->symbols == NULL)
405 return NULL;
406 pp_symbol_init (&self->symbols[self->count]);
407 return &self->symbols[self->count++];
408 }
409
410 static GLboolean
411 pp_symbols_erase (pp_symbols *self, pp_symbol *symbol)
412 {
413 assert (symbol >= self->symbols && symbol < self->symbols + self->count);
414
415 self->count--;
416 pp_symbol_free (symbol);
417 if (symbol < self->symbols + self->count)
418 _mesa_memcpy (symbol, symbol + 1, sizeof (pp_symbol) * (self->symbols + self->count - symbol));
419 self->symbols = (pp_symbol *) (_mesa_realloc (self->symbols, (self->count + 1) * sizeof (pp_symbol),
420 self->count * sizeof (pp_symbol)));
421 return self->symbols != NULL;
422 }
423
424 static pp_symbol *
425 pp_symbols_find (pp_symbols *self, const char *name)
426 {
427 GLuint i;
428
429 for (i = 0; i < self->count; i++)
430 if (_mesa_strcmp (name, slang_string_cstr (&self->symbols[i].name)) == 0)
431 return &self->symbols[i];
432 return NULL;
433 }
434
435 /*
436 * The condition context of a single #if/#else/#endif level. Those can be nested, so there
437 * is a stack of condition contexts.
438 * There is a special global context on the bottom of the stack. It is there to simplify
439 * context handling.
440 */
441
442 typedef struct
443 {
444 GLboolean current; /* The condition value of this level. */
445 GLboolean effective; /* The effective product of current condition, outer level conditions
446 * and position within #if-#else-#endif sections. */
447 GLboolean else_allowed; /* TRUE if in #if-#else section, FALSE if in #else-#endif section
448 * and for global context. */
449 GLboolean endif_required; /* FALSE for global context only. */
450 } pp_cond_ctx;
451
452 /* Should be enuff. */
453 #define CONDITION_STACK_SIZE 64
454
455 typedef struct
456 {
457 pp_cond_ctx stack[CONDITION_STACK_SIZE];
458 pp_cond_ctx *top;
459 } pp_cond_stack;
460
461 static GLboolean
462 pp_cond_stack_push (pp_cond_stack *self, slang_info_log *elog)
463 {
464 if (self->top == self->stack) {
465 slang_info_log_error (elog, "internal compiler error: preprocessor condition stack overflow.");
466 return GL_FALSE;
467 }
468 self->top--;
469 return GL_TRUE;
470 }
471
472 static GLvoid
473 pp_cond_stack_reevaluate (pp_cond_stack *self)
474 {
475 /* There must be at least 2 conditions on the stack - one global and one being evaluated. */
476 assert (self->top <= &self->stack[CONDITION_STACK_SIZE - 2]);
477
478 self->top->effective = self->top->current && self->top[1].effective;
479 }
480
481
482 /**
483 * Extension enables through #extension directive.
484 * NOTE: Currently, only enable/disable state is stored.
485 */
486 typedef struct
487 {
488 GLboolean ARB_draw_buffers;
489 GLboolean ARB_texture_rectangle;
490 } pp_ext;
491
492
493 /**
494 * Disable all extensions. Called at startup and on #extension all: disable.
495 */
496 static GLvoid
497 pp_ext_disable_all(pp_ext *self)
498 {
499 _mesa_memset(self, 0, sizeof(self));
500 }
501
502
503 /**
504 * Called during preprocessor initialization to set the initial enable/disable
505 * state of extensions.
506 */
507 static GLvoid
508 pp_ext_init(pp_ext *self, const struct gl_extensions *extensions)
509 {
510 pp_ext_disable_all (self);
511 self->ARB_draw_buffers = GL_TRUE;
512 if (extensions->NV_texture_rectangle)
513 self->ARB_texture_rectangle = GL_TRUE;
514 }
515
516 /**
517 * Called in response to #extension directives to enable/disable
518 * the named extension.
519 */
520 static GLboolean
521 pp_ext_set(pp_ext *self, const char *name, GLboolean enable)
522 {
523 if (_mesa_strcmp (name, "GL_ARB_draw_buffers") == 0)
524 self->ARB_draw_buffers = enable;
525 else if (_mesa_strcmp (name, "GL_ARB_texture_rectangle") == 0)
526 self->ARB_texture_rectangle = enable;
527 else
528 return GL_FALSE;
529 return GL_TRUE;
530 }
531
532
533 /**
534 * Called in response to #pragma. For example, "#pragma debug(on)" would
535 * call this function as pp_pragma("debug", "on").
536 * \return GL_TRUE if pragma is valid, GL_FALSE if invalid
537 */
538 static GLboolean
539 pp_pragma(struct gl_sl_pragmas *pragmas, const char *pragma, const char *param)
540 {
541 #if 0
542 printf("#pragma %s %s\n", pragma, param);
543 #endif
544 if (_mesa_strcmp(pragma, "optimize") == 0) {
545 if (!param)
546 return GL_FALSE; /* missing required param */
547 if (_mesa_strcmp(param, "on") == 0) {
548 if (!pragmas->IgnoreOptimize)
549 pragmas->Optimize = GL_TRUE;
550 }
551 else if (_mesa_strcmp(param, "off") == 0) {
552 if (!pragmas->IgnoreOptimize)
553 pragmas->Optimize = GL_FALSE;
554 }
555 else {
556 return GL_FALSE; /* invalid param */
557 }
558 }
559 else if (_mesa_strcmp(pragma, "debug") == 0) {
560 if (!param)
561 return GL_FALSE; /* missing required param */
562 if (_mesa_strcmp(param, "on") == 0) {
563 if (!pragmas->IgnoreDebug)
564 pragmas->Debug = GL_TRUE;
565 }
566 else if (_mesa_strcmp(param, "off") == 0) {
567 if (!pragmas->IgnoreDebug)
568 pragmas->Debug = GL_FALSE;
569 }
570 else {
571 return GL_FALSE; /* invalid param */
572 }
573 }
574 /* all other pragmas are silently ignored */
575 return GL_TRUE;
576 }
577
578
579 /**
580 * The state of preprocessor: current line, file and version number, list
581 * of all defined macros and the #if/#endif context.
582 */
583 typedef struct
584 {
585 GLint line;
586 GLint file;
587 GLint version;
588 pp_symbols symbols;
589 pp_ext ext;
590 slang_info_log *elog;
591 pp_cond_stack cond;
592 } pp_state;
593
594 static GLvoid
595 pp_state_init (pp_state *self, slang_info_log *elog,
596 const struct gl_extensions *extensions)
597 {
598 self->line = 0;
599 self->file = 1;
600 #if FEATURE_es2_glsl
601 self->version = 100;
602 #else
603 self->version = 110;
604 #endif
605 pp_symbols_init (&self->symbols);
606 pp_ext_init (&self->ext, extensions);
607 self->elog = elog;
608
609 /* Initialize condition stack and create the global context. */
610 self->cond.top = &self->cond.stack[CONDITION_STACK_SIZE - 1];
611 self->cond.top->current = GL_TRUE;
612 self->cond.top->effective = GL_TRUE;
613 self->cond.top->else_allowed = GL_FALSE;
614 self->cond.top->endif_required = GL_FALSE;
615 }
616
617 static GLvoid
618 pp_state_free (pp_state *self)
619 {
620 pp_symbols_free (&self->symbols);
621 }
622
623 #define IS_FIRST_ID_CHAR(x) (((x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') || (x) == '_')
624 #define IS_NEXT_ID_CHAR(x) (IS_FIRST_ID_CHAR(x) || ((x) >= '0' && (x) <= '9'))
625 #define IS_WHITE(x) ((x) == ' ' || (x) == '\n')
626 #define IS_NULL(x) ((x) == '\0')
627
628 #define SKIP_WHITE(x) do { while (IS_WHITE(*(x))) (x)++; } while (GL_FALSE)
629
630 typedef struct
631 {
632 slang_string *output;
633 const char *input;
634 pp_state *state;
635 } expand_state;
636
637 static GLboolean
638 expand_defined (expand_state *e, slang_string *buffer)
639 {
640 GLboolean in_paren = GL_FALSE;
641 const char *id;
642
643 /* Parse the optional opening parenthesis. */
644 SKIP_WHITE(e->input);
645 if (*e->input == '(') {
646 e->input++;
647 in_paren = GL_TRUE;
648 SKIP_WHITE(e->input);
649 }
650
651 /* Parse operand. */
652 if (!IS_FIRST_ID_CHAR(*e->input)) {
653 slang_info_log_error (e->state->elog,
654 "preprocess error: identifier expected after operator 'defined'.");
655 return GL_FALSE;
656 }
657 slang_string_reset (buffer);
658 slang_string_pushc (buffer, *e->input++);
659 while (IS_NEXT_ID_CHAR(*e->input))
660 slang_string_pushc (buffer, *e->input++);
661 id = slang_string_cstr (buffer);
662
663 /* Check if the operand is defined. Output 1 if it is defined, output 0 if not. */
664 if (pp_symbols_find (&e->state->symbols, id) == NULL)
665 slang_string_pushs (e->output, " 0 ", 3);
666 else
667 slang_string_pushs (e->output, " 1 ", 3);
668
669 /* Parse the closing parentehesis if the opening one was there. */
670 if (in_paren) {
671 SKIP_WHITE(e->input);
672 if (*e->input != ')') {
673 slang_info_log_error (e->state->elog, "preprocess error: ')' expected.");
674 return GL_FALSE;
675 }
676 e->input++;
677 SKIP_WHITE(e->input);
678 }
679 return GL_TRUE;
680 }
681
682 static GLboolean
683 expand (expand_state *, pp_symbols *);
684
685 static GLboolean
686 expand_symbol (expand_state *e, pp_symbol *symbol)
687 {
688 expand_state es;
689
690 /* If the macro has some parameters, we need to parse them. */
691 if (symbol->parameters.count != 0) {
692 GLuint i;
693
694 /* Parse the opening parenthesis. */
695 SKIP_WHITE(e->input);
696 if (*e->input != '(') {
697 slang_info_log_error (e->state->elog, "preprocess error: '(' expected.");
698 return GL_FALSE;
699 }
700 e->input++;
701 SKIP_WHITE(e->input);
702
703 /* Parse macro actual parameters. This can be anything, separated by a colon.
704 */
705 for (i = 0; i < symbol->parameters.count; i++) {
706 GLuint nested_paren_count = 0; /* track number of nested parentheses */
707
708 if (*e->input == ')') {
709 slang_info_log_error (e->state->elog, "preprocess error: unexpected ')'.");
710 return GL_FALSE;
711 }
712
713 /* Eat all characters up to the comma or closing parentheses. */
714 pp_symbol_reset (&symbol->parameters.symbols[i]);
715 while (!IS_NULL(*e->input)) {
716 /* Exit loop only when all nested parens have been eaten. */
717 if (nested_paren_count == 0 && (*e->input == ',' || *e->input == ')'))
718 break;
719
720 /* Actually count nested parens here. */
721 if (*e->input == '(')
722 nested_paren_count++;
723 else if (*e->input == ')')
724 nested_paren_count--;
725
726 slang_string_pushc (&symbol->parameters.symbols[i].replacement, *e->input++);
727 }
728
729 /* If it was not the last paremeter, skip the comma. Otherwise, skip the
730 * closing parentheses. */
731 if (i + 1 == symbol->parameters.count) {
732 /* This is the last paremeter - skip the closing parentheses. */
733 if (*e->input != ')') {
734 slang_info_log_error (e->state->elog, "preprocess error: ')' expected.");
735 return GL_FALSE;
736 }
737 e->input++;
738 SKIP_WHITE(e->input);
739 }
740 else {
741 /* Skip the separating comma. */
742 if (*e->input != ',') {
743 slang_info_log_error (e->state->elog, "preprocess error: ',' expected.");
744 return GL_FALSE;
745 }
746 e->input++;
747 SKIP_WHITE(e->input);
748 }
749 }
750 }
751
752 /* Expand the macro. Use its parameters as a priority symbol list to expand
753 * macro parameters correctly. */
754 es.output = e->output;
755 es.input = slang_string_cstr (&symbol->replacement);
756 es.state = e->state;
757 slang_string_pushc (e->output, ' ');
758 if (!expand (&es, &symbol->parameters))
759 return GL_FALSE;
760 slang_string_pushc (e->output, ' ');
761 return GL_TRUE;
762 }
763
764 /*
765 * Function expand() expands source text from <input> to <output>. The expansion is made using
766 * the list passed in <symbols> parameter. It allows us to expand macro formal parameters with
767 * actual parameters. The global list of symbols from pp state is used when doing a recursive
768 * call of expand().
769 */
770
771 static GLboolean
772 expand (expand_state *e, pp_symbols *symbols)
773 {
774 while (!IS_NULL(*e->input)) {
775 if (IS_FIRST_ID_CHAR(*e->input)) {
776 slang_string buffer;
777 const char *id;
778
779 /* Parse the identifier. */
780 slang_string_init (&buffer);
781 slang_string_pushc (&buffer, *e->input++);
782 while (IS_NEXT_ID_CHAR(*e->input))
783 slang_string_pushc (&buffer, *e->input++);
784 id = slang_string_cstr (&buffer);
785
786 /* Now check if the identifier is special in some way. The "defined" identifier is
787 * actually an operator that we must handle here and expand it either to " 0 " or " 1 ".
788 * The other identifiers start with "__" and we expand it to appropriate values
789 * taken from the preprocessor state. */
790 if (_mesa_strcmp (id, "defined") == 0) {
791 if (!expand_defined (e, &buffer))
792 return GL_FALSE;
793 }
794 else if (_mesa_strcmp (id, "__LINE__") == 0) {
795 slang_string_pushc (e->output, ' ');
796 slang_string_pushi (e->output, e->state->line);
797 slang_string_pushc (e->output, ' ');
798 }
799 else if (_mesa_strcmp (id, "__FILE__") == 0) {
800 slang_string_pushc (e->output, ' ');
801 slang_string_pushi (e->output, e->state->file);
802 slang_string_pushc (e->output, ' ');
803 }
804 else if (_mesa_strcmp (id, "__VERSION__") == 0) {
805 slang_string_pushc (e->output, ' ');
806 slang_string_pushi (e->output, e->state->version);
807 slang_string_pushc (e->output, ' ');
808 }
809 #if FEATURE_es2_glsl
810 else if (_mesa_strcmp (id, "GL_ES") == 0 ||
811 _mesa_strcmp (id, "GL_FRAGMENT_PRECISION_HIGH") == 0) {
812 slang_string_pushc (e->output, ' ');
813 slang_string_pushi (e->output, '1');
814 slang_string_pushc (e->output, ' ');
815 }
816 #endif
817 else {
818 pp_symbol *symbol;
819
820 /* The list of symbols from <symbols> take precedence over the list from <state>.
821 * Note that in some cases this is the same list so avoid double look-up. */
822 symbol = pp_symbols_find (symbols, id);
823 if (symbol == NULL && symbols != &e->state->symbols)
824 symbol = pp_symbols_find (&e->state->symbols, id);
825
826 /* If the symbol was found, recursively expand its definition. */
827 if (symbol != NULL) {
828 if (!expand_symbol (e, symbol)) {
829 slang_string_free (&buffer);
830 return GL_FALSE;
831 }
832 }
833 else {
834 slang_string_push (e->output, &buffer);
835 }
836 }
837 slang_string_free (&buffer);
838 }
839 else if (IS_WHITE(*e->input)) {
840 slang_string_pushc (e->output, *e->input++);
841 }
842 else {
843 while (!IS_WHITE(*e->input) && !IS_NULL(*e->input) && !IS_FIRST_ID_CHAR(*e->input))
844 slang_string_pushc (e->output, *e->input++);
845 }
846 }
847 return GL_TRUE;
848 }
849
850 static GLboolean
851 parse_if (slang_string *output, const byte *prod, GLuint *pi, GLint *result, pp_state *state,
852 grammar eid)
853 {
854 const char *text;
855 GLuint len;
856
857 text = (const char *) (&prod[*pi]);
858 len = _mesa_strlen (text);
859
860 if (state->cond.top->effective) {
861 slang_string expr;
862 GLuint count;
863 GLint results[2];
864 expand_state es;
865
866 /* Expand the expression. */
867 slang_string_init (&expr);
868 es.output = &expr;
869 es.input = text;
870 es.state = state;
871 if (!expand (&es, &state->symbols))
872 return GL_FALSE;
873
874 /* Execute the expression. */
875 count = execute_expressions (output, eid, (const byte *) (slang_string_cstr (&expr)),
876 results, state->elog);
877 slang_string_free (&expr);
878 if (count != 1)
879 return GL_FALSE;
880 *result = results[0];
881 }
882 else {
883 /* The directive is dead. */
884 *result = 0;
885 }
886
887 *pi += len + 1;
888 return GL_TRUE;
889 }
890
891 #define ESCAPE_TOKEN 0
892
893 #define TOKEN_END 0
894 #define TOKEN_DEFINE 1
895 #define TOKEN_UNDEF 2
896 #define TOKEN_IF 3
897 #define TOKEN_ELSE 4
898 #define TOKEN_ELIF 5
899 #define TOKEN_ENDIF 6
900 #define TOKEN_ERROR 7
901 #define TOKEN_PRAGMA 8
902 #define TOKEN_EXTENSION 9
903 #define TOKEN_LINE 10
904
905 #define PARAM_END 0
906 #define PARAM_PARAMETER 1
907
908 #define BEHAVIOR_REQUIRE 1
909 #define BEHAVIOR_ENABLE 2
910 #define BEHAVIOR_WARN 3
911 #define BEHAVIOR_DISABLE 4
912
913 #define PRAGMA_NO_PARAM 0
914 #define PRAGMA_PARAM 1
915
916
917 static GLboolean
918 preprocess_source (slang_string *output, const char *source,
919 grammar pid, grammar eid,
920 slang_info_log *elog,
921 const struct gl_extensions *extensions,
922 struct gl_sl_pragmas *pragmas)
923 {
924 static const char *predefined[] = {
925 "__FILE__",
926 "__LINE__",
927 "__VERSION__",
928 #if FEATURE_es2_glsl
929 "GL_ES",
930 "GL_FRAGMENT_PRECISION_HIGH",
931 #endif
932 NULL
933 };
934 byte *prod;
935 GLuint size, i;
936 pp_state state;
937
938 if (!grammar_fast_check (pid, (const byte *) (source), &prod, &size, 65536)) {
939 grammar_error_to_log (elog);
940 return GL_FALSE;
941 }
942
943 pp_state_init (&state, elog, extensions);
944
945 /* add the predefined symbols to the symbol table */
946 for (i = 0; predefined[i]; i++) {
947 pp_symbol *symbol = NULL;
948 symbol = pp_symbols_push(&state.symbols);
949 assert(symbol);
950 slang_string_pushs(&symbol->name,
951 predefined[i], _mesa_strlen(predefined[i]));
952 }
953
954 i = 0;
955 while (i < size) {
956 if (prod[i] != ESCAPE_TOKEN) {
957 if (state.cond.top->effective) {
958 slang_string input;
959 expand_state es;
960
961 /* Eat only one line of source code to expand it.
962 * FIXME: This approach has one drawback. If a macro with parameters spans across
963 * multiple lines, the preprocessor will raise an error. */
964 slang_string_init (&input);
965 while (prod[i] != '\0' && prod[i] != '\n')
966 slang_string_pushc (&input, prod[i++]);
967 if (prod[i] != '\0')
968 slang_string_pushc (&input, prod[i++]);
969
970 /* Increment line number. */
971 state.line++;
972
973 es.output = output;
974 es.input = slang_string_cstr (&input);
975 es.state = &state;
976 if (!expand (&es, &state.symbols))
977 goto error;
978
979 slang_string_free (&input);
980 }
981 else {
982 /* Condition stack is disabled - keep track on line numbers and output only newlines. */
983 if (prod[i] == '\n') {
984 state.line++;
985 /*pp_annotate (output, "%c", prod[i]);*/
986 }
987 else {
988 /*pp_annotate (output, "%c", prod[i]);*/
989 }
990 i++;
991 }
992 }
993 else {
994 const char *id;
995 GLuint idlen;
996 GLubyte token;
997
998 i++;
999 token = prod[i++];
1000 switch (token) {
1001
1002 case TOKEN_END:
1003 /* End of source string.
1004 * Check if all #ifs have been terminated by matching #endifs.
1005 * On condition stack there should be only the global condition context. */
1006 if (state.cond.top->endif_required) {
1007 slang_info_log_error (elog, "end of source without matching #endif.");
1008 return GL_FALSE;
1009 }
1010 break;
1011
1012 case TOKEN_DEFINE:
1013 {
1014 pp_symbol *symbol = NULL;
1015
1016 /* Parse macro name. */
1017 id = (const char *) (&prod[i]);
1018 idlen = _mesa_strlen (id);
1019 if (state.cond.top->effective) {
1020 pp_annotate (output, "// #define %s(", id);
1021
1022 /* If the symbol is already defined, override it. */
1023 symbol = pp_symbols_find (&state.symbols, id);
1024 if (symbol == NULL) {
1025 symbol = pp_symbols_push (&state.symbols);
1026 if (symbol == NULL)
1027 goto error;
1028 slang_string_pushs (&symbol->name, id, idlen);
1029 }
1030 else {
1031 pp_symbol_reset (symbol);
1032 }
1033 }
1034 i += idlen + 1;
1035
1036 /* Parse optional macro parameters. */
1037 while (prod[i++] != PARAM_END) {
1038 if (state.cond.top->effective) {
1039 pp_symbol *param;
1040
1041 id = (const char *) (&prod[i]);
1042 idlen = _mesa_strlen (id);
1043 pp_annotate (output, "%s, ", id);
1044 param = pp_symbols_push (&symbol->parameters);
1045 if (param == NULL)
1046 goto error;
1047 slang_string_pushs (&param->name, id, idlen);
1048 }
1049 i += idlen + 1;
1050 }
1051
1052 /* Parse macro replacement. */
1053 id = (const char *) (&prod[i]);
1054 idlen = _mesa_strlen (id);
1055 if (state.cond.top->effective) {
1056 pp_annotate (output, ") %s", id);
1057 slang_string_pushs (&symbol->replacement, id, idlen);
1058 }
1059 i += idlen + 1;
1060 }
1061 break;
1062
1063 case TOKEN_UNDEF:
1064 id = (const char *) (&prod[i]);
1065 i += _mesa_strlen (id) + 1;
1066 if (state.cond.top->effective) {
1067 pp_symbol *symbol;
1068
1069 pp_annotate (output, "// #undef %s", id);
1070 /* Try to find symbol with given name and remove it. */
1071 symbol = pp_symbols_find (&state.symbols, id);
1072 if (symbol != NULL)
1073 if (!pp_symbols_erase (&state.symbols, symbol))
1074 goto error;
1075 }
1076 break;
1077
1078 case TOKEN_IF:
1079 {
1080 GLint result;
1081
1082 /* Parse #if expression end execute it. */
1083 pp_annotate (output, "// #if ");
1084 if (!parse_if (output, prod, &i, &result, &state, eid))
1085 goto error;
1086
1087 /* Push new condition on the stack. */
1088 if (!pp_cond_stack_push (&state.cond, state.elog))
1089 goto error;
1090 state.cond.top->current = result ? GL_TRUE : GL_FALSE;
1091 state.cond.top->else_allowed = GL_TRUE;
1092 state.cond.top->endif_required = GL_TRUE;
1093 pp_cond_stack_reevaluate (&state.cond);
1094 }
1095 break;
1096
1097 case TOKEN_ELSE:
1098 /* Check if #else is alloved here. */
1099 if (!state.cond.top->else_allowed) {
1100 slang_info_log_error (elog, "#else without matching #if.");
1101 goto error;
1102 }
1103
1104 /* Negate current condition and reevaluate it. */
1105 state.cond.top->current = !state.cond.top->current;
1106 state.cond.top->else_allowed = GL_FALSE;
1107 pp_cond_stack_reevaluate (&state.cond);
1108 if (state.cond.top->effective)
1109 pp_annotate (output, "// #else");
1110 break;
1111
1112 case TOKEN_ELIF:
1113 /* Check if #elif is alloved here. */
1114 if (!state.cond.top->else_allowed) {
1115 slang_info_log_error (elog, "#elif without matching #if.");
1116 goto error;
1117 }
1118
1119 /* Negate current condition and reevaluate it. */
1120 state.cond.top->current = !state.cond.top->current;
1121 pp_cond_stack_reevaluate (&state.cond);
1122
1123 if (state.cond.top->effective)
1124 pp_annotate (output, "// #elif ");
1125
1126 {
1127 GLint result;
1128
1129 /* Parse #elif expression end execute it. */
1130 if (!parse_if (output, prod, &i, &result, &state, eid))
1131 goto error;
1132
1133 /* Update current condition and reevaluate it. */
1134 state.cond.top->current = result ? GL_TRUE : GL_FALSE;
1135 pp_cond_stack_reevaluate (&state.cond);
1136 }
1137 break;
1138
1139 case TOKEN_ENDIF:
1140 /* Check if #endif is alloved here. */
1141 if (!state.cond.top->endif_required) {
1142 slang_info_log_error (elog, "#endif without matching #if.");
1143 goto error;
1144 }
1145
1146 /* Pop the condition off the stack. */
1147 state.cond.top++;
1148 if (state.cond.top->effective)
1149 pp_annotate (output, "// #endif");
1150 break;
1151
1152 case TOKEN_EXTENSION:
1153 /* Parse the extension name. */
1154 id = (const char *) (&prod[i]);
1155 i += _mesa_strlen (id) + 1;
1156 if (state.cond.top->effective)
1157 pp_annotate (output, "// #extension %s: ", id);
1158
1159 /* Parse and apply extension behavior. */
1160 if (state.cond.top->effective) {
1161 switch (prod[i++]) {
1162
1163 case BEHAVIOR_REQUIRE:
1164 pp_annotate (output, "require");
1165 if (!pp_ext_set (&state.ext, id, GL_TRUE)) {
1166 if (_mesa_strcmp (id, "all") == 0) {
1167 slang_info_log_error (elog, "require: bad behavior for #extension all.");
1168 goto error;
1169 }
1170 else {
1171 slang_info_log_error (elog, "%s: required extension is not supported.", id);
1172 goto error;
1173 }
1174 }
1175 break;
1176
1177 case BEHAVIOR_ENABLE:
1178 pp_annotate (output, "enable");
1179 if (!pp_ext_set (&state.ext, id, GL_TRUE)) {
1180 if (_mesa_strcmp (id, "all") == 0) {
1181 slang_info_log_error (elog, "enable: bad behavior for #extension all.");
1182 goto error;
1183 }
1184 else {
1185 slang_info_log_warning (elog, "%s: enabled extension is not supported.", id);
1186 }
1187 }
1188 break;
1189
1190 case BEHAVIOR_WARN:
1191 pp_annotate (output, "warn");
1192 if (!pp_ext_set (&state.ext, id, GL_TRUE)) {
1193 if (_mesa_strcmp (id, "all") != 0) {
1194 slang_info_log_warning (elog, "%s: enabled extension is not supported.", id);
1195 }
1196 }
1197 break;
1198
1199 case BEHAVIOR_DISABLE:
1200 pp_annotate (output, "disable");
1201 if (!pp_ext_set (&state.ext, id, GL_FALSE)) {
1202 if (_mesa_strcmp (id, "all") == 0) {
1203 pp_ext_disable_all (&state.ext);
1204 }
1205 else {
1206 slang_info_log_warning (elog, "%s: disabled extension is not supported.", id);
1207 }
1208 }
1209 break;
1210
1211 default:
1212 assert (0);
1213 }
1214 }
1215 break;
1216
1217 case TOKEN_PRAGMA:
1218 {
1219 GLint have_param;
1220 const char *pragma, *param;
1221
1222 pragma = (const char *) (&prod[i]);
1223 i += _mesa_strlen(pragma) + 1;
1224 have_param = (prod[i++] == PRAGMA_PARAM);
1225 if (have_param) {
1226 param = (const char *) (&prod[i]);
1227 i += _mesa_strlen(param) + 1;
1228 }
1229 else {
1230 param = NULL;
1231 }
1232 pp_pragma(pragmas, pragma, param);
1233 }
1234 break;
1235
1236 case TOKEN_LINE:
1237 id = (const char *) (&prod[i]);
1238 i += _mesa_strlen (id) + 1;
1239
1240 if (state.cond.top->effective) {
1241 slang_string buffer;
1242 GLuint count;
1243 GLint results[2];
1244 expand_state es;
1245
1246 slang_string_init (&buffer);
1247 state.line++;
1248 es.output = &buffer;
1249 es.input = id;
1250 es.state = &state;
1251 if (!expand (&es, &state.symbols))
1252 goto error;
1253
1254 pp_annotate (output, "// #line ");
1255 count = execute_expressions (output, eid,
1256 (const byte *) (slang_string_cstr (&buffer)),
1257 results, state.elog);
1258 slang_string_free (&buffer);
1259 if (count == 0)
1260 goto error;
1261
1262 state.line = results[0] - 1;
1263 if (count == 2)
1264 state.file = results[1];
1265 }
1266 break;
1267 }
1268 }
1269 }
1270
1271 /* Check for missing #endifs. */
1272 if (state.cond.top->endif_required) {
1273 slang_info_log_error (elog, "#endif expected but end of source found.");
1274 goto error;
1275 }
1276
1277 grammar_alloc_free(prod);
1278 pp_state_free (&state);
1279 return GL_TRUE;
1280
1281 error:
1282 grammar_alloc_free(prod);
1283 pp_state_free (&state);
1284 return GL_FALSE;
1285 }
1286
1287
1288 /**
1289 * Run preprocessor on source code.
1290 * \param extensions indicates which GL extensions are enabled
1291 * \param output the post-process results
1292 * \param input the input text
1293 * \param elog log to record warnings, errors
1294 * \param extensions out extension settings
1295 * \param pragmas in/out #pragma settings
1296 * \return GL_TRUE for success, GL_FALSE for error
1297 */
1298 GLboolean
1299 _slang_preprocess_directives(slang_string *output,
1300 const char *input,
1301 slang_info_log *elog,
1302 const struct gl_extensions *extensions,
1303 struct gl_sl_pragmas *pragmas)
1304 {
1305 grammar pid, eid;
1306 GLboolean success;
1307
1308 pid = grammar_load_from_text ((const byte *) (slang_pp_directives_syn));
1309 if (pid == 0) {
1310 grammar_error_to_log (elog);
1311 return GL_FALSE;
1312 }
1313 eid = grammar_load_from_text ((const byte *) (slang_pp_expression_syn));
1314 if (eid == 0) {
1315 grammar_error_to_log (elog);
1316 grammar_destroy (pid);
1317 return GL_FALSE;
1318 }
1319 success = preprocess_source (output, input, pid, eid, elog, extensions, pragmas);
1320 grammar_destroy (eid);
1321 grammar_destroy (pid);
1322 return success;
1323 }
1324