Debian Codegraph @

mojoshader_preprocessor.c

raw symbols SCIP
1 /**
2 * MojoShader; generate shader programs from bytecode of compiled
3 * Direct3D shaders.
4 *
5 * Please see the file LICENSE.txt in the source's root directory.
6 *
7 * This file written by Ryan C. Gordon.
8 */
9
10 #define __MOJOSHADER_INTERNAL__ 1
11 #include "mojoshader_internal.h"
12
13 #if DEBUG_PREPROCESSOR
14 #define print_debug_token(token, len, val) \
15 MOJOSHADER_print_debug_token("PREPROCESSOR", token, len, val)
16 #else
17 #define print_debug_token(token, len, val)
18 #endif
19
20 #if DEBUG_LEXER
21 static Token debug_preprocessor_lexer(IncludeState *s)
22 {
23 const Token retval = preprocessor_lexer(s);
24 MOJOSHADER_print_debug_token("LEXER", s->token, s->tokenlen, retval);
25 return retval;
26 } // debug_preprocessor_lexer
27 #define preprocessor_lexer(s) debug_preprocessor_lexer(s)
28 #endif
29
30 #if DEBUG_TOKENIZER
31 static void print_debug_lexing_position(IncludeState *s)
32 {
33 if (s != NULL)
34 printf("NOW LEXING %s:%d ...\n", s->filename, s->line);
35 } // print_debug_lexing_position
36 #else
37 #define print_debug_lexing_position(s)
38 #endif
39
40 typedef struct Context
41 {
42 int isfail;
43 int out_of_memory;
44 char failstr[256];
45 int recursion_count;
46 int asm_comments;
47 int parsing_pragma;
48 Conditional *conditional_pool;
49 IncludeState *include_stack;
50 IncludeState *include_pool;
51 Define *define_hashtable[256];
52 Define *define_pool;
53 Define *file_macro;
54 Define *line_macro;
55 StringCache *filename_cache;
56 MOJOSHADER_includeOpen open_callback;
57 MOJOSHADER_includeClose close_callback;
58 MOJOSHADER_malloc malloc;
59 MOJOSHADER_free free;
60 void *malloc_data;
61 } Context;
62
63
64 // Convenience functions for allocators...
65
66 static inline void out_of_memory(Context *ctx)
67 {
68 ctx->out_of_memory = 1;
69 } // out_of_memory
70
71 static inline void *Malloc(Context *ctx, const size_t len)
72 {
73 void *retval = ctx->malloc((int) len, ctx->malloc_data);
74 if (retval == NULL)
75 out_of_memory(ctx);
76 return retval;
77 } // Malloc
78
79 static inline void Free(Context *ctx, void *ptr)
80 {
81 ctx->free(ptr, ctx->malloc_data);
82 } // Free
83
84 static void *MallocBridge(int bytes, void *data)
85 {
86 return Malloc((Context *) data, (size_t) bytes);
87 } // MallocBridge
88
89 static void FreeBridge(void *ptr, void *data)
90 {
91 Free((Context *) data, ptr);
92 } // FreeBridge
93
94 static inline char *StrDup(Context *ctx, const char *str)
95 {
96 char *retval = (char *) Malloc(ctx, strlen(str) + 1);
97 if (retval != NULL)
98 strcpy(retval, str);
99 return retval;
100 } // StrDup
101
102 static void failf(Context *ctx, const char *fmt, ...) ISPRINTF(2,3);
103 static void failf(Context *ctx, const char *fmt, ...)
104 {
105 ctx->isfail = 1;
106 va_list ap;
107 va_start(ap, fmt);
108 vsnprintf(ctx->failstr, sizeof (ctx->failstr), fmt, ap);
109 va_end(ap);
110 } // failf
111
112 static inline void fail(Context *ctx, const char *reason)
113 {
114 failf(ctx, "%s", reason);
115 } // fail
116
117
118 #if DEBUG_TOKENIZER
119 void MOJOSHADER_print_debug_token(const char *subsystem, const char *token,
120 const unsigned int tokenlen,
121 const Token tokenval)
122 {
123 printf("%s TOKEN: \"", subsystem);
124 unsigned int i;
125 for (i = 0; i < tokenlen; i++)
126 {
127 if (token[i] == '\n')
128 printf("\\n");
129 else if (token[i] == '\\')
130 printf("\\\\");
131 else
132 printf("%c", token[i]);
133 } // for
134 printf("\" (");
135 switch (tokenval)
136 {
137 #define TOKENCASE(x) case x: printf("%s", #x); break
138 TOKENCASE(TOKEN_UNKNOWN);
139 TOKENCASE(TOKEN_IDENTIFIER);
140 TOKENCASE(TOKEN_INT_LITERAL);
141 TOKENCASE(TOKEN_FLOAT_LITERAL);
142 TOKENCASE(TOKEN_STRING_LITERAL);
143 TOKENCASE(TOKEN_ADDASSIGN);
144 TOKENCASE(TOKEN_SUBASSIGN);
145 TOKENCASE(TOKEN_MULTASSIGN);
146 TOKENCASE(TOKEN_DIVASSIGN);
147 TOKENCASE(TOKEN_MODASSIGN);
148 TOKENCASE(TOKEN_XORASSIGN);
149 TOKENCASE(TOKEN_ANDASSIGN);
150 TOKENCASE(TOKEN_ORASSIGN);
151 TOKENCASE(TOKEN_INCREMENT);
152 TOKENCASE(TOKEN_DECREMENT);
153 TOKENCASE(TOKEN_RSHIFT);
154 TOKENCASE(TOKEN_LSHIFT);
155 TOKENCASE(TOKEN_ANDAND);
156 TOKENCASE(TOKEN_OROR);
157 TOKENCASE(TOKEN_LEQ);
158 TOKENCASE(TOKEN_GEQ);
159 TOKENCASE(TOKEN_EQL);
160 TOKENCASE(TOKEN_NEQ);
161 TOKENCASE(TOKEN_HASH);
162 TOKENCASE(TOKEN_HASHHASH);
163 TOKENCASE(TOKEN_PP_INCLUDE);
164 TOKENCASE(TOKEN_PP_LINE);
165 TOKENCASE(TOKEN_PP_DEFINE);
166 TOKENCASE(TOKEN_PP_UNDEF);
167 TOKENCASE(TOKEN_PP_IF);
168 TOKENCASE(TOKEN_PP_IFDEF);
169 TOKENCASE(TOKEN_PP_IFNDEF);
170 TOKENCASE(TOKEN_PP_ELSE);
171 TOKENCASE(TOKEN_PP_ELIF);
172 TOKENCASE(TOKEN_PP_ENDIF);
173 TOKENCASE(TOKEN_PP_ERROR);
174 TOKENCASE(TOKEN_PP_PRAGMA);
175 TOKENCASE(TOKEN_INCOMPLETE_COMMENT);
176 TOKENCASE(TOKEN_BAD_CHARS);
177 TOKENCASE(TOKEN_SINGLE_COMMENT);
178 TOKENCASE(TOKEN_MULTI_COMMENT);
179 TOKENCASE(TOKEN_EOI);
180 TOKENCASE(TOKEN_PREPROCESSING_ERROR);
181 #undef TOKENCASE
182
183 case ((Token) '\n'):
184 printf("'\\n'");
185 break;
186
187 case ((Token) '\\'):
188 printf("'\\\\'");
189 break;
190
191 default:
192 assert(((int)tokenval) < 256);
193 printf("'%c'", (char) tokenval);
194 break;
195 } // switch
196 printf(")\n");
197 } // MOJOSHADER_print_debug_token
198 #endif
199
200
201
202 #if !MOJOSHADER_FORCE_INCLUDE_CALLBACKS
203
204 #ifdef _WIN32
205 #define WIN32_LEAN_AND_MEAN 1
206 #include <windows.h> // GL headers need this for WINGDIAPI definition.
207 #else
208 #include <sys/stat.h>
209 #include <fcntl.h>
210 #include <unistd.h>
211 #endif
212
213 int MOJOSHADER_internal_include_open(MOJOSHADER_includeType inctype,
214 const char *fname, const char *parent,
215 const char **outdata,
216 unsigned int *outbytes,
217 MOJOSHADER_malloc m, MOJOSHADER_free f,
218 void *d)
219 {
220 #ifdef _WIN32
221 WCHAR wpath[MAX_PATH];
222 if (!MultiByteToWideChar(CP_UTF8, 0, fname, -1, wpath, MAX_PATH))
223 return 0;
224
225 const DWORD share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
226 const HANDLE handle = CreateFileW(wpath, FILE_GENERIC_READ, share,
227 NULL, OPEN_EXISTING, NULL, NULL);
228 if (handle == INVALID_HANDLE_VALUE)
229 return 0;
230
231 const DWORD fileSize = GetFileSize(handle, NULL);
232 if (fileSize == INVALID_FILE_SIZE)
233 {
234 CloseHandle(handle);
235 return 0;
236 } // if
237
238 char *data = (char *) m(fileSize, d);
239 if (data == NULL)
240 {
241 CloseHandle(handle);
242 return 0;
243 } // if
244
245 DWORD readLength = 0;
246 if (!ReadFile(handle, data, fileSize, &readLength, NULL))
247 {
248 CloseHandle(handle);
249 f(data, d);
250 return 0;
251 } // if
252
253 CloseHandle(handle);
254
255 if (readLength != fileSize)
256 {
257 f(data, d);
258 return 0;
259 } // if
260 *outdata = data;
261 *outbytes = fileSize;
262 return 1;
263 #else
264 struct stat statbuf;
265 if (stat(fname, &statbuf) == -1)
266 return 0;
267 char *data = (char *) m(statbuf.st_size, d);
268 if (data == NULL)
269 return 0;
270 const int fd = open(fname, O_RDONLY);
271 if (fd == -1)
272 {
273 f(data, d);
274 return 0;
275 } // if
276 if (read(fd, data, statbuf.st_size) != statbuf.st_size)
277 {
278 f(data, d);
279 close(fd);
280 return 0;
281 } // if
282 close(fd);
283 *outdata = data;
284 *outbytes = (unsigned int) statbuf.st_size;
285 return 1;
286 #endif
287 } // MOJOSHADER_internal_include_open
288
289
290 void MOJOSHADER_internal_include_close(const char *data, MOJOSHADER_malloc m,
291 MOJOSHADER_free f, void *d)
292 {
293 f((void *) data, d);
294 } // MOJOSHADER_internal_include_close
295 #endif // !MOJOSHADER_FORCE_INCLUDE_CALLBACKS
296
297
298 // !!! FIXME: maybe use these pool magic elsewhere?
299 // !!! FIXME: maybe just get rid of this? (maybe the fragmentation isn't a big deal?)
300
301 // Pool stuff...
302 // ugh, I hate this macro salsa.
303 #define FREE_POOL(type, poolname) \
304 static void free_##poolname##_pool(Context *ctx) { \
305 type *item = ctx->poolname##_pool; \
306 while (item != NULL) { \
307 type *next = item->next; \
308 Free(ctx, item); \
309 item = next; \
310 } \
311 }
312
313 #define GET_POOL(type, poolname) \
314 static type *get_##poolname(Context *ctx) { \
315 type *retval = ctx->poolname##_pool; \
316 if (retval != NULL) \
317 ctx->poolname##_pool = retval->next; \
318 else \
319 retval = (type *) Malloc(ctx, sizeof (type)); \
320 if (retval != NULL) \
321 memset(retval, '\0', sizeof (type)); \
322 return retval; \
323 }
324
325 #define PUT_POOL(type, poolname) \
326 static void put_##poolname(Context *ctx, type *item) { \
327 item->next = ctx->poolname##_pool; \
328 ctx->poolname##_pool = item; \
329 }
330
331 #define IMPLEMENT_POOL(type, poolname) \
332 FREE_POOL(type, poolname) \
333 GET_POOL(type, poolname) \
334 PUT_POOL(type, poolname)
335
336 IMPLEMENT_POOL(Conditional, conditional)
337 IMPLEMENT_POOL(IncludeState, include)
338 IMPLEMENT_POOL(Define, define)
339
340
341 // Preprocessor define hashtable stuff...
342
343 // !!! FIXME: why isn't this using mojoshader_common.c's code?
344
345 // this is djb's xor hashing function.
346 static inline uint32 hash_string_djbxor(const char *sym)
347 {
348 register uint32 hash = 5381;
349 while (*sym)
350 hash = ((hash << 5) + hash) ^ *(sym++);
351 return hash;
352 } // hash_string_djbxor
353
354 static inline uint8 hash_define(const char *sym)
355 {
356 return (uint8) hash_string_djbxor(sym);
357 } // hash_define
358
359
360 static int add_define(Context *ctx, const char *sym, const char *val,
361 char **parameters, int paramcount)
362 {
363 const uint8 hash = hash_define(sym);
364 Define *bucket = ctx->define_hashtable[hash];
365 while (bucket)
366 {
367 if (strcmp(bucket->identifier, sym) == 0)
368 {
369 failf(ctx, "'%s' already defined", sym); // !!! FIXME: warning?
370 // !!! FIXME: gcc reports the location of previous #define here.
371 return 0;
372 } // if
373 bucket = bucket->next;
374 } // while
375
376 bucket = get_define(ctx);
377 if (bucket == NULL)
378 return 0;
379
380 bucket->definition = val;
381 bucket->original = NULL;
382 bucket->identifier = sym;
383 bucket->parameters = (const char **) parameters;
384 bucket->paramcount = paramcount;
385 bucket->next = ctx->define_hashtable[hash];
386 ctx->define_hashtable[hash] = bucket;
387 return 1;
388 } // add_define
389
390
391 static void free_define(Context *ctx, Define *def)
392 {
393 if (def != NULL)
394 {
395 int i;
396 for (i = 0; i < def->paramcount; i++)
397 Free(ctx, (void *) def->parameters[i]);
398 Free(ctx, (void *) def->parameters);
399 Free(ctx, (void *) def->identifier);
400 Free(ctx, (void *) def->definition);
401 Free(ctx, (void *) def->original);
402 put_define(ctx, def);
403 } // if
404 } // free_define
405
406
407 static int remove_define(Context *ctx, const char *sym)
408 {
409 const uint8 hash = hash_define(sym);
410 Define *bucket = ctx->define_hashtable[hash];
411 Define *prev = NULL;
412 while (bucket)
413 {
414 if (strcmp(bucket->identifier, sym) == 0)
415 {
416 if (prev == NULL)
417 ctx->define_hashtable[hash] = bucket->next;
418 else
419 prev->next = bucket->next;
420 free_define(ctx, bucket);
421 return 1;
422 } // if
423 prev = bucket;
424 bucket = bucket->next;
425 } // while
426
427 return 0;
428 } // remove_define
429
430
431 static const Define *find_define(Context *ctx, const char *sym)
432 {
433 const uint8 hash = hash_define(sym);
434 Define *bucket = ctx->define_hashtable[hash];
435 while (bucket)
436 {
437 if (strcmp(bucket->identifier, sym) == 0)
438 return bucket;
439 bucket = bucket->next;
440 } // while
441
442 const uint8 filestrhash = 67;
443 assert(hash_define("__FILE__") == filestrhash);
444
445 const uint8 linestrhash = 75;
446 assert(hash_define("__LINE__") == linestrhash);
447
448 if ( (hash == filestrhash) && (ctx->file_macro) && (strcmp(sym, "__FILE__") == 0) )
449 {
450 Free(ctx, (char *) ctx->file_macro->definition);
451 const IncludeState *state = ctx->include_stack;
452 const char *fname = state ? state->filename : "";
453 const size_t len = strlen(fname) + 2;
454 char *str = (char *) Malloc(ctx, len + 1);
455 if (!str)
456 return NULL;
457 str[0] = '\"';
458 memcpy(str + 1, fname, len - 2);
459 str[len - 1] = '\"';
460 str[len] = '\0';
461 ctx->file_macro->definition = str;
462 return ctx->file_macro;
463 } // if
464
465 else if ( (hash == linestrhash) && (ctx->line_macro) && (strcmp(sym, "__LINE__") == 0) )
466 {
467 Free(ctx, (char *) ctx->line_macro->definition);
468 const IncludeState *state = ctx->include_stack;
469 const size_t bufsize = 32;
470 char *str = (char *) Malloc(ctx, bufsize);
471 if (!str)
472 return 0;
473
474 const size_t len = snprintf(str, bufsize, "%u", state->line);
475 assert(len < bufsize); (void) len;
476 ctx->line_macro->definition = str;
477 return ctx->line_macro;
478 } // else
479
480 return NULL;
481 } // find_define
482
483
484 static const Define *find_define_by_token(Context *ctx)
485 {
486 IncludeState *state = ctx->include_stack;
487 assert(state->tokenval == TOKEN_IDENTIFIER);
488 char *sym = (char *) alloca(state->tokenlen+1);
489 memcpy(sym, state->token, state->tokenlen);
490 sym[state->tokenlen] = '\0';
491 return find_define(ctx, sym);
492 } // find_define_by_token
493
494
495 static const Define *find_macro_arg(const IncludeState *state,
496 const Define *defines)
497 {
498 const Define *def = NULL;
499 char *sym = (char *) alloca(state->tokenlen + 1);
500 memcpy(sym, state->token, state->tokenlen);
501 sym[state->tokenlen] = '\0';
502
503 for (def = defines; def != NULL; def = def->next)
504 {
505 assert(def->parameters == NULL); // args can't have args!
506 assert(def->paramcount == 0); // args can't have args!
507 if (strcmp(def->identifier, sym) == 0)
508 break;
509 } // while
510
511 return def;
512 } // find_macro_arg
513
514
515 static void put_all_defines(Context *ctx)
516 {
517 size_t i;
518 for (i = 0; i < STATICARRAYLEN(ctx->define_hashtable); i++)
519 {
520 Define *bucket = ctx->define_hashtable[i];
521 ctx->define_hashtable[i] = NULL;
522 while (bucket)
523 {
524 Define *next = bucket->next;
525 free_define(ctx, bucket);
526 bucket = next;
527 } // while
528 } // for
529 } // put_all_defines
530
531
532 static int push_source(Context *ctx, const char *fname, const char *source,
533 unsigned int srclen, unsigned int linenum,
534 MOJOSHADER_includeClose close_callback)
535 {
536 IncludeState *state = get_include(ctx);
537 if (state == NULL)
538 return 0;
539
540 if (fname != NULL)
541 {
542 state->filename = stringcache(ctx->filename_cache, fname);
543 if (state->filename == NULL)
544 {
545 put_include(ctx, state);
546 return 0;
547 } // if
548 } // if
549
550 state->close_callback = close_callback;
551 state->source_base = source;
552 state->source = source;
553 state->token = source;
554 state->tokenval = ((Token) '\n');
555 state->orig_length = srclen;
556 state->bytes_left = srclen;
557 state->line = linenum;
558 state->next = ctx->include_stack;
559 state->asm_comments = ctx->asm_comments;
560
561 print_debug_lexing_position(state);
562
563 ctx->include_stack = state;
564
565 return 1;
566 } // push_source
567
568
569 static void pop_source(Context *ctx)
570 {
571 IncludeState *state = ctx->include_stack;
572 assert(state != NULL); // more pops than pushes!
573 if (state == NULL)
574 return;
575
576 if (state->close_callback)
577 {
578 state->close_callback(state->source_base, ctx->malloc,
579 ctx->free, ctx->malloc_data);
580 } // if
581
582 // state->filename is a pointer to the filename cache; don't free it here!
583
584 Conditional *cond = state->conditional_stack;
585 while (cond)
586 {
587 Conditional *next = cond->next;
588 put_conditional(ctx, cond);
589 cond = next;
590 } // while
591
592 ctx->include_stack = state->next;
593
594 print_debug_lexing_position(ctx->include_stack);
595
596 put_include(ctx, state);
597 } // pop_source
598
599
600 static void close_define_include(const char *data, MOJOSHADER_malloc m,
601 MOJOSHADER_free f, void *d)
602 {
603 f((void *) data, d);
604 } // close_define_include
605
606
607 Preprocessor *preprocessor_start(const char *fname, const char *source,
608 unsigned int sourcelen,
609 MOJOSHADER_includeOpen open_callback,
610 MOJOSHADER_includeClose close_callback,
611 const MOJOSHADER_preprocessorDefine *defines,
612 unsigned int define_count, int asm_comments,
613 MOJOSHADER_malloc m, MOJOSHADER_free f, void *d)
614 {
615 int okay = 1;
616 unsigned int i = 0;
617
618 // the preprocessor is internal-only, so we verify all these are != NULL.
619 assert(m != NULL);
620 assert(f != NULL);
621
622 Context *ctx = (Context *) m(sizeof (Context), d);
623 if (ctx == NULL)
624 return NULL;
625
626 memset(ctx, '\0', sizeof (Context));
627 ctx->malloc = m;
628 ctx->free = f;
629 ctx->malloc_data = d;
630 ctx->open_callback = open_callback;
631 ctx->close_callback = close_callback;
632 ctx->asm_comments = asm_comments;
633
634 ctx->filename_cache = stringcache_create(MallocBridge, FreeBridge, ctx);
635 okay = ((okay) && (ctx->filename_cache != NULL));
636
637 ctx->file_macro = get_define(ctx);
638 okay = ((okay) && (ctx->file_macro != NULL));
639 if ((okay) && (ctx->file_macro))
640 okay = ((ctx->file_macro->identifier = StrDup(ctx, "__FILE__")) != 0);
641
642 ctx->line_macro = get_define(ctx);
643 okay = ((okay) && (ctx->line_macro != NULL));
644 if ((okay) && (ctx->line_macro))
645 okay = ((ctx->line_macro->identifier = StrDup(ctx, "__LINE__")) != 0);
646
647 // let the usual preprocessor parser sort these out.
648 char *define_include = NULL;
649 unsigned int define_include_len = 0;
650 if ((okay) && (define_count > 0))
651 {
652 Buffer *predefbuf = buffer_create(256, MallocBridge, FreeBridge, ctx);
653 okay = okay && (predefbuf != NULL);
654 for (i = 0; okay && (i < define_count); i++)
655 {
656 okay = okay && buffer_append_fmt(predefbuf, "#define %s %s\n",
657 defines[i].identifier, defines[i].definition);
658 } // for
659
660 define_include_len = buffer_size(predefbuf);
661 if (define_include_len > 0)
662 {
663 define_include = buffer_flatten(predefbuf);
664 okay = okay && (define_include != NULL);
665 } // if
666 buffer_destroy(predefbuf);
667 } // if
668
669 if ((okay) && (!push_source(ctx,fname,source,sourcelen,1,NULL)))
670 okay = 0;
671
672 if ((okay) && (define_include_len > 0))
673 {
674 assert(define_include != NULL);
675 okay = push_source(ctx, "<predefined macros>", define_include,
676 define_include_len, 1, close_define_include);
677 } // if
678
679 if (!okay)
680 {
681 preprocessor_end((Preprocessor *) ctx);
682 return NULL;
683 } // if
684
685 return (Preprocessor *) ctx;
686 } // preprocessor_start
687
688
689 void preprocessor_end(Preprocessor *_ctx)
690 {
691 Context *ctx = (Context *) _ctx;
692 if (ctx == NULL)
693 return;
694
695 while (ctx->include_stack != NULL)
696 pop_source(ctx);
697
698 put_all_defines(ctx);
699
700 if (ctx->filename_cache != NULL)
701 stringcache_destroy(ctx->filename_cache);
702
703 free_define(ctx, ctx->file_macro);
704 free_define(ctx, ctx->line_macro);
705 free_define_pool(ctx);
706 free_conditional_pool(ctx);
707 free_include_pool(ctx);
708
709 Free(ctx, ctx);
710 } // preprocessor_end
711
712
713 int preprocessor_outofmemory(Preprocessor *_ctx)
714 {
715 Context *ctx = (Context *) _ctx;
716 return ctx->out_of_memory;
717 } // preprocessor_outofmemory
718
719
720 static inline void pushback(IncludeState *state)
721 {
722 #if DEBUG_PREPROCESSOR
723 printf("PREPROCESSOR PUSHBACK\n");
724 #endif
725 assert(!state->pushedback);
726 state->pushedback = 1;
727 } // pushback
728
729
730 static Token lexer(IncludeState *state)
731 {
732 if (!state->pushedback)
733 return preprocessor_lexer(state);
734 state->pushedback = 0;
735 return state->tokenval;
736 } // lexer
737
738
739 // !!! FIXME: parsing fails on preprocessor directives should skip rest of line.
740 static int require_newline(IncludeState *state)
741 {
742 const Token token = lexer(state);
743 pushback(state); // rewind no matter what.
744 return ( (token == TOKEN_INCOMPLETE_COMMENT) || // call it an eol.
745 (token == ((Token) '\n')) || (token == TOKEN_EOI) );
746 } // require_newline
747
748 // !!! FIXME: didn't we implement this by hand elsewhere?
749 static int token_to_int(IncludeState *state)
750 {
751 assert(state->tokenval == TOKEN_INT_LITERAL);
752 char *buf = (char *) alloca(state->tokenlen+1);
753 memcpy(buf, state->token, state->tokenlen);
754 buf[state->tokenlen] = '\0';
755 return atoi(buf);
756 } // token_to_int
757
758
759 static void handle_pp_include(Context *ctx)
760 {
761 IncludeState *state = ctx->include_stack;
762 Token token = lexer(state);
763 MOJOSHADER_includeType incltype;
764 char *filename = NULL;
765 int bogus = 0;
766
767 if (token == TOKEN_STRING_LITERAL)
768 incltype = MOJOSHADER_INCLUDETYPE_LOCAL;
769 else if (token == ((Token) '<'))
770 {
771 incltype = MOJOSHADER_INCLUDETYPE_SYSTEM;
772 // can't use lexer, since every byte between the < > pair is
773 // considered part of the filename. :/
774 while (!bogus)
775 {
776 if ( !(bogus = (state->bytes_left == 0)) )
777 {
778 const char ch = *state->source;
779 if ( !(bogus = ((ch == '\r') || (ch == '\n'))) )
780 {
781 state->source++;
782 state->bytes_left--;
783
784 if (ch == '>')
785 break;
786 } // if
787 } // if
788 } // while
789 } // else if
790 else
791 {
792 bogus = 1;
793 } // else
794
795 if (!bogus)
796 {
797 state->token++; // skip '<' or '\"'...
798 const unsigned int len = ((unsigned int) (state->source-state->token));
799 filename = (char *) alloca(len);
800 memcpy(filename, state->token, len-1);
801 filename[len-1] = '\0';
802 bogus = !require_newline(state);
803 } // if
804
805 if (bogus)
806 {
807 fail(ctx, "Invalid #include directive");
808 return;
809 } // else
810
811 const char *newdata = NULL;
812 unsigned int newbytes = 0;
813 if ((ctx->open_callback == NULL) || (ctx->close_callback == NULL))
814 {
815 fail(ctx, "Saw #include, but no include callbacks defined");
816 return;
817 } // if
818
819 if (!ctx->open_callback(incltype, filename, state->source_base,
820 &newdata, &newbytes, ctx->malloc,
821 ctx->free, ctx->malloc_data))
822 {
823 fail(ctx, "Include callback failed"); // !!! FIXME: better error
824 return;
825 } // if
826
827 MOJOSHADER_includeClose callback = ctx->close_callback;
828 if (!push_source(ctx, filename, newdata, newbytes, 1, callback))
829 {
830 assert(ctx->out_of_memory);
831 ctx->close_callback(newdata, ctx->malloc, ctx->free, ctx->malloc_data);
832 } // if
833 } // handle_pp_include
834
835
836 static void handle_pp_line(Context *ctx)
837 {
838 IncludeState *state = ctx->include_stack;
839 char *filename = NULL;
840 int linenum = 0;
841 int bogus = 0;
842
843 if (lexer(state) != TOKEN_INT_LITERAL)
844 bogus = 1;
845 else
846 linenum = token_to_int(state);
847
848 if (!bogus)
849 {
850 Token t = lexer(state);
851 if (t == ((Token) '\n'))
852 {
853 state->line = linenum;
854 return;
855 }
856 bogus = (t != TOKEN_STRING_LITERAL);
857 }
858
859 if (!bogus)
860 {
861 state->token++; // skip '\"'...
862 filename = (char *) alloca(state->tokenlen);
863 memcpy(filename, state->token, state->tokenlen-1);
864 filename[state->tokenlen-1] = '\0';
865 bogus = !require_newline(state);
866 } // if
867
868 if (bogus)
869 {
870 fail(ctx, "Invalid #line directive");
871 return;
872 } // if
873
874 const char *cached = stringcache(ctx->filename_cache, filename);
875 state->filename = cached; // may be NULL if stringcache() failed.
876 state->line = linenum;
877 } // handle_pp_line
878
879
880 static void handle_pp_error(Context *ctx)
881 {
882 IncludeState *state = ctx->include_stack;
883 char *ptr = ctx->failstr;
884 int avail = sizeof (ctx->failstr) - 1;
885 int cpy = 0;
886 int done = 0;
887
888 const char *prefix = "#error";
889 const size_t prefixlen = strlen(prefix);
890 strcpy(ctx->failstr, prefix);
891 avail -= prefixlen;
892 ptr += prefixlen;
893
894 state->report_whitespace = 1;
895 while (!done)
896 {
897 const Token token = lexer(state);
898 switch (token)
899 {
900 case ((Token) '\n'):
901 state->line--; // make sure error is on the right line.
902 // fall through!
903 case TOKEN_INCOMPLETE_COMMENT:
904 case TOKEN_EOI:
905 pushback(state); // move back so we catch this later.
906 done = 1;
907 break;
908
909 case ((Token) ' '):
910 if (!avail)
911 break;
912 *(ptr++) = ' ';
913 avail--;
914 break;
915
916 default:
917 cpy = Min(avail, (int) state->tokenlen);
918 if (cpy)
919 memcpy(ptr, state->token, cpy);
920 ptr += cpy;
921 avail -= cpy;
922 break;
923 } // switch
924 } // while
925
926 *ptr = '\0';
927 state->report_whitespace = 0;
928 ctx->isfail = 1;
929 } // handle_pp_error
930
931
932 static void handle_pp_define(Context *ctx)
933 {
934 IncludeState *state = ctx->include_stack;
935 int done = 0;
936
937 if (lexer(state) != TOKEN_IDENTIFIER)
938 {
939 fail(ctx, "Macro names must be identifiers");
940 return;
941 } // if
942
943 char *definition = NULL;
944 char *sym = (char *) Malloc(ctx, state->tokenlen+1);
945 if (sym == NULL)
946 return;
947 memcpy(sym, state->token, state->tokenlen);
948 sym[state->tokenlen] = '\0';
949
950 if (strcmp(sym, "defined") == 0)
951 {
952 Free(ctx, sym);
953 fail(ctx, "'defined' cannot be used as a macro name");
954 return;
955 } // if
956
957 // Don't treat these symbols as special anymore if they get (re)#defined.
958 if (strcmp(sym, "__FILE__") == 0)
959 {
960 if (ctx->file_macro)
961 {
962 failf(ctx, "'%s' already defined", sym); // !!! FIXME: warning?
963 free_define(ctx, ctx->file_macro);
964 ctx->file_macro = NULL;
965 } // if
966 } // if
967 else if (strcmp(sym, "__LINE__") == 0)
968 {
969 if (ctx->line_macro)
970 {
971 failf(ctx, "'%s' already defined", sym); // !!! FIXME: warning?
972 free_define(ctx, ctx->line_macro);
973 ctx->line_macro = NULL;
974 } // if
975 } // else if
976
977 // #define a(b) is different than #define a (b) :(
978 state->report_whitespace = 1;
979 lexer(state);
980 state->report_whitespace = 0;
981
982 int params = 0;
983 char **idents = NULL;
984 static const char space = ' ';
985
986 if (state->tokenval == ((Token) ' '))
987 lexer(state); // skip it.
988 else if (state->tokenval == ((Token) '('))
989 {
990 IncludeState saved;
991 memcpy(&saved, state, sizeof (IncludeState));
992 while (1)
993 {
994 if (lexer(state) != TOKEN_IDENTIFIER)
995 break;
996 params++;
997 if (lexer(state) != ((Token) ','))
998 break;
999 } // while
1000
1001 if (state->tokenval != ((Token) ')'))
1002 {
1003 fail(ctx, "syntax error in macro parameter list");
1004 goto handle_pp_define_failed;
1005 } // if
1006
1007 if (params == 0) // special case for void args: "#define a() b"
1008 params = -1;
1009 else
1010 {
1011 idents = (char **) Malloc(ctx, sizeof (char *) * params);
1012 if (idents == NULL)
1013 goto handle_pp_define_failed;
1014
1015 // roll all the way back, do it again.
1016 memcpy(state, &saved, sizeof (IncludeState));
1017 memset(idents, '\0', sizeof (char *) * params);
1018
1019 int i;
1020 for (i = 0; i < params; i++)
1021 {
1022 lexer(state);
1023 assert(state->tokenval == TOKEN_IDENTIFIER);
1024
1025 char *dst = (char *) Malloc(ctx, state->tokenlen+1);
1026 if (dst == NULL)
1027 break;
1028
1029 memcpy(dst, state->token, state->tokenlen);
1030 dst[state->tokenlen] = '\0';
1031 idents[i] = dst;
1032
1033 if (i < (params-1))
1034 {
1035 lexer(state);
1036 assert(state->tokenval == ((Token) ','));
1037 } // if
1038 } // for
1039
1040 if (i != params)
1041 {
1042 assert(ctx->out_of_memory);
1043 goto handle_pp_define_failed;
1044 } // if
1045
1046 lexer(state);
1047 assert(state->tokenval == ((Token) ')'));
1048 } // else
1049
1050 lexer(state);
1051 } // else if
1052
1053 pushback(state);
1054
1055 Buffer *buffer = buffer_create(128, MallocBridge, FreeBridge, ctx);
1056
1057 state->report_whitespace = 1;
1058 while ((!done) && (!ctx->out_of_memory))
1059 {
1060 const Token token = lexer(state);
1061 switch (token)
1062 {
1063 case TOKEN_INCOMPLETE_COMMENT:
1064 case TOKEN_EOI:
1065 pushback(state); // move back so we catch this later.
1066 done = 1;
1067 break;
1068
1069 case ((Token) '\n'):
1070 done = 1;
1071 break;
1072
1073 case ((Token) ' '): // may not actually point to ' '.
1074 assert(buffer_size(buffer) > 0);
1075 buffer_append(buffer, &space, 1);
1076 break;
1077
1078 default:
1079 buffer_append(buffer, state->token, state->tokenlen);
1080 break;
1081 } // switch
1082 } // while
1083 state->report_whitespace = 0;
1084
1085 size_t buflen = buffer_size(buffer) + 1;
1086 if (!ctx->out_of_memory)
1087 definition = buffer_flatten(buffer);
1088
1089 buffer_destroy(buffer);
1090
1091 if (ctx->out_of_memory)
1092 goto handle_pp_define_failed;
1093
1094 int hashhash_error = 0;
1095 if ((buflen > 2) && (definition[0] == '#') && (definition[1] == '#'))
1096 {
1097 hashhash_error = 1;
1098 buflen -= 2;
1099 memmove(definition, definition + 2, buflen);
1100 } // if
1101
1102 if (buflen > 2)
1103 {
1104 char *ptr = (definition + buflen) - 2;
1105 if (*ptr == ' ')
1106 {
1107 ptr--;
1108 buflen--;
1109 } // if
1110 if ((buflen > 2) && (ptr[0] == '#') && (ptr[-1] == '#'))
1111 {
1112 hashhash_error = 1;
1113 buflen -= 2;
1114 ptr[-1] = '\0';
1115 } // if
1116 } // if
1117
1118 if (hashhash_error)
1119 fail(ctx, "'##' cannot appear at either end of a macro expansion");
1120
1121 assert(done);
1122
1123 if (!add_define(ctx, sym, definition, idents, params))
1124 goto handle_pp_define_failed;
1125
1126 return;
1127
1128 handle_pp_define_failed:
1129 Free(ctx, sym);
1130 Free(ctx, definition);
1131 if (idents != NULL)
1132 {
1133 while (params--)
1134 Free(ctx, idents[params]);
1135 } // if
1136 Free(ctx, idents);
1137 } // handle_pp_define
1138
1139
1140 static void handle_pp_undef(Context *ctx)
1141 {
1142 IncludeState *state = ctx->include_stack;
1143
1144 if (lexer(state) != TOKEN_IDENTIFIER)
1145 {
1146 fail(ctx, "Macro names must be indentifiers");
1147 return;
1148 } // if
1149
1150 char *sym = (char *) alloca(state->tokenlen+1);
1151 memcpy(sym, state->token, state->tokenlen);
1152 sym[state->tokenlen] = '\0';
1153
1154 if (!require_newline(state))
1155 {
1156 fail(ctx, "Invalid #undef directive");
1157 return;
1158 } // if
1159
1160 if (strcmp(sym, "__FILE__") == 0)
1161 {
1162 if (ctx->file_macro)
1163 {
1164 failf(ctx, "undefining \"%s\"", sym); // !!! FIXME: should be warning.
1165 free_define(ctx, ctx->file_macro);
1166 ctx->file_macro = NULL;
1167 } // if
1168 } // if
1169 else if (strcmp(sym, "__LINE__") == 0)
1170 {
1171 if (ctx->line_macro)
1172 {
1173 failf(ctx, "undefining \"%s\"", sym); // !!! FIXME: should be warning.
1174 free_define(ctx, ctx->line_macro);
1175 ctx->line_macro = NULL;
1176 } // if
1177 } // if
1178
1179 remove_define(ctx, sym);
1180 } // handle_pp_undef
1181
1182
1183 static Conditional *_handle_pp_ifdef(Context *ctx, const Token type)
1184 {
1185 IncludeState *state = ctx->include_stack;
1186
1187 assert((type == TOKEN_PP_IFDEF) || (type == TOKEN_PP_IFNDEF));
1188
1189 if (lexer(state) != TOKEN_IDENTIFIER)
1190 {
1191 fail(ctx, "Macro names must be indentifiers");
1192 return NULL;
1193 } // if
1194
1195 char *sym = (char *) alloca(state->tokenlen+1);
1196 memcpy(sym, state->token, state->tokenlen);
1197 sym[state->tokenlen] = '\0';
1198
1199 if (!require_newline(state))
1200 {
1201 if (type == TOKEN_PP_IFDEF)
1202 fail(ctx, "Invalid #ifdef directive");
1203 else
1204 fail(ctx, "Invalid #ifndef directive");
1205 return NULL;
1206 } // if
1207
1208 Conditional *conditional = get_conditional(ctx);
1209 assert((conditional != NULL) || (ctx->out_of_memory));
1210 if (conditional == NULL)
1211 return NULL;
1212
1213 Conditional *parent = state->conditional_stack;
1214 const int found = (find_define(ctx, sym) != NULL);
1215 const int chosen = (type == TOKEN_PP_IFDEF) ? found : !found;
1216 const int skipping = ( (((parent) && (parent->skipping))) || (!chosen) );
1217
1218 conditional->type = type;
1219 conditional->linenum = state->line - 1;
1220 conditional->skipping = skipping;
1221 conditional->chosen = chosen;
1222 conditional->next = parent;
1223 state->conditional_stack = conditional;
1224 return conditional;
1225 } // _handle_pp_ifdef
1226
1227
1228 static inline void handle_pp_ifdef(Context *ctx)
1229 {
1230 _handle_pp_ifdef(ctx, TOKEN_PP_IFDEF);
1231 } // handle_pp_ifdef
1232
1233
1234 static inline void handle_pp_ifndef(Context *ctx)
1235 {
1236 _handle_pp_ifdef(ctx, TOKEN_PP_IFNDEF);
1237 } // handle_pp_ifndef
1238
1239
1240 static int replace_and_push_macro(Context *ctx, const Define *def,
1241 const Define *params)
1242 {
1243 char *final = NULL;
1244
1245 // We push the #define and lex it, building a buffer with argument
1246 // replacement, stringification, and concatenation.
1247 Buffer *buffer = buffer_create(128, MallocBridge, FreeBridge, ctx);
1248 if (buffer == NULL)
1249 return 0;
1250
1251 IncludeState *state = ctx->include_stack;
1252 if (!push_source(ctx, state->filename, def->definition,
1253 strlen(def->definition), state->line, NULL))
1254 {
1255 buffer_destroy(buffer);
1256 return 0;
1257 } // if
1258
1259 state = ctx->include_stack;
1260 while (lexer(state) != TOKEN_EOI)
1261 {
1262 int wantorig = 0;
1263 const Define *arg = NULL;
1264
1265 // put a space between tokens if we're not concatenating.
1266 if (state->tokenval == TOKEN_HASHHASH) // concatenate?
1267 {
1268 wantorig = 1;
1269 lexer(state);
1270 assert(state->tokenval != TOKEN_EOI);
1271 } // if
1272 else
1273 {
1274 if (buffer_size(buffer) > 0)
1275 {
1276 if (!buffer_append(buffer, " ", 1))
1277 goto replace_and_push_macro_failed;
1278 } // if
1279 } // else
1280
1281 const char *data = state->token;
1282 unsigned int len = state->tokenlen;
1283
1284 if (state->tokenval == TOKEN_HASH) // stringify?
1285 {
1286 lexer(state);
1287 assert(state->tokenval != TOKEN_EOI); // we checked for this.
1288
1289 if (!buffer_append(buffer, "\"", 1))
1290 goto replace_and_push_macro_failed;
1291
1292 if (state->tokenval == TOKEN_IDENTIFIER)
1293 {
1294 arg = find_macro_arg(state, params);
1295 if (arg != NULL)
1296 {
1297 data = arg->original;
1298 len = strlen(data);
1299 } // if
1300 } // if
1301
1302 if (!buffer_append(buffer, data, len))
1303 goto replace_and_push_macro_failed;
1304
1305 if (!buffer_append(buffer, "\"", 1))
1306 goto replace_and_push_macro_failed;
1307
1308 continue;
1309 } // if
1310
1311 if (state->tokenval == TOKEN_IDENTIFIER)
1312 {
1313 arg = find_macro_arg(state, params);
1314 if (arg != NULL)
1315 {
1316 if (!wantorig)
1317 {
1318 wantorig = (lexer(state) == TOKEN_HASHHASH);
1319 pushback(state);
1320 } // if
1321 data = wantorig ? arg->original : arg->definition;
1322 len = strlen(data);
1323 } // if
1324 } // if
1325
1326 if (!buffer_append(buffer, data, len))
1327 goto replace_and_push_macro_failed;
1328 } // while
1329
1330 final = buffer_flatten(buffer);
1331 if (!final)
1332 goto replace_and_push_macro_failed;
1333
1334 buffer_destroy(buffer);
1335 pop_source(ctx); // ditch the macro.
1336 state = ctx->include_stack;
1337 if (!push_source(ctx, state->filename, final, strlen(final), state->line,
1338 close_define_include))
1339 {
1340 Free(ctx, final);
1341 return 0;
1342 } // if
1343
1344 return 1;
1345
1346 replace_and_push_macro_failed:
1347 pop_source(ctx);
1348 buffer_destroy(buffer);
1349 return 0;
1350 } // replace_and_push_macro
1351
1352
1353 static int handle_macro_args(Context *ctx, const char *sym, const Define *def)
1354 {
1355 int retval = 0;
1356 IncludeState *state = ctx->include_stack;
1357 Define *params = NULL;
1358 const int expected = (def->paramcount < 0) ? 0 : def->paramcount;
1359 int saw_params = 0;
1360 IncludeState saved; // can't pushback, we need the original token.
1361 memcpy(&saved, state, sizeof (IncludeState));
1362 if (lexer(state) != ((Token) '('))
1363 {
1364 memcpy(state, &saved, sizeof (IncludeState));
1365 goto handle_macro_args_failed; // gcc abandons replacement, too.
1366 } // if
1367
1368 state->report_whitespace = 1;
1369
1370 int void_call = 0;
1371 int paren = 1;
1372 while (paren > 0)
1373 {
1374 Buffer *buffer = buffer_create(128, MallocBridge, FreeBridge, ctx);
1375 Buffer *origbuffer = buffer_create(128, MallocBridge, FreeBridge, ctx);
1376
1377 Token t = lexer(state);
1378
1379 assert(!void_call);
1380
1381 while (1)
1382 {
1383 const char *origexpr = state->token;
1384 unsigned int origexprlen = state->tokenlen;
1385 const char *expr = state->token;
1386 unsigned int exprlen = state->tokenlen;
1387
1388 if (t == ((Token) '('))
1389 paren++;
1390
1391 else if (t == ((Token) ')'))
1392 {
1393 paren--;
1394 if (paren < 1) // end of macro?
1395 break;
1396 } // else if
1397
1398 else if (t == ((Token) ','))
1399 {
1400 if (paren == 1) // new macro arg?
1401 break;
1402 } // else if
1403
1404 else if (t == ((Token) ' '))
1405 {
1406 // don't add whitespace to the start, so we recognize
1407 // void calls correctly.
1408 origexpr = expr = " ";
1409 origexprlen = (buffer_size(origbuffer) == 0) ? 0 : 1;
1410 exprlen = (buffer_size(buffer) == 0) ? 0 : 1;
1411 } // else if
1412
1413 else if (t == TOKEN_IDENTIFIER)
1414 {
1415 const Define *def = find_define_by_token(ctx);
1416 // don't replace macros with arguments so they replace correctly, later.
1417 if ((def) && (def->paramcount == 0))
1418 {
1419 expr = def->definition;
1420 exprlen = strlen(def->definition);
1421 } // if
1422 } // else if
1423
1424 else if ((t == TOKEN_INCOMPLETE_COMMENT) || (t == TOKEN_EOI))
1425 {
1426 pushback(state);
1427 fail(ctx, "Unterminated macro list");
1428 goto handle_macro_args_failed;
1429 } // else if
1430
1431 assert(expr != NULL);
1432
1433 if (!buffer_append(buffer, expr, exprlen))
1434 goto handle_macro_args_failed;
1435
1436 if (!buffer_append(origbuffer, origexpr, origexprlen))
1437 goto handle_macro_args_failed;
1438
1439 t = lexer(state);
1440 } // while
1441
1442 if (buffer_size(buffer) == 0)
1443 void_call = ((saw_params == 0) && (paren == 0));
1444
1445 if (saw_params < expected)
1446 {
1447 const int origdeflen = (int) buffer_size(origbuffer);
1448 char *origdefinition = buffer_flatten(origbuffer);
1449 const int deflen = (int) buffer_size(buffer);
1450 char *definition = buffer_flatten(buffer);
1451 Define *p = get_define(ctx);
1452 if ((!origdefinition) || (!definition) || (!p))
1453 {
1454 Free(ctx, origdefinition);
1455 Free(ctx, definition);
1456 buffer_destroy(origbuffer);
1457 buffer_destroy(buffer);
1458 free_define(ctx, p);
1459 goto handle_macro_args_failed;
1460 } // if
1461
1462 // trim any whitespace from the end of the string...
1463 int i;
1464 for (i = deflen - 1; i >= 0; i--)
1465 {
1466 if (definition[i] == ' ')
1467 definition[i] = '\0';
1468 else
1469 break;
1470 } // for
1471
1472 for (i = origdeflen - 1; i >= 0; i--)
1473 {
1474 if (origdefinition[i] == ' ')
1475 origdefinition[i] = '\0';
1476 else
1477 break;
1478 } // for
1479
1480 p->identifier = def->parameters[saw_params];
1481 p->definition = definition;
1482 p->original = origdefinition;
1483 p->next = params;
1484 params = p;
1485 } // if
1486
1487 buffer_destroy(buffer);
1488 buffer_destroy(origbuffer);
1489 saw_params++;
1490 } // while
1491
1492 assert(paren == 0);
1493
1494 // "a()" should match "#define a()" ...
1495 if ((expected == 0) && (saw_params == 1) && (void_call))
1496 {
1497 assert(params == NULL);
1498 saw_params = 0;
1499 } // if
1500
1501 if (saw_params != expected)
1502 {
1503 failf(ctx, "macro '%s' passed %d arguments, but requires %d",
1504 sym, saw_params, expected);
1505 goto handle_macro_args_failed;
1506 } // if
1507
1508 // this handles arg replacement and the '##' and '#' operators.
1509 retval = replace_and_push_macro(ctx, def, params);
1510
1511 handle_macro_args_failed:
1512 while (params)
1513 {
1514 Define *next = params->next;
1515 params->identifier = NULL;
1516 free_define(ctx, params);
1517 params = next;
1518 } // while
1519
1520 state->report_whitespace = 0;
1521 return retval;
1522 } // handle_macro_args
1523
1524
1525 static int handle_pp_identifier(Context *ctx)
1526 {
1527 if (ctx->recursion_count++ >= 256) // !!! FIXME: gcc can figure this out.
1528 {
1529 fail(ctx, "Recursing macros");
1530 return 0;
1531 } // if
1532
1533 IncludeState *state = ctx->include_stack;
1534 const char *fname = state->filename;
1535 const unsigned int line = state->line;
1536 char *sym = (char *) alloca(state->tokenlen+1);
1537 memcpy(sym, state->token, state->tokenlen);
1538 sym[state->tokenlen] = '\0';
1539
1540 // Is this identifier #defined?
1541 const Define *def = find_define(ctx, sym);
1542 if (def == NULL)
1543 return 0; // just send the token through unchanged.
1544 else if (def->paramcount != 0)
1545 return handle_macro_args(ctx, sym, def);
1546
1547 const size_t deflen = strlen(def->definition);
1548 return push_source(ctx, fname, def->definition, deflen, line, NULL);
1549 } // handle_pp_identifier
1550
1551
1552 static int find_precedence(const Token token)
1553 {
1554 // operator precedence, left and right associative...
1555 typedef struct { int precedence; Token token; } Precedence;
1556 static const Precedence ops[] = {
1557 { 0, TOKEN_OROR }, { 1, TOKEN_ANDAND }, { 2, ((Token) '|') },
1558 { 3, ((Token) '^') }, { 4, ((Token) '&') }, { 5, TOKEN_NEQ },
1559 { 6, TOKEN_EQL }, { 7, ((Token) '<') }, { 7, ((Token) '>') },
1560 { 7, TOKEN_LEQ }, { 7, TOKEN_GEQ }, { 8, TOKEN_LSHIFT },
1561 { 8, TOKEN_RSHIFT }, { 9, ((Token) '-') }, { 9, ((Token) '+') },
1562 { 10, ((Token) '%') }, { 10, ((Token) '/') }, { 10, ((Token) '*') },
1563 { 11, TOKEN_PP_UNARY_PLUS }, { 11, TOKEN_PP_UNARY_MINUS },
1564 { 11, ((Token) '!') }, { 11, ((Token) '~') },
1565 };
1566
1567 size_t i;
1568 for (i = 0; i < STATICARRAYLEN(ops); i++)
1569 {
1570 if (ops[i].token == token)
1571 return ops[i].precedence;
1572 } // for
1573
1574 return -1;
1575 } // find_precedence
1576
1577 // !!! FIXME: we're using way too much stack space here...
1578 typedef struct RpnTokens
1579 {
1580 int isoperator;
1581 int value;
1582 } RpnTokens;
1583
1584 static long interpret_rpn(const RpnTokens *tokens, int tokencount, int *error)
1585 {
1586 long stack[128];
1587 size_t stacksize = 0;
1588
1589 *error = 1;
1590
1591 #define NEED_X_TOKENS(x) do { if (stacksize < x) return 0; } while (0)
1592
1593 #define BINARY_OPERATION(op) do { \
1594 NEED_X_TOKENS(2); \
1595 stack[stacksize-2] = stack[stacksize-2] op stack[stacksize-1]; \
1596 stacksize--; \
1597 } while (0)
1598
1599 #define UNARY_OPERATION(op) do { \
1600 NEED_X_TOKENS(1); \
1601 stack[stacksize-1] = op stack[stacksize-1]; \
1602 } while (0)
1603
1604 while (tokencount-- > 0)
1605 {
1606 if (!tokens->isoperator)
1607 {
1608 assert(stacksize < STATICARRAYLEN(stack));
1609 stack[stacksize++] = (long) tokens->value;
1610 tokens++;
1611 continue;
1612 } // if
1613
1614 // operators.
1615 switch (tokens->value)
1616 {
1617 case '!': UNARY_OPERATION(!); break;
1618 case '~': UNARY_OPERATION(~); break;
1619 case TOKEN_PP_UNARY_MINUS: UNARY_OPERATION(-); break;
1620 case TOKEN_PP_UNARY_PLUS: UNARY_OPERATION(+); break;
1621 case TOKEN_OROR: BINARY_OPERATION(||); break;
1622 case TOKEN_ANDAND: BINARY_OPERATION(&&); break;
1623 case '|': BINARY_OPERATION(|); break;
1624 case '^': BINARY_OPERATION(^); break;
1625 case '&': BINARY_OPERATION(&); break;
1626 case TOKEN_NEQ: BINARY_OPERATION(!=); break;
1627 case TOKEN_EQL: BINARY_OPERATION(==); break;
1628 case '<': BINARY_OPERATION(<); break;
1629 case '>': BINARY_OPERATION(>); break;
1630 case TOKEN_LEQ: BINARY_OPERATION(<=); break;
1631 case TOKEN_GEQ: BINARY_OPERATION(>=); break;
1632 case TOKEN_LSHIFT: BINARY_OPERATION(<<); break;
1633 case TOKEN_RSHIFT: BINARY_OPERATION(>>); break;
1634 case '-': BINARY_OPERATION(-); break;
1635 case '+': BINARY_OPERATION(+); break;
1636 case '%': BINARY_OPERATION(%); break;
1637 case '/': BINARY_OPERATION(/); break;
1638 case '*': BINARY_OPERATION(*); break;
1639 default: return 0;
1640 } // switch
1641
1642 tokens++;
1643 } // while
1644
1645 #undef NEED_X_TOKENS
1646 #undef BINARY_OPERATION
1647 #undef UNARY_OPERATION
1648
1649 if (stacksize != 1)
1650 return 0;
1651
1652 *error = 0;
1653 return stack[0];
1654 } // interpret_rpn
1655
1656 // http://en.wikipedia.org/wiki/Shunting_yard_algorithm
1657 // Convert from infix to postfix, then use this for constant folding.
1658 // Everything that parses should fold down to a constant value: any
1659 // identifiers that aren't resolved as macros become zero. Anything we
1660 // don't explicitly expect becomes a parsing error.
1661 // returns 1 (true), 0 (false), or -1 (error)
1662 static int reduce_pp_expression(Context *ctx)
1663 {
1664 IncludeState *orig_state = ctx->include_stack;
1665 RpnTokens output[128];
1666 Token stack[64];
1667 Token previous_token = TOKEN_UNKNOWN;
1668 size_t outputsize = 0;
1669 size_t stacksize = 0;
1670 int matched = 0;
1671 int done = 0;
1672
1673 #define ADD_TO_OUTPUT(op, val) \
1674 assert(outputsize < STATICARRAYLEN(output)); \
1675 output[outputsize].isoperator = op; \
1676 output[outputsize].value = val; \
1677 outputsize++;
1678
1679 #define PUSH_TO_STACK(t) \
1680 assert(stacksize < STATICARRAYLEN(stack)); \
1681 stack[stacksize] = t; \
1682 stacksize++;
1683
1684 while (!done)
1685 {
1686 IncludeState *state = ctx->include_stack;
1687 Token token = lexer(state);
1688 int isleft = 1;
1689 int precedence = -1;
1690
1691 if ( (token == ((Token) '!')) || (token == ((Token) '~')) )
1692 isleft = 0;
1693 else if (token == ((Token) '-'))
1694 {
1695 isleft = ((previous_token == TOKEN_INT_LITERAL) ||
1696 (previous_token == ((Token) ')')));
1697 if (!isleft)
1698 token = TOKEN_PP_UNARY_MINUS;
1699 } // else if
1700 else if (token == ((Token) '+'))
1701 {
1702 isleft = ((previous_token == TOKEN_INT_LITERAL) ||
1703 (previous_token == ((Token) ')')));
1704 if (!isleft)
1705 token = TOKEN_PP_UNARY_PLUS;
1706 } // else if
1707
1708 if (token != TOKEN_IDENTIFIER)
1709 ctx->recursion_count = 0;
1710
1711 switch (token)
1712 {
1713 case TOKEN_EOI:
1714 if (state != orig_state) // end of a substate, or the expr?
1715 {
1716 pop_source(ctx);
1717 continue; // substate, go again with the parent state.
1718 } // if
1719 done = 1; // the expression itself is done.
1720 break;
1721
1722 case ((Token) '\n'):
1723 done = 1;
1724 break; // we're done!
1725
1726 case TOKEN_IDENTIFIER:
1727 if (handle_pp_identifier(ctx))
1728 continue; // go again with new IncludeState.
1729
1730 if ( (state->tokenlen == 7) &&
1731 (memcmp(state->token, "defined", 7) == 0) )
1732 {
1733 token = lexer(state);
1734 const int paren = (token == ((Token) '('));
1735 if (paren) // gcc doesn't let us nest parens here, either.
1736 token = lexer(state);
1737 if (token != TOKEN_IDENTIFIER)
1738 {
1739 fail(ctx, "operator 'defined' requires an identifier");
1740 return -1;
1741 } // if
1742 const int found = (find_define_by_token(ctx) != NULL);
1743
1744 if (paren)
1745 {
1746 if (lexer(state) != ((Token) ')'))
1747 {
1748 fail(ctx, "Unmatched ')'");
1749 return -1;
1750 } // if
1751 } // if
1752
1753 ADD_TO_OUTPUT(0, found);
1754 continue;
1755 } // if
1756
1757 // can't replace identifier with a number? It becomes zero.
1758 token = TOKEN_INT_LITERAL;
1759 ADD_TO_OUTPUT(0, 0);
1760 break;
1761
1762 case TOKEN_INT_LITERAL:
1763 ADD_TO_OUTPUT(0, token_to_int(state));
1764 break;
1765
1766 case ((Token) '('):
1767 PUSH_TO_STACK((Token) '(');
1768 break;
1769
1770 case ((Token) ')'):
1771 matched = 0;
1772 while (stacksize > 0)
1773 {
1774 const Token t = stack[--stacksize];
1775 if (t == ((Token) '('))
1776 {
1777 matched = 1;
1778 break;
1779 } // if
1780 ADD_TO_OUTPUT(1, t);
1781 } // while
1782
1783 if (!matched)
1784 {
1785 fail(ctx, "Unmatched ')'");
1786 return -1;
1787 } // if
1788 break;
1789
1790 default:
1791 precedence = find_precedence(token);
1792 // bogus token, or two operators together.
1793 if (precedence < 0)
1794 {
1795 pushback(state);
1796 fail(ctx, "Invalid expression");
1797 return -1;
1798 } // if
1799
1800 else // it's an operator.
1801 {
1802 while (stacksize > 0)
1803 {
1804 const Token t = stack[stacksize-1];
1805 const int p = find_precedence(t);
1806 if ( (p >= 0) &&
1807 ( ((isleft) && (precedence <= p)) ||
1808 ((!isleft) && (precedence < p)) ) )
1809 {
1810 stacksize--;
1811 ADD_TO_OUTPUT(1, t);
1812 } // if
1813 else
1814 {
1815 break;
1816 } // else
1817 } // while
1818 PUSH_TO_STACK(token);
1819 } // else
1820 break;
1821 } // switch
1822 previous_token = token;
1823 } // while
1824
1825 while (stacksize > 0)
1826 {
1827 const Token t = stack[--stacksize];
1828 if (t == ((Token) '('))
1829 {
1830 fail(ctx, "Unmatched ')'");
1831 return -1;
1832 } // if
1833 ADD_TO_OUTPUT(1, t);
1834 } // while
1835
1836 #undef ADD_TO_OUTPUT
1837 #undef PUSH_TO_STACK
1838
1839 // okay, you now have some validated data in reverse polish notation.
1840 #if DEBUG_PREPROCESSOR
1841 printf("PREPROCESSOR EXPRESSION RPN:");
1842 int i = 0;
1843 for (i = 0; i < outputsize; i++)
1844 {
1845 if (!output[i].isoperator)
1846 printf(" %d", output[i].value);
1847 else
1848 {
1849 switch (output[i].value)
1850 {
1851 case TOKEN_OROR: printf(" ||"); break;
1852 case TOKEN_ANDAND: printf(" &&"); break;
1853 case TOKEN_NEQ: printf(" !="); break;
1854 case TOKEN_EQL: printf(" =="); break;
1855 case TOKEN_LEQ: printf(" <="); break;
1856 case TOKEN_GEQ: printf(" >="); break;
1857 case TOKEN_LSHIFT: printf(" <<"); break;
1858 case TOKEN_RSHIFT: printf(" >>"); break;
1859 case TOKEN_PP_UNARY_PLUS: printf(" +"); break;
1860 case TOKEN_PP_UNARY_MINUS: printf(" -"); break;
1861 default: printf(" %c", output[i].value); break;
1862 } // switch
1863 } // else
1864 } // for
1865 printf("\n");
1866 #endif
1867
1868 int error = 0;
1869 const long val = interpret_rpn(output, outputsize, &error);
1870
1871 #if DEBUG_PREPROCESSOR
1872 printf("PREPROCESSOR RPN RESULT: %ld%s\n", val, error ? " (ERROR)" : "");
1873 #endif
1874
1875 if (error)
1876 {
1877 fail(ctx, "Invalid expression");
1878 return -1;
1879 } // if
1880
1881 return ((val) ? 1 : 0);
1882 } // reduce_pp_expression
1883
1884
1885 static Conditional *handle_pp_if(Context *ctx)
1886 {
1887 IncludeState *state = ctx->include_stack;
1888 const int result = reduce_pp_expression(ctx);
1889 if (result == -1)
1890 return NULL;
1891
1892 Conditional *conditional = get_conditional(ctx);
1893 assert((conditional != NULL) || (ctx->out_of_memory));
1894 if (conditional == NULL)
1895 return NULL;
1896
1897 Conditional *parent = state->conditional_stack;
1898 const int chosen = result;
1899 const int skipping = ( (((parent) && (parent->skipping))) || (!chosen) );
1900
1901 conditional->type = TOKEN_PP_IF;
1902 conditional->linenum = state->line - 1;
1903 conditional->skipping = skipping;
1904 conditional->chosen = chosen;
1905 conditional->next = parent;
1906 state->conditional_stack = conditional;
1907 return conditional;
1908 } // handle_pp_if
1909
1910
1911 static void handle_pp_elif(Context *ctx)
1912 {
1913 const int rc = reduce_pp_expression(ctx);
1914 if (rc == -1)
1915 return;
1916
1917 IncludeState *state = ctx->include_stack;
1918 Conditional *cond = state->conditional_stack;
1919 if (cond == NULL)
1920 fail(ctx, "#elif without #if");
1921 else if (cond->type == TOKEN_PP_ELSE)
1922 fail(ctx, "#elif after #else");
1923 else
1924 {
1925 const Conditional *parent = cond->next;
1926 cond->type = TOKEN_PP_ELIF;
1927 cond->skipping = (parent && parent->skipping) || cond->chosen || !rc;
1928 if (!cond->chosen)
1929 cond->chosen = rc;
1930 } // else
1931 } // handle_pp_elif
1932
1933
1934 static void handle_pp_else(Context *ctx)
1935 {
1936 IncludeState *state = ctx->include_stack;
1937 Conditional *cond = state->conditional_stack;
1938
1939 if (!require_newline(state))
1940 fail(ctx, "Invalid #else directive");
1941 else if (cond == NULL)
1942 fail(ctx, "#else without #if");
1943 else if (cond->type == TOKEN_PP_ELSE)
1944 fail(ctx, "#else after #else");
1945 else
1946 {
1947 const Conditional *parent = cond->next;
1948 cond->type = TOKEN_PP_ELSE;
1949 cond->skipping = (parent && parent->skipping) || cond->chosen;
1950 if (!cond->chosen)
1951 cond->chosen = 1;
1952 } // else
1953 } // handle_pp_else
1954
1955
1956 static void handle_pp_endif(Context *ctx)
1957 {
1958 IncludeState *state = ctx->include_stack;
1959 Conditional *cond = state->conditional_stack;
1960
1961 if (!require_newline(state))
1962 fail(ctx, "Invalid #endif directive");
1963 else if (cond == NULL)
1964 fail(ctx, "Unmatched #endif");
1965 else
1966 {
1967 state->conditional_stack = cond->next; // pop it.
1968 put_conditional(ctx, cond);
1969 } // else
1970 } // handle_pp_endif
1971
1972
1973 static void unterminated_pp_condition(Context *ctx)
1974 {
1975 IncludeState *state = ctx->include_stack;
1976 Conditional *cond = state->conditional_stack;
1977
1978 // !!! FIXME: report the line number where the #if is, not the EOI.
1979 switch (cond->type)
1980 {
1981 case TOKEN_PP_IF: fail(ctx, "Unterminated #if"); break;
1982 case TOKEN_PP_IFDEF: fail(ctx, "Unterminated #ifdef"); break;
1983 case TOKEN_PP_IFNDEF: fail(ctx, "Unterminated #ifndef"); break;
1984 case TOKEN_PP_ELSE: fail(ctx, "Unterminated #else"); break;
1985 case TOKEN_PP_ELIF: fail(ctx, "Unterminated #elif"); break;
1986 default: assert(0 && "Shouldn't hit this case"); break;
1987 } // switch
1988
1989 // pop this conditional, we'll report the next error next time...
1990
1991 state->conditional_stack = cond->next; // pop it.
1992 put_conditional(ctx, cond);
1993 } // unterminated_pp_condition
1994
1995
1996 static inline const char *_preprocessor_nexttoken(Preprocessor *_ctx,
1997 unsigned int *_len, Token *_token)
1998 {
1999 Context *ctx = (Context *) _ctx;
2000
2001 while (1)
2002 {
2003 if (ctx->isfail)
2004 {
2005 ctx->isfail = 0;
2006 *_token = TOKEN_PREPROCESSING_ERROR;
2007 *_len = strlen(ctx->failstr);
2008 return ctx->failstr;
2009 } // if
2010
2011 IncludeState *state = ctx->include_stack;
2012 if (state == NULL)
2013 {
2014 *_token = TOKEN_EOI;
2015 *_len = 0;
2016 return NULL; // we're done!
2017 } // if
2018
2019 const Conditional *cond = state->conditional_stack;
2020 const int skipping = ((cond != NULL) && (cond->skipping));
2021
2022 #if !MATCH_MICROSOFT_PREPROCESSOR
2023 state->report_whitespace = 1;
2024 state->report_comments = 1;
2025 #endif
2026
2027 const Token token = lexer(state);
2028
2029 #if !MATCH_MICROSOFT_PREPROCESSOR
2030 state->report_whitespace = 0;
2031 state->report_comments = 0;
2032 #endif
2033
2034 if (token != TOKEN_IDENTIFIER)
2035 ctx->recursion_count = 0;
2036
2037 if (token == TOKEN_EOI)
2038 {
2039 assert(state->bytes_left == 0);
2040 if (state->conditional_stack != NULL)
2041 {
2042 unterminated_pp_condition(ctx);
2043 continue; // returns an error.
2044 } // if
2045
2046 pop_source(ctx);
2047 continue; // pick up again after parent's #include line.
2048 } // if
2049
2050 else if (token == TOKEN_INCOMPLETE_COMMENT)
2051 {
2052 fail(ctx, "Incomplete multiline comment");
2053 continue; // will return at top of loop.
2054 } // else if
2055
2056 else if (token == TOKEN_PP_IFDEF)
2057 {
2058 handle_pp_ifdef(ctx);
2059 continue; // get the next thing.
2060 } // else if
2061
2062 else if (token == TOKEN_PP_IFNDEF)
2063 {
2064 handle_pp_ifndef(ctx);
2065 continue; // get the next thing.
2066 } // else if
2067
2068 else if (token == TOKEN_PP_IF)
2069 {
2070 handle_pp_if(ctx);
2071 continue; // get the next thing.
2072 } // else if
2073
2074 else if (token == TOKEN_PP_ELIF)
2075 {
2076 handle_pp_elif(ctx);
2077 continue; // get the next thing.
2078 } // else if
2079
2080 else if (token == TOKEN_PP_ENDIF)
2081 {
2082 handle_pp_endif(ctx);
2083 continue; // get the next thing.
2084 } // else if
2085
2086 else if (token == TOKEN_PP_ELSE)
2087 {
2088 handle_pp_else(ctx);
2089 continue; // get the next thing.
2090 } // else if
2091
2092 // NOTE: Conditionals must be above (skipping) test.
2093 else if (skipping)
2094 continue; // just keep dumping tokens until we get end of block.
2095
2096 else if (token == TOKEN_PP_INCLUDE)
2097 {
2098 handle_pp_include(ctx);
2099 continue; // will return error or use new top of include_stack.
2100 } // else if
2101
2102 else if (token == TOKEN_PP_LINE)
2103 {
2104 handle_pp_line(ctx);
2105 continue; // get the next thing.
2106 } // else if
2107
2108 else if (token == TOKEN_PP_ERROR)
2109 {
2110 handle_pp_error(ctx);
2111 continue; // will return at top of loop.
2112 } // else if
2113
2114 else if (token == TOKEN_PP_DEFINE)
2115 {
2116 handle_pp_define(ctx);
2117 continue; // will return at top of loop.
2118 } // else if
2119
2120 else if (token == TOKEN_PP_UNDEF)
2121 {
2122 handle_pp_undef(ctx);
2123 continue; // will return at top of loop.
2124 } // else if
2125
2126 else if (token == TOKEN_PP_PRAGMA)
2127 {
2128 ctx->parsing_pragma = 1;
2129 } // else if
2130
2131 if (token == TOKEN_IDENTIFIER)
2132 {
2133 if (handle_pp_identifier(ctx))
2134 continue; // pushed the include_stack.
2135 } // else if
2136
2137 // you don't ever see these unless you enable state->report_comments.
2138 else if ((token == TOKEN_SINGLE_COMMENT) || (token == TOKEN_MULTI_COMMENT))
2139 {
2140 print_debug_lexing_position(state);
2141 } // else if
2142
2143 else if (token == ((Token) '\n'))
2144 {
2145 print_debug_lexing_position(state);
2146 if (ctx->parsing_pragma) // let this one through.
2147 ctx->parsing_pragma = 0;
2148 else
2149 {
2150 #if MATCH_MICROSOFT_PREPROCESSOR
2151 // preprocessor is line-oriented, nothing else gets newlines.
2152 continue; // get the next thing.
2153 #endif
2154 } // else
2155 } // else if
2156
2157 assert(!skipping);
2158 *_token = token;
2159 *_len = state->tokenlen;
2160 return state->token;
2161 } // while
2162
2163 assert(0 && "shouldn't hit this code");
2164 *_token = TOKEN_UNKNOWN;
2165 *_len = 0;
2166 return NULL;
2167 } // _preprocessor_nexttoken
2168
2169
2170 const char *preprocessor_nexttoken(Preprocessor *ctx, unsigned int *len,
2171 Token *token)
2172 {
2173 const char *retval = _preprocessor_nexttoken(ctx, len, token);
2174 print_debug_token(retval, *len, *token);
2175 return retval;
2176 } // preprocessor_nexttoken
2177
2178
2179 const char *preprocessor_sourcepos(Preprocessor *_ctx, unsigned int *pos)
2180 {
2181 Context *ctx = (Context *) _ctx;
2182 if (ctx->include_stack == NULL)
2183 {
2184 *pos = 0;
2185 return NULL;
2186 } // if
2187
2188 *pos = ctx->include_stack->line;
2189 return ctx->include_stack->filename;
2190 } // preprocessor_sourcepos
2191
2192
2193 static void indent_buffer(Buffer *buffer, int n, const int newline)
2194 {
2195 #if MATCH_MICROSOFT_PREPROCESSOR
2196 static char spaces[4] = { ' ', ' ', ' ', ' ' };
2197 if (newline)
2198 {
2199 while (n--)
2200 {
2201 if (!buffer_append(buffer, spaces, sizeof (spaces)))
2202 return;
2203 } // while
2204 } // if
2205 else
2206 {
2207 if (!buffer_append(buffer, spaces, 1))
2208 return;
2209 } // else
2210 #endif
2211 } // indent_buffer
2212
2213
2214 static const MOJOSHADER_preprocessData out_of_mem_data_preprocessor = {
2215 1, &MOJOSHADER_out_of_mem_error, 0, 0, 0, 0, 0
2216 };
2217
2218
2219 // public API...
2220
2221 const MOJOSHADER_preprocessData *MOJOSHADER_preprocess(const char *filename,
2222 const char *source, unsigned int sourcelen,
2223 const MOJOSHADER_preprocessorDefine *defines,
2224 unsigned int define_count,
2225 MOJOSHADER_includeOpen include_open,
2226 MOJOSHADER_includeClose include_close,
2227 MOJOSHADER_malloc m, MOJOSHADER_free f, void *d)
2228 {
2229 MOJOSHADER_preprocessData *retval = NULL;
2230 Preprocessor *pp = NULL;
2231 ErrorList *errors = NULL;
2232 Buffer *buffer = NULL;
2233 Token token = TOKEN_UNKNOWN;
2234 const char *tokstr = NULL;
2235 int nl = 1;
2236 int indent = 0;
2237 unsigned int len = 0;
2238 char *output = NULL;
2239 int errcount = 0;
2240 size_t total_bytes = 0;
2241
2242 // !!! FIXME: what's wrong with ENDLINE_STR?
2243 #ifdef _WINDOWS
2244 static const char endline[] = { '\r', '\n' };
2245 #else
2246 static const char endline[] = { '\n' };
2247 #endif
2248
2249 if (!m) m = MOJOSHADER_internal_malloc;
2250 if (!f) f = MOJOSHADER_internal_free;
2251 if (!include_open) include_open = MOJOSHADER_internal_include_open;
2252 if (!include_close) include_close = MOJOSHADER_internal_include_close;
2253
2254 pp = preprocessor_start(filename, source, sourcelen,
2255 include_open, include_close,
2256 defines, define_count, 0, m, f, d);
2257 if (pp == NULL)
2258 goto preprocess_out_of_mem;
2259
2260 errors = errorlist_create(MallocBridge, FreeBridge, pp);
2261 if (errors == NULL)
2262 goto preprocess_out_of_mem;
2263
2264 buffer = buffer_create(4096, MallocBridge, FreeBridge, pp);
2265 if (buffer == NULL)
2266 goto preprocess_out_of_mem;
2267
2268 while ((tokstr = preprocessor_nexttoken(pp, &len, &token)) != NULL)
2269 {
2270 int isnewline = 0;
2271
2272 assert(token != TOKEN_EOI);
2273
2274 if (preprocessor_outofmemory(pp))
2275 goto preprocess_out_of_mem;
2276
2277 if (token == ((Token) '\n'))
2278 {
2279 buffer_append(buffer, endline, sizeof (endline));
2280 isnewline = 1;
2281 } // else if
2282
2283 #if MATCH_MICROSOFT_PREPROCESSOR
2284 // Microsoft's preprocessor is weird.
2285 // It ignores newlines, and then inserts its own around certain
2286 // tokens. For example, after a semicolon. This allows HLSL code to
2287 // be mostly readable, instead of a stream of tokens.
2288 else if ( (token == ((Token) '}')) || (token == ((Token) ';')) )
2289 {
2290 if ( (token == ((Token) '}')) && (indent > 0) )
2291 indent--;
2292
2293 indent_buffer(buffer, indent, nl);
2294 buffer_append(buffer, tokstr, len);
2295 buffer_append(buffer, endline, sizeof (endline));
2296
2297 isnewline = 1;
2298 } // if
2299
2300 else if (token == ((Token) '{'))
2301 {
2302 buffer_append(buffer, endline, sizeof (endline));
2303 indent_buffer(buffer, indent, 1);
2304 buffer_append(buffer, "{", 1);
2305 buffer_append(buffer, endline, sizeof (endline));
2306 indent++;
2307 isnewline = 1;
2308 } // else if
2309 #endif
2310
2311 else if (token == TOKEN_PREPROCESSING_ERROR)
2312 {
2313 unsigned int pos = 0;
2314 const char *fname = preprocessor_sourcepos(pp, &pos);
2315 errorlist_add(errors, fname, (int) pos, tokstr);
2316 } // else if
2317
2318 else
2319 {
2320 indent_buffer(buffer, indent, nl);
2321 buffer_append(buffer, tokstr, len);
2322 } // else
2323
2324 nl = isnewline;
2325 } // while
2326
2327 assert(token == TOKEN_EOI);
2328
2329 total_bytes = buffer_size(buffer);
2330 output = buffer_flatten(buffer);
2331 buffer_destroy(buffer);
2332 buffer = NULL; // don't free this pointer again.
2333
2334 if (output == NULL)
2335 goto preprocess_out_of_mem;
2336
2337 retval = (MOJOSHADER_preprocessData *) m(sizeof (*retval), d);
2338 if (retval == NULL)
2339 goto preprocess_out_of_mem;
2340
2341 memset(retval, '\0', sizeof (*retval));
2342 errcount = errorlist_count(errors);
2343 if (errcount > 0)
2344 {
2345 retval->error_count = errcount;
2346 retval->errors = errorlist_flatten(errors);
2347 if (retval->errors == NULL)
2348 goto preprocess_out_of_mem;
2349 } // if
2350
2351 retval->output = output;
2352 retval->output_len = total_bytes;
2353 retval->malloc = m;
2354 retval->free = f;
2355 retval->malloc_data = d;
2356
2357 errorlist_destroy(errors);
2358 preprocessor_end(pp);
2359 return retval;
2360
2361 preprocess_out_of_mem:
2362 if (retval != NULL)
2363 f(retval->errors, d);
2364 f(retval, d);
2365 f(output, d);
2366 buffer_destroy(buffer);
2367 errorlist_destroy(errors);
2368 preprocessor_end(pp);
2369 return &out_of_mem_data_preprocessor;
2370 } // MOJOSHADER_preprocess
2371
2372
2373 void MOJOSHADER_freePreprocessData(const MOJOSHADER_preprocessData *_data)
2374 {
2375 MOJOSHADER_preprocessData *data = (MOJOSHADER_preprocessData *) _data;
2376 if ((data == NULL) || (data == &out_of_mem_data_preprocessor))
2377 return;
2378
2379 MOJOSHADER_free f = (data->free == NULL) ? MOJOSHADER_internal_free : data->free;
2380 void *d = data->malloc_data;
2381 int i;
2382
2383 f((void *) data->output, d);
2384
2385 for (i = 0; i < data->error_count; i++)
2386 {
2387 f((void *) data->errors[i].error, d);
2388 f((void *) data->errors[i].filename, d);
2389 } // for
2390 f(data->errors, d);
2391
2392 f(data, d);
2393 } // MOJOSHADER_freePreprocessData
2394
2395
2396 // end of mojoshader_preprocessor.c ...
2397