If we don't specify -g, actually suppress debugging output
[nasm.git] / preproc.c
bloba4928aee0df923d917a5a2bf3baf721b316aa5da
1 /* -*- mode: c; c-file-style: "bsd" -*- */
2 /* preproc.c macro preprocessor for the Netwide Assembler
4 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
5 * Julian Hall. All rights reserved. The software is
6 * redistributable under the licence given in the file "Licence"
7 * distributed in the NASM archive.
9 * initial version 18/iii/97 by Simon Tatham
12 /* Typical flow of text through preproc
14 * pp_getline gets tokenised lines, either
16 * from a macro expansion
18 * or
19 * {
20 * read_line gets raw text from stdmacpos, or predef, or current input file
21 * tokenise converts to tokens
22 * }
24 * expand_mmac_params is used to expand %1 etc., unless a macro is being
25 * defined or a false conditional is being processed
26 * (%0, %1, %+1, %-1, %%foo
28 * do_directive checks for directives
30 * expand_smacro is used to expand single line macros
32 * expand_mmacro is used to expand multi-line macros
34 * detoken is used to convert the line back to text
37 #include <stdio.h>
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <stddef.h>
41 #include <string.h>
42 #include <ctype.h>
43 #include <limits.h>
45 #include "nasm.h"
46 #include "nasmlib.h"
48 typedef struct SMacro SMacro;
49 typedef struct MMacro MMacro;
50 typedef struct Context Context;
51 typedef struct Token Token;
52 typedef struct Blocks Blocks;
53 typedef struct Line Line;
54 typedef struct Include Include;
55 typedef struct Cond Cond;
56 typedef struct IncPath IncPath;
59 * Store the definition of a single-line macro.
61 struct SMacro
63 SMacro *next;
64 char *name;
65 int casesense;
66 int nparam;
67 int in_progress;
68 Token *expansion;
72 * Store the definition of a multi-line macro. This is also used to
73 * store the interiors of `%rep...%endrep' blocks, which are
74 * effectively self-re-invoking multi-line macros which simply
75 * don't have a name or bother to appear in the hash tables. %rep
76 * blocks are signified by having a NULL `name' field.
78 * In a MMacro describing a `%rep' block, the `in_progress' field
79 * isn't merely boolean, but gives the number of repeats left to
80 * run.
82 * The `next' field is used for storing MMacros in hash tables; the
83 * `next_active' field is for stacking them on istk entries.
85 * When a MMacro is being expanded, `params', `iline', `nparam',
86 * `paramlen', `rotate' and `unique' are local to the invocation.
88 struct MMacro
90 MMacro *next;
91 char *name;
92 int casesense;
93 int nparam_min, nparam_max;
94 int plus; /* is the last parameter greedy? */
95 int nolist; /* is this macro listing-inhibited? */
96 int in_progress;
97 Token *dlist; /* All defaults as one list */
98 Token **defaults; /* Parameter default pointers */
99 int ndefs; /* number of default parameters */
100 Line *expansion;
102 MMacro *next_active;
103 MMacro *rep_nest; /* used for nesting %rep */
104 Token **params; /* actual parameters */
105 Token *iline; /* invocation line */
106 int nparam, rotate, *paramlen;
107 unsigned long unique;
108 int lineno; /* Current line number on expansion */
112 * The context stack is composed of a linked list of these.
114 struct Context
116 Context *next;
117 SMacro *localmac;
118 char *name;
119 unsigned long number;
123 * This is the internal form which we break input lines up into.
124 * Typically stored in linked lists.
126 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
127 * necessarily used as-is, but is intended to denote the number of
128 * the substituted parameter. So in the definition
130 * %define a(x,y) ( (x) & ~(y) )
132 * the token representing `x' will have its type changed to
133 * TOK_SMAC_PARAM, but the one representing `y' will be
134 * TOK_SMAC_PARAM+1.
136 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
137 * which doesn't need quotes around it. Used in the pre-include
138 * mechanism as an alternative to trying to find a sensible type of
139 * quote to use on the filename we were passed.
141 struct Token
143 Token *next;
144 char *text;
145 SMacro *mac; /* associated macro for TOK_SMAC_END */
146 int type;
148 enum
150 TOK_WHITESPACE = 1, TOK_COMMENT, TOK_ID, TOK_PREPROC_ID, TOK_STRING,
151 TOK_NUMBER, TOK_SMAC_END, TOK_OTHER, TOK_SMAC_PARAM,
152 TOK_INTERNAL_STRING
156 * Multi-line macro definitions are stored as a linked list of
157 * these, which is essentially a container to allow several linked
158 * lists of Tokens.
160 * Note that in this module, linked lists are treated as stacks
161 * wherever possible. For this reason, Lines are _pushed_ on to the
162 * `expansion' field in MMacro structures, so that the linked list,
163 * if walked, would give the macro lines in reverse order; this
164 * means that we can walk the list when expanding a macro, and thus
165 * push the lines on to the `expansion' field in _istk_ in reverse
166 * order (so that when popped back off they are in the right
167 * order). It may seem cockeyed, and it relies on my design having
168 * an even number of steps in, but it works...
170 * Some of these structures, rather than being actual lines, are
171 * markers delimiting the end of the expansion of a given macro.
172 * This is for use in the cycle-tracking and %rep-handling code.
173 * Such structures have `finishes' non-NULL, and `first' NULL. All
174 * others have `finishes' NULL, but `first' may still be NULL if
175 * the line is blank.
177 struct Line
179 Line *next;
180 MMacro *finishes;
181 Token *first;
185 * To handle an arbitrary level of file inclusion, we maintain a
186 * stack (ie linked list) of these things.
188 struct Include
190 Include *next;
191 FILE *fp;
192 Cond *conds;
193 Line *expansion;
194 char *fname;
195 int lineno, lineinc;
196 MMacro *mstk; /* stack of active macros/reps */
200 * Include search path. This is simply a list of strings which get
201 * prepended, in turn, to the name of an include file, in an
202 * attempt to find the file if it's not in the current directory.
204 struct IncPath
206 IncPath *next;
207 char *path;
211 * Conditional assembly: we maintain a separate stack of these for
212 * each level of file inclusion. (The only reason we keep the
213 * stacks separate is to ensure that a stray `%endif' in a file
214 * included from within the true branch of a `%if' won't terminate
215 * it and cause confusion: instead, rightly, it'll cause an error.)
217 struct Cond
219 Cond *next;
220 int state;
222 enum
225 * These states are for use just after %if or %elif: IF_TRUE
226 * means the condition has evaluated to truth so we are
227 * currently emitting, whereas IF_FALSE means we are not
228 * currently emitting but will start doing so if a %else comes
229 * up. In these states, all directives are admissible: %elif,
230 * %else and %endif. (And of course %if.)
232 COND_IF_TRUE, COND_IF_FALSE,
234 * These states come up after a %else: ELSE_TRUE means we're
235 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
236 * any %elif or %else will cause an error.
238 COND_ELSE_TRUE, COND_ELSE_FALSE,
240 * This state means that we're not emitting now, and also that
241 * nothing until %endif will be emitted at all. It's for use in
242 * two circumstances: (i) when we've had our moment of emission
243 * and have now started seeing %elifs, and (ii) when the
244 * condition construct in question is contained within a
245 * non-emitting branch of a larger condition construct.
247 COND_NEVER
249 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
252 * These defines are used as the possible return values for do_directive
254 #define NO_DIRECTIVE_FOUND 0
255 #define DIRECTIVE_FOUND 1
258 * Condition codes. Note that we use c_ prefix not C_ because C_ is
259 * used in nasm.h for the "real" condition codes. At _this_ level,
260 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
261 * ones, so we need a different enum...
263 static const char *conditions[] = {
264 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
265 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
266 "np", "ns", "nz", "o", "p", "pe", "po", "s", "z"
268 enum
270 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
271 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
272 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_S, c_Z
274 static int inverse_ccs[] = {
275 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
276 c_A, c_AE, c_B, c_BE, c_C, c_E, c_G, c_GE, c_L, c_LE, c_O, c_P, c_S,
277 c_Z, c_NO, c_NP, c_PO, c_PE, c_NS, c_NZ
281 * Directive names.
283 static const char *directives[] = {
284 "%arg",
285 "%assign", "%clear", "%define", "%elif", "%elifctx", "%elifdef",
286 "%elifid", "%elifidn", "%elifidni", "%elifmacro", "%elifnctx", "%elifndef",
287 "%elifnid", "%elifnidn", "%elifnidni", "%elifnmacro", "%elifnnum", "%elifnstr",
288 "%elifnum", "%elifstr", "%else", "%endif", "%endm", "%endmacro",
289 "%endrep", "%error", "%exitrep", "%iassign", "%idefine", "%if",
290 "%ifctx", "%ifdef", "%ifid", "%ifidn", "%ifidni", "%ifmacro", "%ifnctx",
291 "%ifndef", "%ifnid", "%ifnidn", "%ifnidni", "%ifnmacro", "%ifnnum",
292 "%ifnstr", "%ifnum", "%ifstr", "%imacro", "%include",
293 "%ixdefine", "%line",
294 "%local",
295 "%macro", "%pop", "%push", "%rep", "%repl", "%rotate",
296 "%stacksize",
297 "%strlen", "%substr", "%undef", "%xdefine"
299 enum
301 PP_ARG,
302 PP_ASSIGN, PP_CLEAR, PP_DEFINE, PP_ELIF, PP_ELIFCTX, PP_ELIFDEF,
303 PP_ELIFID, PP_ELIFIDN, PP_ELIFIDNI, PP_ELIFMACRO, PP_ELIFNCTX, PP_ELIFNDEF,
304 PP_ELIFNID, PP_ELIFNIDN, PP_ELIFNIDNI, PP_ELIFNMACRO, PP_ELIFNNUM, PP_ELIFNSTR,
305 PP_ELIFNUM, PP_ELIFSTR, PP_ELSE, PP_ENDIF, PP_ENDM, PP_ENDMACRO,
306 PP_ENDREP, PP_ERROR, PP_EXITREP, PP_IASSIGN, PP_IDEFINE, PP_IF,
307 PP_IFCTX, PP_IFDEF, PP_IFID, PP_IFIDN, PP_IFIDNI, PP_IFMACRO, PP_IFNCTX,
308 PP_IFNDEF, PP_IFNID, PP_IFNIDN, PP_IFNIDNI, PP_IFNMACRO, PP_IFNNUM,
309 PP_IFNSTR, PP_IFNUM, PP_IFSTR, PP_IMACRO, PP_INCLUDE,
310 PP_IXDEFINE, PP_LINE,
311 PP_LOCAL,
312 PP_MACRO, PP_POP, PP_PUSH, PP_REP, PP_REPL, PP_ROTATE,
313 PP_STACKSIZE,
314 PP_STRLEN, PP_SUBSTR, PP_UNDEF, PP_XDEFINE
317 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
318 static int is_condition(int arg)
320 return ((arg >= PP_ELIF) && (arg <= PP_ENDIF)) ||
321 ((arg >= PP_IF) && (arg <= PP_IFSTR));
324 /* For TASM compatibility we need to be able to recognise TASM compatible
325 * conditional compilation directives. Using the NASM pre-processor does
326 * not work, so we look for them specifically from the following list and
327 * then jam in the equivalent NASM directive into the input stream.
330 #ifndef MAX
331 # define MAX(a,b) ( ((a) > (b)) ? (a) : (b))
332 #endif
334 enum
336 TM_ARG, TM_ELIF, TM_ELSE, TM_ENDIF, TM_IF, TM_IFDEF, TM_IFDIFI,
337 TM_IFNDEF, TM_INCLUDE, TM_LOCAL
340 static const char *tasm_directives[] = {
341 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
342 "ifndef", "include", "local"
345 static int StackSize = 4;
346 static char *StackPointer = "ebp";
347 static int ArgOffset = 8;
348 static int LocalOffset = 4;
351 static Context *cstk;
352 static Include *istk;
353 static IncPath *ipath = NULL;
355 static efunc _error; /* Pointer to client-provided error reporting function */
356 static evalfunc evaluate;
358 static int pass; /* HACK: pass 0 = generate dependencies only */
360 static unsigned long unique; /* unique identifier numbers */
362 static Line *predef = NULL;
364 static ListGen *list;
367 * The number of hash values we use for the macro lookup tables.
368 * FIXME: We should *really* be able to configure this at run time,
369 * or even have the hash table automatically expanding when necessary.
371 #define NHASH 31
374 * The current set of multi-line macros we have defined.
376 static MMacro *mmacros[NHASH];
379 * The current set of single-line macros we have defined.
381 static SMacro *smacros[NHASH];
384 * The multi-line macro we are currently defining, or the %rep
385 * block we are currently reading, if any.
387 static MMacro *defining;
390 * The number of macro parameters to allocate space for at a time.
392 #define PARAM_DELTA 16
395 * The standard macro set: defined as `static char *stdmac[]'. Also
396 * gives our position in the macro set, when we're processing it.
398 #include "macros.c"
399 static const char **stdmacpos;
402 * The extra standard macros that come from the object format, if
403 * any.
405 static const char **extrastdmac = NULL;
406 int any_extrastdmac;
409 * Tokens are allocated in blocks to improve speed
411 #define TOKEN_BLOCKSIZE 4096
412 static Token *freeTokens = NULL;
413 struct Blocks {
414 Blocks *next;
415 void *chunk;
418 static Blocks blocks = { NULL, NULL };
421 * Forward declarations.
423 static Token *expand_mmac_params(Token * tline);
424 static Token *expand_smacro(Token * tline);
425 static Token *expand_id(Token * tline);
426 static Context *get_ctx(char *name, int all_contexts);
427 static void make_tok_num(Token * tok, long val);
428 static void error(int severity, const char *fmt, ...);
429 static void *new_Block(size_t size);
430 static void delete_Blocks(void);
431 static Token *new_Token(Token * next, int type, char *text, int txtlen);
432 static Token *delete_Token(Token * t);
435 * Macros for safe checking of token pointers, avoid *(NULL)
437 #define tok_type_(x,t) ((x) && (x)->type == (t))
438 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
439 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
440 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
442 /* Handle TASM specific directives, which do not contain a % in
443 * front of them. We do it here because I could not find any other
444 * place to do it for the moment, and it is a hack (ideally it would
445 * be nice to be able to use the NASM pre-processor to do it).
447 static char *
448 check_tasm_directive(char *line)
450 int i, j, k, m, len;
451 char *p = line, *oldline, oldchar;
453 /* Skip whitespace */
454 while (isspace(*p) && *p != 0)
455 p++;
457 /* Binary search for the directive name */
458 i = -1;
459 j = elements(tasm_directives);
460 len = 0;
461 while (!isspace(p[len]) && p[len] != 0)
462 len++;
463 if (len)
465 oldchar = p[len];
466 p[len] = 0;
467 while (j - i > 1)
469 k = (j + i) / 2;
470 m = nasm_stricmp(p, tasm_directives[k]);
471 if (m == 0)
473 /* We have found a directive, so jam a % in front of it
474 * so that NASM will then recognise it as one if it's own.
476 p[len] = oldchar;
477 len = strlen(p);
478 oldline = line;
479 line = nasm_malloc(len + 2);
480 line[0] = '%';
481 if (k == TM_IFDIFI)
483 /* NASM does not recognise IFDIFI, so we convert it to
484 * %ifdef BOGUS. This is not used in NASM comaptible
485 * code, but does need to parse for the TASM macro
486 * package.
488 strcpy(line + 1, "ifdef BOGUS");
490 else
492 memcpy(line + 1, p, len + 1);
494 nasm_free(oldline);
495 return line;
497 else if (m < 0)
499 j = k;
501 else
502 i = k;
504 p[len] = oldchar;
506 return line;
510 * The pre-preprocessing stage... This function translates line
511 * number indications as they emerge from GNU cpp (`# lineno "file"
512 * flags') into NASM preprocessor line number indications (`%line
513 * lineno file').
515 static char *
516 prepreproc(char *line)
518 int lineno, fnlen;
519 char *fname, *oldline;
521 if (line[0] == '#' && line[1] == ' ')
523 oldline = line;
524 fname = oldline + 2;
525 lineno = atoi(fname);
526 fname += strspn(fname, "0123456789 ");
527 if (*fname == '"')
528 fname++;
529 fnlen = strcspn(fname, "\"");
530 line = nasm_malloc(20 + fnlen);
531 sprintf(line, "%%line %d %.*s", lineno, fnlen, fname);
532 nasm_free(oldline);
534 if (tasm_compatible_mode)
535 return check_tasm_directive(line);
536 return line;
540 * The hash function for macro lookups. Note that due to some
541 * macros having case-insensitive names, the hash function must be
542 * invariant under case changes. We implement this by applying a
543 * perfectly normal hash function to the uppercase of the string.
545 static int
546 hash(char *s)
548 unsigned int h = 0;
549 int i = 0;
551 * Powers of three, mod 31.
553 static const int multipliers[] = {
554 1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10,
555 30, 28, 22, 4, 12, 5, 15, 14, 11, 2, 6, 18, 23, 7, 21
559 while (*s)
561 h += multipliers[i] * (unsigned char) (toupper(*s));
562 s++;
563 if (++i >= elements(multipliers))
564 i = 0;
566 h %= NHASH;
567 return h;
571 * Free a linked list of tokens.
573 static void
574 free_tlist(Token * list)
576 while (list)
578 list = delete_Token(list);
583 * Free a linked list of lines.
585 static void
586 free_llist(Line * list)
588 Line *l;
589 while (list)
591 l = list;
592 list = list->next;
593 free_tlist(l->first);
594 nasm_free(l);
599 * Free an MMacro
601 static void
602 free_mmacro(MMacro * m)
604 nasm_free(m->name);
605 free_tlist(m->dlist);
606 nasm_free(m->defaults);
607 free_llist(m->expansion);
608 nasm_free(m);
612 * Pop the context stack.
614 static void
615 ctx_pop(void)
617 Context *c = cstk;
618 SMacro *smac, *s;
620 cstk = cstk->next;
621 smac = c->localmac;
622 while (smac)
624 s = smac;
625 smac = smac->next;
626 nasm_free(s->name);
627 free_tlist(s->expansion);
628 nasm_free(s);
630 nasm_free(c->name);
631 nasm_free(c);
634 #define BUF_DELTA 512
636 * Read a line from the top file in istk, handling multiple CR/LFs
637 * at the end of the line read, and handling spurious ^Zs. Will
638 * return lines from the standard macro set if this has not already
639 * been done.
641 static char *
642 read_line(void)
644 char *buffer, *p, *q;
645 int bufsize, continued_count;
647 if (stdmacpos)
649 if (*stdmacpos)
651 char *ret = nasm_strdup(*stdmacpos++);
652 if (!*stdmacpos && any_extrastdmac)
654 stdmacpos = extrastdmac;
655 any_extrastdmac = FALSE;
656 return ret;
659 * Nasty hack: here we push the contents of `predef' on
660 * to the top-level expansion stack, since this is the
661 * most convenient way to implement the pre-include and
662 * pre-define features.
664 if (!*stdmacpos)
666 Line *pd, *l;
667 Token *head, **tail, *t;
669 for (pd = predef; pd; pd = pd->next)
671 head = NULL;
672 tail = &head;
673 for (t = pd->first; t; t = t->next)
675 *tail = new_Token(NULL, t->type, t->text, 0);
676 tail = &(*tail)->next;
678 l = nasm_malloc(sizeof(Line));
679 l->next = istk->expansion;
680 l->first = head;
681 l->finishes = FALSE;
682 istk->expansion = l;
685 return ret;
687 else
689 stdmacpos = NULL;
693 bufsize = BUF_DELTA;
694 buffer = nasm_malloc(BUF_DELTA);
695 p = buffer;
696 continued_count = 0;
697 while (1)
699 q = fgets(p, bufsize - (p - buffer), istk->fp);
700 if (!q)
701 break;
702 p += strlen(p);
703 if (p > buffer && p[-1] == '\n')
705 /* Convert backslash-CRLF line continuation sequences into
706 nothing at all (for DOS and Windows) */
707 if (((p - 2) > buffer) && (p[-3] == '\\') && (p[-2] == '\r')) {
708 p -= 3;
709 *p = 0;
710 continued_count++;
712 /* Also convert backslash-LF line continuation sequences into
713 nothing at all (for Unix) */
714 else if (((p - 1) > buffer) && (p[-2] == '\\')) {
715 p -= 2;
716 *p = 0;
717 continued_count++;
719 else {
720 break;
723 if (p - buffer > bufsize - 10)
725 long offset = p - buffer;
726 bufsize += BUF_DELTA;
727 buffer = nasm_realloc(buffer, bufsize);
728 p = buffer + offset; /* prevent stale-pointer problems */
732 if (!q && p == buffer)
734 nasm_free(buffer);
735 return NULL;
738 src_set_linnum(src_get_linnum() + istk->lineinc + (continued_count * istk->lineinc));
741 * Play safe: remove CRs as well as LFs, if any of either are
742 * present at the end of the line.
744 while (--p >= buffer && (*p == '\n' || *p == '\r'))
745 *p = '\0';
748 * Handle spurious ^Z, which may be inserted into source files
749 * by some file transfer utilities.
751 buffer[strcspn(buffer, "\032")] = '\0';
753 list->line(LIST_READ, buffer);
755 return buffer;
759 * Tokenise a line of text. This is a very simple process since we
760 * don't need to parse the value out of e.g. numeric tokens: we
761 * simply split one string into many.
763 static Token *
764 tokenise(char *line)
766 char *p = line;
767 int type;
768 Token *list = NULL;
769 Token *t, **tail = &list;
771 while (*line)
773 p = line;
774 if (*p == '%')
776 p++;
777 if ( isdigit(*p) ||
778 ((*p == '-' || *p == '+') && isdigit(p[1])) ||
779 ((*p == '+') && (isspace(p[1]) || !p[1])))
783 p++;
785 while (isdigit(*p));
786 type = TOK_PREPROC_ID;
788 else if (*p == '{')
790 p++;
791 while (*p && *p != '}')
793 p[-1] = *p;
794 p++;
796 p[-1] = '\0';
797 if (*p)
798 p++;
799 type = TOK_PREPROC_ID;
801 else if (isidchar(*p) ||
802 ((*p == '!' || *p == '%' || *p == '$') &&
803 isidchar(p[1])))
807 p++;
809 while (isidchar(*p));
810 type = TOK_PREPROC_ID;
812 else
814 type = TOK_OTHER;
815 if (*p == '%')
816 p++;
819 else if (isidstart(*p) || (*p == '$' && isidstart(p[1])))
821 type = TOK_ID;
822 p++;
823 while (*p && isidchar(*p))
824 p++;
826 else if (*p == '\'' || *p == '"')
829 * A string token.
831 char c = *p;
832 p++;
833 type = TOK_STRING;
834 while (*p && *p != c)
835 p++;
836 if (*p)
838 p++;
840 else
842 error(ERR_WARNING, "unterminated string");
845 else if (isnumstart(*p))
848 * A number token.
850 type = TOK_NUMBER;
851 p++;
852 while (*p && isnumchar(*p))
853 p++;
855 else if (isspace(*p))
857 type = TOK_WHITESPACE;
858 p++;
859 while (*p && isspace(*p))
860 p++;
862 * Whitespace just before end-of-line is discarded by
863 * pretending it's a comment; whitespace just before a
864 * comment gets lumped into the comment.
866 if (!*p || *p == ';')
868 type = TOK_COMMENT;
869 while (*p)
870 p++;
873 else if (*p == ';')
875 type = TOK_COMMENT;
876 while (*p)
877 p++;
879 else
882 * Anything else is an operator of some kind. We check
883 * for all the double-character operators (>>, <<, //,
884 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
885 * else is a single-character operator.
887 type = TOK_OTHER;
888 if ((p[0] == '>' && p[1] == '>') ||
889 (p[0] == '<' && p[1] == '<') ||
890 (p[0] == '/' && p[1] == '/') ||
891 (p[0] == '<' && p[1] == '=') ||
892 (p[0] == '>' && p[1] == '=') ||
893 (p[0] == '=' && p[1] == '=') ||
894 (p[0] == '!' && p[1] == '=') ||
895 (p[0] == '<' && p[1] == '>') ||
896 (p[0] == '&' && p[1] == '&') ||
897 (p[0] == '|' && p[1] == '|') ||
898 (p[0] == '^' && p[1] == '^'))
900 p++;
902 p++;
904 if (type != TOK_COMMENT)
906 *tail = t = new_Token(NULL, type, line, p - line);
907 tail = &t->next;
909 line = p;
911 return list;
915 * this function allocates a new managed block of memory and
916 * returns a pointer to the block. The managed blocks are
917 * deleted only all at once by the delete_Blocks function.
919 static void *
920 new_Block(size_t size)
922 Blocks *b = &blocks;
924 /* first, get to the end of the linked list */
925 while (b->next)
926 b = b->next;
927 /* now allocate the requested chunk */
928 b->chunk = nasm_malloc(size);
930 /* now allocate a new block for the next request */
931 b->next = nasm_malloc(sizeof(Blocks));
932 /* and initialize the contents of the new block */
933 b->next->next = NULL;
934 b->next->chunk = NULL;
935 return b->chunk;
939 * this function deletes all managed blocks of memory
941 static void
942 delete_Blocks(void)
944 Blocks *a,*b = &blocks;
947 * keep in mind that the first block, pointed to by blocks
948 * is a static and not dynamically allocated, so we don't
949 * free it.
951 while (b)
953 if (b->chunk)
954 nasm_free(b->chunk);
955 a = b;
956 b = b->next;
957 if (a != &blocks)
958 nasm_free(a);
963 * this function creates a new Token and passes a pointer to it
964 * back to the caller. It sets the type and text elements, and
965 * also the mac and next elements to NULL.
967 static Token *
968 new_Token(Token * next, int type, char *text, int txtlen)
970 Token *t;
971 int i;
973 if (freeTokens == NULL)
975 freeTokens = (Token *)new_Block(TOKEN_BLOCKSIZE * sizeof(Token));
976 for (i = 0; i < TOKEN_BLOCKSIZE - 1; i++)
977 freeTokens[i].next = &freeTokens[i + 1];
978 freeTokens[i].next = NULL;
980 t = freeTokens;
981 freeTokens = t->next;
982 t->next = next;
983 t->mac = NULL;
984 t->type = type;
985 if (type == TOK_WHITESPACE || text == NULL)
987 t->text = NULL;
989 else
991 if (txtlen == 0)
992 txtlen = strlen(text);
993 t->text = nasm_malloc(1 + txtlen);
994 strncpy(t->text, text, txtlen);
995 t->text[txtlen] = '\0';
997 return t;
1000 static Token *
1001 delete_Token(Token * t)
1003 Token *next = t->next;
1004 nasm_free(t->text);
1005 t->next = freeTokens;
1006 freeTokens = t;
1007 return next;
1011 * Convert a line of tokens back into text.
1012 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1013 * will be transformed into ..@ctxnum.xxx
1015 static char *
1016 detoken(Token * tlist, int expand_locals)
1018 Token *t;
1019 int len;
1020 char *line, *p;
1022 len = 0;
1023 for (t = tlist; t; t = t->next)
1025 if (t->type == TOK_PREPROC_ID && t->text[1] == '!')
1027 char *p = getenv(t->text + 2);
1028 nasm_free(t->text);
1029 if (p)
1030 t->text = nasm_strdup(p);
1031 else
1032 t->text = NULL;
1034 /* Expand local macros here and not during preprocessing */
1035 if (expand_locals &&
1036 t->type == TOK_PREPROC_ID && t->text &&
1037 t->text[0] == '%' && t->text[1] == '$')
1039 Context *ctx = get_ctx(t->text, FALSE);
1040 if (ctx)
1042 char buffer[40];
1043 char *p, *q = t->text + 2;
1045 q += strspn(q, "$");
1046 sprintf(buffer, "..@%lu.", ctx->number);
1047 p = nasm_strcat(buffer, q);
1048 nasm_free(t->text);
1049 t->text = p;
1052 if (t->type == TOK_WHITESPACE)
1054 len++;
1056 else if (t->text)
1058 len += strlen(t->text);
1061 p = line = nasm_malloc(len + 1);
1062 for (t = tlist; t; t = t->next)
1064 if (t->type == TOK_WHITESPACE)
1066 *p = ' ';
1067 p++;
1068 *p = '\0';
1070 else if (t->text)
1072 strcpy(p, t->text);
1073 p += strlen(p);
1076 *p = '\0';
1077 return line;
1081 * A scanner, suitable for use by the expression evaluator, which
1082 * operates on a line of Tokens. Expects a pointer to a pointer to
1083 * the first token in the line to be passed in as its private_data
1084 * field.
1086 static int
1087 ppscan(void *private_data, struct tokenval *tokval)
1089 Token **tlineptr = private_data;
1090 Token *tline;
1094 tline = *tlineptr;
1095 *tlineptr = tline ? tline->next : NULL;
1097 while (tline && (tline->type == TOK_WHITESPACE ||
1098 tline->type == TOK_COMMENT));
1100 if (!tline)
1101 return tokval->t_type = TOKEN_EOS;
1103 if (tline->text[0] == '$' && !tline->text[1])
1104 return tokval->t_type = TOKEN_HERE;
1105 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[2])
1106 return tokval->t_type = TOKEN_BASE;
1108 if (tline->type == TOK_ID)
1110 tokval->t_charptr = tline->text;
1111 if (tline->text[0] == '$')
1113 tokval->t_charptr++;
1114 return tokval->t_type = TOKEN_ID;
1118 * This is the only special case we actually need to worry
1119 * about in this restricted context.
1121 if (!nasm_stricmp(tline->text, "seg"))
1122 return tokval->t_type = TOKEN_SEG;
1124 return tokval->t_type = TOKEN_ID;
1127 if (tline->type == TOK_NUMBER)
1129 int rn_error;
1131 tokval->t_integer = readnum(tline->text, &rn_error);
1132 if (rn_error)
1133 return tokval->t_type = TOKEN_ERRNUM;
1134 tokval->t_charptr = NULL;
1135 return tokval->t_type = TOKEN_NUM;
1138 if (tline->type == TOK_STRING)
1140 int rn_warn;
1141 char q, *r;
1142 int l;
1144 r = tline->text;
1145 q = *r++;
1146 l = strlen(r);
1148 if (l == 0 || r[l - 1] != q)
1149 return tokval->t_type = TOKEN_ERRNUM;
1150 tokval->t_integer = readstrnum(r, l - 1, &rn_warn);
1151 if (rn_warn)
1152 error(ERR_WARNING | ERR_PASS1, "character constant too long");
1153 tokval->t_charptr = NULL;
1154 return tokval->t_type = TOKEN_NUM;
1157 if (tline->type == TOK_OTHER)
1159 if (!strcmp(tline->text, "<<"))
1160 return tokval->t_type = TOKEN_SHL;
1161 if (!strcmp(tline->text, ">>"))
1162 return tokval->t_type = TOKEN_SHR;
1163 if (!strcmp(tline->text, "//"))
1164 return tokval->t_type = TOKEN_SDIV;
1165 if (!strcmp(tline->text, "%%"))
1166 return tokval->t_type = TOKEN_SMOD;
1167 if (!strcmp(tline->text, "=="))
1168 return tokval->t_type = TOKEN_EQ;
1169 if (!strcmp(tline->text, "<>"))
1170 return tokval->t_type = TOKEN_NE;
1171 if (!strcmp(tline->text, "!="))
1172 return tokval->t_type = TOKEN_NE;
1173 if (!strcmp(tline->text, "<="))
1174 return tokval->t_type = TOKEN_LE;
1175 if (!strcmp(tline->text, ">="))
1176 return tokval->t_type = TOKEN_GE;
1177 if (!strcmp(tline->text, "&&"))
1178 return tokval->t_type = TOKEN_DBL_AND;
1179 if (!strcmp(tline->text, "^^"))
1180 return tokval->t_type = TOKEN_DBL_XOR;
1181 if (!strcmp(tline->text, "||"))
1182 return tokval->t_type = TOKEN_DBL_OR;
1186 * We have no other options: just return the first character of
1187 * the token text.
1189 return tokval->t_type = tline->text[0];
1193 * Compare a string to the name of an existing macro; this is a
1194 * simple wrapper which calls either strcmp or nasm_stricmp
1195 * depending on the value of the `casesense' parameter.
1197 static int
1198 mstrcmp(char *p, char *q, int casesense)
1200 return casesense ? strcmp(p, q) : nasm_stricmp(p, q);
1204 * Return the Context structure associated with a %$ token. Return
1205 * NULL, having _already_ reported an error condition, if the
1206 * context stack isn't deep enough for the supplied number of $
1207 * signs.
1208 * If all_contexts == TRUE, contexts that enclose current are
1209 * also scanned for such smacro, until it is found; if not -
1210 * only the context that directly results from the number of $'s
1211 * in variable's name.
1213 static Context *
1214 get_ctx(char *name, int all_contexts)
1216 Context *ctx;
1217 SMacro *m;
1218 int i;
1220 if (!name || name[0] != '%' || name[1] != '$')
1221 return NULL;
1223 if (!cstk)
1225 error(ERR_NONFATAL, "`%s': context stack is empty", name);
1226 return NULL;
1229 for (i = strspn(name + 2, "$"), ctx = cstk; (i > 0) && ctx; i--)
1231 ctx = ctx->next;
1232 /* i--; Lino - 02/25/02 */
1234 if (!ctx)
1236 error(ERR_NONFATAL, "`%s': context stack is only"
1237 " %d level%s deep", name, i - 1, (i == 2 ? "" : "s"));
1238 return NULL;
1240 if (!all_contexts)
1241 return ctx;
1245 /* Search for this smacro in found context */
1246 m = ctx->localmac;
1247 while (m)
1249 if (!mstrcmp(m->name, name, m->casesense))
1250 return ctx;
1251 m = m->next;
1253 ctx = ctx->next;
1255 while (ctx);
1256 return NULL;
1260 * Open an include file. This routine must always return a valid
1261 * file pointer if it returns - it's responsible for throwing an
1262 * ERR_FATAL and bombing out completely if not. It should also try
1263 * the include path one by one until it finds the file or reaches
1264 * the end of the path.
1266 static FILE *
1267 inc_fopen(char *file)
1269 FILE *fp;
1270 char *prefix = "", *combine;
1271 IncPath *ip = ipath;
1272 static int namelen = 0;
1273 int len = strlen(file);
1275 while (1)
1277 combine = nasm_malloc(strlen(prefix) + len + 1);
1278 strcpy(combine, prefix);
1279 strcat(combine, file);
1280 fp = fopen(combine, "r");
1281 if (pass == 0 && fp)
1283 namelen += strlen(combine) + 1;
1284 if (namelen > 62)
1286 printf(" \\\n ");
1287 namelen = 2;
1289 printf(" %s", combine);
1291 nasm_free(combine);
1292 if (fp)
1293 return fp;
1294 if (!ip)
1295 break;
1296 prefix = ip->path;
1297 ip = ip->next;
1300 error(ERR_FATAL, "unable to open include file `%s'", file);
1301 return NULL; /* never reached - placate compilers */
1305 * Determine if we should warn on defining a single-line macro of
1306 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1307 * return TRUE if _any_ single-line macro of that name is defined.
1308 * Otherwise, will return TRUE if a single-line macro with either
1309 * `nparam' or no parameters is defined.
1311 * If a macro with precisely the right number of parameters is
1312 * defined, or nparam is -1, the address of the definition structure
1313 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1314 * is NULL, no action will be taken regarding its contents, and no
1315 * error will occur.
1317 * Note that this is also called with nparam zero to resolve
1318 * `ifdef'.
1320 * If you already know which context macro belongs to, you can pass
1321 * the context pointer as first parameter; if you won't but name begins
1322 * with %$ the context will be automatically computed. If all_contexts
1323 * is true, macro will be searched in outer contexts as well.
1325 static int
1326 smacro_defined(Context * ctx, char *name, int nparam, SMacro ** defn,
1327 int nocase)
1329 SMacro *m;
1331 if (ctx)
1332 m = ctx->localmac;
1333 else if (name[0] == '%' && name[1] == '$')
1335 if (cstk)
1336 ctx = get_ctx(name, FALSE);
1337 if (!ctx)
1338 return FALSE; /* got to return _something_ */
1339 m = ctx->localmac;
1341 else
1342 m = smacros[hash(name)];
1344 while (m)
1346 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
1347 (nparam <= 0 || m->nparam == 0 || nparam == m->nparam))
1349 if (defn)
1351 if (nparam == m->nparam || nparam == -1)
1352 *defn = m;
1353 else
1354 *defn = NULL;
1356 return TRUE;
1358 m = m->next;
1361 return FALSE;
1365 * Count and mark off the parameters in a multi-line macro call.
1366 * This is called both from within the multi-line macro expansion
1367 * code, and also to mark off the default parameters when provided
1368 * in a %macro definition line.
1370 static void
1371 count_mmac_params(Token * t, int *nparam, Token *** params)
1373 int paramsize, brace;
1375 *nparam = paramsize = 0;
1376 *params = NULL;
1377 while (t)
1379 if (*nparam >= paramsize)
1381 paramsize += PARAM_DELTA;
1382 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1384 skip_white_(t);
1385 brace = FALSE;
1386 if (tok_is_(t, "{"))
1387 brace = TRUE;
1388 (*params)[(*nparam)++] = t;
1389 while (tok_isnt_(t, brace ? "}" : ","))
1390 t = t->next;
1391 if (t)
1392 { /* got a comma/brace */
1393 t = t->next;
1394 if (brace)
1397 * Now we've found the closing brace, look further
1398 * for the comma.
1400 skip_white_(t);
1401 if (tok_isnt_(t, ","))
1403 error(ERR_NONFATAL,
1404 "braces do not enclose all of macro parameter");
1405 while (tok_isnt_(t, ","))
1406 t = t->next;
1408 if (t)
1409 t = t->next; /* eat the comma */
1416 * Determine whether one of the various `if' conditions is true or
1417 * not.
1419 * We must free the tline we get passed.
1421 static int
1422 if_condition(Token * tline, int i)
1424 int j, casesense;
1425 Token *t, *tt, **tptr, *origline;
1426 struct tokenval tokval;
1427 expr *evalresult;
1429 origline = tline;
1431 switch (i)
1433 case PP_IFCTX:
1434 case PP_ELIFCTX:
1435 case PP_IFNCTX:
1436 case PP_ELIFNCTX:
1437 j = FALSE; /* have we matched yet? */
1438 while (cstk && tline)
1440 skip_white_(tline);
1441 if (!tline || tline->type != TOK_ID)
1443 error(ERR_NONFATAL,
1444 "`%s' expects context identifiers",
1445 directives[i]);
1446 free_tlist(origline);
1447 return -1;
1449 if (!nasm_stricmp(tline->text, cstk->name))
1450 j = TRUE;
1451 tline = tline->next;
1453 if (i == PP_IFNCTX || i == PP_ELIFNCTX)
1454 j = !j;
1455 free_tlist(origline);
1456 return j;
1458 case PP_IFDEF:
1459 case PP_ELIFDEF:
1460 case PP_IFNDEF:
1461 case PP_ELIFNDEF:
1462 j = FALSE; /* have we matched yet? */
1463 while (tline)
1465 skip_white_(tline);
1466 if (!tline || (tline->type != TOK_ID &&
1467 (tline->type != TOK_PREPROC_ID ||
1468 tline->text[1] != '$')))
1470 error(ERR_NONFATAL,
1471 "`%s' expects macro identifiers",
1472 directives[i]);
1473 free_tlist(origline);
1474 return -1;
1476 if (smacro_defined(NULL, tline->text, 0, NULL, 1))
1477 j = TRUE;
1478 tline = tline->next;
1480 if (i == PP_IFNDEF || i == PP_ELIFNDEF)
1481 j = !j;
1482 free_tlist(origline);
1483 return j;
1485 case PP_IFIDN:
1486 case PP_ELIFIDN:
1487 case PP_IFNIDN:
1488 case PP_ELIFNIDN:
1489 case PP_IFIDNI:
1490 case PP_ELIFIDNI:
1491 case PP_IFNIDNI:
1492 case PP_ELIFNIDNI:
1493 tline = expand_smacro(tline);
1494 t = tt = tline;
1495 while (tok_isnt_(tt, ","))
1496 tt = tt->next;
1497 if (!tt)
1499 error(ERR_NONFATAL,
1500 "`%s' expects two comma-separated arguments",
1501 directives[i]);
1502 free_tlist(tline);
1503 return -1;
1505 tt = tt->next;
1506 casesense = (i == PP_IFIDN || i == PP_ELIFIDN ||
1507 i == PP_IFNIDN || i == PP_ELIFNIDN);
1508 j = TRUE; /* assume equality unless proved not */
1509 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt)
1511 if (tt->type == TOK_OTHER && !strcmp(tt->text, ","))
1513 error(ERR_NONFATAL, "`%s': more than one comma on line",
1514 directives[i]);
1515 free_tlist(tline);
1516 return -1;
1518 if (t->type == TOK_WHITESPACE)
1520 t = t->next;
1521 continue;
1523 else if (tt->type == TOK_WHITESPACE)
1525 tt = tt->next;
1526 continue;
1528 else if (tt->type != t->type ||
1529 mstrcmp(tt->text, t->text, casesense))
1531 j = FALSE; /* found mismatching tokens */
1532 break;
1534 else
1536 t = t->next;
1537 tt = tt->next;
1538 continue;
1541 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1542 j = FALSE; /* trailing gunk on one end or other */
1543 if (i == PP_IFNIDN || i == PP_ELIFNIDN ||
1544 i == PP_IFNIDNI || i == PP_ELIFNIDNI)
1545 j = !j;
1546 free_tlist(tline);
1547 return j;
1549 case PP_IFMACRO:
1550 case PP_ELIFMACRO:
1551 case PP_IFNMACRO:
1552 case PP_ELIFNMACRO:
1554 int found = 0;
1555 MMacro searching, *mmac;
1557 tline = tline->next;
1558 skip_white_(tline);
1559 tline = expand_id(tline);
1560 if (!tok_type_(tline, TOK_ID))
1562 error(ERR_NONFATAL,
1563 "`%s' expects a macro name",
1564 directives[i]);
1565 return -1;
1567 searching.name = nasm_strdup(tline->text);
1568 searching.casesense = (i == PP_MACRO);
1569 searching.plus = FALSE;
1570 searching.nolist = FALSE;
1571 searching.in_progress = FALSE;
1572 searching.rep_nest = NULL;
1573 searching.nparam_min = 0;
1574 searching.nparam_max = INT_MAX;
1575 tline = expand_smacro(tline->next);
1576 skip_white_(tline);
1577 if (!tline)
1579 } else if (!tok_type_(tline, TOK_NUMBER))
1581 error(ERR_NONFATAL,
1582 "`%s' expects a parameter count or nothing",
1583 directives[i]);
1585 else
1587 searching.nparam_min = searching.nparam_max =
1588 readnum(tline->text, &j);
1589 if (j)
1590 error(ERR_NONFATAL,
1591 "unable to parse parameter count `%s'",
1592 tline->text);
1594 if (tline && tok_is_(tline->next, "-"))
1596 tline = tline->next->next;
1597 if (tok_is_(tline, "*"))
1598 searching.nparam_max = INT_MAX;
1599 else if (!tok_type_(tline, TOK_NUMBER))
1600 error(ERR_NONFATAL,
1601 "`%s' expects a parameter count after `-'",
1602 directives[i]);
1603 else
1605 searching.nparam_max = readnum(tline->text, &j);
1606 if (j)
1607 error(ERR_NONFATAL,
1608 "unable to parse parameter count `%s'",
1609 tline->text);
1610 if (searching.nparam_min > searching.nparam_max)
1611 error(ERR_NONFATAL,
1612 "minimum parameter count exceeds maximum");
1615 if (tline && tok_is_(tline->next, "+"))
1617 tline = tline->next;
1618 searching.plus = TRUE;
1620 mmac = mmacros[hash(searching.name)];
1621 while (mmac)
1623 if (!strcmp(mmac->name, searching.name) &&
1624 (mmac->nparam_min <= searching.nparam_max
1625 || searching.plus)
1626 && (searching.nparam_min <= mmac->nparam_max
1627 || mmac->plus))
1629 found = TRUE;
1630 break;
1632 mmac = mmac->next;
1634 nasm_free(searching.name);
1635 free_tlist(origline);
1636 if (i == PP_IFNMACRO || i == PP_ELIFNMACRO)
1637 found = !found;
1638 return found;
1641 case PP_IFID:
1642 case PP_ELIFID:
1643 case PP_IFNID:
1644 case PP_ELIFNID:
1645 case PP_IFNUM:
1646 case PP_ELIFNUM:
1647 case PP_IFNNUM:
1648 case PP_ELIFNNUM:
1649 case PP_IFSTR:
1650 case PP_ELIFSTR:
1651 case PP_IFNSTR:
1652 case PP_ELIFNSTR:
1653 tline = expand_smacro(tline);
1654 t = tline;
1655 while (tok_type_(t, TOK_WHITESPACE))
1656 t = t->next;
1657 j = FALSE; /* placate optimiser */
1658 if (t)
1659 switch (i)
1661 case PP_IFID:
1662 case PP_ELIFID:
1663 case PP_IFNID:
1664 case PP_ELIFNID:
1665 j = (t->type == TOK_ID);
1666 break;
1667 case PP_IFNUM:
1668 case PP_ELIFNUM:
1669 case PP_IFNNUM:
1670 case PP_ELIFNNUM:
1671 j = (t->type == TOK_NUMBER);
1672 break;
1673 case PP_IFSTR:
1674 case PP_ELIFSTR:
1675 case PP_IFNSTR:
1676 case PP_ELIFNSTR:
1677 j = (t->type == TOK_STRING);
1678 break;
1680 if (i == PP_IFNID || i == PP_ELIFNID ||
1681 i == PP_IFNNUM || i == PP_ELIFNNUM ||
1682 i == PP_IFNSTR || i == PP_ELIFNSTR)
1683 j = !j;
1684 free_tlist(tline);
1685 return j;
1687 case PP_IF:
1688 case PP_ELIF:
1689 t = tline = expand_smacro(tline);
1690 tptr = &t;
1691 tokval.t_type = TOKEN_INVALID;
1692 evalresult = evaluate(ppscan, tptr, &tokval,
1693 NULL, pass | CRITICAL, error, NULL);
1694 free_tlist(tline);
1695 if (!evalresult)
1696 return -1;
1697 if (tokval.t_type)
1698 error(ERR_WARNING,
1699 "trailing garbage after expression ignored");
1700 if (!is_simple(evalresult))
1702 error(ERR_NONFATAL,
1703 "non-constant value given to `%s'", directives[i]);
1704 return -1;
1706 return reloc_value(evalresult) != 0;
1708 default:
1709 error(ERR_FATAL,
1710 "preprocessor directive `%s' not yet implemented",
1711 directives[i]);
1712 free_tlist(origline);
1713 return -1; /* yeah, right */
1718 * Expand macros in a string. Used in %error and %include directives.
1719 * First tokenise the string, apply "expand_smacro" and then de-tokenise back.
1720 * The returned variable should ALWAYS be freed after usage.
1722 void
1723 expand_macros_in_string(char **p)
1725 Token *line = tokenise(*p);
1726 line = expand_smacro(line);
1727 *p = detoken(line, FALSE);
1731 * find and process preprocessor directive in passed line
1732 * Find out if a line contains a preprocessor directive, and deal
1733 * with it if so.
1735 * If a directive _is_ found, it is the responsibility of this routine
1736 * (and not the caller) to free_tlist() the line.
1738 * @param tline a pointer to the current tokeninzed line linked list
1739 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
1742 static int
1743 do_directive(Token * tline)
1745 int i, j, k, m, nparam, nolist;
1746 int offset;
1747 char *p, *mname;
1748 Include *inc;
1749 Context *ctx;
1750 Cond *cond;
1751 SMacro *smac, **smhead;
1752 MMacro *mmac;
1753 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
1754 Line *l;
1755 struct tokenval tokval;
1756 expr *evalresult;
1757 MMacro *tmp_defining; /* Used when manipulating rep_nest */
1759 origline = tline;
1761 skip_white_(tline);
1762 if (!tok_type_(tline, TOK_PREPROC_ID) ||
1763 (tline->text[1] == '%' || tline->text[1] == '$'
1764 || tline->text[1] == '!'))
1765 return NO_DIRECTIVE_FOUND;
1767 i = -1;
1768 j = elements(directives);
1769 while (j - i > 1)
1771 k = (j + i) / 2;
1772 m = nasm_stricmp(tline->text, directives[k]);
1773 if (m == 0) {
1774 if (tasm_compatible_mode) {
1775 i = k;
1776 j = -2;
1777 } else if (k != PP_ARG && k != PP_LOCAL && k != PP_STACKSIZE) {
1778 i = k;
1779 j = -2;
1781 break;
1783 else if (m < 0) {
1784 j = k;
1786 else
1787 i = k;
1791 * If we're in a non-emitting branch of a condition construct,
1792 * or walking to the end of an already terminated %rep block,
1793 * we should ignore all directives except for condition
1794 * directives.
1796 if (((istk->conds && !emitting(istk->conds->state)) ||
1797 (istk->mstk && !istk->mstk->in_progress)) &&
1798 !is_condition(i))
1800 return NO_DIRECTIVE_FOUND;
1804 * If we're defining a macro or reading a %rep block, we should
1805 * ignore all directives except for %macro/%imacro (which
1806 * generate an error), %endm/%endmacro, and (only if we're in a
1807 * %rep block) %endrep. If we're in a %rep block, another %rep
1808 * causes an error, so should be let through.
1810 if (defining && i != PP_MACRO && i != PP_IMACRO &&
1811 i != PP_ENDMACRO && i != PP_ENDM &&
1812 (defining->name || (i != PP_ENDREP && i != PP_REP)))
1814 return NO_DIRECTIVE_FOUND;
1817 if (j != -2)
1819 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
1820 tline->text);
1821 return NO_DIRECTIVE_FOUND; /* didn't get it */
1824 switch (i)
1826 case PP_STACKSIZE:
1827 /* Directive to tell NASM what the default stack size is. The
1828 * default is for a 16-bit stack, and this can be overriden with
1829 * %stacksize large.
1830 * the following form:
1832 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
1834 tline = tline->next;
1835 if (tline && tline->type == TOK_WHITESPACE)
1836 tline = tline->next;
1837 if (!tline || tline->type != TOK_ID)
1839 error(ERR_NONFATAL, "`%%stacksize' missing size parameter");
1840 free_tlist(origline);
1841 return DIRECTIVE_FOUND;
1843 if (nasm_stricmp(tline->text, "flat") == 0)
1845 /* All subsequent ARG directives are for a 32-bit stack */
1846 StackSize = 4;
1847 StackPointer = "ebp";
1848 ArgOffset = 8;
1849 LocalOffset = 4;
1851 else if (nasm_stricmp(tline->text, "large") == 0)
1853 /* All subsequent ARG directives are for a 16-bit stack,
1854 * far function call.
1856 StackSize = 2;
1857 StackPointer = "bp";
1858 ArgOffset = 4;
1859 LocalOffset = 2;
1861 else if (nasm_stricmp(tline->text, "small") == 0)
1863 /* All subsequent ARG directives are for a 16-bit stack,
1864 * far function call. We don't support near functions.
1866 StackSize = 2;
1867 StackPointer = "bp";
1868 ArgOffset = 6;
1869 LocalOffset = 2;
1871 else
1873 error(ERR_NONFATAL, "`%%stacksize' invalid size type");
1874 free_tlist(origline);
1875 return DIRECTIVE_FOUND;
1877 free_tlist(origline);
1878 return DIRECTIVE_FOUND;
1880 case PP_ARG:
1881 /* TASM like ARG directive to define arguments to functions, in
1882 * the following form:
1884 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
1886 offset = ArgOffset;
1889 char *arg, directive[256];
1890 int size = StackSize;
1892 /* Find the argument name */
1893 tline = tline->next;
1894 if (tline && tline->type == TOK_WHITESPACE)
1895 tline = tline->next;
1896 if (!tline || tline->type != TOK_ID)
1898 error(ERR_NONFATAL, "`%%arg' missing argument parameter");
1899 free_tlist(origline);
1900 return DIRECTIVE_FOUND;
1902 arg = tline->text;
1904 /* Find the argument size type */
1905 tline = tline->next;
1906 if (!tline || tline->type != TOK_OTHER
1907 || tline->text[0] != ':')
1909 error(ERR_NONFATAL,
1910 "Syntax error processing `%%arg' directive");
1911 free_tlist(origline);
1912 return DIRECTIVE_FOUND;
1914 tline = tline->next;
1915 if (!tline || tline->type != TOK_ID)
1917 error(ERR_NONFATAL,
1918 "`%%arg' missing size type parameter");
1919 free_tlist(origline);
1920 return DIRECTIVE_FOUND;
1923 /* Allow macro expansion of type parameter */
1924 tt = tokenise(tline->text);
1925 tt = expand_smacro(tt);
1926 if (nasm_stricmp(tt->text, "byte") == 0)
1928 size = MAX(StackSize, 1);
1930 else if (nasm_stricmp(tt->text, "word") == 0)
1932 size = MAX(StackSize, 2);
1934 else if (nasm_stricmp(tt->text, "dword") == 0)
1936 size = MAX(StackSize, 4);
1938 else if (nasm_stricmp(tt->text, "qword") == 0)
1940 size = MAX(StackSize, 8);
1942 else if (nasm_stricmp(tt->text, "tword") == 0)
1944 size = MAX(StackSize, 10);
1946 else
1948 error(ERR_NONFATAL,
1949 "Invalid size type for `%%arg' missing directive");
1950 free_tlist(tt);
1951 free_tlist(origline);
1952 return DIRECTIVE_FOUND;
1954 free_tlist(tt);
1956 /* Now define the macro for the argument */
1957 sprintf(directive, "%%define %s (%s+%d)", arg, StackPointer,
1958 offset);
1959 do_directive(tokenise(directive));
1960 offset += size;
1962 /* Move to the next argument in the list */
1963 tline = tline->next;
1964 if (tline && tline->type == TOK_WHITESPACE)
1965 tline = tline->next;
1967 while (tline && tline->type == TOK_OTHER
1968 && tline->text[0] == ',');
1969 free_tlist(origline);
1970 return DIRECTIVE_FOUND;
1972 case PP_LOCAL:
1973 /* TASM like LOCAL directive to define local variables for a
1974 * function, in the following form:
1976 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
1978 * The '= LocalSize' at the end is ignored by NASM, but is
1979 * required by TASM to define the local parameter size (and used
1980 * by the TASM macro package).
1982 offset = LocalOffset;
1985 char *local, directive[256];
1986 int size = StackSize;
1988 /* Find the argument name */
1989 tline = tline->next;
1990 if (tline && tline->type == TOK_WHITESPACE)
1991 tline = tline->next;
1992 if (!tline || tline->type != TOK_ID)
1994 error(ERR_NONFATAL,
1995 "`%%local' missing argument parameter");
1996 free_tlist(origline);
1997 return DIRECTIVE_FOUND;
1999 local = tline->text;
2001 /* Find the argument size type */
2002 tline = tline->next;
2003 if (!tline || tline->type != TOK_OTHER
2004 || tline->text[0] != ':')
2006 error(ERR_NONFATAL,
2007 "Syntax error processing `%%local' directive");
2008 free_tlist(origline);
2009 return DIRECTIVE_FOUND;
2011 tline = tline->next;
2012 if (!tline || tline->type != TOK_ID)
2014 error(ERR_NONFATAL,
2015 "`%%local' missing size type parameter");
2016 free_tlist(origline);
2017 return DIRECTIVE_FOUND;
2020 /* Allow macro expansion of type parameter */
2021 tt = tokenise(tline->text);
2022 tt = expand_smacro(tt);
2023 if (nasm_stricmp(tt->text, "byte") == 0)
2025 size = MAX(StackSize, 1);
2027 else if (nasm_stricmp(tt->text, "word") == 0)
2029 size = MAX(StackSize, 2);
2031 else if (nasm_stricmp(tt->text, "dword") == 0)
2033 size = MAX(StackSize, 4);
2035 else if (nasm_stricmp(tt->text, "qword") == 0)
2037 size = MAX(StackSize, 8);
2039 else if (nasm_stricmp(tt->text, "tword") == 0)
2041 size = MAX(StackSize, 10);
2043 else
2045 error(ERR_NONFATAL,
2046 "Invalid size type for `%%local' missing directive");
2047 free_tlist(tt);
2048 free_tlist(origline);
2049 return DIRECTIVE_FOUND;
2051 free_tlist(tt);
2053 /* Now define the macro for the argument */
2054 sprintf(directive, "%%define %s (%s-%d)", local, StackPointer,
2055 offset);
2056 do_directive(tokenise(directive));
2057 offset += size;
2059 /* Now define the assign to setup the enter_c macro correctly */
2060 sprintf(directive, "%%assign %%$localsize %%$localsize+%d",
2061 size);
2062 do_directive(tokenise(directive));
2064 /* Move to the next argument in the list */
2065 tline = tline->next;
2066 if (tline && tline->type == TOK_WHITESPACE)
2067 tline = tline->next;
2069 while (tline && tline->type == TOK_OTHER
2070 && tline->text[0] == ',');
2071 free_tlist(origline);
2072 return DIRECTIVE_FOUND;
2074 case PP_CLEAR:
2075 if (tline->next)
2076 error(ERR_WARNING,
2077 "trailing garbage after `%%clear' ignored");
2078 for (j = 0; j < NHASH; j++)
2080 while (mmacros[j])
2082 MMacro *m = mmacros[j];
2083 mmacros[j] = m->next;
2084 free_mmacro(m);
2086 while (smacros[j])
2088 SMacro *s = smacros[j];
2089 smacros[j] = smacros[j]->next;
2090 nasm_free(s->name);
2091 free_tlist(s->expansion);
2092 nasm_free(s);
2095 free_tlist(origline);
2096 return DIRECTIVE_FOUND;
2098 case PP_INCLUDE:
2099 tline = tline->next;
2100 skip_white_(tline);
2101 if (!tline || (tline->type != TOK_STRING &&
2102 tline->type != TOK_INTERNAL_STRING))
2104 error(ERR_NONFATAL, "`%%include' expects a file name");
2105 free_tlist(origline);
2106 return DIRECTIVE_FOUND; /* but we did _something_ */
2108 if (tline->next)
2109 error(ERR_WARNING,
2110 "trailing garbage after `%%include' ignored");
2111 if (tline->type != TOK_INTERNAL_STRING)
2113 p = tline->text + 1; /* point past the quote to the name */
2114 p[strlen(p) - 1] = '\0'; /* remove the trailing quote */
2116 else
2117 p = tline->text; /* internal_string is easier */
2118 expand_macros_in_string(&p);
2119 inc = nasm_malloc(sizeof(Include));
2120 inc->next = istk;
2121 inc->conds = NULL;
2122 inc->fp = inc_fopen(p);
2123 inc->fname = src_set_fname(p);
2124 inc->lineno = src_set_linnum(0);
2125 inc->lineinc = 1;
2126 inc->expansion = NULL;
2127 inc->mstk = NULL;
2128 istk = inc;
2129 list->uplevel(LIST_INCLUDE);
2130 free_tlist(origline);
2131 return DIRECTIVE_FOUND;
2133 case PP_PUSH:
2134 tline = tline->next;
2135 skip_white_(tline);
2136 tline = expand_id(tline);
2137 if (!tok_type_(tline, TOK_ID))
2139 error(ERR_NONFATAL, "`%%push' expects a context identifier");
2140 free_tlist(origline);
2141 return DIRECTIVE_FOUND; /* but we did _something_ */
2143 if (tline->next)
2144 error(ERR_WARNING, "trailing garbage after `%%push' ignored");
2145 ctx = nasm_malloc(sizeof(Context));
2146 ctx->next = cstk;
2147 ctx->localmac = NULL;
2148 ctx->name = nasm_strdup(tline->text);
2149 ctx->number = unique++;
2150 cstk = ctx;
2151 free_tlist(origline);
2152 break;
2154 case PP_REPL:
2155 tline = tline->next;
2156 skip_white_(tline);
2157 tline = expand_id(tline);
2158 if (!tok_type_(tline, TOK_ID))
2160 error(ERR_NONFATAL, "`%%repl' expects a context identifier");
2161 free_tlist(origline);
2162 return DIRECTIVE_FOUND; /* but we did _something_ */
2164 if (tline->next)
2165 error(ERR_WARNING, "trailing garbage after `%%repl' ignored");
2166 if (!cstk)
2167 error(ERR_NONFATAL, "`%%repl': context stack is empty");
2168 else
2170 nasm_free(cstk->name);
2171 cstk->name = nasm_strdup(tline->text);
2173 free_tlist(origline);
2174 break;
2176 case PP_POP:
2177 if (tline->next)
2178 error(ERR_WARNING, "trailing garbage after `%%pop' ignored");
2179 if (!cstk)
2180 error(ERR_NONFATAL,
2181 "`%%pop': context stack is already empty");
2182 else
2183 ctx_pop();
2184 free_tlist(origline);
2185 break;
2187 case PP_ERROR:
2188 tline->next = expand_smacro(tline->next);
2189 tline = tline->next;
2190 skip_white_(tline);
2191 if (tok_type_(tline, TOK_STRING))
2193 p = tline->text + 1; /* point past the quote to the name */
2194 p[strlen(p) - 1] = '\0'; /* remove the trailing quote */
2195 expand_macros_in_string(&p);
2196 error(ERR_NONFATAL, "%s", p);
2197 nasm_free(p);
2199 else
2201 p = detoken(tline, FALSE);
2202 error(ERR_WARNING, "%s", p);
2203 nasm_free(p);
2205 free_tlist(origline);
2206 break;
2208 case PP_IF:
2209 case PP_IFCTX:
2210 case PP_IFDEF:
2211 case PP_IFID:
2212 case PP_IFIDN:
2213 case PP_IFIDNI:
2214 case PP_IFMACRO:
2215 case PP_IFNCTX:
2216 case PP_IFNDEF:
2217 case PP_IFNID:
2218 case PP_IFNIDN:
2219 case PP_IFNIDNI:
2220 case PP_IFNMACRO:
2221 case PP_IFNNUM:
2222 case PP_IFNSTR:
2223 case PP_IFNUM:
2224 case PP_IFSTR:
2225 if (istk->conds && !emitting(istk->conds->state))
2226 j = COND_NEVER;
2227 else
2229 j = if_condition(tline->next, i);
2230 tline->next = NULL; /* it got freed */
2231 free_tlist(origline);
2232 j = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2234 cond = nasm_malloc(sizeof(Cond));
2235 cond->next = istk->conds;
2236 cond->state = j;
2237 istk->conds = cond;
2238 return DIRECTIVE_FOUND;
2240 case PP_ELIF:
2241 case PP_ELIFCTX:
2242 case PP_ELIFDEF:
2243 case PP_ELIFID:
2244 case PP_ELIFIDN:
2245 case PP_ELIFIDNI:
2246 case PP_ELIFMACRO:
2247 case PP_ELIFNCTX:
2248 case PP_ELIFNDEF:
2249 case PP_ELIFNID:
2250 case PP_ELIFNIDN:
2251 case PP_ELIFNIDNI:
2252 case PP_ELIFNMACRO:
2253 case PP_ELIFNNUM:
2254 case PP_ELIFNSTR:
2255 case PP_ELIFNUM:
2256 case PP_ELIFSTR:
2257 if (!istk->conds)
2258 error(ERR_FATAL, "`%s': no matching `%%if'", directives[i]);
2259 if (emitting(istk->conds->state)
2260 || istk->conds->state == COND_NEVER)
2261 istk->conds->state = COND_NEVER;
2262 else
2265 * IMPORTANT: In the case of %if, we will already have
2266 * called expand_mmac_params(); however, if we're
2267 * processing an %elif we must have been in a
2268 * non-emitting mode, which would have inhibited
2269 * the normal invocation of expand_mmac_params(). Therefore,
2270 * we have to do it explicitly here.
2272 j = if_condition(expand_mmac_params(tline->next), i);
2273 tline->next = NULL; /* it got freed */
2274 free_tlist(origline);
2275 istk->conds->state =
2276 j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
2278 return DIRECTIVE_FOUND;
2280 case PP_ELSE:
2281 if (tline->next)
2282 error(ERR_WARNING, "trailing garbage after `%%else' ignored");
2283 if (!istk->conds)
2284 error(ERR_FATAL, "`%%else': no matching `%%if'");
2285 if (emitting(istk->conds->state)
2286 || istk->conds->state == COND_NEVER)
2287 istk->conds->state = COND_ELSE_FALSE;
2288 else
2289 istk->conds->state = COND_ELSE_TRUE;
2290 free_tlist(origline);
2291 return DIRECTIVE_FOUND;
2293 case PP_ENDIF:
2294 if (tline->next)
2295 error(ERR_WARNING,
2296 "trailing garbage after `%%endif' ignored");
2297 if (!istk->conds)
2298 error(ERR_FATAL, "`%%endif': no matching `%%if'");
2299 cond = istk->conds;
2300 istk->conds = cond->next;
2301 nasm_free(cond);
2302 free_tlist(origline);
2303 return DIRECTIVE_FOUND;
2305 case PP_MACRO:
2306 case PP_IMACRO:
2307 if (defining)
2308 error(ERR_FATAL,
2309 "`%%%smacro': already defining a macro",
2310 (i == PP_IMACRO ? "i" : ""));
2311 tline = tline->next;
2312 skip_white_(tline);
2313 tline = expand_id(tline);
2314 if (!tok_type_(tline, TOK_ID))
2316 error(ERR_NONFATAL,
2317 "`%%%smacro' expects a macro name",
2318 (i == PP_IMACRO ? "i" : ""));
2319 return DIRECTIVE_FOUND;
2321 defining = nasm_malloc(sizeof(MMacro));
2322 defining->name = nasm_strdup(tline->text);
2323 defining->casesense = (i == PP_MACRO);
2324 defining->plus = FALSE;
2325 defining->nolist = FALSE;
2326 defining->in_progress = FALSE;
2327 defining->rep_nest = NULL;
2328 tline = expand_smacro(tline->next);
2329 skip_white_(tline);
2330 if (!tok_type_(tline, TOK_NUMBER))
2332 error(ERR_NONFATAL,
2333 "`%%%smacro' expects a parameter count",
2334 (i == PP_IMACRO ? "i" : ""));
2335 defining->nparam_min = defining->nparam_max = 0;
2337 else
2339 defining->nparam_min = defining->nparam_max =
2340 readnum(tline->text, &j);
2341 if (j)
2342 error(ERR_NONFATAL,
2343 "unable to parse parameter count `%s'",
2344 tline->text);
2346 if (tline && tok_is_(tline->next, "-"))
2348 tline = tline->next->next;
2349 if (tok_is_(tline, "*"))
2350 defining->nparam_max = INT_MAX;
2351 else if (!tok_type_(tline, TOK_NUMBER))
2352 error(ERR_NONFATAL,
2353 "`%%%smacro' expects a parameter count after `-'",
2354 (i == PP_IMACRO ? "i" : ""));
2355 else
2357 defining->nparam_max = readnum(tline->text, &j);
2358 if (j)
2359 error(ERR_NONFATAL,
2360 "unable to parse parameter count `%s'",
2361 tline->text);
2362 if (defining->nparam_min > defining->nparam_max)
2363 error(ERR_NONFATAL,
2364 "minimum parameter count exceeds maximum");
2367 if (tline && tok_is_(tline->next, "+"))
2369 tline = tline->next;
2370 defining->plus = TRUE;
2372 if (tline && tok_type_(tline->next, TOK_ID) &&
2373 !nasm_stricmp(tline->next->text, ".nolist"))
2375 tline = tline->next;
2376 defining->nolist = TRUE;
2378 mmac = mmacros[hash(defining->name)];
2379 while (mmac)
2381 if (!strcmp(mmac->name, defining->name) &&
2382 (mmac->nparam_min <= defining->nparam_max
2383 || defining->plus)
2384 && (defining->nparam_min <= mmac->nparam_max
2385 || mmac->plus))
2387 error(ERR_WARNING,
2388 "redefining multi-line macro `%s'",
2389 defining->name);
2390 break;
2392 mmac = mmac->next;
2395 * Handle default parameters.
2397 if (tline && tline->next)
2399 defining->dlist = tline->next;
2400 tline->next = NULL;
2401 count_mmac_params(defining->dlist, &defining->ndefs,
2402 &defining->defaults);
2404 else
2406 defining->dlist = NULL;
2407 defining->defaults = NULL;
2409 defining->expansion = NULL;
2410 free_tlist(origline);
2411 return DIRECTIVE_FOUND;
2413 case PP_ENDM:
2414 case PP_ENDMACRO:
2415 if (!defining)
2417 error(ERR_NONFATAL, "`%s': not defining a macro",
2418 tline->text);
2419 return DIRECTIVE_FOUND;
2421 k = hash(defining->name);
2422 defining->next = mmacros[k];
2423 mmacros[k] = defining;
2424 defining = NULL;
2425 free_tlist(origline);
2426 return DIRECTIVE_FOUND;
2428 case PP_ROTATE:
2429 if (tline->next && tline->next->type == TOK_WHITESPACE)
2430 tline = tline->next;
2431 if (tline->next == NULL)
2433 free_tlist(origline);
2434 error(ERR_NONFATAL, "`%%rotate' missing rotate count");
2435 return DIRECTIVE_FOUND;
2437 t = expand_smacro(tline->next);
2438 tline->next = NULL;
2439 free_tlist(origline);
2440 tline = t;
2441 tptr = &t;
2442 tokval.t_type = TOKEN_INVALID;
2443 evalresult =
2444 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2445 free_tlist(tline);
2446 if (!evalresult)
2447 return DIRECTIVE_FOUND;
2448 if (tokval.t_type)
2449 error(ERR_WARNING,
2450 "trailing garbage after expression ignored");
2451 if (!is_simple(evalresult))
2453 error(ERR_NONFATAL, "non-constant value given to `%%rotate'");
2454 return DIRECTIVE_FOUND;
2456 mmac = istk->mstk;
2457 while (mmac && !mmac->name) /* avoid mistaking %reps for macros */
2458 mmac = mmac->next_active;
2459 if (!mmac)
2461 error(ERR_NONFATAL,
2462 "`%%rotate' invoked outside a macro call");
2464 else if (mmac->nparam == 0)
2466 error(ERR_NONFATAL,
2467 "`%%rotate' invoked within macro without parameters");
2469 else
2471 mmac->rotate = mmac->rotate + reloc_value(evalresult);
2473 if (mmac->rotate < 0)
2474 mmac->rotate =
2475 mmac->nparam - (-mmac->rotate) % mmac->nparam;
2476 mmac->rotate %= mmac->nparam;
2478 return DIRECTIVE_FOUND;
2480 case PP_REP:
2481 nolist = FALSE;
2482 do {
2483 tline = tline->next;
2484 } while (tok_type_(tline, TOK_WHITESPACE));
2486 if (tok_type_(tline, TOK_ID) &&
2487 nasm_stricmp(tline->text, ".nolist") == 0)
2489 nolist = TRUE;
2490 do {
2491 tline = tline->next;
2492 } while (tok_type_(tline, TOK_WHITESPACE));
2495 if (tline)
2497 t = expand_smacro(tline);
2498 tptr = &t;
2499 tokval.t_type = TOKEN_INVALID;
2500 evalresult =
2501 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2502 if (!evalresult)
2504 free_tlist(origline);
2505 return DIRECTIVE_FOUND;
2507 if (tokval.t_type)
2508 error(ERR_WARNING,
2509 "trailing garbage after expression ignored");
2510 if (!is_simple(evalresult))
2512 error(ERR_NONFATAL, "non-constant value given to `%%rep'");
2513 return DIRECTIVE_FOUND;
2515 i = (int)reloc_value(evalresult) + 1;
2517 else
2519 error(ERR_NONFATAL, "`%%rep' expects a repeat count");
2520 i = 0;
2522 free_tlist(origline);
2524 tmp_defining = defining;
2525 defining = nasm_malloc(sizeof(MMacro));
2526 defining->name = NULL; /* flags this macro as a %rep block */
2527 defining->casesense = 0;
2528 defining->plus = FALSE;
2529 defining->nolist = nolist;
2530 defining->in_progress = i;
2531 defining->nparam_min = defining->nparam_max = 0;
2532 defining->defaults = NULL;
2533 defining->dlist = NULL;
2534 defining->expansion = NULL;
2535 defining->next_active = istk->mstk;
2536 defining->rep_nest = tmp_defining;
2537 return DIRECTIVE_FOUND;
2539 case PP_ENDREP:
2540 if (!defining || defining->name)
2542 error(ERR_NONFATAL, "`%%endrep': no matching `%%rep'");
2543 return DIRECTIVE_FOUND;
2547 * Now we have a "macro" defined - although it has no name
2548 * and we won't be entering it in the hash tables - we must
2549 * push a macro-end marker for it on to istk->expansion.
2550 * After that, it will take care of propagating itself (a
2551 * macro-end marker line for a macro which is really a %rep
2552 * block will cause the macro to be re-expanded, complete
2553 * with another macro-end marker to ensure the process
2554 * continues) until the whole expansion is forcibly removed
2555 * from istk->expansion by a %exitrep.
2557 l = nasm_malloc(sizeof(Line));
2558 l->next = istk->expansion;
2559 l->finishes = defining;
2560 l->first = NULL;
2561 istk->expansion = l;
2563 istk->mstk = defining;
2565 list->uplevel(defining->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
2566 tmp_defining = defining;
2567 defining = defining->rep_nest;
2568 free_tlist(origline);
2569 return DIRECTIVE_FOUND;
2571 case PP_EXITREP:
2573 * We must search along istk->expansion until we hit a
2574 * macro-end marker for a macro with no name. Then we set
2575 * its `in_progress' flag to 0.
2577 for (l = istk->expansion; l; l = l->next)
2578 if (l->finishes && !l->finishes->name)
2579 break;
2581 if (l)
2582 l->finishes->in_progress = 0;
2583 else
2584 error(ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
2585 free_tlist(origline);
2586 return DIRECTIVE_FOUND;
2588 case PP_XDEFINE:
2589 case PP_IXDEFINE:
2590 case PP_DEFINE:
2591 case PP_IDEFINE:
2592 tline = tline->next;
2593 skip_white_(tline);
2594 tline = expand_id(tline);
2595 if (!tline || (tline->type != TOK_ID &&
2596 (tline->type != TOK_PREPROC_ID ||
2597 tline->text[1] != '$')))
2599 error(ERR_NONFATAL,
2600 "`%%%s%sdefine' expects a macro identifier",
2601 ((i == PP_IDEFINE || i == PP_IXDEFINE) ? "i" : ""),
2602 ((i == PP_XDEFINE || i == PP_IXDEFINE) ? "x" : ""));
2603 free_tlist(origline);
2604 return DIRECTIVE_FOUND;
2607 ctx = get_ctx(tline->text, FALSE);
2608 if (!ctx)
2609 smhead = &smacros[hash(tline->text)];
2610 else
2611 smhead = &ctx->localmac;
2612 mname = tline->text;
2613 last = tline;
2614 param_start = tline = tline->next;
2615 nparam = 0;
2617 /* Expand the macro definition now for %xdefine and %ixdefine */
2618 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
2619 tline = expand_smacro(tline);
2621 if (tok_is_(tline, "("))
2624 * This macro has parameters.
2627 tline = tline->next;
2628 while (1)
2630 skip_white_(tline);
2631 if (!tline)
2633 error(ERR_NONFATAL, "parameter identifier expected");
2634 free_tlist(origline);
2635 return DIRECTIVE_FOUND;
2637 if (tline->type != TOK_ID)
2639 error(ERR_NONFATAL,
2640 "`%s': parameter identifier expected",
2641 tline->text);
2642 free_tlist(origline);
2643 return DIRECTIVE_FOUND;
2645 tline->type = TOK_SMAC_PARAM + nparam++;
2646 tline = tline->next;
2647 skip_white_(tline);
2648 if (tok_is_(tline, ","))
2650 tline = tline->next;
2651 continue;
2653 if (!tok_is_(tline, ")"))
2655 error(ERR_NONFATAL,
2656 "`)' expected to terminate macro template");
2657 free_tlist(origline);
2658 return DIRECTIVE_FOUND;
2660 break;
2662 last = tline;
2663 tline = tline->next;
2665 if (tok_type_(tline, TOK_WHITESPACE))
2666 last = tline, tline = tline->next;
2667 macro_start = NULL;
2668 last->next = NULL;
2669 t = tline;
2670 while (t)
2672 if (t->type == TOK_ID)
2674 for (tt = param_start; tt; tt = tt->next)
2675 if (tt->type >= TOK_SMAC_PARAM &&
2676 !strcmp(tt->text, t->text))
2677 t->type = tt->type;
2679 tt = t->next;
2680 t->next = macro_start;
2681 macro_start = t;
2682 t = tt;
2685 * Good. We now have a macro name, a parameter count, and a
2686 * token list (in reverse order) for an expansion. We ought
2687 * to be OK just to create an SMacro, store it, and let
2688 * free_tlist have the rest of the line (which we have
2689 * carefully re-terminated after chopping off the expansion
2690 * from the end).
2692 if (smacro_defined(ctx, mname, nparam, &smac, i == PP_DEFINE))
2694 if (!smac)
2696 error(ERR_WARNING,
2697 "single-line macro `%s' defined both with and"
2698 " without parameters", mname);
2699 free_tlist(origline);
2700 free_tlist(macro_start);
2701 return DIRECTIVE_FOUND;
2703 else
2706 * We're redefining, so we have to take over an
2707 * existing SMacro structure. This means freeing
2708 * what was already in it.
2710 nasm_free(smac->name);
2711 free_tlist(smac->expansion);
2714 else
2716 smac = nasm_malloc(sizeof(SMacro));
2717 smac->next = *smhead;
2718 *smhead = smac;
2720 smac->name = nasm_strdup(mname);
2721 smac->casesense = ((i == PP_DEFINE) || (i == PP_XDEFINE));
2722 smac->nparam = nparam;
2723 smac->expansion = macro_start;
2724 smac->in_progress = FALSE;
2725 free_tlist(origline);
2726 return DIRECTIVE_FOUND;
2728 case PP_UNDEF:
2729 tline = tline->next;
2730 skip_white_(tline);
2731 tline = expand_id(tline);
2732 if (!tline || (tline->type != TOK_ID &&
2733 (tline->type != TOK_PREPROC_ID ||
2734 tline->text[1] != '$')))
2736 error(ERR_NONFATAL, "`%%undef' expects a macro identifier");
2737 free_tlist(origline);
2738 return DIRECTIVE_FOUND;
2740 if (tline->next)
2742 error(ERR_WARNING,
2743 "trailing garbage after macro name ignored");
2746 /* Find the context that symbol belongs to */
2747 ctx = get_ctx(tline->text, FALSE);
2748 if (!ctx)
2749 smhead = &smacros[hash(tline->text)];
2750 else
2751 smhead = &ctx->localmac;
2753 mname = tline->text;
2754 last = tline;
2755 last->next = NULL;
2758 * We now have a macro name... go hunt for it.
2760 while (smacro_defined(ctx, mname, -1, &smac, 1))
2762 /* Defined, so we need to find its predecessor and nuke it */
2763 SMacro **s;
2764 for (s = smhead; *s && *s != smac; s = &(*s)->next);
2765 if (*s)
2767 *s = smac->next;
2768 nasm_free(smac->name);
2769 free_tlist(smac->expansion);
2770 nasm_free(smac);
2773 free_tlist(origline);
2774 return DIRECTIVE_FOUND;
2776 case PP_STRLEN:
2777 tline = tline->next;
2778 skip_white_(tline);
2779 tline = expand_id(tline);
2780 if (!tline || (tline->type != TOK_ID &&
2781 (tline->type != TOK_PREPROC_ID ||
2782 tline->text[1] != '$')))
2784 error(ERR_NONFATAL,
2785 "`%%strlen' expects a macro identifier as first parameter");
2786 free_tlist(origline);
2787 return DIRECTIVE_FOUND;
2789 ctx = get_ctx(tline->text, FALSE);
2790 if (!ctx)
2791 smhead = &smacros[hash(tline->text)];
2792 else
2793 smhead = &ctx->localmac;
2794 mname = tline->text;
2795 last = tline;
2796 tline = expand_smacro(tline->next);
2797 last->next = NULL;
2799 t = tline;
2800 while (tok_type_(t, TOK_WHITESPACE))
2801 t = t->next;
2802 /* t should now point to the string */
2803 if (t->type != TOK_STRING)
2805 error(ERR_NONFATAL,
2806 "`%%strlen` requires string as second parameter");
2807 free_tlist(tline);
2808 free_tlist(origline);
2809 return DIRECTIVE_FOUND;
2812 macro_start = nasm_malloc(sizeof(*macro_start));
2813 macro_start->next = NULL;
2814 make_tok_num(macro_start, strlen(t->text) - 2);
2815 macro_start->mac = NULL;
2818 * We now have a macro name, an implicit parameter count of
2819 * zero, and a numeric token to use as an expansion. Create
2820 * and store an SMacro.
2822 if (smacro_defined(ctx, mname, 0, &smac, i == PP_STRLEN))
2824 if (!smac)
2825 error(ERR_WARNING,
2826 "single-line macro `%s' defined both with and"
2827 " without parameters", mname);
2828 else
2831 * We're redefining, so we have to take over an
2832 * existing SMacro structure. This means freeing
2833 * what was already in it.
2835 nasm_free(smac->name);
2836 free_tlist(smac->expansion);
2839 else
2841 smac = nasm_malloc(sizeof(SMacro));
2842 smac->next = *smhead;
2843 *smhead = smac;
2845 smac->name = nasm_strdup(mname);
2846 smac->casesense = (i == PP_STRLEN);
2847 smac->nparam = 0;
2848 smac->expansion = macro_start;
2849 smac->in_progress = FALSE;
2850 free_tlist(tline);
2851 free_tlist(origline);
2852 return DIRECTIVE_FOUND;
2854 case PP_SUBSTR:
2855 tline = tline->next;
2856 skip_white_(tline);
2857 tline = expand_id(tline);
2858 if (!tline || (tline->type != TOK_ID &&
2859 (tline->type != TOK_PREPROC_ID ||
2860 tline->text[1] != '$')))
2862 error(ERR_NONFATAL,
2863 "`%%substr' expects a macro identifier as first parameter");
2864 free_tlist(origline);
2865 return DIRECTIVE_FOUND;
2867 ctx = get_ctx(tline->text, FALSE);
2868 if (!ctx)
2869 smhead = &smacros[hash(tline->text)];
2870 else
2871 smhead = &ctx->localmac;
2872 mname = tline->text;
2873 last = tline;
2874 tline = expand_smacro(tline->next);
2875 last->next = NULL;
2877 t = tline->next;
2878 while (tok_type_(t, TOK_WHITESPACE))
2879 t = t->next;
2881 /* t should now point to the string */
2882 if (t->type != TOK_STRING)
2884 error(ERR_NONFATAL,
2885 "`%%substr` requires string as second parameter");
2886 free_tlist(tline);
2887 free_tlist(origline);
2888 return DIRECTIVE_FOUND;
2891 tt = t->next;
2892 tptr = &tt;
2893 tokval.t_type = TOKEN_INVALID;
2894 evalresult =
2895 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2896 if (!evalresult)
2898 free_tlist(tline);
2899 free_tlist(origline);
2900 return DIRECTIVE_FOUND;
2902 if (!is_simple(evalresult))
2904 error(ERR_NONFATAL, "non-constant value given to `%%substr`");
2905 free_tlist(tline);
2906 free_tlist(origline);
2907 return DIRECTIVE_FOUND;
2910 macro_start = nasm_malloc(sizeof(*macro_start));
2911 macro_start->next = NULL;
2912 macro_start->text = nasm_strdup("'''");
2913 if (evalresult->value > 0
2914 && evalresult->value < strlen(t->text) - 1)
2916 macro_start->text[1] = t->text[evalresult->value];
2918 else
2920 macro_start->text[2] = '\0';
2922 macro_start->type = TOK_STRING;
2923 macro_start->mac = NULL;
2926 * We now have a macro name, an implicit parameter count of
2927 * zero, and a numeric token to use as an expansion. Create
2928 * and store an SMacro.
2930 if (smacro_defined(ctx, mname, 0, &smac, i == PP_SUBSTR))
2932 if (!smac)
2933 error(ERR_WARNING,
2934 "single-line macro `%s' defined both with and"
2935 " without parameters", mname);
2936 else
2939 * We're redefining, so we have to take over an
2940 * existing SMacro structure. This means freeing
2941 * what was already in it.
2943 nasm_free(smac->name);
2944 free_tlist(smac->expansion);
2947 else
2949 smac = nasm_malloc(sizeof(SMacro));
2950 smac->next = *smhead;
2951 *smhead = smac;
2953 smac->name = nasm_strdup(mname);
2954 smac->casesense = (i == PP_SUBSTR);
2955 smac->nparam = 0;
2956 smac->expansion = macro_start;
2957 smac->in_progress = FALSE;
2958 free_tlist(tline);
2959 free_tlist(origline);
2960 return DIRECTIVE_FOUND;
2963 case PP_ASSIGN:
2964 case PP_IASSIGN:
2965 tline = tline->next;
2966 skip_white_(tline);
2967 tline = expand_id(tline);
2968 if (!tline || (tline->type != TOK_ID &&
2969 (tline->type != TOK_PREPROC_ID ||
2970 tline->text[1] != '$')))
2972 error(ERR_NONFATAL,
2973 "`%%%sassign' expects a macro identifier",
2974 (i == PP_IASSIGN ? "i" : ""));
2975 free_tlist(origline);
2976 return DIRECTIVE_FOUND;
2978 ctx = get_ctx(tline->text, FALSE);
2979 if (!ctx)
2980 smhead = &smacros[hash(tline->text)];
2981 else
2982 smhead = &ctx->localmac;
2983 mname = tline->text;
2984 last = tline;
2985 tline = expand_smacro(tline->next);
2986 last->next = NULL;
2988 t = tline;
2989 tptr = &t;
2990 tokval.t_type = TOKEN_INVALID;
2991 evalresult =
2992 evaluate(ppscan, tptr, &tokval, NULL, pass, error, NULL);
2993 free_tlist(tline);
2994 if (!evalresult)
2996 free_tlist(origline);
2997 return DIRECTIVE_FOUND;
3000 if (tokval.t_type)
3001 error(ERR_WARNING,
3002 "trailing garbage after expression ignored");
3004 if (!is_simple(evalresult))
3006 error(ERR_NONFATAL,
3007 "non-constant value given to `%%%sassign'",
3008 (i == PP_IASSIGN ? "i" : ""));
3009 free_tlist(origline);
3010 return DIRECTIVE_FOUND;
3013 macro_start = nasm_malloc(sizeof(*macro_start));
3014 macro_start->next = NULL;
3015 make_tok_num(macro_start, reloc_value(evalresult));
3016 macro_start->mac = NULL;
3019 * We now have a macro name, an implicit parameter count of
3020 * zero, and a numeric token to use as an expansion. Create
3021 * and store an SMacro.
3023 if (smacro_defined(ctx, mname, 0, &smac, i == PP_ASSIGN))
3025 if (!smac)
3026 error(ERR_WARNING,
3027 "single-line macro `%s' defined both with and"
3028 " without parameters", mname);
3029 else
3032 * We're redefining, so we have to take over an
3033 * existing SMacro structure. This means freeing
3034 * what was already in it.
3036 nasm_free(smac->name);
3037 free_tlist(smac->expansion);
3040 else
3042 smac = nasm_malloc(sizeof(SMacro));
3043 smac->next = *smhead;
3044 *smhead = smac;
3046 smac->name = nasm_strdup(mname);
3047 smac->casesense = (i == PP_ASSIGN);
3048 smac->nparam = 0;
3049 smac->expansion = macro_start;
3050 smac->in_progress = FALSE;
3051 free_tlist(origline);
3052 return DIRECTIVE_FOUND;
3054 case PP_LINE:
3056 * Syntax is `%line nnn[+mmm] [filename]'
3058 tline = tline->next;
3059 skip_white_(tline);
3060 if (!tok_type_(tline, TOK_NUMBER))
3062 error(ERR_NONFATAL, "`%%line' expects line number");
3063 free_tlist(origline);
3064 return DIRECTIVE_FOUND;
3066 k = readnum(tline->text, &j);
3067 m = 1;
3068 tline = tline->next;
3069 if (tok_is_(tline, "+"))
3071 tline = tline->next;
3072 if (!tok_type_(tline, TOK_NUMBER))
3074 error(ERR_NONFATAL, "`%%line' expects line increment");
3075 free_tlist(origline);
3076 return DIRECTIVE_FOUND;
3078 m = readnum(tline->text, &j);
3079 tline = tline->next;
3081 skip_white_(tline);
3082 src_set_linnum(k);
3083 istk->lineinc = m;
3084 if (tline)
3086 nasm_free(src_set_fname(detoken(tline, FALSE)));
3088 free_tlist(origline);
3089 return DIRECTIVE_FOUND;
3091 default:
3092 error(ERR_FATAL,
3093 "preprocessor directive `%s' not yet implemented",
3094 directives[i]);
3095 break;
3097 return DIRECTIVE_FOUND;
3101 * Ensure that a macro parameter contains a condition code and
3102 * nothing else. Return the condition code index if so, or -1
3103 * otherwise.
3105 static int
3106 find_cc(Token * t)
3108 Token *tt;
3109 int i, j, k, m;
3111 skip_white_(t);
3112 if (t->type != TOK_ID)
3113 return -1;
3114 tt = t->next;
3115 skip_white_(tt);
3116 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
3117 return -1;
3119 i = -1;
3120 j = elements(conditions);
3121 while (j - i > 1)
3123 k = (j + i) / 2;
3124 m = nasm_stricmp(t->text, conditions[k]);
3125 if (m == 0)
3127 i = k;
3128 j = -2;
3129 break;
3131 else if (m < 0)
3133 j = k;
3135 else
3136 i = k;
3138 if (j != -2)
3139 return -1;
3140 return i;
3144 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3145 * %-n) and MMacro-local identifiers (%%foo).
3147 static Token *
3148 expand_mmac_params(Token * tline)
3150 Token *t, *tt, **tail, *thead;
3152 tail = &thead;
3153 thead = NULL;
3155 while (tline)
3157 if (tline->type == TOK_PREPROC_ID &&
3158 (((tline->text[1] == '+' || tline->text[1] == '-')
3159 && tline->text[2]) || tline->text[1] == '%'
3160 || (tline->text[1] >= '0' && tline->text[1] <= '9')))
3162 char *text = NULL;
3163 int type = 0, cc; /* type = 0 to placate optimisers */
3164 char tmpbuf[30];
3165 int n, i;
3166 MMacro *mac;
3168 t = tline;
3169 tline = tline->next;
3171 mac = istk->mstk;
3172 while (mac && !mac->name) /* avoid mistaking %reps for macros */
3173 mac = mac->next_active;
3174 if (!mac)
3175 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
3176 else
3177 switch (t->text[1])
3180 * We have to make a substitution of one of the
3181 * forms %1, %-1, %+1, %%foo, %0.
3183 case '0':
3184 type = TOK_NUMBER;
3185 sprintf(tmpbuf, "%d", mac->nparam);
3186 text = nasm_strdup(tmpbuf);
3187 break;
3188 case '%':
3189 type = TOK_ID;
3190 sprintf(tmpbuf, "..@%lu.", mac->unique);
3191 text = nasm_strcat(tmpbuf, t->text + 2);
3192 break;
3193 case '-':
3194 n = atoi(t->text + 2) - 1;
3195 if (n >= mac->nparam)
3196 tt = NULL;
3197 else
3199 if (mac->nparam > 1)
3200 n = (n + mac->rotate) % mac->nparam;
3201 tt = mac->params[n];
3203 cc = find_cc(tt);
3204 if (cc == -1)
3206 error(ERR_NONFATAL,
3207 "macro parameter %d is not a condition code",
3208 n + 1);
3209 text = NULL;
3211 else
3213 type = TOK_ID;
3214 if (inverse_ccs[cc] == -1)
3216 error(ERR_NONFATAL,
3217 "condition code `%s' is not invertible",
3218 conditions[cc]);
3219 text = NULL;
3221 else
3222 text =
3223 nasm_strdup(conditions[inverse_ccs
3224 [cc]]);
3226 break;
3227 case '+':
3228 n = atoi(t->text + 2) - 1;
3229 if (n >= mac->nparam)
3230 tt = NULL;
3231 else
3233 if (mac->nparam > 1)
3234 n = (n + mac->rotate) % mac->nparam;
3235 tt = mac->params[n];
3237 cc = find_cc(tt);
3238 if (cc == -1)
3240 error(ERR_NONFATAL,
3241 "macro parameter %d is not a condition code",
3242 n + 1);
3243 text = NULL;
3245 else
3247 type = TOK_ID;
3248 text = nasm_strdup(conditions[cc]);
3250 break;
3251 default:
3252 n = atoi(t->text + 1) - 1;
3253 if (n >= mac->nparam)
3254 tt = NULL;
3255 else
3257 if (mac->nparam > 1)
3258 n = (n + mac->rotate) % mac->nparam;
3259 tt = mac->params[n];
3261 if (tt)
3263 for (i = 0; i < mac->paramlen[n]; i++)
3265 *tail =
3266 new_Token(NULL, tt->type, tt->text,
3268 tail = &(*tail)->next;
3269 tt = tt->next;
3272 text = NULL; /* we've done it here */
3273 break;
3275 if (!text)
3277 delete_Token(t);
3279 else
3281 *tail = t;
3282 tail = &t->next;
3283 t->type = type;
3284 nasm_free(t->text);
3285 t->text = text;
3286 t->mac = NULL;
3288 continue;
3290 else
3292 t = *tail = tline;
3293 tline = tline->next;
3294 t->mac = NULL;
3295 tail = &t->next;
3298 *tail = NULL;
3299 t = thead;
3300 for (; t && (tt = t->next) != NULL; t = t->next)
3301 switch (t->type)
3303 case TOK_WHITESPACE:
3304 if (tt->type == TOK_WHITESPACE)
3306 t->next = delete_Token(tt);
3308 break;
3309 case TOK_ID:
3310 if (tt->type == TOK_ID || tt->type == TOK_NUMBER)
3312 char *tmp = nasm_strcat(t->text, tt->text);
3313 nasm_free(t->text);
3314 t->text = tmp;
3315 t->next = delete_Token(tt);
3317 break;
3318 case TOK_NUMBER:
3319 if (tt->type == TOK_NUMBER)
3321 char *tmp = nasm_strcat(t->text, tt->text);
3322 nasm_free(t->text);
3323 t->text = tmp;
3324 t->next = delete_Token(tt);
3326 break;
3329 return thead;
3333 * Expand all single-line macro calls made in the given line.
3334 * Return the expanded version of the line. The original is deemed
3335 * to be destroyed in the process. (In reality we'll just move
3336 * Tokens from input to output a lot of the time, rather than
3337 * actually bothering to destroy and replicate.)
3339 static Token *
3340 expand_smacro(Token * tline)
3342 Token *t, *tt, *mstart, **tail, *thead;
3343 SMacro *head = NULL, *m;
3344 Token **params;
3345 int *paramsize;
3346 int nparam, sparam, brackets, rescan;
3347 Token *org_tline = tline;
3348 Context *ctx;
3349 char *mname;
3352 * Trick: we should avoid changing the start token pointer since it can
3353 * be contained in "next" field of other token. Because of this
3354 * we allocate a copy of first token and work with it; at the end of
3355 * routine we copy it back
3357 if (org_tline)
3359 tline =
3360 new_Token(org_tline->next, org_tline->type, org_tline->text,
3362 tline->mac = org_tline->mac;
3363 nasm_free(org_tline->text);
3364 org_tline->text = NULL;
3367 again:
3368 tail = &thead;
3369 thead = NULL;
3371 while (tline)
3372 { /* main token loop */
3373 if ((mname = tline->text))
3375 /* if this token is a local macro, look in local context */
3376 if (tline->type == TOK_ID || tline->type == TOK_PREPROC_ID)
3377 ctx = get_ctx(mname, TRUE);
3378 else
3379 ctx = NULL;
3380 if (!ctx)
3381 head = smacros[hash(mname)];
3382 else
3383 head = ctx->localmac;
3385 * We've hit an identifier. As in is_mmacro below, we first
3386 * check whether the identifier is a single-line macro at
3387 * all, then think about checking for parameters if
3388 * necessary.
3390 for (m = head; m; m = m->next)
3391 if (!mstrcmp(m->name, mname, m->casesense))
3392 break;
3393 if (m)
3395 mstart = tline;
3396 params = NULL;
3397 paramsize = NULL;
3398 if (m->nparam == 0)
3401 * Simple case: the macro is parameterless. Discard the
3402 * one token that the macro call took, and push the
3403 * expansion back on the to-do stack.
3405 if (!m->expansion)
3407 if (!strcmp("__FILE__", m->name))
3409 long num = 0;
3410 src_get(&num, &(tline->text));
3411 nasm_quote(&(tline->text));
3412 tline->type = TOK_STRING;
3413 continue;
3415 if (!strcmp("__LINE__", m->name))
3417 nasm_free(tline->text);
3418 make_tok_num(tline, src_get_linnum());
3419 continue;
3421 tline = delete_Token(tline);
3422 continue;
3425 else
3428 * Complicated case: at least one macro with this name
3429 * exists and takes parameters. We must find the
3430 * parameters in the call, count them, find the SMacro
3431 * that corresponds to that form of the macro call, and
3432 * substitute for the parameters when we expand. What a
3433 * pain.
3435 /*tline = tline->next;
3436 skip_white_(tline);*/
3437 do {
3438 t = tline->next;
3439 while (tok_type_(t, TOK_SMAC_END))
3441 t->mac->in_progress = FALSE;
3442 t->text = NULL;
3443 t = tline->next = delete_Token(t);
3445 tline = t;
3446 } while (tok_type_(tline, TOK_WHITESPACE));
3447 if (!tok_is_(tline, "("))
3450 * This macro wasn't called with parameters: ignore
3451 * the call. (Behaviour borrowed from gnu cpp.)
3453 tline = mstart;
3454 m = NULL;
3456 else
3458 int paren = 0;
3459 int white = 0;
3460 brackets = 0;
3461 nparam = 0;
3462 sparam = PARAM_DELTA;
3463 params = nasm_malloc(sparam * sizeof(Token *));
3464 params[0] = tline->next;
3465 paramsize = nasm_malloc(sparam * sizeof(int));
3466 paramsize[0] = 0;
3467 while (TRUE)
3468 { /* parameter loop */
3470 * For some unusual expansions
3471 * which concatenates function call
3473 t = tline->next;
3474 while (tok_type_(t, TOK_SMAC_END))
3476 t->mac->in_progress = FALSE;
3477 t->text = NULL;
3478 t = tline->next = delete_Token(t);
3480 tline = t;
3482 if (!tline)
3484 error(ERR_NONFATAL,
3485 "macro call expects terminating `)'");
3486 break;
3488 if (tline->type == TOK_WHITESPACE
3489 && brackets <= 0)
3491 if (paramsize[nparam])
3492 white++;
3493 else
3494 params[nparam] = tline->next;
3495 continue; /* parameter loop */
3497 if (tline->type == TOK_OTHER
3498 && tline->text[1] == 0)
3500 char ch = tline->text[0];
3501 if (ch == ',' && !paren && brackets <= 0)
3503 if (++nparam >= sparam)
3505 sparam += PARAM_DELTA;
3506 params = nasm_realloc(params,
3507 sparam * sizeof(Token *));
3508 paramsize = nasm_realloc(paramsize,
3509 sparam * sizeof(int));
3511 params[nparam] = tline->next;
3512 paramsize[nparam] = 0;
3513 white = 0;
3514 continue; /* parameter loop */
3516 if (ch == '{' &&
3517 (brackets > 0 || (brackets == 0 &&
3518 !paramsize[nparam])))
3520 if (!(brackets++))
3522 params[nparam] = tline->next;
3523 continue; /* parameter loop */
3526 if (ch == '}' && brackets > 0)
3527 if (--brackets == 0)
3529 brackets = -1;
3530 continue; /* parameter loop */
3532 if (ch == '(' && !brackets)
3533 paren++;
3534 if (ch == ')' && brackets <= 0)
3535 if (--paren < 0)
3536 break;
3538 if (brackets < 0)
3540 brackets = 0;
3541 error(ERR_NONFATAL, "braces do not "
3542 "enclose all of macro parameter");
3544 paramsize[nparam] += white + 1;
3545 white = 0;
3546 } /* parameter loop */
3547 nparam++;
3548 while (m && (m->nparam != nparam ||
3549 mstrcmp(m->name, mname,
3550 m->casesense)))
3551 m = m->next;
3552 if (!m)
3553 error(ERR_WARNING | ERR_WARN_MNP,
3554 "macro `%s' exists, "
3555 "but not taking %d parameters",
3556 mstart->text, nparam);
3559 if (m && m->in_progress)
3560 m = NULL;
3561 if (!m) /* in progess or didn't find '(' or wrong nparam */
3564 * Design question: should we handle !tline, which
3565 * indicates missing ')' here, or expand those
3566 * macros anyway, which requires the (t) test a few
3567 * lines down?
3569 nasm_free(params);
3570 nasm_free(paramsize);
3571 tline = mstart;
3573 else
3576 * Expand the macro: we are placed on the last token of the
3577 * call, so that we can easily split the call from the
3578 * following tokens. We also start by pushing an SMAC_END
3579 * token for the cycle removal.
3581 t = tline;
3582 if (t)
3584 tline = t->next;
3585 t->next = NULL;
3587 tt = new_Token(tline, TOK_SMAC_END, NULL, 0);
3588 tt->mac = m;
3589 m->in_progress = TRUE;
3590 tline = tt;
3591 for (t = m->expansion; t; t = t->next)
3593 if (t->type >= TOK_SMAC_PARAM)
3595 Token *pcopy = tline, **ptail = &pcopy;
3596 Token *ttt, *pt;
3597 int i;
3599 ttt = params[t->type - TOK_SMAC_PARAM];
3600 for (i = paramsize[t->type - TOK_SMAC_PARAM];
3601 --i >= 0;)
3603 pt = *ptail =
3604 new_Token(tline, ttt->type, ttt->text,
3606 ptail = &pt->next;
3607 ttt = ttt->next;
3609 tline = pcopy;
3611 else
3613 tt = new_Token(tline, t->type, t->text, 0);
3614 tline = tt;
3619 * Having done that, get rid of the macro call, and clean
3620 * up the parameters.
3622 nasm_free(params);
3623 nasm_free(paramsize);
3624 free_tlist(mstart);
3625 continue; /* main token loop */
3630 if (tline->type == TOK_SMAC_END)
3632 tline->mac->in_progress = FALSE;
3633 tline = delete_Token(tline);
3635 else
3637 t = *tail = tline;
3638 tline = tline->next;
3639 t->mac = NULL;
3640 t->next = NULL;
3641 tail = &t->next;
3646 * Now scan the entire line and look for successive TOK_IDs that resulted
3647 * after expansion (they can't be produced by tokenise()). The successive
3648 * TOK_IDs should be concatenated.
3649 * Also we look for %+ tokens and concatenate the tokens before and after
3650 * them (without white spaces in between).
3652 t = thead;
3653 rescan = 0;
3654 while (t)
3656 while (t && t->type != TOK_ID && t->type != TOK_PREPROC_ID)
3657 t = t->next;
3658 if (!t || !t->next)
3659 break;
3660 if (t->next->type == TOK_ID ||
3661 t->next->type == TOK_PREPROC_ID ||
3662 t->next->type == TOK_NUMBER)
3664 char *p = nasm_strcat(t->text, t->next->text);
3665 nasm_free(t->text);
3666 t->next = delete_Token(t->next);
3667 t->text = p;
3668 rescan = 1;
3670 else if (t->next->type == TOK_WHITESPACE && t->next->next &&
3671 t->next->next->type == TOK_PREPROC_ID &&
3672 strcmp(t->next->next->text, "%+") == 0)
3674 /* free the next whitespace, the %+ token and next whitespace */
3675 int i;
3676 for (i = 1; i <= 3; i++)
3678 if (!t->next || (i != 2 && t->next->type != TOK_WHITESPACE))
3679 break;
3680 t->next = delete_Token(t->next);
3681 } /* endfor */
3683 else
3684 t = t->next;
3686 /* If we concatenaded something, re-scan the line for macros */
3687 if (rescan)
3689 tline = thead;
3690 goto again;
3693 if (org_tline)
3695 if (thead)
3697 *org_tline = *thead;
3698 /* since we just gave text to org_line, don't free it */
3699 thead->text = NULL;
3700 delete_Token(thead);
3702 else
3704 /* the expression expanded to empty line;
3705 we can't return NULL for some reasons
3706 we just set the line to a single WHITESPACE token. */
3707 memset(org_tline, 0, sizeof(*org_tline));
3708 org_tline->text = NULL;
3709 org_tline->type = TOK_WHITESPACE;
3711 thead = org_tline;
3714 return thead;
3718 * Similar to expand_smacro but used exclusively with macro identifiers
3719 * right before they are fetched in. The reason is that there can be
3720 * identifiers consisting of several subparts. We consider that if there
3721 * are more than one element forming the name, user wants a expansion,
3722 * otherwise it will be left as-is. Example:
3724 * %define %$abc cde
3726 * the identifier %$abc will be left as-is so that the handler for %define
3727 * will suck it and define the corresponding value. Other case:
3729 * %define _%$abc cde
3731 * In this case user wants name to be expanded *before* %define starts
3732 * working, so we'll expand %$abc into something (if it has a value;
3733 * otherwise it will be left as-is) then concatenate all successive
3734 * PP_IDs into one.
3736 static Token *
3737 expand_id(Token * tline)
3739 Token *cur, *oldnext = NULL;
3741 if (!tline || !tline->next)
3742 return tline;
3744 cur = tline;
3745 while (cur->next &&
3746 (cur->next->type == TOK_ID ||
3747 cur->next->type == TOK_PREPROC_ID || cur->next->type == TOK_NUMBER))
3748 cur = cur->next;
3750 /* If identifier consists of just one token, don't expand */
3751 if (cur == tline)
3752 return tline;
3754 if (cur)
3756 oldnext = cur->next; /* Detach the tail past identifier */
3757 cur->next = NULL; /* so that expand_smacro stops here */
3760 tline = expand_smacro(tline);
3762 if (cur)
3764 /* expand_smacro possibly changhed tline; re-scan for EOL */
3765 cur = tline;
3766 while (cur && cur->next)
3767 cur = cur->next;
3768 if (cur)
3769 cur->next = oldnext;
3772 return tline;
3776 * Determine whether the given line constitutes a multi-line macro
3777 * call, and return the MMacro structure called if so. Doesn't have
3778 * to check for an initial label - that's taken care of in
3779 * expand_mmacro - but must check numbers of parameters. Guaranteed
3780 * to be called with tline->type == TOK_ID, so the putative macro
3781 * name is easy to find.
3783 static MMacro *
3784 is_mmacro(Token * tline, Token *** params_array)
3786 MMacro *head, *m;
3787 Token **params;
3788 int nparam;
3790 head = mmacros[hash(tline->text)];
3793 * Efficiency: first we see if any macro exists with the given
3794 * name. If not, we can return NULL immediately. _Then_ we
3795 * count the parameters, and then we look further along the
3796 * list if necessary to find the proper MMacro.
3798 for (m = head; m; m = m->next)
3799 if (!mstrcmp(m->name, tline->text, m->casesense))
3800 break;
3801 if (!m)
3802 return NULL;
3805 * OK, we have a potential macro. Count and demarcate the
3806 * parameters.
3808 count_mmac_params(tline->next, &nparam, &params);
3811 * So we know how many parameters we've got. Find the MMacro
3812 * structure that handles this number.
3814 while (m)
3816 if (m->nparam_min <= nparam && (m->plus || nparam <= m->nparam_max))
3819 * This one is right. Just check if cycle removal
3820 * prohibits us using it before we actually celebrate...
3822 if (m->in_progress)
3824 #if 0
3825 error(ERR_NONFATAL,
3826 "self-reference in multi-line macro `%s'", m->name);
3827 #endif
3828 nasm_free(params);
3829 return NULL;
3832 * It's right, and we can use it. Add its default
3833 * parameters to the end of our list if necessary.
3835 if (m->defaults && nparam < m->nparam_min + m->ndefs)
3837 params =
3838 nasm_realloc(params,
3839 ((m->nparam_min + m->ndefs + 1) * sizeof(*params)));
3840 while (nparam < m->nparam_min + m->ndefs)
3842 params[nparam] = m->defaults[nparam - m->nparam_min];
3843 nparam++;
3847 * If we've gone over the maximum parameter count (and
3848 * we're in Plus mode), ignore parameters beyond
3849 * nparam_max.
3851 if (m->plus && nparam > m->nparam_max)
3852 nparam = m->nparam_max;
3854 * Then terminate the parameter list, and leave.
3856 if (!params)
3857 { /* need this special case */
3858 params = nasm_malloc(sizeof(*params));
3859 nparam = 0;
3861 params[nparam] = NULL;
3862 *params_array = params;
3863 return m;
3866 * This one wasn't right: look for the next one with the
3867 * same name.
3869 for (m = m->next; m; m = m->next)
3870 if (!mstrcmp(m->name, tline->text, m->casesense))
3871 break;
3875 * After all that, we didn't find one with the right number of
3876 * parameters. Issue a warning, and fail to expand the macro.
3878 error(ERR_WARNING | ERR_WARN_MNP,
3879 "macro `%s' exists, but not taking %d parameters",
3880 tline->text, nparam);
3881 nasm_free(params);
3882 return NULL;
3886 * Expand the multi-line macro call made by the given line, if
3887 * there is one to be expanded. If there is, push the expansion on
3888 * istk->expansion and return 1. Otherwise return 0.
3890 static int
3891 expand_mmacro(Token * tline)
3893 Token *startline = tline;
3894 Token *label = NULL;
3895 int dont_prepend = 0;
3896 Token **params, *t, *tt;
3897 MMacro *m;
3898 Line *l, *ll;
3899 int i, nparam, *paramlen;
3901 t = tline;
3902 skip_white_(t);
3903 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
3904 if (!tok_type_(t, TOK_ID) && !tok_type_(t, TOK_PREPROC_ID))
3905 return 0;
3906 m = is_mmacro(t, &params);
3907 if (!m)
3909 Token *last;
3911 * We have an id which isn't a macro call. We'll assume
3912 * it might be a label; we'll also check to see if a
3913 * colon follows it. Then, if there's another id after
3914 * that lot, we'll check it again for macro-hood.
3916 label = last = t;
3917 t = t->next;
3918 if (tok_type_(t, TOK_WHITESPACE))
3919 last = t, t = t->next;
3920 if (tok_is_(t, ":"))
3922 dont_prepend = 1;
3923 last = t, t = t->next;
3924 if (tok_type_(t, TOK_WHITESPACE))
3925 last = t, t = t->next;
3927 if (!tok_type_(t, TOK_ID) || (m = is_mmacro(t, &params)) == NULL)
3928 return 0;
3929 last->next = NULL;
3930 tline = t;
3934 * Fix up the parameters: this involves stripping leading and
3935 * trailing whitespace, then stripping braces if they are
3936 * present.
3938 for (nparam = 0; params[nparam]; nparam++)
3940 paramlen = nparam ? nasm_malloc(nparam * sizeof(*paramlen)) : NULL;
3942 for (i = 0; params[i]; i++)
3944 int brace = FALSE;
3945 int comma = (!m->plus || i < nparam - 1);
3947 t = params[i];
3948 skip_white_(t);
3949 if (tok_is_(t, "{"))
3950 t = t->next, brace = TRUE, comma = FALSE;
3951 params[i] = t;
3952 paramlen[i] = 0;
3953 while (t)
3955 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
3956 break; /* ... because we have hit a comma */
3957 if (comma && t->type == TOK_WHITESPACE && tok_is_(t->next, ","))
3958 break; /* ... or a space then a comma */
3959 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
3960 break; /* ... or a brace */
3961 t = t->next;
3962 paramlen[i]++;
3967 * OK, we have a MMacro structure together with a set of
3968 * parameters. We must now go through the expansion and push
3969 * copies of each Line on to istk->expansion. Substitution of
3970 * parameter tokens and macro-local tokens doesn't get done
3971 * until the single-line macro substitution process; this is
3972 * because delaying them allows us to change the semantics
3973 * later through %rotate.
3975 * First, push an end marker on to istk->expansion, mark this
3976 * macro as in progress, and set up its invocation-specific
3977 * variables.
3979 ll = nasm_malloc(sizeof(Line));
3980 ll->next = istk->expansion;
3981 ll->finishes = m;
3982 ll->first = NULL;
3983 istk->expansion = ll;
3985 m->in_progress = TRUE;
3986 m->params = params;
3987 m->iline = tline;
3988 m->nparam = nparam;
3989 m->rotate = 0;
3990 m->paramlen = paramlen;
3991 m->unique = unique++;
3992 m->lineno = 0;
3994 m->next_active = istk->mstk;
3995 istk->mstk = m;
3997 for (l = m->expansion; l; l = l->next)
3999 Token **tail;
4001 ll = nasm_malloc(sizeof(Line));
4002 ll->finishes = NULL;
4003 ll->next = istk->expansion;
4004 istk->expansion = ll;
4005 tail = &ll->first;
4007 for (t = l->first; t; t = t->next)
4009 Token *x = t;
4010 if (t->type == TOK_PREPROC_ID &&
4011 t->text[1] == '0' && t->text[2] == '0')
4013 dont_prepend = -1;
4014 x = label;
4015 if (!x)
4016 continue;
4018 tt = *tail = new_Token(NULL, x->type, x->text, 0);
4019 tail = &tt->next;
4021 *tail = NULL;
4025 * If we had a label, push it on as the first line of
4026 * the macro expansion.
4028 if (label)
4030 if (dont_prepend < 0)
4031 free_tlist(startline);
4032 else
4034 ll = nasm_malloc(sizeof(Line));
4035 ll->finishes = NULL;
4036 ll->next = istk->expansion;
4037 istk->expansion = ll;
4038 ll->first = startline;
4039 if (!dont_prepend)
4041 while (label->next)
4042 label = label->next;
4043 label->next = tt = new_Token(NULL, TOK_OTHER, ":", 0);
4048 list->uplevel(m->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
4050 return 1;
4054 * Since preprocessor always operate only on the line that didn't
4055 * arrived yet, we should always use ERR_OFFBY1. Also since user
4056 * won't want to see same error twice (preprocessing is done once
4057 * per pass) we will want to show errors only during pass one.
4059 static void
4060 error(int severity, const char *fmt, ...)
4062 va_list arg;
4063 char buff[1024];
4065 /* If we're in a dead branch of IF or something like it, ignore the error */
4066 if (istk && istk->conds && !emitting(istk->conds->state))
4067 return;
4069 va_start(arg, fmt);
4070 vsprintf(buff, fmt, arg);
4071 va_end(arg);
4073 if (istk && istk->mstk && istk->mstk->name)
4074 _error(severity | ERR_PASS1, "(%s:%d) %s", istk->mstk->name,
4075 istk->mstk->lineno, buff);
4076 else
4077 _error(severity | ERR_PASS1, "%s", buff);
4080 static void
4081 pp_reset(char *file, int apass, efunc errfunc, evalfunc eval,
4082 ListGen * listgen)
4084 int h;
4086 _error = errfunc;
4087 cstk = NULL;
4088 istk = nasm_malloc(sizeof(Include));
4089 istk->next = NULL;
4090 istk->conds = NULL;
4091 istk->expansion = NULL;
4092 istk->mstk = NULL;
4093 istk->fp = fopen(file, "r");
4094 istk->fname = NULL;
4095 src_set_fname(nasm_strdup(file));
4096 src_set_linnum(0);
4097 istk->lineinc = 1;
4098 if (!istk->fp)
4099 error(ERR_FATAL | ERR_NOFILE, "unable to open input file `%s'", file);
4100 defining = NULL;
4101 for (h = 0; h < NHASH; h++)
4103 mmacros[h] = NULL;
4104 smacros[h] = NULL;
4106 unique = 0;
4107 if (tasm_compatible_mode) {
4108 stdmacpos = stdmac;
4109 } else {
4110 stdmacpos = &stdmac[TASM_MACRO_COUNT];
4112 any_extrastdmac = (extrastdmac != NULL);
4113 list = listgen;
4114 evaluate = eval;
4115 pass = apass;
4118 static char *
4119 pp_getline(void)
4121 char *line;
4122 Token *tline;
4124 while (1)
4127 * Fetch a tokenised line, either from the macro-expansion
4128 * buffer or from the input file.
4130 tline = NULL;
4131 while (istk->expansion && istk->expansion->finishes)
4133 Line *l = istk->expansion;
4134 if (!l->finishes->name && l->finishes->in_progress > 1)
4136 Line *ll;
4139 * This is a macro-end marker for a macro with no
4140 * name, which means it's not really a macro at all
4141 * but a %rep block, and the `in_progress' field is
4142 * more than 1, meaning that we still need to
4143 * repeat. (1 means the natural last repetition; 0
4144 * means termination by %exitrep.) We have
4145 * therefore expanded up to the %endrep, and must
4146 * push the whole block on to the expansion buffer
4147 * again. We don't bother to remove the macro-end
4148 * marker: we'd only have to generate another one
4149 * if we did.
4151 l->finishes->in_progress--;
4152 for (l = l->finishes->expansion; l; l = l->next)
4154 Token *t, *tt, **tail;
4156 ll = nasm_malloc(sizeof(Line));
4157 ll->next = istk->expansion;
4158 ll->finishes = NULL;
4159 ll->first = NULL;
4160 tail = &ll->first;
4162 for (t = l->first; t; t = t->next)
4164 if (t->text || t->type == TOK_WHITESPACE)
4166 tt = *tail = new_Token(NULL, t->type, t->text, 0);
4167 tail = &tt->next;
4171 istk->expansion = ll;
4174 else
4177 * Check whether a `%rep' was started and not ended
4178 * within this macro expansion. This can happen and
4179 * should be detected. It's a fatal error because
4180 * I'm too confused to work out how to recover
4181 * sensibly from it.
4183 if (defining)
4185 if (defining->name)
4186 error(ERR_PANIC, "defining with name in expansion");
4187 else if (istk->mstk->name)
4188 error(ERR_FATAL, "`%%rep' without `%%endrep' within"
4189 " expansion of macro `%s'", istk->mstk->name);
4193 * FIXME: investigate the relationship at this point between
4194 * istk->mstk and l->finishes
4197 MMacro *m = istk->mstk;
4198 istk->mstk = m->next_active;
4199 if (m->name)
4202 * This was a real macro call, not a %rep, and
4203 * therefore the parameter information needs to
4204 * be freed.
4206 nasm_free(m->params);
4207 free_tlist(m->iline);
4208 nasm_free(m->paramlen);
4209 l->finishes->in_progress = FALSE;
4211 else
4212 free_mmacro(m);
4214 istk->expansion = l->next;
4215 nasm_free(l);
4216 list->downlevel(LIST_MACRO);
4219 while (1)
4220 { /* until we get a line we can use */
4222 if (istk->expansion)
4223 { /* from a macro expansion */
4224 char *p;
4225 Line *l = istk->expansion;
4226 if (istk->mstk)
4227 istk->mstk->lineno++;
4228 tline = l->first;
4229 istk->expansion = l->next;
4230 nasm_free(l);
4231 p = detoken(tline, FALSE);
4232 list->line(LIST_MACRO, p);
4233 nasm_free(p);
4234 break;
4236 line = read_line();
4237 if (line)
4238 { /* from the current input file */
4239 line = prepreproc(line);
4240 tline = tokenise(line);
4241 nasm_free(line);
4242 break;
4245 * The current file has ended; work down the istk
4248 Include *i = istk;
4249 fclose(i->fp);
4250 if (i->conds)
4251 error(ERR_FATAL, "expected `%%endif' before end of file");
4252 /* only set line and file name if there's a next node */
4253 if (i->next)
4255 src_set_linnum(i->lineno);
4256 nasm_free(src_set_fname(i->fname));
4258 istk = i->next;
4259 list->downlevel(LIST_INCLUDE);
4260 nasm_free(i);
4261 if (!istk)
4262 return NULL;
4267 * We must expand MMacro parameters and MMacro-local labels
4268 * _before_ we plunge into directive processing, to cope
4269 * with things like `%define something %1' such as STRUC
4270 * uses. Unless we're _defining_ a MMacro, in which case
4271 * those tokens should be left alone to go into the
4272 * definition; and unless we're in a non-emitting
4273 * condition, in which case we don't want to meddle with
4274 * anything.
4276 if (!defining && !(istk->conds && !emitting(istk->conds->state)))
4277 tline = expand_mmac_params(tline);
4280 * Check the line to see if it's a preprocessor directive.
4282 if (do_directive(tline) == DIRECTIVE_FOUND)
4284 continue;
4286 else if (defining)
4289 * We're defining a multi-line macro. We emit nothing
4290 * at all, and just
4291 * shove the tokenised line on to the macro definition.
4293 Line *l = nasm_malloc(sizeof(Line));
4294 l->next = defining->expansion;
4295 l->first = tline;
4296 l->finishes = FALSE;
4297 defining->expansion = l;
4298 continue;
4300 else if (istk->conds && !emitting(istk->conds->state))
4303 * We're in a non-emitting branch of a condition block.
4304 * Emit nothing at all, not even a blank line: when we
4305 * emerge from the condition we'll give a line-number
4306 * directive so we keep our place correctly.
4308 free_tlist(tline);
4309 continue;
4311 else if (istk->mstk && !istk->mstk->in_progress)
4314 * We're in a %rep block which has been terminated, so
4315 * we're walking through to the %endrep without
4316 * emitting anything. Emit nothing at all, not even a
4317 * blank line: when we emerge from the %rep block we'll
4318 * give a line-number directive so we keep our place
4319 * correctly.
4321 free_tlist(tline);
4322 continue;
4324 else
4326 tline = expand_smacro(tline);
4327 if (!expand_mmacro(tline))
4330 * De-tokenise the line again, and emit it.
4332 line = detoken(tline, TRUE);
4333 free_tlist(tline);
4334 break;
4336 else
4338 continue; /* expand_mmacro calls free_tlist */
4343 return line;
4346 static void
4347 pp_cleanup(int pass)
4349 int h;
4351 if (defining)
4353 error(ERR_NONFATAL, "end of file while still defining macro `%s'",
4354 defining->name);
4355 free_mmacro(defining);
4357 while (cstk)
4358 ctx_pop();
4359 for (h = 0; h < NHASH; h++)
4361 while (mmacros[h])
4363 MMacro *m = mmacros[h];
4364 mmacros[h] = mmacros[h]->next;
4365 free_mmacro(m);
4367 while (smacros[h])
4369 SMacro *s = smacros[h];
4370 smacros[h] = smacros[h]->next;
4371 nasm_free(s->name);
4372 free_tlist(s->expansion);
4373 nasm_free(s);
4376 while (istk)
4378 Include *i = istk;
4379 istk = istk->next;
4380 fclose(i->fp);
4381 nasm_free(i->fname);
4382 nasm_free(i);
4384 while (cstk)
4385 ctx_pop();
4386 if (pass == 0)
4388 free_llist(predef);
4389 delete_Blocks();
4393 void
4394 pp_include_path(char *path)
4396 IncPath *i;
4397 /* by alexfru: order of path inclusion fixed (was reverse order) */
4398 i = nasm_malloc(sizeof(IncPath));
4399 i->path = nasm_strdup(path);
4400 i->next = NULL;
4402 if (ipath != NULL)
4404 IncPath *j = ipath;
4405 while (j->next != NULL)
4406 j = j->next;
4407 j->next = i;
4409 else
4411 ipath = i;
4416 * added by alexfru:
4418 * This function is used to "export" the include paths, e.g.
4419 * the paths specified in the '-I' command switch.
4420 * The need for such exporting is due to the 'incbin' directive,
4421 * which includes raw binary files (unlike '%include', which
4422 * includes text source files). It would be real nice to be
4423 * able to specify paths to search for incbin'ned files also.
4424 * So, this is a simple workaround.
4426 * The function use is simple:
4428 * The 1st call (with NULL argument) returns a pointer to the 1st path
4429 * (char** type) or NULL if none include paths available.
4431 * All subsequent calls take as argument the value returned by this
4432 * function last. The return value is either the next path
4433 * (char** type) or NULL if the end of the paths list is reached.
4435 * It is maybe not the best way to do things, but I didn't want
4436 * to export too much, just one or two functions and no types or
4437 * variables exported.
4439 * Can't say I like the current situation with e.g. this path list either,
4440 * it seems to be never deallocated after creation...
4442 char**
4443 pp_get_include_path_ptr (char **pPrevPath)
4445 /* This macro returns offset of a member of a structure */
4446 #define GetMemberOffset(StructType,MemberName)\
4447 ((size_t)&((StructType*)0)->MemberName)
4448 IncPath *i;
4450 if (pPrevPath == NULL)
4452 if(ipath != NULL)
4453 return &ipath->path;
4454 else
4455 return NULL;
4457 i = (IncPath*) ((char*)pPrevPath - GetMemberOffset(IncPath,path));
4458 i = i->next;
4459 if (i != NULL)
4460 return &i->path;
4461 else
4462 return NULL;
4463 #undef GetMemberOffset
4466 void
4467 pp_pre_include(char *fname)
4469 Token *inc, *space, *name;
4470 Line *l;
4472 name = new_Token(NULL, TOK_INTERNAL_STRING, fname, 0);
4473 space = new_Token(name, TOK_WHITESPACE, NULL, 0);
4474 inc = new_Token(space, TOK_PREPROC_ID, "%include", 0);
4476 l = nasm_malloc(sizeof(Line));
4477 l->next = predef;
4478 l->first = inc;
4479 l->finishes = FALSE;
4480 predef = l;
4483 void
4484 pp_pre_define(char *definition)
4486 Token *def, *space;
4487 Line *l;
4488 char *equals;
4490 equals = strchr(definition, '=');
4491 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4492 def = new_Token(space, TOK_PREPROC_ID, "%define", 0);
4493 if (equals)
4494 *equals = ' ';
4495 space->next = tokenise(definition);
4496 if (equals)
4497 *equals = '=';
4499 l = nasm_malloc(sizeof(Line));
4500 l->next = predef;
4501 l->first = def;
4502 l->finishes = FALSE;
4503 predef = l;
4506 void
4507 pp_pre_undefine(char *definition)
4509 Token *def, *space;
4510 Line *l;
4512 space = new_Token(NULL, TOK_WHITESPACE, NULL, 0);
4513 def = new_Token(space, TOK_PREPROC_ID, "%undef", 0);
4514 space->next = tokenise(definition);
4516 l = nasm_malloc(sizeof(Line));
4517 l->next = predef;
4518 l->first = def;
4519 l->finishes = FALSE;
4520 predef = l;
4523 void
4524 pp_extra_stdmac(const char **macros)
4526 extrastdmac = macros;
4529 static void
4530 make_tok_num(Token * tok, long val)
4532 char numbuf[20];
4533 sprintf(numbuf, "%ld", val);
4534 tok->text = nasm_strdup(numbuf);
4535 tok->type = TOK_NUMBER;
4538 Preproc nasmpp = {
4539 pp_reset,
4540 pp_getline,
4541 pp_cleanup