preproc.c 14.1 KB
Newer Older
Alexandre Julliard's avatar
Alexandre Julliard committed
1 2 3
/*
 * Copyright 1998 Bertho A. Stultiens (BS)
 *
4 5 6 7 8 9 10 11 12 13 14 15 16
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
Alexandre Julliard's avatar
Alexandre Julliard committed
17 18
 */

19
#include "config.h"
Jon Griffiths's avatar
Jon Griffiths committed
20
#include "wine/port.h"
21

22 23
#include <assert.h>
#include <fcntl.h>
Alexandre Julliard's avatar
Alexandre Julliard committed
24 25 26
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
27
#include <stdarg.h>
28 29 30
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
Alexandre Julliard's avatar
Alexandre Julliard committed
31

32
#include "wpp_private.h"
Alexandre Julliard's avatar
Alexandre Julliard committed
33

34
struct pp_status pp_status;
Alexandre Julliard's avatar
Alexandre Julliard committed
35 36

#define HASHKEY		2039
37 38 39 40 41 42 43 44

typedef struct pp_def_state
{
    struct pp_def_state *next;
    pp_entry_t          *defines[HASHKEY];
} pp_def_state_t;

static pp_def_state_t *pp_def_state;
Alexandre Julliard's avatar
Alexandre Julliard committed
45 46

#define MAXIFSTACK	64
47
static pp_if_state_t if_stack[MAXIFSTACK];
48
static int if_stack_idx = 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
49 50

