makefiles: Remove the no longer needed explicit dependencies for bison files.
[wine] / libs / wpp / preproc.c
1 /*
2  * Copyright 1998 Bertho A. Stultiens (BS)
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #include "config.h"
20 #include "wine/port.h"
21
22 #include <assert.h>
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <stdarg.h>
29 #ifdef HAVE_UNISTD_H
30 # include <unistd.h>
31 #endif
32 #ifdef HAVE_IO_H
33 # include <io.h>
34 #endif
35
36 #include "wine/wpp.h"
37 #include "wpp_private.h"
38
39 struct pp_status pp_status;
40
41 #define HASHKEY         2039
42
43 typedef struct pp_def_state
44 {
45     struct pp_def_state *next;
46     pp_entry_t          *defines[HASHKEY];
47 } pp_def_state_t;
48
49 static pp_def_state_t *pp_def_state;
50
51 #define MAXIFSTACK      64
52 static pp_if_state_t if_stack[MAXIFSTACK];
53 static int if_stack_idx = 0;
54
55 #if 0
56 void pp_print_status(void) __attribute__((destructor));
57 void pp_print_status(void)
58 {
59         int i;
60         int sum;
61         int total = 0;
62         pp_entry_t *ppp;
63
64         fprintf(stderr, "Defines statistics:\n");
65         for(i = 0; i < HASHKEY; i++)
66         {
67                 sum = 0;
68                 for(ppp = pp_def_state->defines[i]; ppp; ppp = ppp->next)
69                         sum++;
70                 total += sum;
71                 if (sum) fprintf(stderr, "%4d, %3d\n", i, sum);
72         }
73         fprintf(stderr, "Total defines: %d\n", total);
74 }
75 #endif
76
77 void *pp_xmalloc(size_t size)
78 {
79     void *res;
80
81     assert(size > 0);
82     res = malloc(size);
83     if(res == NULL)
84     {
85         /* Set the error flag */
86         pp_status.state = 1;
87     }
88     return res;
89 }
90
91 void *pp_xrealloc(void *p, size_t size)
92 {
93     void *res;
94
95     assert(size > 0);
96     res = realloc(p, size);
97     if(res == NULL)
98     {
99         /* Set the error flag */
100         pp_status.state = 1;
101     }
102     return res;
103 }
104
105 char *pp_xstrdup(const char *str)
106 {
107         char *s;
108         int len;
109
110         assert(str != NULL);
111         len = strlen(str)+1;
112         s = pp_xmalloc(len);
113         if(!s)
114                 return NULL;
115         return memcpy(s, str, len);
116 }
117
118 static char *wpp_default_lookup(const char *name, const char *parent_name,
119                                 char **include_path, int include_path_count)
120 {
121     char *cpy;
122     char *cptr;
123     char *path;
124     const char *ccptr;
125     int i, fd;
126
127     cpy = pp_xmalloc(strlen(name)+1);
128     if(!cpy)
129         return NULL;
130     cptr = cpy;
131
132     for(ccptr = name; *ccptr; ccptr++)
133     {
134         /* Convert to forward slash */
135         if(*ccptr == '\\') {
136             /* kill double backslash */
137             if(ccptr[1] == '\\')
138                 ccptr++;
139             *cptr = '/';
140         }else {
141             *cptr = *ccptr;
142         }
143         cptr++;
144     }
145     *cptr = '\0';
146
147     if(parent_name)
148     {
149         /* Search directory of parent include and then -I path */
150         const char *p;
151
152         if ((p = strrchr( parent_name, '/' ))) p++;
153         else p = parent_name;
154         path = pp_xmalloc( (p - parent_name) + strlen(cpy) + 1 );
155         if(!path)
156         {
157             free(cpy);
158             return NULL;
159         }
160         memcpy( path, parent_name, p - parent_name );
161         strcpy( path + (p - parent_name), cpy );
162         fd = open( path, O_RDONLY );
163         if (fd != -1)
164         {
165             close( fd );
166             free( cpy );
167             return path;
168         }
169         free( path );
170     }
171     /* Search -I path */
172     for(i = 0; i < include_path_count; i++)
173     {
174         path = pp_xmalloc(strlen(include_path[i]) + strlen(cpy) + 2);
175         if(!path)
176         {
177             free(cpy);
178             return NULL;
179         }
180         strcpy(path, include_path[i]);
181         strcat(path, "/");
182         strcat(path, cpy);
183         fd = open( path, O_RDONLY );
184         if (fd != -1)
185         {
186             close( fd );
187             free( cpy );
188             return path;
189         }
190         free( path );
191     }
192     free( cpy );
193     return NULL;
194 }
195
196 static void *wpp_default_open(const char *filename, int type) {
197     return fopen(filename,"rt");
198 }
199
200 static void wpp_default_close(void *file) {
201     fclose(file);
202 }
203
204 static int wpp_default_read(void *file, char *buffer, unsigned int len){
205     return fread(buffer, 1, len, file);
206 }
207
208 static void wpp_default_write( const char *buffer, unsigned int len ) {
209     fwrite(buffer, 1, len, ppy_out);
210 }
211
212 /* Don't comment on the hash, its primitive but functional... */
213 static int pphash(const char *str)
214 {
215         int sum = 0;
216         while(*str)
217                 sum += *str++;
218         return sum % HASHKEY;
219 }
220
221 pp_entry_t *pplookup(const char *ident)
222 {
223         int idx;
224         pp_entry_t *ppp;
225
226         if(!ident)
227                 return NULL;
228         idx = pphash(ident);
229         for(ppp = pp_def_state->defines[idx]; ppp; ppp = ppp->next)
230         {
231                 if(!strcmp(ident, ppp->ident))
232                         return ppp;
233         }
234         return NULL;
235 }
236
237 static void free_pp_entry( pp_entry_t *ppp, int idx )
238 {
239         if(ppp->iep)
240         {
241                 if(ppp->iep == pp_includelogiclist)
242                 {
243                         pp_includelogiclist = ppp->iep->next;
244                         if(pp_includelogiclist)
245                                 pp_includelogiclist->prev = NULL;
246                 }
247                 else
248                 {
249                         ppp->iep->prev->next = ppp->iep->next;
250                         if(ppp->iep->next)
251                                 ppp->iep->next->prev = ppp->iep->prev;
252                 }
253                 free(ppp->iep->filename);
254                 free(ppp->iep);
255         }
256
257         if(pp_def_state->defines[idx] == ppp)
258         {
259                 pp_def_state->defines[idx] = ppp->next;
260                 if(pp_def_state->defines[idx])
261                         pp_def_state->defines[idx]->prev = NULL;
262         }
263         else
264         {
265                 ppp->prev->next = ppp->next;
266                 if(ppp->next)
267                         ppp->next->prev = ppp->prev;
268         }
269
270         free(ppp);
271 }
272
273 /* push a new (empty) define state */
274 int pp_push_define_state(void)
275 {
276     pp_def_state_t *state = pp_xmalloc( sizeof(*state) );
277     if(!state)
278         return 1;
279
280     memset( state->defines, 0, sizeof(state->defines) );
281     state->next = pp_def_state;
282     pp_def_state = state;
283     return 0;
284 }
285
286 /* pop the current define state */
287 void pp_pop_define_state(void)
288 {
289     int i;
290     pp_entry_t *ppp;
291     pp_def_state_t *state;
292
293     for (i = 0; i < HASHKEY; i++)
294     {
295         while ((ppp = pp_def_state->defines[i]) != NULL) free_pp_entry( ppp, i );
296     }
297     state = pp_def_state;
298     pp_def_state = state->next;
299     free( state );
300 }
301
302 void pp_del_define(const char *name)
303 {
304         pp_entry_t *ppp;
305
306         if((ppp = pplookup(name)) == NULL)
307         {
308                 if(pp_status.pedantic)
309                         ppy_warning("%s was not defined", name);
310                 return;
311         }
312
313         free_pp_entry( ppp, pphash(name) );
314
315         if(pp_status.debug)
316                 printf("Deleted (%s, %d) <%s>\n", pp_status.input, pp_status.line_number, name);
317 }
318
319 pp_entry_t *pp_add_define(char *def, char *text)
320 {
321         int len;
322         char *cptr;
323         int idx;
324         pp_entry_t *ppp;
325
326         if(!def)
327                 return NULL;
328         idx = pphash(def);
329         if((ppp = pplookup(def)) != NULL)
330         {
331                 if(pp_status.pedantic)
332                         ppy_warning("Redefinition of %s\n\tPrevious definition: %s:%d", def, ppp->filename, ppp->linenumber);
333                 pp_del_define(def);
334         }
335         ppp = pp_xmalloc(sizeof(pp_entry_t));
336         if(!ppp)
337                 return NULL;
338         memset( ppp, 0, sizeof(*ppp) );
339         ppp->ident = def;
340         ppp->type = def_define;
341         ppp->subst.text = text;
342         ppp->filename = pp_xstrdup(pp_status.input ? pp_status.input : "<internal or cmdline>");
343         if(!ppp->filename)
344         {
345                 free(ppp);
346                 return NULL;
347         }
348         ppp->linenumber = pp_status.input ? pp_status.line_number : 0;
349         ppp->next = pp_def_state->defines[idx];
350         pp_def_state->defines[idx] = ppp;
351         if(ppp->next)
352                 ppp->next->prev = ppp;
353         if(text)
354         {
355                 /* Strip trailing white space from subst text */
356                 len = strlen(text);
357                 while(len && strchr(" \t\r\n", text[len-1]))
358                 {
359                         text[--len] = '\0';
360                 }
361                 /* Strip leading white space from subst text */
362                 for(cptr = text; *cptr && strchr(" \t\r", *cptr); cptr++)
363                 ;
364                 if(text != cptr)
365                         memmove(text, cptr, strlen(cptr)+1);
366         }
367         if(pp_status.debug)
368                 printf("Added define (%s, %d) <%s> to <%s>\n", pp_status.input, pp_status.line_number, ppp->ident, text ? text : "(null)");
369
370         return ppp;
371 }
372
373 pp_entry_t *pp_add_macro(char *id, marg_t *args[], int nargs, mtext_t *exp)
374 {
375         int idx;
376         pp_entry_t *ppp;
377
378         if(!id)
379                 return NULL;
380         idx = pphash(id);
381         if((ppp = pplookup(id)) != NULL)
382         {
383                 if(pp_status.pedantic)
384                         ppy_warning("Redefinition of %s\n\tPrevious definition: %s:%d", id, ppp->filename, ppp->linenumber);
385                 pp_del_define(id);
386         }
387         ppp = pp_xmalloc(sizeof(pp_entry_t));
388         if(!ppp)
389                 return NULL;
390         memset( ppp, 0, sizeof(*ppp) );
391         ppp->ident      = id;
392         ppp->type       = def_macro;
393         ppp->margs      = args;
394         ppp->nargs      = nargs;
395         ppp->subst.mtext= exp;
396         ppp->filename = pp_xstrdup(pp_status.input ? pp_status.input : "<internal or cmdline>");
397         if(!ppp->filename)
398         {
399                 free(ppp);
400                 return NULL;
401         }
402         ppp->linenumber = pp_status.input ? pp_status.line_number : 0;
403         ppp->next       = pp_def_state->defines[idx];
404         pp_def_state->defines[idx] = ppp;
405         if(ppp->next)
406                 ppp->next->prev = ppp;
407
408         if(pp_status.debug)
409         {
410                 fprintf(stderr, "Added macro (%s, %d) <%s(%d)> to <", pp_status.input, pp_status.line_number, ppp->ident, nargs);
411                 for(; exp; exp = exp->next)
412                 {
413                         switch(exp->type)
414                         {
415                         case exp_text:
416                                 fprintf(stderr, " \"%s\" ", exp->subst.text);
417                                 break;
418                         case exp_stringize:
419                                 fprintf(stderr, " #(%d) ", exp->subst.argidx);
420                                 break;
421                         case exp_concat:
422                                 fprintf(stderr, "##");
423                                 break;
424                         case exp_subst:
425                                 fprintf(stderr, " <%d> ", exp->subst.argidx);
426                                 break;
427                         }
428                 }
429                 fprintf(stderr, ">\n");
430         }
431         return ppp;
432 }
433
434
435 /*
436  *-------------------------------------------------------------------------
437  * Include management
438  *-------------------------------------------------------------------------
439  */
440 #if defined(_Windows) || defined(__MSDOS__)
441 #define INCLUDESEPARATOR        ";"
442 #else
443 #define INCLUDESEPARATOR        ":"
444 #endif
445
446 static char **includepath;
447 static int nincludepath = 0;
448
449 int wpp_add_include_path(const char *path)
450 {
451         char *tok;
452         char *cpy = pp_xstrdup(path);
453         if(!cpy)
454                 return 1;
455
456         tok = strtok(cpy, INCLUDESEPARATOR);
457         while(tok)
458         {
459                 if(*tok) {
460                         char *dir;
461                         char *cptr;
462                         char **new_path;
463
464                         dir = pp_xstrdup(tok);
465                         if(!dir)
466                         {
467                                 free(cpy);
468                                 return 1;
469                         }
470                         for(cptr = dir; *cptr; cptr++)
471                         {
472                                 /* Convert to forward slash */
473                                 if(*cptr == '\\')
474                                         *cptr = '/';
475                         }
476                         /* Kill eventual trailing '/' */
477                         if(*(cptr = dir + strlen(dir)-1) == '/')
478                                 *cptr = '\0';
479
480                         /* Add to list */
481                         new_path = pp_xrealloc(includepath, (nincludepath+1) * sizeof(*includepath));
482                         if(!new_path)
483                         {
484                                 free(dir);
485                                 free(cpy);
486                                 return 1;
487                         }
488                         includepath = new_path;
489                         includepath[nincludepath] = dir;
490                         nincludepath++;
491                 }
492                 tok = strtok(NULL, INCLUDESEPARATOR);
493         }
494         free(cpy);
495         return 0;
496 }
497
498 char *wpp_find_include(const char *name, const char *parent_name)
499 {
500     return wpp_default_lookup(name, parent_name, includepath, nincludepath);
501 }
502
503 void *pp_open_include(const char *name, const char *parent_name, char **newpath)
504 {
505     char *path;
506     void *fp;
507
508     if (!(path = wpp_callbacks->lookup(name, parent_name, includepath,
509                                        nincludepath))) return NULL;
510     fp = wpp_callbacks->open(path, parent_name == NULL ? 1 : 0);
511
512     if (fp)
513     {
514         if (pp_status.debug)
515             printf("Going to include <%s>\n", path);
516         if (newpath) *newpath = path;
517         else free( path );
518         return fp;
519     }
520     free( path );
521     return NULL;
522 }
523
524 /*
525  *-------------------------------------------------------------------------
526  * #if, #ifdef, #ifndef, #else, #elif and #endif state management
527  *
528  * #if state transitions are made on basis of the current TOS and the next
529  * required state. The state transitions are required to housekeep because
530  * #if:s can be nested. The ignore case is activated to prevent output from
531  * within a false clause.
532  * Some special cases come from the fact that the #elif cases are not
533  * binary, but three-state. The problem is that all other elif-cases must
534  * be false when one true one has been found. A second problem is that the
535  * #else clause is a final clause. No extra #else:s may follow.
536  *
537  * The states mean:
538  * if_true      Process input to output
539  * if_false     Process input but no output
540  * if_ignore    Process input but no output
541  * if_elif      Process input but no output
542  * if_elsefalse Process input but no output
543  * if_elsettrue Process input to output
544  *
545  * The possible state-sequences are [state(stack depth)] (rest can be deduced):
546  *      TOS             #if 1           #else                   #endif
547  *      if_true(n)      if_true(n+1)    if_elsefalse(n+1)
548  *      if_false(n)     if_ignore(n+1)  if_ignore(n+1)
549  *      if_elsetrue(n)  if_true(n+1)    if_elsefalse(n+1)
550  *      if_elsefalse(n) if_ignore(n+1)  if_ignore(n+1)
551  *      if_elif(n)      if_ignore(n+1)  if_ignore(n+1)
552  *      if_ignore(n)    if_ignore(n+1)  if_ignore(n+1)
553  *
554  *      TOS             #if 1           #elif 0         #else           #endif
555  *      if_true(n)      if_true(n+1)    if_elif(n+1)    if_elif(n+1)
556  *      if_false(n)     if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
557  *      if_elsetrue(n)  if_true(n+1)    if_elif(n+1)    if_elif(n+1)
558  *      if_elsefalse(n) if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
559  *      if_elif(n)      if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
560  *      if_ignore(n)    if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
561  *
562  *      TOS             #if 0           #elif 1         #else           #endif
563  *      if_true(n)      if_false(n+1)   if_true(n+1)    if_elsefalse(n+1)
564  *      if_false(n)     if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
565  *      if_elsetrue(n)  if_false(n+1)   if_true(n+1)    if_elsefalse(n+1)
566  *      if_elsefalse(n) if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
567  *      if_elif(n)      if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
568  *      if_ignore(n)    if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
569  *
570  *-------------------------------------------------------------------------
571  */
572 static const char * const pp_if_state_str[] = {
573         "if_false",
574         "if_true",
575         "if_elif",
576         "if_elsefalse",
577         "if_elsetrue",
578         "if_ignore"
579 };
580
581 void pp_push_if(pp_if_state_t s)
582 {
583         if(if_stack_idx >= MAXIFSTACK)
584                 pp_internal_error(__FILE__, __LINE__, "#if-stack overflow; #{if,ifdef,ifndef} nested too deeply (> %d)", MAXIFSTACK);
585
586         if(pp_flex_debug)
587                 fprintf(stderr, "Push if %s:%d: %s(%d) -> %s(%d)\n", pp_status.input, pp_status.line_number, pp_if_state_str[pp_if_state()], if_stack_idx, pp_if_state_str[s], if_stack_idx+1);
588
589         if_stack[if_stack_idx++] = s;
590
591         switch(s)
592         {
593         case if_true:
594         case if_elsetrue:
595                 break;
596         case if_false:
597         case if_elsefalse:
598         case if_elif:
599         case if_ignore:
600                 pp_push_ignore_state();
601                 break;
602         default:
603                 pp_internal_error(__FILE__, __LINE__, "Invalid pp_if_state (%d)", (int)pp_if_state());
604         }
605 }
606
607 pp_if_state_t pp_pop_if(void)
608 {
609         if(if_stack_idx <= 0)
610         {
611                 ppy_error("#{endif,else,elif} without #{if,ifdef,ifndef} (#if-stack underflow)");
612                 return if_error;
613         }
614
615         switch(pp_if_state())
616         {
617         case if_true:
618         case if_elsetrue:
619                 break;
620         case if_false:
621         case if_elsefalse:
622         case if_elif:
623         case if_ignore:
624                 pp_pop_ignore_state();
625                 break;
626         default:
627                 pp_internal_error(__FILE__, __LINE__, "Invalid pp_if_state (%d)", (int)pp_if_state());
628         }
629
630         if(pp_flex_debug)
631                 fprintf(stderr, "Pop if %s:%d: %s(%d) -> %s(%d)\n",
632                                 pp_status.input,
633                                 pp_status.line_number,
634                                 pp_if_state_str[pp_if_state()],
635                                 if_stack_idx,
636                                 pp_if_state_str[if_stack[if_stack_idx <= 1 ? if_true : if_stack_idx-2]],
637                                 if_stack_idx-1);
638
639         return if_stack[--if_stack_idx];
640 }
641
642 pp_if_state_t pp_if_state(void)
643 {
644         if(!if_stack_idx)
645                 return if_true;
646         else
647                 return if_stack[if_stack_idx-1];
648 }
649
650
651 void pp_next_if_state(int i)
652 {
653         switch(pp_if_state())
654         {
655         case if_true:
656         case if_elsetrue:
657                 pp_push_if(i ? if_true : if_false);
658                 break;
659         case if_false:
660         case if_elsefalse:
661         case if_elif:
662         case if_ignore:
663                 pp_push_if(if_ignore);
664                 break;
665         default:
666                 pp_internal_error(__FILE__, __LINE__, "Invalid pp_if_state (%d) in #{if,ifdef,ifndef} directive", (int)pp_if_state());
667         }
668 }
669
670 int pp_get_if_depth(void)
671 {
672         return if_stack_idx;
673 }
674
675 /* #define WANT_NEAR_INDICATION */
676
677 static void generic_msg(const char *s, const char *t, const char *n, va_list ap)
678 {
679         fprintf(stderr, "%s:%d:%d: %s: ", pp_status.input ? pp_status.input : "stdin",
680                 pp_status.line_number, pp_status.char_number, t);
681         vfprintf(stderr, s, ap);
682 #ifdef WANT_NEAR_INDICATION
683         {
684                 char *cpy, *p;
685                 if(n)
686                 {
687                         cpy = pp_xstrdup(n);
688                         if(!cpy)
689                                 goto end;
690                         for (p = cpy; *p; p++) if(!isprint(*p)) *p = ' ';
691                         fprintf(stderr, " near '%s'", cpy);
692                         free(cpy);
693                 }
694         }
695 end:
696 #endif
697         fprintf(stderr, "\n");
698 }
699
700 static void wpp_default_error(const char *file, int line, int col, const char *near, const char *msg, va_list ap)
701 {
702         generic_msg(msg, "Error", near, ap);
703         exit(1);
704 }
705
706 static void wpp_default_warning(const char *file, int line, int col, const char *near, const char *msg, va_list ap)
707 {
708         generic_msg(msg, "Warning", near, ap);
709 }
710
711 static const struct wpp_callbacks default_callbacks =
712 {
713         wpp_default_lookup,
714         wpp_default_open,
715         wpp_default_close,
716         wpp_default_read,
717         wpp_default_write,
718         wpp_default_error,
719         wpp_default_warning,
720 };
721
722 const struct wpp_callbacks *wpp_callbacks = &default_callbacks;
723
724 int ppy_error(const char *s, ...)
725 {
726         va_list ap;
727         va_start(ap, s);
728         wpp_callbacks->error(pp_status.input, pp_status.line_number, pp_status.char_number, ppy_text, s, ap);
729         va_end(ap);
730         pp_status.state = 1;
731         return 1;
732 }
733
734 int ppy_warning(const char *s, ...)
735 {
736         va_list ap;
737         va_start(ap, s);
738         wpp_callbacks->warning(pp_status.input, pp_status.line_number, pp_status.char_number, ppy_text, s, ap);
739         va_end(ap);
740         return 0;
741 }
742
743 void pp_internal_error(const char *file, int line, const char *s, ...)
744 {
745         va_list ap;
746         va_start(ap, s);
747         fprintf(stderr, "Internal error (please report) %s %d: ", file, line);
748         vfprintf(stderr, s, ap);
749         fprintf(stderr, "\n");
750         va_end(ap);
751         exit(3);
752 }