Not everyone has <unistd.h>, some files need <io.h> too (msvc).
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19 #include "config.h"
20 #include "wine/port.h"
21
22 #include <assert.h>
23 #include <fcntl.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdarg.h>
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif
31 #ifdef HAVE_IO_H
32 # include <io.h>
33 #endif
34
35 #include "wpp_private.h"
36
37 struct pp_status pp_status;
38
39 #define HASHKEY         2039
40
41 typedef struct pp_def_state
42 {
43     struct pp_def_state *next;
44     pp_entry_t          *defines[HASHKEY];
45 } pp_def_state_t;
46
47 static pp_def_state_t *pp_def_state;
48
49 #define MAXIFSTACK      64
50 static pp_if_state_t if_stack[MAXIFSTACK];
51 static int if_stack_idx = 0;
52
53 #if 0
54 void pp_print_status(void) __attribute__((destructor));
55 void pp_print_status(void)
56 {
57         int i;
58         int sum;
59         int total = 0;
60         pp_entry_t *ppp;
61
62         fprintf(stderr, "Defines statistics:\n");
63         for(i = 0; i < HASHKEY; i++)
64         {
65                 sum = 0;
66                 for(ppp = pp_def_state->defines[i]; ppp; ppp = ppp->next)
67                         sum++;
68                 total += sum;
69                 if (sum) fprintf(stderr, "%4d, %3d\n", i, sum);
70         }
71         fprintf(stderr, "Total defines: %d\n", total);
72 }
73 #endif
74
75 void *pp_xmalloc(size_t size)
76 {
77     void *res;
78
79     assert(size > 0);
80     res = malloc(size);
81     if(res == NULL)
82     {
83         fprintf(stderr, "Virtual memory exhausted.\n");
84         exit(2);
85     }
86     return res;
87 }
88
89 void *pp_xrealloc(void *p, size_t size)
90 {
91     void *res;
92
93     assert(size > 0);
94     res = realloc(p, size);
95     if(res == NULL)
96     {
97         fprintf(stderr, "Virtual memory exhausted.\n");
98         exit(2);
99     }
100     return res;
101 }
102
103 char *pp_xstrdup(const char *str)
104 {
105         char *s;
106
107         assert(str != NULL);
108         s = pp_xmalloc(strlen(str)+1);
109         return strcpy(s, str);
110 }
111
112 /* Don't comment on the hash, its primitive but functional... */
113 static int pphash(const char *str)
114 {
115         int sum = 0;
116         while(*str)
117                 sum += *str++;
118         return sum % HASHKEY;
119 }
120
121 pp_entry_t *pplookup(const char *ident)
122 {
123         int idx = pphash(ident);
124         pp_entry_t *ppp;
125
126         for(ppp = pp_def_state->defines[idx]; ppp; ppp = ppp->next)
127         {
128                 if(!strcmp(ident, ppp->ident))
129                         return ppp;
130         }
131         return NULL;
132 }
133
134 static void free_pp_entry( pp_entry_t *ppp, int idx )
135 {
136         if(ppp->iep)
137         {
138                 if(ppp->iep == pp_includelogiclist)
139                 {
140                         pp_includelogiclist = ppp->iep->next;
141                         if(pp_includelogiclist)
142                                 pp_includelogiclist->prev = NULL;
143                 }
144                 else
145                 {
146                         ppp->iep->prev->next = ppp->iep->next;
147                         if(ppp->iep->next)
148                                 ppp->iep->next->prev = ppp->iep->prev;
149                 }
150                 free(ppp->iep->filename);
151                 free(ppp->iep);
152         }
153
154         if(pp_def_state->defines[idx] == ppp)
155         {
156                 pp_def_state->defines[idx] = ppp->next;
157                 if(pp_def_state->defines[idx])
158                         pp_def_state->defines[idx]->prev = NULL;
159         }
160         else
161         {
162                 ppp->prev->next = ppp->next;
163                 if(ppp->next)
164                         ppp->next->prev = ppp->prev;
165         }
166
167         free(ppp);
168 }
169
170 /* push a new (empty) define state */
171 void pp_push_define_state(void)
172 {
173     pp_def_state_t *state = pp_xmalloc( sizeof(*state) );
174
175     memset( state->defines, 0, sizeof(state->defines) );
176     state->next = pp_def_state;
177     pp_def_state = state;
178 }
179
180 /* pop the current define state */
181 void pp_pop_define_state(void)
182 {
183     int i;
184     pp_entry_t *ppp;
185     pp_def_state_t *state;
186
187     for (i = 0; i < HASHKEY; i++)
188     {
189         while ((ppp = pp_def_state->defines[i]) != NULL) free_pp_entry( ppp, i );
190     }
191     state = pp_def_state;
192     pp_def_state = state->next;
193     free( state );
194 }
195
196 void pp_del_define(const char *name)
197 {
198         pp_entry_t *ppp;
199
200         if((ppp = pplookup(name)) == NULL)
201         {
202                 if(pp_status.pedantic)
203                         ppwarning("%s was not defined", name);
204                 return;
205         }
206
207         free_pp_entry( ppp, pphash(name) );
208
209         if(pp_status.debug)
210                 printf("Deleted (%s, %d) <%s>\n", pp_status.input, pp_status.line_number, name);
211 }
212
213 pp_entry_t *pp_add_define(char *def, char *text)
214 {
215         int len;
216         char *cptr;
217         int idx = pphash(def);
218         pp_entry_t *ppp;
219
220         if((ppp = pplookup(def)) != NULL)
221         {
222                 if(pp_status.pedantic)
223                         ppwarning("Redefinition of %s\n\tPrevious definition: %s:%d", def, ppp->filename, ppp->linenumber);
224                 pp_del_define(def);
225         }
226         ppp = pp_xmalloc(sizeof(pp_entry_t));
227         memset( ppp, 0, sizeof(*ppp) );
228         ppp->ident = def;
229         ppp->type = def_define;
230         ppp->subst.text = text;
231         ppp->filename = pp_status.input ? pp_xstrdup(pp_status.input) : "<internal or cmdline>";
232         ppp->linenumber = pp_status.input ? pp_status.line_number : 0;
233         ppp->next = pp_def_state->defines[idx];
234         pp_def_state->defines[idx] = ppp;
235         if(ppp->next)
236                 ppp->next->prev = ppp;
237         if(text)
238         {
239                 /* Strip trailing white space from subst text */
240                 len = strlen(text);
241                 while(len && strchr(" \t\r\n", text[len-1]))
242                 {
243                         text[--len] = '\0';
244                 }
245                 /* Strip leading white space from subst text */
246                 for(cptr = text; *cptr && strchr(" \t\r", *cptr); cptr++)
247                 ;
248                 if(text != cptr)
249                         memmove(text, cptr, strlen(cptr)+1);
250         }
251         if(pp_status.debug)
252                 printf("Added define (%s, %d) <%s> to <%s>\n", pp_status.input, pp_status.line_number, ppp->ident, text ? text : "(null)");
253
254         return ppp;
255 }
256
257 pp_entry_t *pp_add_macro(char *id, marg_t *args[], int nargs, mtext_t *exp)
258 {
259         int idx = pphash(id);
260         pp_entry_t *ppp;
261
262         if((ppp = pplookup(id)) != NULL)
263         {
264                 if(pp_status.pedantic)
265                         ppwarning("Redefinition of %s\n\tPrevious definition: %s:%d", id, ppp->filename, ppp->linenumber);
266                 pp_del_define(id);
267         }
268         ppp = pp_xmalloc(sizeof(pp_entry_t));
269         memset( ppp, 0, sizeof(*ppp) );
270         ppp->ident      = id;
271         ppp->type       = def_macro;
272         ppp->margs      = args;
273         ppp->nargs      = nargs;
274         ppp->subst.mtext= exp;
275         ppp->filename = pp_status.input ? pp_xstrdup(pp_status.input) : "<internal or cmdline>";
276         ppp->linenumber = pp_status.input ? pp_status.line_number : 0;
277         ppp->next       = pp_def_state->defines[idx];
278         pp_def_state->defines[idx] = ppp;
279         if(ppp->next)
280                 ppp->next->prev = ppp;
281
282         if(pp_status.debug)
283         {
284                 fprintf(stderr, "Added macro (%s, %d) <%s(%d)> to <", pp_status.input, pp_status.line_number, ppp->ident, nargs);
285                 for(; exp; exp = exp->next)
286                 {
287                         switch(exp->type)
288                         {
289                         case exp_text:
290                                 fprintf(stderr, " \"%s\" ", exp->subst.text);
291                                 break;
292                         case exp_stringize:
293                                 fprintf(stderr, " #(%d) ", exp->subst.argidx);
294                                 break;
295                         case exp_concat:
296                                 fprintf(stderr, "##");
297                                 break;
298                         case exp_subst:
299                                 fprintf(stderr, " <%d> ", exp->subst.argidx);
300                                 break;
301                         }
302                 }
303                 fprintf(stderr, ">\n");
304         }
305         return ppp;
306 }
307
308
309 /*
310  *-------------------------------------------------------------------------
311  * Include management
312  *-------------------------------------------------------------------------
313  */
314 #if defined(_Windows) || defined(__MSDOS__)
315 #define INCLUDESEPARATOR        ";"
316 #else
317 #define INCLUDESEPARATOR        ":"
318 #endif
319
320 static char **includepath;
321 static int nincludepath = 0;
322
323 void wpp_add_include_path(const char *path)
324 {
325         char *tok;
326         char *cpy = pp_xstrdup(path);
327
328         tok = strtok(cpy, INCLUDESEPARATOR);
329         while(tok)
330         {
331                 char *dir;
332                 char *cptr;
333                 if(strlen(tok) == 0)
334                         continue;
335                 dir = pp_xstrdup(tok);
336                 for(cptr = dir; *cptr; cptr++)
337                 {
338                         /* Convert to forward slash */
339                         if(*cptr == '\\')
340                                 *cptr = '/';
341                 }
342                 /* Kill eventual trailing '/' */
343                 if(*(cptr = dir + strlen(dir)-1) == '/')
344                         *cptr = '\0';
345
346                 /* Add to list */
347                 nincludepath++;
348                 includepath = pp_xrealloc(includepath, nincludepath * sizeof(*includepath));
349                 includepath[nincludepath-1] = dir;
350                 tok = strtok(NULL, INCLUDESEPARATOR);
351         }
352         free(cpy);
353 }
354
355 char *wpp_find_include(const char *name, int search)
356 {
357     char *cpy = pp_xstrdup(name);
358     char *cptr;
359     int i, fd;
360
361     for(cptr = cpy; *cptr; cptr++)
362     {
363         /* kill double backslash */
364         if(*cptr == '\\' && *(cptr+1) == '\\')
365             memmove(cptr, cptr+1, strlen(cptr));
366         /* Convert to forward slash */
367         if(*cptr == '\\')
368             *cptr = '/';
369     }
370
371     if(search)
372     {
373         /* Search current dir and then -I path */
374         fd = open( cpy, O_RDONLY );
375         if (fd != -1)
376         {
377             close( fd );
378             return cpy;
379         }
380     }
381     /* Search -I path */
382     for(i = 0; i < nincludepath; i++)
383     {
384         char *path;
385         path = pp_xmalloc(strlen(includepath[i]) + strlen(cpy) + 2);
386         strcpy(path, includepath[i]);
387         strcat(path, "/");
388         strcat(path, cpy);
389         fd = open( path, O_RDONLY );
390         if (fd != -1)
391         {
392             close( fd );
393             free( cpy );
394             return path;
395         }
396         free( path );
397     }
398     free( cpy );
399     return NULL;
400 }
401
402 FILE *pp_open_include(const char *name, int search, char **newpath)
403 {
404     char *path;
405     FILE *fp;
406
407     if (!(path = wpp_find_include( name, search ))) return NULL;
408     fp = fopen(path, "rt");
409
410     if (fp)
411     {
412         if (pp_status.debug)
413             printf("Going to include <%s>\n", path);
414         if (newpath) *newpath = path;
415         else free( path );
416         return fp;
417     }
418     free( path );
419     return NULL;
420 }
421
422 /*
423  *-------------------------------------------------------------------------
424  * #if, #ifdef, #ifndef, #else, #elif and #endif state management
425  *
426  * #if state transitions are made on basis of the current TOS and the next
427  * required state. The state transitions are required to housekeep because
428  * #if:s can be nested. The ignore case is activated to prevent output from
429  * within a false clause.
430  * Some special cases come from the fact that the #elif cases are not
431  * binary, but three-state. The problem is that all other elif-cases must
432  * be false when one true one has been found. A second problem is that the
433  * #else clause is a final clause. No extra #else:s may follow.
434  *
435  * The states mean:
436  * if_true      Process input to output
437  * if_false     Process input but no output
438  * if_ignore    Process input but no output
439  * if_elif      Process input but no output
440  * if_elsefalse Process input but no output
441  * if_elsettrue Process input to output
442  *
443  * The possible state-sequences are [state(stack depth)] (rest can be deduced):
444  *      TOS             #if 1           #else                   #endif
445  *      if_true(n)      if_true(n+1)    if_elsefalse(n+1)
446  *      if_false(n)     if_ignore(n+1)  if_ignore(n+1)
447  *      if_elsetrue(n)  if_true(n+1)    if_elsefalse(n+1)
448  *      if_elsefalse(n) if_ignore(n+1)  if_ignore(n+1)
449  *      if_elif(n)      if_ignore(n+1)  if_ignore(n+1)
450  *      if_ignore(n)    if_ignore(n+1)  if_ignore(n+1)
451  *
452  *      TOS             #if 1           #elif 0         #else           #endif
453  *      if_true(n)      if_true(n+1)    if_elif(n+1)    if_elif(n+1)
454  *      if_false(n)     if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
455  *      if_elsetrue(n)  if_true(n+1)    if_elif(n+1)    if_elif(n+1)
456  *      if_elsefalse(n) if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
457  *      if_elif(n)      if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
458  *      if_ignore(n)    if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
459  *
460  *      TOS             #if 0           #elif 1         #else           #endif
461  *      if_true(n)      if_false(n+1)   if_true(n+1)    if_elsefalse(n+1)
462  *      if_false(n)     if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
463  *      if_elsetrue(n)  if_false(n+1)   if_true(n+1)    if_elsefalse(n+1)
464  *      if_elsefalse(n) if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
465  *      if_elif(n)      if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
466  *      if_ignore(n)    if_ignore(n+1)  if_ignore(n+1)  if_ignore(n+1)
467  *
468  *-------------------------------------------------------------------------
469  */
470 static char *pp_if_state_str[] = {
471         "if_false",
472         "if_true",
473         "if_elif",
474         "if_elsefalse",
475         "if_elsetrue",
476         "if_ignore"
477 };
478
479 void pp_push_if(pp_if_state_t s)
480 {
481         if(if_stack_idx >= MAXIFSTACK)
482                 pp_internal_error(__FILE__, __LINE__, "#if-stack overflow; #{if,ifdef,ifndef} nested too deeply (> %d)", MAXIFSTACK);
483
484         if(pp_flex_debug)
485                 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);
486
487         if_stack[if_stack_idx++] = s;
488
489         switch(s)
490         {
491         case if_true:
492         case if_elsetrue:
493                 break;
494         case if_false:
495         case if_elsefalse:
496         case if_elif:
497         case if_ignore:
498                 pp_push_ignore_state();
499                 break;
500         }
501 }
502
503 pp_if_state_t pp_pop_if(void)
504 {
505         if(if_stack_idx <= 0)
506                 pperror("#{endif,else,elif} without #{if,ifdef,ifndef} (#if-stack underflow)");
507
508         switch(pp_if_state())
509         {
510         case if_true:
511         case if_elsetrue:
512                 break;
513         case if_false:
514         case if_elsefalse:
515         case if_elif:
516         case if_ignore:
517                 pp_pop_ignore_state();
518                 break;
519         }
520
521         if(pp_flex_debug)
522                 fprintf(stderr, "Pop if %s:%d: %s(%d) -> %s(%d)\n",
523                                 pp_status.input,
524                                 pp_status.line_number,
525                                 pp_if_state_str[pp_if_state()],
526                                 if_stack_idx,
527                                 pp_if_state_str[if_stack[if_stack_idx <= 1 ? if_true : if_stack_idx-2]],
528                                 if_stack_idx-1);
529
530         return if_stack[--if_stack_idx];
531 }
532
533 pp_if_state_t pp_if_state(void)
534 {
535         if(!if_stack_idx)
536                 return if_true;
537         else
538                 return if_stack[if_stack_idx-1];
539 }
540
541
542 void pp_next_if_state(int i)
543 {
544         switch(pp_if_state())
545         {
546         case if_true:
547         case if_elsetrue:
548                 pp_push_if(i ? if_true : if_false);
549                 break;
550         case if_false:
551         case if_elsefalse:
552         case if_elif:
553         case if_ignore:
554                 pp_push_if(if_ignore);
555                 break;
556         default:
557                 pp_internal_error(__FILE__, __LINE__, "Invalid pp_if_state (%d) in #{if,ifdef,ifndef} directive", (int)pp_if_state());
558         }
559 }
560
561 int pp_get_if_depth(void)
562 {
563         return if_stack_idx;
564 }
565
566 /* #define WANT_NEAR_INDICATION */
567
568 static void generic_msg(const char *s, const char *t, const char *n, va_list ap)
569 {
570         fprintf(stderr, "%s:%d:%d: %s: ", pp_status.input ? pp_status.input : "stdin",
571                 pp_status.line_number, pp_status.char_number, t);
572         vfprintf(stderr, s, ap);
573 #ifdef WANT_NEAR_INDICATION
574         {
575                 char *cpy, *p;
576                 if(n)
577                 {
578                         cpy = pp_xstrdup(n);
579                         for (p = cpy; *p; p++) if(!isprint(*p)) *p = ' ';
580                         fprintf(stderr, " near '%s'", cpy);
581                         free(cpy);
582                 }
583         }
584 #endif
585         fprintf(stderr, "\n");
586 }
587
588 int pperror(const char *s, ...)
589 {
590         va_list ap;
591         va_start(ap, s);
592         generic_msg(s, "Error", pptext, ap);
593         va_end(ap);
594         exit(1);
595         return 1;
596 }
597
598 int ppwarning(const char *s, ...)
599 {
600         va_list ap;
601         va_start(ap, s);
602         generic_msg(s, "Warning", pptext, ap);
603         va_end(ap);
604         return 0;
605 }
606
607 void pp_internal_error(const char *file, int line, const char *s, ...)
608 {
609         va_list ap;
610         va_start(ap, s);
611         fprintf(stderr, "Internal error (please report) %s %d: ", file, line);
612         vfprintf(stderr, s, ap);
613         fprintf(stderr, "\n");
614         va_end(ap);
615         exit(3);
616 }