#if 0
51 52
void pp_print_status(void) __attribute__((destructor));
void pp_print_status(void)
Alexandre Julliard's avatar
Alexandre Julliard committed
53 54 55 56
{
	int i;
	int sum;
	int total = 0;
57
	pp_entry_t *ppp;
Alexandre Julliard's avatar
Alexandre Julliard committed
58

59
	fprintf(stderr, "Defines statistics:\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
60 61 62
	for(i = 0; i < HASHKEY; i++)
	{
		sum = 0;
63
		for(ppp = pp_def_state->defines[i]; ppp; ppp = ppp->next)
Alexandre Julliard's avatar
Alexandre Julliard committed
64 65
			sum++;
		total += sum;
66
		if (sum) fprintf(stderr, "%4d, %3d\n", i, sum);
Alexandre Julliard's avatar
Alexandre Julliard committed
67
	}
68
	fprintf(stderr, "Total defines: %d\n", total);
Alexandre Julliard's avatar
Alexandre Julliard committed
69 70 71
}
#endif

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
void *pp_xmalloc(size_t size)
{
    void *res;

    assert(size > 0);
    res = malloc(size);
    if(res == NULL)
    {
        fprintf(stderr, "Virtual memory exhausted.\n");
        exit(2);
    }
    return res;
}

void *pp_xrealloc(void *p, size_t size)
{
    void *res;

    assert(size > 0);
    res = realloc(p, size);
    if(res == NULL)
    {
        fprintf(stderr, "Virtual memory exhausted.\n");
        exit(2);
    }
    return res;
}

char *pp_xstrdup(const char *str)
{
	char *s;

	assert(str != NULL);
	s = pp_xmalloc(strlen(str)+1);
	return strcpy(s, str);
}

Alexandre Julliard's avatar
Alexandre Julliard committed
109
/* Don't comment on the hash, its primitive but functional... */
110
static int pphash(const char *str)
Alexandre Julliard's avatar
Alexandre Julliard committed
111 112 113 114 115 116 117
{
	int sum = 0;
	while(*str)
		sum += *str++;
	return sum % HASHKEY;
}

118
pp_entry_t *pplookup(const char *ident)
Alexandre Julliard's avatar
Alexandre Julliard committed
119
{
120 121 122
	int idx = pphash(ident);
	pp_entry_t *ppp;

123
	for(ppp = pp_def_state->defines[idx]; ppp; ppp = ppp->next)
Alexandre Julliard's avatar
Alexandre Julliard committed
124 125 126 127 128 129 130
	{
		if(!strcmp(ident, ppp->ident))
			return ppp;
	}
	return NULL;
}

131
static void free_pp_entry( pp_entry_t *ppp, int idx )
Alexandre Julliard's avatar
Alexandre Julliard committed
132
{
133
	if(ppp->iep)
Alexandre Julliard's avatar
Alexandre Julliard committed
134
	{
135
		if(ppp->iep == pp_includelogiclist)
136
		{
137 138 139
			pp_includelogiclist = ppp->iep->next;
			if(pp_includelogiclist)
				pp_includelogiclist->prev = NULL;
140 141 142 143 144 145 146 147 148 149 150
		}
		else
		{
			ppp->iep->prev->next = ppp->iep->next;
			if(ppp->iep->next)
				ppp->iep->next->prev = ppp->iep->prev;
		}
		free(ppp->iep->filename);
		free(ppp->iep);
	}

151
	if(pp_def_state->defines[idx] == ppp)
152
	{
153 154 155
		pp_def_state->defines[idx] = ppp->next;
		if(pp_def_state->defines[idx])
			pp_def_state->defines[idx]->prev = NULL;
Alexandre Julliard's avatar
Alexandre Julliard committed
156 157 158 159 160 161 162
	}
	else
	{
		ppp->prev->next = ppp->next;
		if(ppp->next)
			ppp->next->prev = ppp->prev;
	}
163

Alexandre Julliard's avatar
Alexandre Julliard committed
164
	free(ppp);
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
}

/* push a new (empty) define state */
void pp_push_define_state(void)
{
    pp_def_state_t *state = pp_xmalloc( sizeof(*state) );

    memset( state->defines, 0, sizeof(state->defines) );
    state->next = pp_def_state;
    pp_def_state = state;
}

/* pop the current define state */
void pp_pop_define_state(void)
{
    int i;
    pp_entry_t *ppp;
    pp_def_state_t *state;

    for (i = 0; i < HASHKEY; i++)
    {
        while ((ppp = pp_def_state->defines[i]) != NULL) free_pp_entry( ppp, i );
    }
    state = pp_def_state;
    pp_def_state = state->next;
    free( state );
}

void pp_del_define(const char *name)
{
	pp_entry_t *ppp;

	if((ppp = pplookup(name)) == NULL)
	{
		if(pp_status.pedantic)
			ppwarning("%s was not defined", name);
		return;
	}

	free_pp_entry( ppp, pphash(name) );
205

206 207
	if(pp_status.debug)
		printf("Deleted (%s, %d) <%s>\n", pp_status.input, pp_status.line_number, name);
Alexandre Julliard's avatar
Alexandre Julliard committed
208 209
}

210
pp_entry_t *pp_add_define(char *def, char *text)
Alexandre Julliard's avatar
Alexandre Julliard committed
211 212 213
{
	int len;
	char *cptr;
214 215 216 217
	int idx = pphash(def);
	pp_entry_t *ppp;

	if((ppp = pplookup(def)) != NULL)
Alexandre Julliard's avatar
Alexandre Julliard committed
218
	{
219 220 221
		if(pp_status.pedantic)
			ppwarning("Redefinition of %s\n\tPrevious definition: %s:%d", def, ppp->filename, ppp->linenumber);
		pp_del_define(def);
Alexandre Julliard's avatar
Alexandre Julliard committed
222
	}
223 224
	ppp = pp_xmalloc(sizeof(pp_entry_t));
	memset( ppp, 0, sizeof(*ppp) );
225 226 227
	ppp->ident = def;
	ppp->type = def_define;
	ppp->subst.text = text;
228 229
	ppp->filename = pp_status.input ? pp_xstrdup(pp_status.input) : "<internal or cmdline>";
	ppp->linenumber = pp_status.input ? pp_status.line_number : 0;
230 231
	ppp->next = pp_def_state->defines[idx];
	pp_def_state->defines[idx] = ppp;
Alexandre Julliard's avatar
Alexandre Julliard committed
232 233
	if(ppp->next)
		ppp->next->prev = ppp;
234
	if(text)
Alexandre Julliard's avatar
Alexandre Julliard committed
235
	{
236 237 238 239 240 241 242 243
		/* Strip trailing white space from subst text */
		len = strlen(text);
		while(len && strchr(" \t\r\n", text[len-1]))
		{
			text[--len] = '\0';
		}
		/* Strip leading white space from subst text */
		for(cptr = text; *cptr && strchr(" \t\r", *cptr); cptr++)
Alexandre Julliard's avatar
Alexandre Julliard committed
244
		;
245 246 247
		if(text != cptr)
			memmove(text, cptr, strlen(cptr)+1);
	}
248 249
	if(pp_status.debug)
		printf("Added define (%s, %d) <%s> to <%s>\n", pp_status.input, pp_status.line_number, ppp->ident, text ? text : "(null)");
250 251 252 253

	return ppp;
}

254
pp_entry_t *pp_add_macro(char *id, marg_t *args[], int nargs, mtext_t *exp)
255 256 257 258 259 260
{
	int idx = pphash(id);
	pp_entry_t *ppp;

	if((ppp = pplookup(id)) != NULL)
	{
261 262 263
		if(pp_status.pedantic)
			ppwarning("Redefinition of %s\n\tPrevious definition: %s:%d", id, ppp->filename, ppp->linenumber);
		pp_del_define(id);
264
	}
265 266
	ppp = pp_xmalloc(sizeof(pp_entry_t));
	memset( ppp, 0, sizeof(*ppp) );
267 268 269 270 271
	ppp->ident	= id;
	ppp->type	= def_macro;
	ppp->margs	= args;
	ppp->nargs	= nargs;
	ppp->subst.mtext= exp;
272 273
	ppp->filename = pp_status.input ? pp_xstrdup(pp_status.input) : "<internal or cmdline>";
	ppp->linenumber = pp_status.input ? pp_status.line_number : 0;
274 275
	ppp->next	= pp_def_state->defines[idx];
	pp_def_state->defines[idx] = ppp;
276 277 278
	if(ppp->next)
		ppp->next->prev = ppp;

279
	if(pp_status.debug)
280
	{
281
		fprintf(stderr, "Added macro (%s, %d) <%s(%d)> to <", pp_status.input, pp_status.line_number, ppp->ident, nargs);
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
		for(; exp; exp = exp->next)
		{
			switch(exp->type)
			{
			case exp_text:
				fprintf(stderr, " \"%s\" ", exp->subst.text);
				break;
			case exp_stringize:
				fprintf(stderr, " #(%d) ", exp->subst.argidx);
				break;
			case exp_concat:
				fprintf(stderr, "##");
				break;
			case exp_subst:
				fprintf(stderr, " <%d> ", exp->subst.argidx);
				break;
			}
		}
		fprintf(stderr, ">\n");
	}
	return ppp;
Alexandre Julliard's avatar
Alexandre Julliard committed
303 304
}

305 306 307 308 309 310

/*
 *-------------------------------------------------------------------------
 * Include management
 *-------------------------------------------------------------------------
 */
Alexandre Julliard's avatar
Alexandre Julliard committed
311 312 313 314 315 316 317 318 319
#if defined(_Windows) || defined(__MSDOS__)
#define INCLUDESEPARATOR	";"
#else
#define INCLUDESEPARATOR	":"
#endif

static char **includepath;
static int nincludepath = 0;

320
void wpp_add_include_path(const char *path)
Alexandre Julliard's avatar
Alexandre Julliard committed
321 322
{
	char *tok;
323
	char *cpy = pp_xstrdup(path);
Alexandre Julliard's avatar
Alexandre Julliard committed
324 325 326 327 328 329 330 331

	tok = strtok(cpy, INCLUDESEPARATOR);
	while(tok)
	{
		char *dir;
		char *cptr;
		if(strlen(tok) == 0)
			continue;
332
		dir = pp_xstrdup(tok);
Alexandre Julliard's avatar
Alexandre Julliard committed
333 334 335 336 337 338 339 340 341 342 343 344
		for(cptr = dir; *cptr; cptr++)
		{
			/* Convert to forward slash */
			if(*cptr == '\\')
				*cptr = '/';
		}
		/* Kill eventual trailing '/' */
		if(*(cptr = dir + strlen(dir)-1) == '/')
			*cptr = '\0';

		/* Add to list */
		nincludepath++;
345
		includepath = pp_xrealloc(includepath, nincludepath * sizeof(*includepath));
Alexandre Julliard's avatar
Alexandre Julliard committed
346 347 348 349 350 351
		includepath[nincludepath-1] = dir;
		tok = strtok(NULL, INCLUDESEPARATOR);
	}
	free(cpy);
}

352
char *wpp_find_include(const char *name, int search)
Alexandre Julliard's avatar
Alexandre Julliard committed
353
{
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    char *cpy = pp_xstrdup(name);
    char *cptr;
    int i, fd;

    for(cptr = cpy; *cptr; cptr++)
    {
        /* kill double backslash */
        if(*cptr == '\\' && *(cptr+1) == '\\')
            memmove(cptr, cptr+1, strlen(cptr));
        /* Convert to forward slash */
        if(*cptr == '\\')
            *cptr = '/';
    }

    if(search)
    {
        /* Search current dir and then -I path */
        fd = open( cpy, O_RDONLY );
        if (fd != -1)
        {
            close( fd );
            return cpy;
        }
    }
    /* Search -I path */
    for(i = 0; i < nincludepath; i++)
    {
        char *path;
        path = pp_xmalloc(strlen(includepath[i]) + strlen(cpy) + 2);
        strcpy(path, includepath[i]);
        strcat(path, "/");
        strcat(path, cpy);
        fd = open( path, O_RDONLY );
        if (fd != -1)
        {
            close( fd );
            free( cpy );
            return path;
        }
        free( path );
    }
    free( cpy );
    return NULL;
}
Alexandre Julliard's avatar
Alexandre Julliard committed
398

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
FILE *pp_open_include(const char *name, int search, char **newpath)
{
    char *path;
    FILE *fp;

    if (!(path = wpp_find_include( name, search ))) return NULL;
    fp = fopen(path, "rt");

    if (fp)
    {
        if (pp_status.debug)
            printf("Going to include <%s>\n", path);
        if (newpath) *newpath = path;
        else free( path );
        return fp;
    }
    free( path );
    return NULL;
Alexandre Julliard's avatar
Alexandre Julliard committed
417 418
}

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
/*
 *-------------------------------------------------------------------------
 * #if, #ifdef, #ifndef, #else, #elif and #endif state management
 *
 * #if state transitions are made on basis of the current TOS and the next
 * required state. The state transitions are required to housekeep because
 * #if:s can be nested. The ignore case is activated to prevent output from
 * within a false clause.
 * Some special cases come from the fact that the #elif cases are not
 * binary, but three-state. The problem is that all other elif-cases must
 * be false when one true one has been found. A second problem is that the
 * #else clause is a final clause. No extra #else:s may follow.
 *
 * The states mean:
 * if_true	Process input to output
 * if_false	Process input but no output
 * if_ignore	Process input but no output
 * if_elif	Process input but no output
 * if_elsefalse	Process input but no output
 * if_elsettrue	Process input to output
 *
 * The possible state-sequences are [state(stack depth)] (rest can be deduced):
 *	TOS		#if 1		#else			#endif
 *	if_true(n)	if_true(n+1)	if_elsefalse(n+1)
 *	if_false(n)	if_ignore(n+1)	if_ignore(n+1)
 *	if_elsetrue(n)	if_true(n+1)	if_elsefalse(n+1)
 *	if_elsefalse(n)	if_ignore(n+1)	if_ignore(n+1)
 *	if_elif(n)	if_ignore(n+1)	if_ignore(n+1)
 *	if_ignore(n)	if_ignore(n+1)	if_ignore(n+1)
 *
 *	TOS		#if 1		#elif 0		#else		#endif
 *	if_true(n)	if_true(n+1)	if_elif(n+1)	if_elif(n+1)
 *	if_false(n)	if_ignore(n+1)	if_ignore(n+1)	if_ignore(n+1)
 *	if_elsetrue(n)	if_true(n+1)	if_elif(n+1)	if_elif(n+1)
 *	if_elsefalse(n)	if_ignore(n+1)	if_ignore(n+1)	if_ignore(n+1)
 *	if_elif(n)	if_ignore(n+1)	if_ignore(n+1)	if_ignore(n+1)
 *	if_ignore(n)	if_ignore(n+1)	if_ignore(n+1)	if_ignore(n+1)
 *
 *	TOS		#if 0		#elif 1		#else		#endif
 *	if_true(n)	if_false(n+1)	if_true(n+1)	if_elsefalse(n+1)
 *	if_false(n)	if_ignore(n+1)	if_ignore(n+1)	if_ignore(n+1)
 *	if_elsetrue(n)	if_false(n+1)	if_true(n+1)	if_elsefalse(n+1)
 *	if_elsefalse(n)	if_ignore(n+1)	if_ignore(n+1)	if_ignore(n+1)
 *	if_elif(n)	if_ignore(n+1)	if_ignore(n+1)	if_ignore(n+1)
 *	if_ignore(n)	if_ignore(n+1)	if_ignore(n+1)	if_ignore(n+1)
 *
 *-------------------------------------------------------------------------
 */
467
static char *pp_if_state_str[] = {
468 469 470 471 472 473 474 475
	"if_false",
	"if_true",
	"if_elif",
	"if_elsefalse",
	"if_elsetrue",
	"if_ignore"
};

476
void pp_push_if(pp_if_state_t s)
Alexandre Julliard's avatar
Alexandre Julliard committed
477
{
478
	if(if_stack_idx >= MAXIFSTACK)
479
		pp_internal_error(__FILE__, __LINE__, "#if-stack overflow; #{if,ifdef,ifndef} nested too deeply (> %d)", MAXIFSTACK);
480

481 482
	if(pp_flex_debug)
		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);
483 484 485 486 487 488 489 490 491 492 493 494

	if_stack[if_stack_idx++] = s;

	switch(s)
	{
	case if_true:
	case if_elsetrue:
		break;
	case if_false:
	case if_elsefalse:
	case if_elif:
	case if_ignore:
495
		pp_push_ignore_state();
496 497 498 499
		break;
	}
}

500
pp_if_state_t pp_pop_if(void)
501 502
{
	if(if_stack_idx <= 0)
503
		pperror("#{endif,else,elif} without #{if,ifdef,ifndef} (#if-stack underflow)");
504

505
	switch(pp_if_state())
506 507 508 509 510 511 512 513
	{
	case if_true:
	case if_elsetrue:
		break;
	case if_false:
	case if_elsefalse:
	case if_elif:
	case if_ignore:
514
		pp_pop_ignore_state();
515 516 517
		break;
	}

518
	if(pp_flex_debug)
519
		fprintf(stderr, "Pop if %s:%d: %s(%d) -> %s(%d)\n",
520 521 522
				pp_status.input,
				pp_status.line_number,
				pp_if_state_str[pp_if_state()],
523
				if_stack_idx,
524
				pp_if_state_str[if_stack[if_stack_idx <= 1 ? if_true : if_stack_idx-2]],
525 526 527
				if_stack_idx-1);

	return if_stack[--if_stack_idx];
Alexandre Julliard's avatar
Alexandre Julliard committed
528 529
}

530
pp_if_state_t pp_if_state(void)
Alexandre Julliard's avatar
Alexandre Julliard committed
531
{
532 533 534 535 536 537 538
	if(!if_stack_idx)
		return if_true;
	else
		return if_stack[if_stack_idx-1];
}


539
void pp_next_if_state(int i)
540
{
541
	switch(pp_if_state())
542 543 544
	{
	case if_true:
	case if_elsetrue:
545
		pp_push_if(i ? if_true : if_false);
546 547 548 549 550
		break;
	case if_false:
	case if_elsefalse:
	case if_elif:
	case if_ignore:
551
		pp_push_if(if_ignore);
552 553
		break;
	default:
554
		pp_internal_error(__FILE__, __LINE__, "Invalid pp_if_state (%d) in #{if,ifdef,ifndef} directive", (int)pp_if_state());
555
	}
Alexandre Julliard's avatar
Alexandre Julliard committed
556 557
}

558
int pp_get_if_depth(void)
Alexandre Julliard's avatar
Alexandre Julliard committed
559
{
560
	return if_stack_idx;
Alexandre Julliard's avatar
Alexandre Julliard committed
561 562
}

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
/* #define WANT_NEAR_INDICATION */

static void generic_msg(const char *s, const char *t, const char *n, va_list ap)
{
	fprintf(stderr, "%s:%d:%d: %s: ", pp_status.input ? pp_status.input : "stdin",
                pp_status.line_number, pp_status.char_number, t);
	vfprintf(stderr, s, ap);
#ifdef WANT_NEAR_INDICATION
	{
		char *cpy, *p;
		if(n)
		{
			cpy = pp_xstrdup(n);
			for (p = cpy; *p; p++) if(!isprint(*p)) *p = ' ';
			fprintf(stderr, " near '%s'", cpy);
			free(cpy);
		}
	}
#endif
	fprintf(stderr, "\n");
}

int pperror(const char *s, ...)
{
	va_list ap;
	va_start(ap, s);
	generic_msg(s, "Error", pptext, ap);
	va_end(ap);
	exit(1);
	return 1;
}

int ppwarning(const char *s, ...)
{
	va_list ap;
	va_start(ap, s);
	generic_msg(s, "Warning", pptext, ap);
	va_end(ap);
	return 0;
}

void pp_internal_error(const char *file, int line, const char *s, ...)
{
	va_list ap;
	va_start(ap, s);
	fprintf(stderr, "Internal error (please report) %s %d: ", file, line);
	vfprintf(stderr, s, ap);
	fprintf(stderr, "\n");
	va_end(ap);
	exit(3);
}