NASM 0.98.03
[nasm/avx512.git] / preproc.c
blob5753cf2c33a6514e0e8856c2dec04677c6c7a3db
1 /* preproc.c macro preprocessor for the Netwide Assembler
3 * The Netwide Assembler is copyright (C) 1996 Simon Tatham and
4 * Julian Hall. All rights reserved. The software is
5 * redistributable under the licence given in the file "Licence"
6 * distributed in the NASM archive.
8 * initial version 18/iii/97 by Simon Tatham
9 */
11 /* Typical flow of text through preproc
13 * pp_getline gets tokenised lines, either
15 * from a macro expansion
17 * or
18 * {
19 * read_line gets raw text from stdmacpos, or predef, or current input file
20 * tokenise converts to tokens
21 * }
23 * expand_mmac_params is used to expand %1 etc., unless a macro is being
24 * defined or a false conditional is being processed
25 * (%0, %1, %+1, %-1, %%foo
27 * do_directive checks for directives
29 * expand_smacro is used to expand single line macros
31 * expand_mmacro is used to expand multi-line macros
33 * detoken is used to convert the line back to text
36 #include <stdio.h>
37 #include <stdarg.h>
38 #include <stdlib.h>
39 #include <stddef.h>
40 #include <string.h>
41 #include <ctype.h>
42 #include <limits.h>
44 #include "nasm.h"
45 #include "nasmlib.h"
47 typedef struct SMacro SMacro;
48 typedef struct MMacro MMacro;
49 typedef struct Context Context;
50 typedef struct Token Token;
51 typedef struct Line Line;
52 typedef struct Include Include;
53 typedef struct Cond Cond;
54 typedef struct IncPath IncPath;
57 * Store the definition of a single-line macro.
59 struct SMacro {
60 SMacro *next;
61 char *name;
62 int casesense;
63 int nparam;
64 int in_progress;
65 Token *expansion;
69 * Store the definition of a multi-line macro. This is also used to
70 * store the interiors of `%rep...%endrep' blocks, which are
71 * effectively self-re-invoking multi-line macros which simply
72 * don't have a name or bother to appear in the hash tables. %rep
73 * blocks are signified by having a NULL `name' field.
75 * In a MMacro describing a `%rep' block, the `in_progress' field
76 * isn't merely boolean, but gives the number of repeats left to
77 * run.
79 * The `next' field is used for storing MMacros in hash tables; the
80 * `next_active' field is for stacking them on istk entries.
82 * When a MMacro is being expanded, `params', `iline', `nparam',
83 * `paramlen', `rotate' and `unique' are local to the invocation.
85 struct MMacro {
86 MMacro *next;
87 char *name;
88 int casesense;
89 int nparam_min, nparam_max;
90 int plus; /* is the last parameter greedy? */
91 int nolist; /* is this macro listing-inhibited? */
92 int in_progress;
93 Token *dlist; /* All defaults as one list */
94 Token **defaults; /* Parameter default pointers */
95 int ndefs; /* number of default parameters */
96 Line *expansion;
98 MMacro *next_active;
99 MMacro *rep_nest; /* used for nesting %rep */
100 Token **params; /* actual parameters */
101 Token *iline; /* invocation line */
102 int nparam, rotate, *paramlen;
103 unsigned long unique;
104 int lineno; /* Current line number on expansion */
108 * The context stack is composed of a linked list of these.
110 struct Context {
111 Context *next;
112 SMacro *localmac;
113 char *name;
114 unsigned long number;
118 * This is the internal form which we break input lines up into.
119 * Typically stored in linked lists.
121 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
122 * necessarily used as-is, but is intended to denote the number of
123 * the substituted parameter. So in the definition
125 * %define a(x,y) ( (x) & ~(y) )
127 * the token representing `x' will have its type changed to
128 * TOK_SMAC_PARAM, but the one representing `y' will be
129 * TOK_SMAC_PARAM+1.
131 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
132 * which doesn't need quotes around it. Used in the pre-include
133 * mechanism as an alternative to trying to find a sensible type of
134 * quote to use on the filename we were passed.
136 struct Token {
137 Token *next;
138 char *text;
139 SMacro *mac; /* associated macro for TOK_SMAC_END */
140 int type;
142 enum {
143 TOK_WHITESPACE = 1, TOK_COMMENT, TOK_ID, TOK_PREPROC_ID, TOK_STRING,
144 TOK_NUMBER, TOK_SMAC_END, TOK_OTHER, TOK_SMAC_PARAM,
145 TOK_INTERNAL_STRING
149 * Multi-line macro definitions are stored as a linked list of
150 * these, which is essentially a container to allow several linked
151 * lists of Tokens.
153 * Note that in this module, linked lists are treated as stacks
154 * wherever possible. For this reason, Lines are _pushed_ on to the
155 * `expansion' field in MMacro structures, so that the linked list,
156 * if walked, would give the macro lines in reverse order; this
157 * means that we can walk the list when expanding a macro, and thus
158 * push the lines on to the `expansion' field in _istk_ in reverse
159 * order (so that when popped back off they are in the right
160 * order). It may seem cockeyed, and it relies on my design having
161 * an even number of steps in, but it works...
163 * Some of these structures, rather than being actual lines, are
164 * markers delimiting the end of the expansion of a given macro.
165 * This is for use in the cycle-tracking and %rep-handling code.
166 * Such structures have `finishes' non-NULL, and `first' NULL. All
167 * others have `finishes' NULL, but `first' may still be NULL if
168 * the line is blank.
170 struct Line {
171 Line *next;
172 MMacro *finishes;
173 Token *first;
177 * To handle an arbitrary level of file inclusion, we maintain a
178 * stack (ie linked list) of these things.
180 struct Include {
181 Include *next;
182 FILE *fp;
183 Cond *conds;
184 Line *expansion;
185 char *fname;
186 int lineno, lineinc;
187 MMacro *mstk; /* stack of active macros/reps */
191 * Include search path. This is simply a list of strings which get
192 * prepended, in turn, to the name of an include file, in an
193 * attempt to find the file if it's not in the current directory.
195 struct IncPath {
196 IncPath *next;
197 char *path;
201 * Conditional assembly: we maintain a separate stack of these for
202 * each level of file inclusion. (The only reason we keep the
203 * stacks separate is to ensure that a stray `%endif' in a file
204 * included from within the true branch of a `%if' won't terminate
205 * it and cause confusion: instead, rightly, it'll cause an error.)
207 struct Cond {
208 Cond *next;
209 int state;
211 enum {
213 * These states are for use just after %if or %elif: IF_TRUE
214 * means the condition has evaluated to truth so we are
215 * currently emitting, whereas IF_FALSE means we are not
216 * currently emitting but will start doing so if a %else comes
217 * up. In these states, all directives are admissible: %elif,
218 * %else and %endif. (And of course %if.)
220 COND_IF_TRUE, COND_IF_FALSE,
222 * These states come up after a %else: ELSE_TRUE means we're
223 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
224 * any %elif or %else will cause an error.
226 COND_ELSE_TRUE, COND_ELSE_FALSE,
228 * This state means that we're not emitting now, and also that
229 * nothing until %endif will be emitted at all. It's for use in
230 * two circumstances: (i) when we've had our moment of emission
231 * and have now started seeing %elifs, and (ii) when the
232 * condition construct in question is contained within a
233 * non-emitting branch of a larger condition construct.
235 COND_NEVER
237 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
240 * Condition codes. Note that we use c_ prefix not C_ because C_ is
241 * used in nasm.h for the "real" condition codes. At _this_ level,
242 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
243 * ones, so we need a different enum...
245 static char *conditions[] = {
246 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
247 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
248 "np", "ns", "nz", "o", "p", "pe", "po", "s", "z"
250 enum {
251 c_A, c_AE, c_B, c_BE, c_C, c_CXZ, c_E, c_ECXZ, c_G, c_GE, c_L, c_LE,
252 c_NA, c_NAE, c_NB, c_NBE, c_NC, c_NE, c_NG, c_NGE, c_NL, c_NLE, c_NO,
253 c_NP, c_NS, c_NZ, c_O, c_P, c_PE, c_PO, c_S, c_Z
255 static int inverse_ccs[] = {
256 c_NA, c_NAE, c_NB, c_NBE, c_NC, -1, c_NE, -1, c_NG, c_NGE, c_NL, c_NLE,
257 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,
258 c_Z, c_NO, c_NP, c_PO, c_PE, c_NS, c_NZ
262 * Directive names.
264 static char *directives[] = {
265 "%assign", "%clear", "%define", "%elif", "%elifctx", "%elifdef",
266 "%elifid", "%elifidn", "%elifidni", "%elifnctx", "%elifndef",
267 "%elifnid", "%elifnidn", "%elifnidni", "%elifnnum", "%elifnstr",
268 "%elifnum", "%elifstr", "%else", "%endif", "%endm", "%endmacro",
269 "%endrep", "%error", "%exitrep", "%iassign", "%idefine", "%if",
270 "%ifctx", "%ifdef", "%ifid", "%ifidn", "%ifidni", "%ifnctx",
271 "%ifndef", "%ifnid", "%ifnidn", "%ifnidni", "%ifnnum",
272 "%ifnstr", "%ifnum", "%ifstr", "%imacro", "%include", "%ixdefine",
273 "%line", "%macro", "%pop", "%push", "%rep", "%repl", "%rotate",
274 "%undef", "%xdefine"
276 enum {
277 PP_ASSIGN, PP_CLEAR, PP_DEFINE, PP_ELIF, PP_ELIFCTX, PP_ELIFDEF,
278 PP_ELIFID, PP_ELIFIDN, PP_ELIFIDNI, PP_ELIFNCTX, PP_ELIFNDEF,
279 PP_ELIFNID, PP_ELIFNIDN, PP_ELIFNIDNI, PP_ELIFNNUM, PP_ELIFNSTR,
280 PP_ELIFNUM, PP_ELIFSTR, PP_ELSE, PP_ENDIF, PP_ENDM, PP_ENDMACRO,
281 PP_ENDREP, PP_ERROR, PP_EXITREP, PP_IASSIGN, PP_IDEFINE, PP_IF,
282 PP_IFCTX, PP_IFDEF, PP_IFID, PP_IFIDN, PP_IFIDNI, PP_IFNCTX,
283 PP_IFNDEF, PP_IFNID, PP_IFNIDN, PP_IFNIDNI, PP_IFNNUM,
284 PP_IFNSTR, PP_IFNUM, PP_IFSTR, PP_IMACRO, PP_INCLUDE, PP_IXDEFINE,
285 PP_LINE, PP_MACRO, PP_POP, PP_PUSH, PP_REP, PP_REPL, PP_ROTATE,
286 PP_UNDEF, PP_XDEFINE
290 static Context *cstk;
291 static Include *istk;
292 static IncPath *ipath = NULL;
294 static efunc __error; /* Pointer to client-provided error reporting function */
295 static evalfunc evaluate;
297 static int pass; /* HACK: pass 0 = generate dependencies only */
299 static unsigned long unique; /* unique identifier numbers */
301 static Line *predef = NULL;
303 static ListGen *list;
306 * The number of hash values we use for the macro lookup tables.
307 * FIXME: We should *really* be able to configure this at run time,
308 * or even have the hash table automatically expanding when necessary.
310 #define NHASH 31
313 * The current set of multi-line macros we have defined.
315 static MMacro *mmacros[NHASH];
318 * The current set of single-line macros we have defined.
320 static SMacro *smacros[NHASH];
323 * The multi-line macro we are currently defining, or the %rep
324 * block we are currently reading, if any.
326 static MMacro *defining;
329 * The number of macro parameters to allocate space for at a time.
331 #define PARAM_DELTA 16
334 * The standard macro set: defined as `static char *stdmac[]'. Also
335 * gives our position in the macro set, when we're processing it.
337 #include "macros.c"
338 static char **stdmacpos;
341 * The extra standard macros that come from the object format, if
342 * any.
344 static char **extrastdmac = NULL;
345 int any_extrastdmac;
348 * Forward declarations.
350 static Token *expand_mmac_params (Token *tline);
351 static Token *expand_smacro (Token *tline);
352 static Token *expand_id (Token *tline);
353 static Context *get_ctx (char *name, int all_contexts);
354 static void make_tok_num(Token *tok, long val);
355 static void error (int severity, char *fmt, ...);
358 * Macros for safe checking of token pointers, avoid *(NULL)
360 #define tok_type_(x,t) ((x) && (x)->type == (t))
361 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
362 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
363 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
366 * The pre-preprocessing stage... This function translates line
367 * number indications as they emerge from GNU cpp (`# lineno "file"
368 * flags') into NASM preprocessor line number indications (`%line
369 * lineno file').
371 static char *prepreproc(char *line)
373 int lineno, fnlen;
374 char *fname, *oldline;
376 if (line[0] == '#' && line[1] == ' ') {
377 oldline = line;
378 fname = oldline+2;
379 lineno = atoi(fname);
380 fname += strspn(fname, "0123456789 ");
381 if (*fname == '"')
382 fname++;
383 fnlen = strcspn(fname, "\"");
384 line = nasm_malloc(20+fnlen);
385 sprintf(line, "%%line %d %.*s", lineno, fnlen, fname);
386 nasm_free (oldline);
388 return line;
392 * The hash function for macro lookups. Note that due to some
393 * macros having case-insensitive names, the hash function must be
394 * invariant under case changes. We implement this by applying a
395 * perfectly normal hash function to the uppercase of the string.
397 static int hash(char *s)
399 unsigned int h = 0;
400 int i = 0;
402 * Powers of three, mod 31.
404 static const int multipliers[] = {
405 1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10,
406 30, 28, 22, 4, 12, 5, 15, 14, 11, 2, 6, 18, 23, 7, 21
410 while (*s) {
411 h += multipliers[i] * (unsigned char) (toupper(*s));
412 s++;
413 if (++i >= sizeof(multipliers)/sizeof(*multipliers))
414 i = 0;
416 h %= NHASH;
417 return h;
421 * Free a linked list of tokens.
423 static void free_tlist (Token *list)
425 Token *t;
426 while (list) {
427 t = list;
428 list = list->next;
429 nasm_free (t->text);
430 nasm_free (t);
435 * Free a linked list of lines.
437 static void free_llist (Line *list)
439 Line *l;
440 while (list) {
441 l = list;
442 list = list->next;
443 free_tlist (l->first);
444 nasm_free (l);
449 * Free an MMacro
451 static void free_mmacro (MMacro *m)
453 nasm_free (m->name);
454 free_tlist (m->dlist);
455 nasm_free (m->defaults);
456 free_llist (m->expansion);
457 nasm_free (m);
461 * Pop the context stack.
463 static void ctx_pop (void)
465 Context *c = cstk;
466 SMacro *smac, *s;
468 cstk = cstk->next;
469 smac = c->localmac;
470 while (smac) {
471 s = smac;
472 smac = smac->next;
473 nasm_free (s->name);
474 free_tlist (s->expansion);
475 nasm_free (s);
477 nasm_free (c->name);
478 nasm_free (c);
481 #define BUF_DELTA 512
483 * Read a line from the top file in istk, handling multiple CR/LFs
484 * at the end of the line read, and handling spurious ^Zs. Will
485 * return lines from the standard macro set if this has not already
486 * been done.
488 static char *read_line (void)
490 char *buffer, *p, *q;
491 int bufsize;
493 if (stdmacpos) {
494 if (*stdmacpos) {
495 char *ret = nasm_strdup(*stdmacpos++);
496 if (!*stdmacpos && any_extrastdmac)
498 stdmacpos = extrastdmac;
499 any_extrastdmac = FALSE;
500 return ret;
503 * Nasty hack: here we push the contents of `predef' on
504 * to the top-level expansion stack, since this is the
505 * most convenient way to implement the pre-include and
506 * pre-define features.
508 if (!*stdmacpos)
510 Line *pd, *l;
511 Token *head, **tail, *t, *tt;
513 for (pd = predef; pd; pd = pd->next) {
514 head = NULL;
515 tail = &head;
516 for (t = pd->first; t; t = t->next) {
517 tt = *tail = nasm_malloc(sizeof(Token));
518 tt->next = NULL;
519 tail = &tt->next;
520 tt->type = t->type;
521 tt->text = nasm_strdup(t->text);
522 tt->mac = t->mac; /* always NULL here, in fact */
524 l = nasm_malloc(sizeof(Line));
525 l->next = istk->expansion;
526 l->first = head;
527 l->finishes = FALSE;
528 istk->expansion = l;
531 return ret;
533 else {
534 stdmacpos = NULL;
538 bufsize = BUF_DELTA;
539 buffer = nasm_malloc(BUF_DELTA);
540 p = buffer;
541 while (1) {
542 q = fgets(p, bufsize-(p-buffer), istk->fp);
543 if (!q)
544 break;
545 p += strlen(p);
546 if (p > buffer && p[-1] == '\n') {
547 break;
549 if (p-buffer > bufsize-10) {
550 long offset = p-buffer;
551 bufsize += BUF_DELTA;
552 buffer = nasm_realloc(buffer, bufsize);
553 p = buffer+offset; /* prevent stale-pointer problems */
557 if (!q && p == buffer) {
558 nasm_free (buffer);
559 return NULL;
562 src_set_linnum(src_get_linnum() + istk->lineinc);
565 * Play safe: remove CRs as well as LFs, if any of either are
566 * present at the end of the line.
568 while (--p >= buffer && (*p == '\n' || *p == '\r'))
569 *p = '\0';
572 * Handle spurious ^Z, which may be inserted into source files
573 * by some file transfer utilities.
575 buffer[strcspn(buffer, "\032")] = '\0';
577 list->line (LIST_READ, buffer);
579 return buffer;
583 * Tokenise a line of text. This is a very simple process since we
584 * don't need to parse the value out of e.g. numeric tokens: we
585 * simply split one string into many.
587 static Token *tokenise (char *line)
589 char *p = line;
590 int type;
591 Token *list = NULL;
592 Token *t, **tail = &list;
594 while (*line) {
595 p = line;
596 if (*p == '%' &&
597 (isdigit(p[1]) ||
598 ((p[1] == '-' || p[1] == '+') && isdigit(p[2])) ||
599 ((p[1] == '+') && (isspace (p[2]) || !p[2]))))
601 p++;
602 do {
603 p++;
604 } while (isdigit(*p));
605 type = TOK_PREPROC_ID;
607 else if (*p == '%' && p[1] == '{') {
608 p += 2;
609 while (*p && *p != '}') {
610 p[-1] = *p;
611 p++;
613 p[-1] = '\0';
614 if (*p) p++;
615 type = TOK_PREPROC_ID;
617 else if (*p == '%' && (isidchar(p[1]) ||
618 ((p[1] == '!' || p[1] == '%' || p[1] == '$') &&
619 isidchar(p[2]))))
621 p++;
622 do {
623 p++;
624 } while (isidchar(*p));
625 type = TOK_PREPROC_ID;
627 else if (isidstart(*p) || (*p == '$' && isidstart(p[1]))) {
628 type = TOK_ID;
629 p++;
630 while (*p && isidchar(*p))
631 p++;
633 else if (*p == '\'' || *p == '"') {
635 * A string token.
637 char c = *p;
638 p++;
639 type = TOK_STRING;
640 while (*p && *p != c)
641 p++;
642 if (*p) p++;
644 else if (isnumstart(*p)) {
646 * A number token.
648 type = TOK_NUMBER;
649 p++;
650 while (*p && isnumchar(*p))
651 p++;
653 else if (isspace(*p)) {
654 type = TOK_WHITESPACE;
655 p++;
656 while (*p && isspace(*p))
657 p++;
659 * Whitespace just before end-of-line is discarded by
660 * pretending it's a comment; whitespace just before a
661 * comment gets lumped into the comment.
663 if (!*p || *p == ';') {
664 type = TOK_COMMENT;
665 while (*p) p++;
668 else if (*p == ';') {
669 type = TOK_COMMENT;
670 while (*p) p++;
672 else {
674 * Anything else is an operator of some kind. We check
675 * for all the double-character operators (>>, <<, //,
676 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
677 * else is a single-character operator.
679 type = TOK_OTHER;
680 if ((p[0] == '>' && p[1] == '>') ||
681 (p[0] == '<' && p[1] == '<') ||
682 (p[0] == '/' && p[1] == '/') ||
683 (p[0] == '%' && p[1] == '%') ||
684 (p[0] == '<' && p[1] == '=') ||
685 (p[0] == '>' && p[1] == '=') ||
686 (p[0] == '=' && p[1] == '=') ||
687 (p[0] == '!' && p[1] == '=') ||
688 (p[0] == '<' && p[1] == '>') ||
689 (p[0] == '&' && p[1] == '&') ||
690 (p[0] == '|' && p[1] == '|') ||
691 (p[0] == '^' && p[1] == '^'))
693 p++;
695 p++;
697 if (type != TOK_COMMENT) {
698 *tail = t = nasm_malloc (sizeof(Token));
699 tail = &t->next;
700 t->next = NULL;
701 t->type = type;
702 t->text = nasm_malloc(1+p-line);
703 strncpy(t->text, line, p-line);
704 t->text[p-line] = '\0';
706 line = p;
709 return list;
713 * Convert a line of tokens back into text.
714 * If expand_locals is not zero, identifiers of the form "%$*xxx"
715 * will be transformed into ..@ctxnum.xxx
717 static char *detoken (Token *tlist, int expand_locals)
719 Token *t;
720 int len;
721 char *line, *p;
723 len = 0;
724 for (t = tlist; t; t = t->next) {
725 if (t->type == TOK_PREPROC_ID && t->text[1] == '!') {
726 char *p = getenv(t->text+2);
727 nasm_free (t->text);
728 if (p)
729 t->text = nasm_strdup(p);
730 else
731 t->text = NULL;
733 /* Expand local macros here and not during preprocessing */
734 if (expand_locals &&
735 t->type == TOK_PREPROC_ID && t->text &&
736 t->text[0] == '%' && t->text [1] == '$') {
737 Context *ctx = get_ctx (t->text, FALSE);
738 if (ctx) {
739 char buffer [40];
740 char *p, *q = t->text + 2;
742 q += strspn (q, "$");
743 sprintf (buffer, "..@%lu.", ctx->number);
744 p = nasm_malloc (strlen(buffer)+strlen(q)+1);
745 strcpy (p, buffer);
746 strcat (p, q);
747 nasm_free (t->text);
748 t->text = p;
751 if (t->text)
752 len += strlen(t->text);
754 p = line = nasm_malloc(len+1);
755 for (t = tlist; t; t = t->next) {
756 if (t->text) {
757 strcpy (p, t->text);
758 p += strlen(p);
761 *p = '\0';
762 return line;
766 * A scanner, suitable for use by the expression evaluator, which
767 * operates on a line of Tokens. Expects a pointer to a pointer to
768 * the first token in the line to be passed in as its private_data
769 * field.
771 static int ppscan(void *private_data, struct tokenval *tokval)
773 Token **tlineptr = private_data;
774 Token *tline;
776 do {
777 tline = *tlineptr;
778 *tlineptr = tline ? tline->next : NULL;
779 } while (tline && (tline->type == TOK_WHITESPACE ||
780 tline->type == TOK_COMMENT));
782 if (!tline)
783 return tokval->t_type = TOKEN_EOS;
785 if (tline->text[0] == '$' && !tline->text[1])
786 return tokval->t_type = TOKEN_HERE;
787 if (tline->text[0] == '$' && tline->text[1] == '$' && !tline->text[1])
788 return tokval->t_type = TOKEN_BASE;
790 if (tline->type == TOK_ID) {
791 tokval->t_charptr = tline->text;
792 if (tline->text[0] == '$') {
793 tokval->t_charptr++;
794 return tokval->t_type = TOKEN_ID;
798 * This is the only special case we actually need to worry
799 * about in this restricted context.
801 if (!nasm_stricmp(tline->text, "seg"))
802 return tokval->t_type = TOKEN_SEG;
804 return tokval->t_type = TOKEN_ID;
807 if (tline->type == TOK_NUMBER) {
808 int rn_error;
810 tokval->t_integer = readnum(tline->text, &rn_error);
811 if (rn_error)
812 return tokval->t_type = TOKEN_ERRNUM;
813 tokval->t_charptr = NULL;
814 return tokval->t_type = TOKEN_NUM;
817 if (tline->type == TOK_STRING) {
818 int rn_warn;
819 char q, *r;
820 int l;
822 r = tline->text;
823 q = *r++;
824 l = strlen(r);
826 if (l == 0 || r[l-1] != q)
827 return tokval->t_type = TOKEN_ERRNUM;
828 tokval->t_integer = readstrnum(r, l-1, &rn_warn);
829 if (rn_warn)
830 error(ERR_WARNING|ERR_PASS1,
831 "character constant too long");
832 tokval->t_charptr = NULL;
833 return tokval->t_type = TOKEN_NUM;
836 if (tline->type == TOK_OTHER) {
837 if (!strcmp(tline->text, "<<")) return tokval->t_type = TOKEN_SHL;
838 if (!strcmp(tline->text, ">>")) return tokval->t_type = TOKEN_SHR;
839 if (!strcmp(tline->text, "//")) return tokval->t_type = TOKEN_SDIV;
840 if (!strcmp(tline->text, "%%")) return tokval->t_type = TOKEN_SMOD;
841 if (!strcmp(tline->text, "==")) return tokval->t_type = TOKEN_EQ;
842 if (!strcmp(tline->text, "<>")) return tokval->t_type = TOKEN_NE;
843 if (!strcmp(tline->text, "!=")) return tokval->t_type = TOKEN_NE;
844 if (!strcmp(tline->text, "<=")) return tokval->t_type = TOKEN_LE;
845 if (!strcmp(tline->text, ">=")) return tokval->t_type = TOKEN_GE;
846 if (!strcmp(tline->text, "&&")) return tokval->t_type = TOKEN_DBL_AND;
847 if (!strcmp(tline->text, "^^")) return tokval->t_type = TOKEN_DBL_XOR;
848 if (!strcmp(tline->text, "||")) return tokval->t_type = TOKEN_DBL_OR;
852 * We have no other options: just return the first character of
853 * the token text.
855 return tokval->t_type = tline->text[0];
859 * Compare a string to the name of an existing macro; this is a
860 * simple wrapper which calls either strcmp or nasm_stricmp
861 * depending on the value of the `casesense' parameter.
863 static int mstrcmp(char *p, char *q, int casesense)
865 return casesense ? strcmp(p,q) : nasm_stricmp(p,q);
869 * Return the Context structure associated with a %$ token. Return
870 * NULL, having _already_ reported an error condition, if the
871 * context stack isn't deep enough for the supplied number of $
872 * signs.
873 * If all_contexts == TRUE, contexts that enclose current are
874 * also scanned for such smacro, until it is found; if not -
875 * only the context that directly results from the number of $'s
876 * in variable's name.
878 static Context *get_ctx (char *name, int all_contexts)
880 Context *ctx;
881 SMacro *m;
882 int i;
884 if (!name || name[0] != '%' || name[1] != '$')
885 return NULL;
887 if (!cstk) {
888 error (ERR_NONFATAL, "`%s': context stack is empty", name);
889 return NULL;
892 for (i = strspn (name+2, "$"), ctx = cstk; (i > 0) && ctx; i--) {
893 ctx = ctx->next;
894 i--;
896 if (!ctx) {
897 error (ERR_NONFATAL, "`%s': context stack is only"
898 " %d level%s deep", name, i-1, (i==2 ? "" : "s"));
899 return NULL;
901 if (!all_contexts)
902 return ctx;
904 do {
905 /* Search for this smacro in found context */
906 m = ctx->localmac;
907 while (m) {
908 if (!mstrcmp(m->name, name, m->casesense))
909 return ctx;
910 m = m->next;
912 ctx = ctx->next;
913 } while (ctx);
914 return NULL;
918 * Open an include file. This routine must always return a valid
919 * file pointer if it returns - it's responsible for throwing an
920 * ERR_FATAL and bombing out completely if not. It should also try
921 * the include path one by one until it finds the file or reaches
922 * the end of the path.
924 static FILE *inc_fopen(char *file)
926 FILE *fp;
927 char *prefix = "", *combine;
928 IncPath *ip = ipath;
929 static int namelen = 0;
931 while (1) {
932 combine = nasm_strcat(prefix,file);
933 fp = fopen(combine, "r");
934 if (pass == 0 && fp)
936 namelen += strlen(combine) + 1;
937 if (namelen > 62)
939 printf(" \\\n ");
940 namelen = 2;
942 printf(" %s", combine);
944 nasm_free (combine);
945 if (fp)
946 return fp;
947 if (!ip)
948 break;
949 prefix = ip->path;
950 ip = ip->next;
953 error (ERR_FATAL,
954 "unable to open include file `%s'", file);
955 return NULL; /* never reached - placate compilers */
959 * Determine if we should warn on defining a single-line macro of
960 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
961 * return TRUE if _any_ single-line macro of that name is defined.
962 * Otherwise, will return TRUE if a single-line macro with either
963 * `nparam' or no parameters is defined.
965 * If a macro with precisely the right number of parameters is
966 * defined, or nparam is -1, the address of the definition structure
967 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
968 * is NULL, no action will be taken regarding its contents, and no
969 * error will occur.
971 * Note that this is also called with nparam zero to resolve
972 * `ifdef'.
974 * If you already know which context macro belongs to, you can pass
975 * the context pointer as first parameter; if you won't but name begins
976 * with %$ the context will be automatically computed. If all_contexts
977 * is true, macro will be searched in outer contexts as well.
979 static int smacro_defined (Context *ctx, char *name, int nparam, SMacro **defn,
980 int nocase)
982 SMacro *m;
984 if (ctx)
985 m = ctx->localmac;
986 else if (name[0] == '%' && name[1] == '$') {
987 if (cstk)
988 ctx = get_ctx (name, FALSE);
989 if (!ctx)
990 return FALSE; /* got to return _something_ */
991 m = ctx->localmac;
992 } else
993 m = smacros[hash(name)];
995 while (m) {
996 if (!mstrcmp(m->name, name, m->casesense && nocase) &&
997 (nparam <= 0 || m->nparam == 0 || nparam == m->nparam)) {
998 if (defn) {
999 if (nparam == m->nparam || nparam == -1)
1000 *defn = m;
1001 else
1002 *defn = NULL;
1004 return TRUE;
1006 m = m->next;
1009 return FALSE;
1013 * Count and mark off the parameters in a multi-line macro call.
1014 * This is called both from within the multi-line macro expansion
1015 * code, and also to mark off the default parameters when provided
1016 * in a %macro definition line.
1018 static void count_mmac_params (Token *t, int *nparam, Token ***params)
1020 int paramsize, brace;
1022 *nparam = paramsize = 0;
1023 *params = NULL;
1024 while (t) {
1025 if (*nparam >= paramsize) {
1026 paramsize += PARAM_DELTA;
1027 *params = nasm_realloc(*params, sizeof(**params) * paramsize);
1029 skip_white_(t);
1030 brace = FALSE;
1031 if (tok_is_(t, "{"))
1032 brace = TRUE;
1033 (*params)[(*nparam)++] = t;
1034 while (tok_isnt_(t, brace ? "}" : ","))
1035 t = t->next;
1036 if (t) { /* got a comma/brace */
1037 t = t->next;
1038 if (brace) {
1040 * Now we've found the closing brace, look further
1041 * for the comma.
1043 skip_white_(t);
1044 if (tok_isnt_(t, ",")) {
1045 error (ERR_NONFATAL,
1046 "braces do not enclose all of macro parameter");
1047 while (tok_isnt_(t, ","))
1048 t = t->next;
1050 if (t)
1051 t = t->next; /* eat the comma */
1058 * Determine whether one of the various `if' conditions is true or
1059 * not.
1061 * We must free the tline we get passed.
1063 static int if_condition (Token *tline, int i)
1065 int j, casesense;
1066 Token * t, * tt, ** tptr, * origline;
1067 struct tokenval tokval;
1068 expr * evalresult;
1070 origline = tline;
1072 switch (i) {
1073 case PP_IFCTX: case PP_ELIFCTX:
1074 case PP_IFNCTX: case PP_ELIFNCTX:
1075 j = FALSE; /* have we matched yet? */
1076 while (cstk && tline) {
1077 skip_white_(tline);
1078 if (!tline || tline->type != TOK_ID) {
1079 error(ERR_NONFATAL,
1080 "`%s' expects context identifiers", directives[i]);
1081 free_tlist (origline);
1082 return -1;
1084 if (!nasm_stricmp(tline->text, cstk->name))
1085 j = TRUE;
1086 tline = tline->next;
1088 if (i == PP_IFNCTX || i == PP_ELIFNCTX)
1089 j = !j;
1090 free_tlist (origline);
1091 return j;
1093 case PP_IFDEF: case PP_ELIFDEF:
1094 case PP_IFNDEF: case PP_ELIFNDEF:
1095 j = FALSE; /* have we matched yet? */
1096 while (tline) {
1097 skip_white_(tline);
1098 if (!tline || (tline->type != TOK_ID &&
1099 (tline->type != TOK_PREPROC_ID ||
1100 tline->text[1] != '$'))) {
1101 error(ERR_NONFATAL,
1102 "`%%if%sdef' expects macro identifiers",
1103 (i==PP_ELIFNDEF ? "n" : ""));
1104 free_tlist (origline);
1105 return -1;
1107 if (smacro_defined (NULL, tline->text, 0, NULL, 1))
1108 j = TRUE;
1109 tline = tline->next;
1111 if (i == PP_IFNDEF || i == PP_ELIFNDEF)
1112 j = !j;
1113 free_tlist (origline);
1114 return j;
1116 case PP_IFIDN: case PP_ELIFIDN: case PP_IFNIDN: case PP_ELIFNIDN:
1117 case PP_IFIDNI: case PP_ELIFIDNI: case PP_IFNIDNI: case PP_ELIFNIDNI:
1118 tline = expand_smacro(tline);
1119 t = tt = tline;
1120 while (tok_isnt_(tt, ","))
1121 tt = tt->next;
1122 if (!tt) {
1123 error(ERR_NONFATAL, "`%s' expects two comma-separated arguments",
1124 directives[i]);
1125 free_tlist (tline);
1126 return -1;
1128 tt = tt->next;
1129 casesense = (i == PP_IFIDN || i == PP_ELIFIDN ||
1130 i == PP_IFNIDN || i == PP_ELIFNIDN);
1131 j = TRUE; /* assume equality unless proved not */
1132 while ((t->type != TOK_OTHER || strcmp(t->text, ",")) && tt) {
1133 if (tt->type == TOK_OTHER && !strcmp(tt->text, ",")) {
1134 error(ERR_NONFATAL, "`%s': more than one comma on line",
1135 directives[i]);
1136 free_tlist (tline);
1137 return -1;
1139 if (t->type == TOK_WHITESPACE) {
1140 t = t->next;
1141 continue;
1142 } else if (tt->type == TOK_WHITESPACE) {
1143 tt = tt->next;
1144 continue;
1145 } else if (tt->type != t->type ||
1146 (casesense ? strcmp(tt->text, t->text) :
1147 nasm_stricmp(tt->text, t->text))) {
1148 j = FALSE; /* found mismatching tokens */
1149 break;
1150 } else {
1151 t = t->next;
1152 tt = tt->next;
1153 continue;
1156 if ((t->type != TOK_OTHER || strcmp(t->text, ",")) || tt)
1157 j = FALSE; /* trailing gunk on one end or other */
1158 if (i == PP_IFNIDN || i == PP_ELIFNIDN ||
1159 i == PP_IFNIDNI || i == PP_ELIFNIDNI)
1160 j = !j;
1161 free_tlist (tline);
1162 return j;
1164 case PP_IFID: case PP_ELIFID: case PP_IFNID: case PP_ELIFNID:
1165 case PP_IFNUM: case PP_ELIFNUM: case PP_IFNNUM: case PP_ELIFNNUM:
1166 case PP_IFSTR: case PP_ELIFSTR: case PP_IFNSTR: case PP_ELIFNSTR:
1167 tline = expand_smacro(tline);
1168 t = tline;
1169 while (tok_type_(t, TOK_WHITESPACE))
1170 t = t->next;
1171 j = FALSE; /* placate optimiser */
1172 if (t) switch (i) {
1173 case PP_IFID: case PP_ELIFID: case PP_IFNID: case PP_ELIFNID:
1174 j = (t->type == TOK_ID);
1175 break;
1176 case PP_IFNUM: case PP_ELIFNUM: case PP_IFNNUM: case PP_ELIFNNUM:
1177 j = (t->type == TOK_NUMBER);
1178 break;
1179 case PP_IFSTR: case PP_ELIFSTR: case PP_IFNSTR: case PP_ELIFNSTR:
1180 j = (t->type == TOK_STRING);
1181 break;
1183 if (i == PP_IFNID || i == PP_ELIFNID ||
1184 i == PP_IFNNUM || i == PP_ELIFNNUM ||
1185 i == PP_IFNSTR || i == PP_ELIFNSTR)
1186 j = !j;
1187 free_tlist (tline);
1188 return j;
1190 case PP_IF: case PP_ELIF:
1191 t = tline = expand_smacro(tline);
1192 tptr = &t;
1193 tokval.t_type = TOKEN_INVALID;
1194 evalresult = evaluate (ppscan, tptr, &tokval,
1195 NULL, pass | CRITICAL, error, NULL);
1196 free_tlist (tline);
1197 if (!evalresult)
1198 return -1;
1199 if (tokval.t_type)
1200 error(ERR_WARNING,
1201 "trailing garbage after expression ignored");
1202 if (!is_simple(evalresult)) {
1203 error(ERR_NONFATAL,
1204 "non-constant value given to `%s'", directives[i]);
1205 return -1;
1207 return reloc_value(evalresult) != 0;
1209 default:
1210 error(ERR_FATAL,
1211 "preprocessor directive `%s' not yet implemented",
1212 directives[i]);
1213 free_tlist (origline);
1214 return -1; /* yeah, right */
1219 * Expand macros in a string. Used in %error and %include directives.
1220 * First tokenise the string, apply "expand_smacro" and then de-tokenise back.
1221 * The returned variable should ALWAYS be freed after usage.
1223 void expand_macros_in_string (char **p)
1225 Token *line = tokenise (*p);
1226 line = expand_smacro (line);
1227 *p = detoken (line, FALSE);
1231 * Find out if a line contains a preprocessor directive, and deal
1232 * with it if so.
1234 * If a directive _is_ found, we are expected to free_tlist() the
1235 * line.
1237 * Return values go like this:
1239 * bit 0 is set if a directive was found (so the line gets freed)
1241 static int do_directive (Token *tline)
1243 int i, j, k, m, nparam, nolist;
1244 char *p, *mname;
1245 Include *inc;
1246 Context *ctx;
1247 Cond *cond;
1248 SMacro *smac, **smhead;
1249 MMacro *mmac;
1250 Token *t, *tt, *param_start, *macro_start, *last, **tptr, *origline;
1251 Line *l;
1252 struct tokenval tokval;
1253 expr *evalresult;
1254 MMacro *tmp_defining; /* Used when manipulating rep_nest */
1256 origline = tline;
1258 skip_white_(tline);
1259 if (!tok_type_(tline, TOK_PREPROC_ID) ||
1260 (tline->text[1]=='%' || tline->text[1]=='$' || tline->text[1]=='!'))
1261 return 0;
1263 i = -1;
1264 j = sizeof(directives)/sizeof(*directives);
1265 while (j-i > 1) {
1266 k = (j+i) / 2;
1267 m = nasm_stricmp(tline->text, directives[k]);
1268 if (m == 0) {
1269 i = k;
1270 j = -2;
1271 break;
1272 } else if (m < 0) {
1273 j = k;
1274 } else
1275 i = k;
1279 * If we're in a non-emitting branch of a condition construct,
1280 * or walking to the end of an already terminated %rep block,
1281 * we should ignore all directives except for condition
1282 * directives.
1284 if (((istk->conds && !emitting(istk->conds->state)) ||
1285 (istk->mstk && !istk->mstk->in_progress)) &&
1286 i != PP_IF && i != PP_ELIF &&
1287 i != PP_IFCTX && i != PP_ELIFCTX &&
1288 i != PP_IFDEF && i != PP_ELIFDEF &&
1289 i != PP_IFID && i != PP_ELIFID &&
1290 i != PP_IFIDN && i != PP_ELIFIDN &&
1291 i != PP_IFIDNI && i != PP_ELIFIDNI &&
1292 i != PP_IFNCTX && i != PP_ELIFNCTX &&
1293 i != PP_IFNDEF && i != PP_ELIFNDEF &&
1294 i != PP_IFNID && i != PP_ELIFNID &&
1295 i != PP_IFNIDN && i != PP_ELIFNIDN &&
1296 i != PP_IFNIDNI && i != PP_ELIFNIDNI &&
1297 i != PP_IFNNUM && i != PP_ELIFNNUM &&
1298 i != PP_IFNSTR && i != PP_ELIFNSTR &&
1299 i != PP_IFNUM && i != PP_ELIFNUM &&
1300 i != PP_IFSTR && i != PP_ELIFSTR &&
1301 i != PP_ELSE && i != PP_ENDIF)
1303 return 0;
1307 * If we're defining a macro or reading a %rep block, we should
1308 * ignore all directives except for %macro/%imacro (which
1309 * generate an error), %endm/%endmacro, and (only if we're in a
1310 * %rep block) %endrep. If we're in a %rep block, another %rep
1311 * causes an error, so should be let through.
1313 if (defining && i != PP_MACRO && i != PP_IMACRO &&
1314 i != PP_ENDMACRO && i != PP_ENDM &&
1315 (defining->name || (i != PP_ENDREP && i != PP_REP)))
1317 return 0;
1320 if (j != -2) {
1321 error(ERR_NONFATAL, "unknown preprocessor directive `%s'",
1322 tline->text);
1323 return 0; /* didn't get it */
1326 switch (i) {
1328 case PP_CLEAR:
1329 if (tline->next)
1330 error(ERR_WARNING,
1331 "trailing garbage after `%%clear' ignored");
1332 for (j=0; j<NHASH; j++) {
1333 while (mmacros[j]) {
1334 MMacro *m = mmacros[j];
1335 mmacros[j] = m->next;
1336 free_mmacro(m);
1338 while (smacros[j]) {
1339 SMacro *s = smacros[j];
1340 smacros[j] = smacros[j]->next;
1341 nasm_free (s->name);
1342 free_tlist (s->expansion);
1343 nasm_free (s);
1346 free_tlist (origline);
1347 return 3;
1349 case PP_INCLUDE:
1350 tline = tline->next;
1351 skip_white_(tline);
1352 if (!tline || (tline->type != TOK_STRING &&
1353 tline->type != TOK_INTERNAL_STRING))
1355 error(ERR_NONFATAL, "`%%include' expects a file name");
1356 free_tlist (origline);
1357 return 3; /* but we did _something_ */
1359 if (tline->next)
1360 error(ERR_WARNING,
1361 "trailing garbage after `%%include' ignored");
1362 if (tline->type != TOK_INTERNAL_STRING) {
1363 p = tline->text+1; /* point past the quote to the name */
1364 p[strlen(p)-1] = '\0'; /* remove the trailing quote */
1365 } else
1366 p = tline->text; /* internal_string is easier */
1367 expand_macros_in_string (&p);
1368 inc = nasm_malloc(sizeof(Include));
1369 inc->next = istk;
1370 inc->conds = NULL;
1371 inc->fp = inc_fopen(p);
1372 inc->fname = src_set_fname (p);
1373 inc->lineno = src_set_linnum(0);
1374 inc->lineinc = 1;
1375 inc->expansion = NULL;
1376 inc->mstk = NULL;
1377 istk = inc;
1378 list->uplevel (LIST_INCLUDE);
1379 free_tlist (origline);
1380 return 5;
1382 case PP_PUSH:
1383 tline = tline->next;
1384 skip_white_(tline);
1385 tline = expand_id (tline);
1386 if (!tok_type_(tline, TOK_ID)) {
1387 error(ERR_NONFATAL,
1388 "`%%push' expects a context identifier");
1389 free_tlist (origline);
1390 return 3; /* but we did _something_ */
1392 if (tline->next)
1393 error(ERR_WARNING,
1394 "trailing garbage after `%%push' ignored");
1395 ctx = nasm_malloc(sizeof(Context));
1396 ctx->next = cstk;
1397 ctx->localmac = NULL;
1398 ctx->name = nasm_strdup(tline->text);
1399 ctx->number = unique++;
1400 cstk = ctx;
1401 free_tlist (origline);
1402 break;
1404 case PP_REPL:
1405 tline = tline->next;
1406 skip_white_(tline);
1407 tline = expand_id (tline);
1408 if (!tok_type_(tline, TOK_ID)) {
1409 error(ERR_NONFATAL,
1410 "`%%repl' expects a context identifier");
1411 free_tlist (origline);
1412 return 3; /* but we did _something_ */
1414 if (tline->next)
1415 error(ERR_WARNING,
1416 "trailing garbage after `%%repl' ignored");
1417 if (!cstk)
1418 error(ERR_NONFATAL,
1419 "`%%repl': context stack is empty");
1420 else {
1421 nasm_free (cstk->name);
1422 cstk->name = nasm_strdup(tline->text);
1424 free_tlist (origline);
1425 break;
1427 case PP_POP:
1428 if (tline->next)
1429 error(ERR_WARNING,
1430 "trailing garbage after `%%pop' ignored");
1431 if (!cstk)
1432 error(ERR_NONFATAL,
1433 "`%%pop': context stack is already empty");
1434 else
1435 ctx_pop();
1436 free_tlist (origline);
1437 break;
1439 case PP_ERROR:
1440 tline->next = expand_smacro (tline->next);
1441 tline = tline->next;
1442 skip_white_(tline);
1443 if (tok_type_(tline, TOK_STRING)) {
1444 p = tline->text+1; /* point past the quote to the name */
1445 p[strlen(p)-1] = '\0'; /* remove the trailing quote */
1446 expand_macros_in_string (&p);
1447 error (ERR_NONFATAL, "%s", p);
1448 nasm_free (p);
1449 } else {
1450 p = detoken(tline, FALSE);
1451 error (ERR_WARNING, "%s", p);
1452 nasm_free(p);
1454 free_tlist (origline);
1455 break;
1457 case PP_IF:
1458 case PP_IFCTX:
1459 case PP_IFDEF:
1460 case PP_IFID:
1461 case PP_IFIDN:
1462 case PP_IFIDNI:
1463 case PP_IFNCTX:
1464 case PP_IFNDEF:
1465 case PP_IFNID:
1466 case PP_IFNIDN:
1467 case PP_IFNIDNI:
1468 case PP_IFNNUM:
1469 case PP_IFNSTR:
1470 case PP_IFNUM:
1471 case PP_IFSTR:
1472 if (istk->conds && !emitting(istk->conds->state))
1473 j = COND_NEVER;
1474 else {
1475 j = if_condition(tline->next, i);
1476 tline->next = NULL; /* it got freed */
1477 free_tlist (origline);
1478 j = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
1480 cond = nasm_malloc(sizeof(Cond));
1481 cond->next = istk->conds;
1482 cond->state = j;
1483 istk->conds = cond;
1484 return (j == COND_IF_TRUE ? 3 : 1);
1486 case PP_ELIF:
1487 case PP_ELIFCTX:
1488 case PP_ELIFDEF:
1489 case PP_ELIFID:
1490 case PP_ELIFIDN:
1491 case PP_ELIFIDNI:
1492 case PP_ELIFNCTX:
1493 case PP_ELIFNDEF:
1494 case PP_ELIFNID:
1495 case PP_ELIFNIDN:
1496 case PP_ELIFNIDNI:
1497 case PP_ELIFNNUM:
1498 case PP_ELIFNSTR:
1499 case PP_ELIFNUM:
1500 case PP_ELIFSTR:
1501 if (!istk->conds)
1502 error(ERR_FATAL, "`%s': no matching `%%if'",
1503 directives[i]);
1504 if (emitting(istk->conds->state) || istk->conds->state == COND_NEVER)
1505 istk->conds->state = COND_NEVER;
1506 else {
1507 j = if_condition(expand_mmac_params(tline->next), i);
1508 tline->next = NULL; /* it got freed */
1509 free_tlist (origline);
1510 istk->conds->state = j < 0 ? COND_NEVER : j ? COND_IF_TRUE : COND_IF_FALSE;
1512 return (istk->conds->state == COND_IF_TRUE ? 5 : 1);
1514 case PP_ELSE:
1515 if (tline->next)
1516 error(ERR_WARNING,
1517 "trailing garbage after `%%else' ignored");
1518 if (!istk->conds)
1519 error(ERR_FATAL,
1520 "`%%else': no matching `%%if'");
1521 if (emitting(istk->conds->state) || istk->conds->state == COND_NEVER)
1522 istk->conds->state = COND_ELSE_FALSE;
1523 else
1524 istk->conds->state = COND_ELSE_TRUE;
1525 free_tlist (origline);
1526 return 5;
1528 case PP_ENDIF:
1529 if (tline->next)
1530 error(ERR_WARNING,
1531 "trailing garbage after `%%endif' ignored");
1532 if (!istk->conds)
1533 error(ERR_FATAL,
1534 "`%%endif': no matching `%%if'");
1535 cond = istk->conds;
1536 istk->conds = cond->next;
1537 nasm_free (cond);
1538 free_tlist (origline);
1539 return 5;
1541 case PP_MACRO:
1542 case PP_IMACRO:
1543 if (defining)
1544 error (ERR_FATAL,
1545 "`%%%smacro': already defining a macro",
1546 (i == PP_IMACRO ? "i" : ""));
1547 tline = tline->next;
1548 skip_white_(tline);
1549 tline = expand_id (tline);
1550 if (!tok_type_(tline, TOK_ID)) {
1551 error (ERR_NONFATAL,
1552 "`%%%smacro' expects a macro name",
1553 (i == PP_IMACRO ? "i" : ""));
1554 return 3;
1556 defining = nasm_malloc(sizeof(MMacro));
1557 defining->name = nasm_strdup(tline->text);
1558 defining->casesense = (i == PP_MACRO);
1559 defining->plus = FALSE;
1560 defining->nolist = FALSE;
1561 defining->in_progress = FALSE;
1562 defining->rep_nest = NULL;
1563 tline = expand_smacro (tline->next);
1564 skip_white_(tline);
1565 if (!tok_type_(tline, TOK_NUMBER)) {
1566 error (ERR_NONFATAL,
1567 "`%%%smacro' expects a parameter count",
1568 (i == PP_IMACRO ? "i" : ""));
1569 defining->nparam_min = defining->nparam_max = 0;
1570 } else {
1571 defining->nparam_min = defining->nparam_max =
1572 readnum(tline->text, &j);
1573 if (j)
1574 error (ERR_NONFATAL,
1575 "unable to parse parameter count `%s'", tline->text);
1577 if (tline && tok_is_(tline->next, "-")) {
1578 tline = tline->next->next;
1579 if (tok_is_(tline, "*"))
1580 defining->nparam_max = INT_MAX;
1581 else if (!tok_type_(tline, TOK_NUMBER))
1582 error (ERR_NONFATAL,
1583 "`%%%smacro' expects a parameter count after `-'",
1584 (i == PP_IMACRO ? "i" : ""));
1585 else {
1586 defining->nparam_max = readnum(tline->text, &j);
1587 if (j)
1588 error (ERR_NONFATAL,
1589 "unable to parse parameter count `%s'",
1590 tline->text);
1591 if (defining->nparam_min > defining->nparam_max)
1592 error (ERR_NONFATAL,
1593 "minimum parameter count exceeds maximum");
1596 if (tline && tok_is_(tline->next, "+")) {
1597 tline = tline->next;
1598 defining->plus = TRUE;
1600 if (tline && tok_type_(tline->next, TOK_ID) &&
1601 !nasm_stricmp(tline->next->text, ".nolist"))
1603 tline = tline->next;
1604 defining->nolist = TRUE;
1606 mmac = mmacros[hash(defining->name)];
1607 while (mmac) {
1608 if (!strcmp(mmac->name, defining->name) &&
1609 (mmac->nparam_min<=defining->nparam_max || defining->plus) &&
1610 (defining->nparam_min<=mmac->nparam_max || mmac->plus))
1612 error (ERR_WARNING,
1613 "redefining multi-line macro `%s'", defining->name);
1614 break;
1616 mmac = mmac->next;
1619 * Handle default parameters.
1621 if (tline && tline->next) {
1622 defining->dlist = tline->next;
1623 tline->next = NULL;
1624 count_mmac_params (defining->dlist, &defining->ndefs,
1625 &defining->defaults);
1626 } else {
1627 defining->dlist = NULL;
1628 defining->defaults = NULL;
1630 defining->expansion = NULL;
1631 free_tlist (origline);
1632 return 1;
1634 case PP_ENDM:
1635 case PP_ENDMACRO:
1636 if (!defining) {
1637 error (ERR_NONFATAL, "`%s': not defining a macro",
1638 tline->text);
1639 return 3;
1641 k = hash(defining->name);
1642 defining->next = mmacros[k];
1643 mmacros[k] = defining;
1644 defining = NULL;
1645 free_tlist (origline);
1646 return 5;
1648 case PP_ROTATE:
1649 if (tline->next && tline->next->type == TOK_WHITESPACE)
1650 tline = tline->next;
1651 t = expand_smacro(tline->next);
1652 tline->next = NULL;
1653 free_tlist (origline);
1654 tline = t;
1655 tptr = &t;
1656 tokval.t_type = TOKEN_INVALID;
1657 evalresult = evaluate (ppscan, tptr, &tokval, NULL, pass, error, NULL);
1658 free_tlist (tline);
1659 if (!evalresult)
1660 return 3;
1661 if (tokval.t_type)
1662 error(ERR_WARNING,
1663 "trailing garbage after expression ignored");
1664 if (!is_simple(evalresult)) {
1665 error(ERR_NONFATAL,
1666 "non-constant value given to `%%rotate'");
1667 return 3;
1669 mmac = istk->mstk;
1670 while (mmac && !mmac->name) /* avoid mistaking %reps for macros */
1671 mmac = mmac->next_active;
1672 if (!mmac)
1673 error(ERR_NONFATAL, "`%%rotate' invoked outside a macro call");
1674 mmac->rotate = mmac->rotate + reloc_value(evalresult);
1675 if (mmac->rotate < 0)
1676 mmac->rotate = mmac->nparam - (-mmac->rotate) % mmac->nparam;
1677 mmac->rotate %= mmac->nparam;
1678 return 1;
1680 case PP_REP:
1681 nolist = FALSE;
1682 tline = tline->next;
1683 if (tline->next && tline->next->type == TOK_WHITESPACE)
1684 tline = tline->next;
1685 if (tline->next && tline->next->type == TOK_ID &&
1686 !nasm_stricmp(tline->next->text, ".nolist")) {
1687 tline = tline->next;
1688 nolist = TRUE;
1690 t = expand_smacro(tline->next);
1691 tline->next = NULL;
1692 free_tlist (origline);
1693 tline = t;
1694 tptr = &t;
1695 tokval.t_type = TOKEN_INVALID;
1696 evalresult = evaluate (ppscan, tptr, &tokval, NULL, pass, error, NULL);
1697 free_tlist (tline);
1698 if (!evalresult)
1699 return 3;
1700 if (tokval.t_type)
1701 error(ERR_WARNING,
1702 "trailing garbage after expression ignored");
1703 if (!is_simple(evalresult)) {
1704 error(ERR_NONFATAL,
1705 "non-constant value given to `%%rep'");
1706 return 3;
1708 tmp_defining = defining;
1709 defining = nasm_malloc(sizeof(MMacro));
1710 defining->name = NULL; /* flags this macro as a %rep block */
1711 defining->casesense = 0;
1712 defining->plus = FALSE;
1713 defining->nolist = nolist;
1714 defining->in_progress = reloc_value(evalresult) + 1;
1715 defining->nparam_min = defining->nparam_max = 0;
1716 defining->defaults = NULL;
1717 defining->dlist = NULL;
1718 defining->expansion = NULL;
1719 defining->next_active = istk->mstk;
1720 defining->rep_nest = tmp_defining;
1721 return 1;
1723 case PP_ENDREP:
1724 if (!defining || defining->name) {
1725 error (ERR_NONFATAL,
1726 "`%%endrep': no matching `%%rep'");
1727 return 3;
1731 * Now we have a "macro" defined - although it has no name
1732 * and we won't be entering it in the hash tables - we must
1733 * push a macro-end marker for it on to istk->expansion.
1734 * After that, it will take care of propagating itself (a
1735 * macro-end marker line for a macro which is really a %rep
1736 * block will cause the macro to be re-expanded, complete
1737 * with another macro-end marker to ensure the process
1738 * continues) until the whole expansion is forcibly removed
1739 * from istk->expansion by a %exitrep.
1741 l = nasm_malloc(sizeof(Line));
1742 l->next = istk->expansion;
1743 l->finishes = defining;
1744 l->first = NULL;
1745 istk->expansion = l;
1747 istk->mstk = defining;
1749 list->uplevel (defining->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
1750 tmp_defining = defining;
1751 defining = defining->rep_nest;
1752 free_tlist (origline);
1753 return 1;
1755 case PP_EXITREP:
1757 * We must search along istk->expansion until we hit a
1758 * macro-end marker for a macro with no name. Then we set
1759 * its `in_progress' flag to 0.
1761 for (l = istk->expansion; l; l = l->next)
1762 if (l->finishes && !l->finishes->name)
1763 break;
1765 if (l)
1766 l->finishes->in_progress = 0;
1767 else
1768 error (ERR_NONFATAL, "`%%exitrep' not within `%%rep' block");
1769 free_tlist (origline);
1770 return 1;
1772 case PP_XDEFINE:
1773 case PP_IXDEFINE:
1774 case PP_DEFINE:
1775 case PP_IDEFINE:
1776 tline = tline->next;
1777 skip_white_(tline);
1778 tline = expand_id (tline);
1779 if (!tline || (tline->type != TOK_ID &&
1780 (tline->type != TOK_PREPROC_ID ||
1781 tline->text[1] != '$'))) {
1782 error (ERR_NONFATAL,
1783 "`%%%s%sdefine' expects a macro identifier",
1784 ((i == PP_IDEFINE || i == PP_IXDEFINE) ? "i" : ""),
1785 ((i == PP_XDEFINE || i == PP_IXDEFINE) ? "x" : ""));
1786 free_tlist (origline);
1787 return 3;
1790 ctx = get_ctx (tline->text, FALSE);
1791 if (!ctx)
1792 smhead = &smacros[hash(tline->text)];
1793 else
1794 smhead = &ctx->localmac;
1795 mname = tline->text;
1796 last = tline;
1797 param_start = tline = tline->next;
1798 nparam = 0;
1800 /* Expand the macro definition now for %xdefine and %ixdefine */
1801 if ((i == PP_XDEFINE) || (i == PP_IXDEFINE))
1802 tline = expand_smacro (tline);
1804 if (tok_is_(tline, "(")) {
1806 * This macro has parameters.
1809 tline = tline->next;
1810 while (1) {
1811 skip_white_(tline);
1812 if (!tline) {
1813 error (ERR_NONFATAL,
1814 "parameter identifier expected");
1815 free_tlist (origline);
1816 return 3;
1818 if (tline->type != TOK_ID) {
1819 error (ERR_NONFATAL,
1820 "`%s': parameter identifier expected",
1821 tline->text);
1822 free_tlist (origline);
1823 return 3;
1825 tline->type = TOK_SMAC_PARAM + nparam++;
1826 tline = tline->next;
1827 skip_white_(tline);
1828 if (tok_is_(tline, ",")) {
1829 tline = tline->next;
1830 continue;
1832 if (!tok_is_(tline, ")")) {
1833 error (ERR_NONFATAL,
1834 "`)' expected to terminate macro template");
1835 free_tlist (origline);
1836 return 3;
1838 break;
1840 last = tline;
1841 tline = tline->next;
1843 if (tok_type_(tline, TOK_WHITESPACE))
1844 last = tline, tline = tline->next;
1845 macro_start = NULL;
1846 last->next = NULL;
1847 t = tline;
1848 while (t) {
1849 if (t->type == TOK_ID) {
1850 for (tt = param_start; tt; tt = tt->next)
1851 if (tt->type >= TOK_SMAC_PARAM &&
1852 !strcmp(tt->text, t->text))
1853 t->type = tt->type;
1855 tt = t->next;
1856 t->next = macro_start;
1857 macro_start = t;
1858 t = tt;
1861 * Good. We now have a macro name, a parameter count, and a
1862 * token list (in reverse order) for an expansion. We ought
1863 * to be OK just to create an SMacro, store it, and let
1864 * free_tlist have the rest of the line (which we have
1865 * carefully re-terminated after chopping off the expansion
1866 * from the end).
1868 if (smacro_defined (ctx, mname, nparam, &smac, i == PP_DEFINE)) {
1869 if (!smac) {
1870 error (ERR_WARNING,
1871 "single-line macro `%s' defined both with and"
1872 " without parameters", mname);
1873 free_tlist (origline);
1874 free_tlist (macro_start);
1875 return 3;
1876 } else {
1878 * We're redefining, so we have to take over an
1879 * existing SMacro structure. This means freeing
1880 * what was already in it.
1882 nasm_free (smac->name);
1883 free_tlist (smac->expansion);
1885 } else {
1886 smac = nasm_malloc(sizeof(SMacro));
1887 smac->next = *smhead;
1888 *smhead = smac;
1890 smac->name = nasm_strdup(mname);
1891 smac->casesense = ((i == PP_DEFINE) || (i == PP_XDEFINE));
1892 smac->nparam = nparam;
1893 smac->expansion = macro_start;
1894 smac->in_progress = FALSE;
1895 free_tlist (origline);
1896 return 3;
1898 case PP_UNDEF:
1899 tline = tline->next;
1900 skip_white_(tline);
1901 tline = expand_id (tline);
1902 if (!tline || (tline->type != TOK_ID &&
1903 (tline->type != TOK_PREPROC_ID ||
1904 tline->text[1] != '$'))) {
1905 error (ERR_NONFATAL,
1906 "`%%undef' expects a macro identifier");
1907 free_tlist (origline);
1908 return 3;
1910 if (tline->next) {
1911 error (ERR_WARNING,
1912 "trailing garbage after macro name ignored");
1915 /* Find the context that symbol belongs to */
1916 ctx = get_ctx (tline->text, FALSE);
1917 if (!ctx)
1918 smhead = &smacros[hash(tline->text)];
1919 else
1920 smhead = &ctx->localmac;
1922 mname = tline->text;
1923 last = tline;
1924 last->next = NULL;
1927 * We now have a macro name... go hunt for it.
1929 while (smacro_defined (ctx, mname, -1, &smac, 1)) {
1930 /* Defined, so we need to find its predecessor and nuke it */
1931 SMacro **s;
1932 for ( s = smhead ; *s && *s != smac ; s = &(*s)->next );
1933 if ( *s ) {
1934 *s = smac->next;
1935 nasm_free(smac->name);
1936 free_tlist(smac->expansion);
1937 nasm_free(smac);
1940 free_tlist (origline);
1941 return 3;
1943 case PP_ASSIGN:
1944 case PP_IASSIGN:
1945 tline = tline->next;
1946 skip_white_(tline);
1947 tline = expand_id (tline);
1948 if (!tline || (tline->type != TOK_ID &&
1949 (tline->type != TOK_PREPROC_ID ||
1950 tline->text[1] != '$'))) {
1951 error (ERR_NONFATAL,
1952 "`%%%sassign' expects a macro identifier",
1953 (i == PP_IASSIGN ? "i" : ""));
1954 free_tlist (origline);
1955 return 3;
1957 ctx = get_ctx (tline->text, FALSE);
1958 if (!ctx)
1959 smhead = &smacros[hash(tline->text)];
1960 else
1961 smhead = &ctx->localmac;
1962 mname = tline->text;
1963 last = tline;
1964 tline = expand_smacro (tline->next);
1965 last->next = NULL;
1967 t = tline;
1968 tptr = &t;
1969 tokval.t_type = TOKEN_INVALID;
1970 evalresult = evaluate (ppscan, tptr, &tokval, NULL, pass, error, NULL);
1971 free_tlist (tline);
1972 if (!evalresult) {
1973 free_tlist (origline);
1974 return 3;
1977 if (tokval.t_type)
1978 error(ERR_WARNING,
1979 "trailing garbage after expression ignored");
1981 if (!is_simple(evalresult)) {
1982 error(ERR_NONFATAL,
1983 "non-constant value given to `%%%sassign'",
1984 (i == PP_IASSIGN ? "i" : ""));
1985 free_tlist (origline);
1986 return 3;
1989 macro_start = nasm_malloc(sizeof(*macro_start));
1990 macro_start->next = NULL;
1991 make_tok_num(macro_start, reloc_value(evalresult));
1992 macro_start->mac = NULL;
1995 * We now have a macro name, an implicit parameter count of
1996 * zero, and a numeric token to use as an expansion. Create
1997 * and store an SMacro.
1999 if (smacro_defined (ctx, mname, 0, &smac, i == PP_ASSIGN)) {
2000 if (!smac)
2001 error (ERR_WARNING,
2002 "single-line macro `%s' defined both with and"
2003 " without parameters", mname);
2004 else {
2006 * We're redefining, so we have to take over an
2007 * existing SMacro structure. This means freeing
2008 * what was already in it.
2010 nasm_free (smac->name);
2011 free_tlist (smac->expansion);
2014 else {
2015 smac = nasm_malloc(sizeof(SMacro));
2016 smac->next = *smhead;
2017 *smhead = smac;
2019 smac->name = nasm_strdup(mname);
2020 smac->casesense = (i == PP_ASSIGN);
2021 smac->nparam = 0;
2022 smac->expansion = macro_start;
2023 smac->in_progress = FALSE;
2024 free_tlist (origline);
2025 return 3;
2027 case PP_LINE:
2029 * Syntax is `%line nnn[+mmm] [filename]'
2031 tline = tline->next;
2032 skip_white_(tline);
2033 if (!tok_type_(tline, TOK_NUMBER)) {
2034 error (ERR_NONFATAL, "`%%line' expects line number");
2035 free_tlist (origline);
2036 return 3;
2038 k = readnum(tline->text, &j);
2039 m = 1;
2040 tline = tline->next;
2041 if (tok_is_(tline, "+")) {
2042 tline = tline->next;
2043 if (!tok_type_(tline, TOK_NUMBER)) {
2044 error (ERR_NONFATAL,
2045 "`%%line' expects line increment");
2046 free_tlist (origline);
2047 return 3;
2049 m = readnum(tline->text, &j);
2050 tline = tline->next;
2052 skip_white_(tline);
2053 src_set_linnum(k);
2054 istk->lineinc = m;
2055 if (tline) {
2056 nasm_free (src_set_fname (detoken (tline, FALSE)));
2058 free_tlist (origline);
2059 return 5;
2061 default:
2062 error(ERR_FATAL,
2063 "preprocessor directive `%s' not yet implemented",
2064 directives[i]);
2065 break;
2067 return 3;
2071 * Ensure that a macro parameter contains a condition code and
2072 * nothing else. Return the condition code index if so, or -1
2073 * otherwise.
2075 static int find_cc (Token *t)
2077 Token *tt;
2078 int i, j, k, m;
2080 skip_white_(t);
2081 if (t->type != TOK_ID)
2082 return -1;
2083 tt = t->next;
2084 skip_white_(tt);
2085 if (tt && (tt->type != TOK_OTHER || strcmp(tt->text, ",")))
2086 return -1;
2088 i = -1;
2089 j = sizeof(conditions)/sizeof(*conditions);
2090 while (j-i > 1) {
2091 k = (j+i) / 2;
2092 m = nasm_stricmp(t->text, conditions[k]);
2093 if (m == 0) {
2094 i = k;
2095 j = -2;
2096 break;
2097 } else if (m < 0) {
2098 j = k;
2099 } else
2100 i = k;
2102 if (j != -2)
2103 return -1;
2104 return i;
2108 * Expand MMacro-local things: parameter references (%0, %n, %+n,
2109 * %-n) and MMacro-local identifiers (%%foo).
2111 static Token *expand_mmac_params (Token *tline)
2113 Token *t, *tt, *ttt, **tail, *thead;
2115 tail = &thead;
2116 thead = NULL;
2118 while (tline) {
2119 if (tline->type == TOK_PREPROC_ID &&
2120 (((tline->text[1] == '+' || tline->text[1] == '-') && tline->text [2]) ||
2121 tline->text[1] == '%' ||
2122 (tline->text[1] >= '0' && tline->text[1] <= '9'))) {
2123 char *text = NULL;
2124 int type = 0, cc; /* type = 0 to placate optimisers */
2125 char tmpbuf[30];
2126 int n, i;
2127 MMacro *mac;
2129 t = tline;
2130 tline = tline->next;
2132 mac = istk->mstk;
2133 while (mac && !mac->name) /* avoid mistaking %reps for macros */
2134 mac = mac->next_active;
2135 if (!mac)
2136 error(ERR_NONFATAL, "`%s': not in a macro call", t->text);
2137 else switch (t->text[1]) {
2139 * We have to make a substitution of one of the
2140 * forms %1, %-1, %+1, %%foo, %0.
2142 case '0':
2143 type = TOK_NUMBER;
2144 sprintf(tmpbuf, "%d", mac->nparam);
2145 text = nasm_strdup(tmpbuf);
2146 break;
2147 case '%':
2148 type = TOK_ID;
2149 sprintf(tmpbuf, "..@%lu.", mac->unique);
2150 text = nasm_strcat(tmpbuf, t->text+2);
2151 break;
2152 case '-':
2153 n = atoi(t->text+2)-1;
2154 if (n >= mac->nparam)
2155 tt = NULL;
2156 else {
2157 if (mac->nparam > 1)
2158 n = (n + mac->rotate) % mac->nparam;
2159 tt = mac->params[n];
2161 cc = find_cc (tt);
2162 if (cc == -1) {
2163 error (ERR_NONFATAL,
2164 "macro parameter %d is not a condition code",
2165 n+1);
2166 text = NULL;
2167 } else {
2168 type = TOK_ID;
2169 if (inverse_ccs[cc] == -1) {
2170 error (ERR_NONFATAL,
2171 "condition code `%s' is not invertible",
2172 conditions[cc]);
2173 text = NULL;
2174 } else
2175 text = nasm_strdup(conditions[inverse_ccs[cc]]);
2177 break;
2178 case '+':
2179 n = atoi(t->text+2)-1;
2180 if (n >= mac->nparam)
2181 tt = NULL;
2182 else {
2183 if (mac->nparam > 1)
2184 n = (n + mac->rotate) % mac->nparam;
2185 tt = mac->params[n];
2187 cc = find_cc (tt);
2188 if (cc == -1) {
2189 error (ERR_NONFATAL,
2190 "macro parameter %d is not a condition code",
2191 n+1);
2192 text = NULL;
2193 } else {
2194 type = TOK_ID;
2195 text = nasm_strdup(conditions[cc]);
2197 break;
2198 default:
2199 n = atoi(t->text+1)-1;
2200 if (n >= mac->nparam)
2201 tt = NULL;
2202 else {
2203 if (mac->nparam > 1)
2204 n = (n + mac->rotate) % mac->nparam;
2205 tt = mac->params[n];
2207 if (tt) {
2208 for (i=0; i<mac->paramlen[n]; i++) {
2209 ttt = *tail = nasm_malloc(sizeof(Token));
2210 tail = &ttt->next;
2211 ttt->type = tt->type;
2212 ttt->text = nasm_strdup(tt->text);
2213 ttt->mac = NULL;
2214 tt = tt->next;
2217 text = NULL; /* we've done it here */
2218 break;
2220 nasm_free (t->text);
2221 if (!text) {
2222 nasm_free (t);
2223 } else {
2224 *tail = t;
2225 tail = &t->next;
2226 t->type = type;
2227 t->text = text;
2228 t->mac = NULL;
2230 continue;
2231 } else {
2232 t = *tail = tline;
2233 tline = tline->next;
2234 t->mac = NULL;
2235 tail = &t->next;
2238 *tail = NULL;
2239 t = thead;
2240 for (; t && (tt=t->next)!=NULL ; t = t->next)
2241 switch (t->type) {
2242 case TOK_WHITESPACE:
2243 if (tt->type == TOK_WHITESPACE) {
2244 t->next = tt->next;
2245 nasm_free(tt->text);
2246 nasm_free(tt);
2248 break;
2249 case TOK_ID:
2250 if (tt->type == TOK_ID || tt->type == TOK_NUMBER) {
2251 char *tmp = nasm_strcat(t->text, tt->text);
2252 nasm_free(t->text);
2253 t->text = tmp;
2254 t->next = tt->next;
2255 nasm_free(tt->text);
2256 nasm_free(tt);
2258 break;
2259 case TOK_NUMBER:
2260 if (tt->type == TOK_NUMBER) {
2261 char *tmp = nasm_strcat(t->text, tt->text);
2262 nasm_free(t->text);
2263 t->text = tmp;
2264 t->next = tt->next;
2265 nasm_free(tt->text);
2266 nasm_free(tt);
2268 break;
2271 return thead;
2275 * Expand all single-line macro calls made in the given line.
2276 * Return the expanded version of the line. The original is deemed
2277 * to be destroyed in the process. (In reality we'll just move
2278 * Tokens from input to output a lot of the time, rather than
2279 * actually bothering to destroy and replicate.)
2281 static Token *expand_smacro (Token *tline)
2283 Token *t, *tt, *mstart, **tail, *thead;
2284 SMacro *head = NULL, *m;
2285 Token **params;
2286 int *paramsize;
2287 int nparam, sparam, brackets, rescan;
2288 Token *org_tline = tline;
2289 Context *ctx;
2290 char *mname;
2293 * Trick: we should avoid changing the start token pointer since it can
2294 * be contained in "next" field of other token. Because of this
2295 * we allocate a copy of first token and work with it; at the end of
2296 * routine we copy it back
2298 if (org_tline)
2300 tline = nasm_malloc (sizeof (Token));
2301 *tline = *org_tline;
2304 again:
2305 tail = &thead;
2306 thead = NULL;
2308 while (tline) { /* main token loop */
2309 if ((mname = tline->text)) {
2310 /* if this token is a local macro, look in local context */
2311 if (tline->type == TOK_ID || tline->type == TOK_PREPROC_ID)
2312 ctx = get_ctx (mname, TRUE);
2313 else
2314 ctx = NULL;
2315 if (!ctx)
2316 head = smacros[hash(mname)];
2317 else
2318 head = ctx->localmac;
2320 * We've hit an identifier. As in is_mmacro below, we first
2321 * check whether the identifier is a single-line macro at
2322 * all, then think about checking for parameters if
2323 * necessary.
2325 for (m = head; m; m = m->next)
2326 if (!mstrcmp(m->name, mname, m->casesense))
2327 break;
2328 if (m) {
2329 mstart = tline;
2330 params = NULL;
2331 paramsize = NULL;
2332 if (m->nparam == 0) {
2334 * Simple case: the macro is parameterless. Discard the
2335 * one token that the macro call took, and push the
2336 * expansion back on the to-do stack.
2338 if (!m->expansion)
2340 if (!strcmp("__FILE__", m->name)) {
2341 long num=0;
2342 src_get(&num, &(tline->text));
2343 nasm_quote(&(tline->text));
2344 tline->type = TOK_STRING;
2345 continue;
2347 if (!strcmp("__LINE__", m->name)) {
2348 nasm_free(tline->text);
2349 make_tok_num(tline, src_get_linnum());
2350 continue;
2352 t = tline;
2353 tline = tline->next;
2354 nasm_free (t->text);
2355 nasm_free (t);
2356 continue;
2358 } else {
2360 * Complicated case: at least one macro with this name
2361 * exists and takes parameters. We must find the
2362 * parameters in the call, count them, find the SMacro
2363 * that corresponds to that form of the macro call, and
2364 * substitute for the parameters when we expand. What a
2365 * pain.
2367 tline = tline->next;
2368 skip_white_(tline);
2369 if (!tok_is_(tline, "(")) {
2371 * This macro wasn't called with parameters: ignore
2372 * the call. (Behaviour borrowed from gnu cpp.)
2374 tline = mstart;
2375 m = NULL;
2377 else {
2378 int paren = 0;
2379 int white = 0;
2380 brackets = 0;
2381 nparam = 0;
2382 tline = tline->next;
2383 sparam = PARAM_DELTA;
2384 params = nasm_malloc (sparam*sizeof(Token *));
2385 params[0] = tline;
2386 paramsize = nasm_malloc (sparam*sizeof(int));
2387 paramsize[0] = 0;
2388 for (;;tline = tline->next) { /* parameter loop */
2389 if (!tline) {
2390 error(ERR_NONFATAL,
2391 "macro call expects terminating `)'");
2392 break;
2394 if (tline->type == TOK_WHITESPACE && brackets<=0) {
2395 if (paramsize[nparam])
2396 white++;
2397 else
2398 params[nparam] = tline->next;
2399 continue; /* parameter loop */
2401 if (tline->type == TOK_OTHER && tline->text[1]==0) {
2402 char ch = tline->text[0];
2403 if (ch == ',' && !paren && brackets<=0) {
2404 if (++nparam >= sparam) {
2405 sparam += PARAM_DELTA;
2406 params = nasm_realloc (params,
2407 sparam*sizeof(Token *));
2408 paramsize = nasm_realloc (paramsize,
2409 sparam*sizeof(int));
2411 params[nparam] = tline->next;
2412 paramsize[nparam] = 0;
2413 white = 0;
2414 continue; /* parameter loop */
2416 if (ch == '{' &&
2417 (brackets>0 || (brackets==0 &&
2418 !paramsize[nparam])))
2420 if (!(brackets++))
2422 params[nparam] = tline->next;
2423 continue; /* parameter loop */
2426 if (ch == '}' && brackets>0)
2427 if (--brackets == 0) {
2428 brackets = -1;
2429 continue; /* parameter loop */
2431 if (ch == '(' && !brackets)
2432 paren++;
2433 if (ch == ')' && brackets<=0)
2434 if (--paren < 0)
2435 break;
2437 if (brackets<0) {
2438 brackets = 0;
2439 error (ERR_NONFATAL, "braces do not "
2440 "enclose all of macro parameter");
2442 paramsize[nparam] += white+1;
2443 white = 0;
2444 } /* parameter loop */
2445 nparam++;
2446 while (m && (m->nparam != nparam ||
2447 mstrcmp(m->name, mname, m->casesense)))
2448 m = m->next;
2449 if (!m)
2450 error (ERR_WARNING|ERR_WARN_MNP,
2451 "macro `%s' exists, "
2452 "but not taking %d parameters",
2453 mstart->text, nparam);
2456 if (m && m->in_progress)
2457 m = NULL;
2458 if (!m) /* in progess or didn't find '(' or wrong nparam */
2461 * Design question: should we handle !tline, which
2462 * indicates missing ')' here, or expand those
2463 * macros anyway, which requires the (t) test a few
2464 * lines down?
2466 nasm_free (params);
2467 nasm_free (paramsize);
2468 tline = mstart;
2469 } else {
2471 * Expand the macro: we are placed on the last token of the
2472 * call, so that we can easily split the call from the
2473 * following tokens. We also start by pushing an SMAC_END
2474 * token for the cycle removal.
2476 t = tline;
2477 if (t) {
2478 tline = t->next;
2479 t->next = NULL;
2481 tt = nasm_malloc(sizeof(Token));
2482 tt->type = TOK_SMAC_END;
2483 tt->text = NULL;
2484 tt->mac = m;
2485 m->in_progress = TRUE;
2486 tt->next = tline;
2487 tline = tt;
2488 for (t = m->expansion; t; t = t->next) {
2489 if (t->type >= TOK_SMAC_PARAM) {
2490 Token *pcopy = tline, **ptail = &pcopy;
2491 Token *ttt, *pt;
2492 int i;
2494 ttt = params[t->type - TOK_SMAC_PARAM];
2495 for (i=paramsize[t->type-TOK_SMAC_PARAM]; --i>=0;) {
2496 pt = *ptail = nasm_malloc(sizeof(Token));
2497 pt->next = tline;
2498 ptail = &pt->next;
2499 pt->text = nasm_strdup(ttt->text);
2500 pt->type = ttt->type;
2501 pt->mac = NULL;
2502 ttt = ttt->next;
2504 tline = pcopy;
2505 } else {
2506 tt = nasm_malloc(sizeof(Token));
2507 tt->type = t->type;
2508 tt->text = nasm_strdup(t->text);
2509 tt->mac = NULL;
2510 tt->next = tline;
2511 tline = tt;
2516 * Having done that, get rid of the macro call, and clean
2517 * up the parameters.
2519 nasm_free (params);
2520 nasm_free (paramsize);
2521 free_tlist (mstart);
2522 continue; /* main token loop */
2527 if (tline->type == TOK_SMAC_END) {
2528 tline->mac->in_progress = FALSE;
2529 t = tline;
2530 tline = tline->next;
2531 nasm_free (t);
2532 } else {
2533 t = *tail = tline;
2534 tline = tline->next;
2535 t->mac = NULL;
2536 t->next = NULL;
2537 tail = &t->next;
2542 * Now scan the entire line and look for successive TOK_IDs that resulted
2543 * after expansion (they can't be produced by tokenise()). The successive
2544 * TOK_IDs should be concatenated.
2545 * Also we look for %+ tokens and concatenate the tokens before and after
2546 * them (without white spaces in between).
2548 t = thead;
2549 rescan = 0;
2550 while (t) {
2551 while (t && t->type != TOK_ID && t->type != TOK_PREPROC_ID)
2552 t = t->next;
2553 if (!t || !t->next)
2554 break;
2555 if (t->next->type == TOK_ID ||
2556 t->next->type == TOK_PREPROC_ID ||
2557 t->next->type == TOK_NUMBER) {
2558 Token *next = t->next->next;
2559 char *p = nasm_malloc (strlen (t->text) + strlen (t->next->text) + 1);
2560 strcpy (p, t->text);
2561 strcat (p, t->next->text);
2562 nasm_free (t->text);
2563 nasm_free (t->next->text);
2564 nasm_free (t->next);
2565 t->next = next;
2566 t->text = p;
2567 rescan = 1;
2568 } else if (t->next->type == TOK_WHITESPACE && t->next->next &&
2569 t->next->next->type == TOK_PREPROC_ID &&
2570 strcmp (t->next->next->text, "%+") == 0) {
2571 /* free the next whitespace, the %+ token and next whitespace */
2572 int i;
2573 for (i = 1; i <= 3; i++)
2575 Token *next;
2576 if (!t->next || (i != 2 && t->next->type != TOK_WHITESPACE))
2577 break;
2578 next = t->next->next;
2579 nasm_free (t->next->text);
2580 nasm_free (t->next);
2581 t->next = next;
2582 } /* endfor */
2583 } else
2584 t = t->next;
2586 /* If we concatenaded something, re-scan the line for macros */
2587 if (rescan) {
2588 tline = thead;
2589 goto again;
2592 if (org_tline)
2594 if (thead) {
2595 *org_tline = *thead;
2596 nasm_free (thead);
2597 } else
2599 /* the expression expanded to empty line;
2600 we can't return NULL for some reasons
2601 we just set the line to a single WHITESPACE token. */
2602 memset (org_tline, 0, sizeof (*org_tline));
2603 org_tline->text = nasm_strdup (" ");
2604 org_tline->type = TOK_WHITESPACE;
2606 thead = org_tline;
2609 return thead;
2613 * Similar to expand_smacro but used exclusively with macro identifiers
2614 * right before they are fetched in. The reason is that there can be
2615 * identifiers consisting of several subparts. We consider that if there
2616 * are more than one element forming the name, user wants a expansion,
2617 * otherwise it will be left as-is. Example:
2619 * %define %$abc cde
2621 * the identifier %$abc will be left as-is so that the handler for %define
2622 * will suck it and define the corresponding value. Other case:
2624 * %define _%$abc cde
2626 * In this case user wants name to be expanded *before* %define starts
2627 * working, so we'll expand %$abc into something (if it has a value;
2628 * otherwise it will be left as-is) then concatenate all successive
2629 * PP_IDs into one.
2631 static Token *expand_id (Token *tline)
2633 Token *cur, *oldnext = NULL;
2635 if (!tline ||
2636 !tline->next)
2637 return tline;
2639 cur = tline;
2640 while (cur->next &&
2641 (cur->next->type == TOK_ID ||
2642 cur->next->type == TOK_PREPROC_ID ||
2643 cur->next->type == TOK_NUMBER))
2644 cur = cur->next;
2646 /* If identifier consists of just one token, don't expand */
2647 if (cur == tline)
2648 return tline;
2650 if (cur) {
2651 oldnext = cur->next; /* Detach the tail past identifier */
2652 cur->next = NULL; /* so that expand_smacro stops here */
2655 tline = expand_smacro (tline);
2657 if (cur) {
2658 /* expand_smacro possibly changhed tline; re-scan for EOL */
2659 cur = tline;
2660 while (cur && cur->next)
2661 cur = cur->next;
2662 if (cur)
2663 cur->next = oldnext;
2666 return tline;
2670 * Determine whether the given line constitutes a multi-line macro
2671 * call, and return the MMacro structure called if so. Doesn't have
2672 * to check for an initial label - that's taken care of in
2673 * expand_mmacro - but must check numbers of parameters. Guaranteed
2674 * to be called with tline->type == TOK_ID, so the putative macro
2675 * name is easy to find.
2677 static MMacro *is_mmacro (Token *tline, Token ***params_array)
2679 MMacro *head, *m;
2680 Token **params;
2681 int nparam;
2683 head = mmacros[hash(tline->text)];
2686 * Efficiency: first we see if any macro exists with the given
2687 * name. If not, we can return NULL immediately. _Then_ we
2688 * count the parameters, and then we look further along the
2689 * list if necessary to find the proper MMacro.
2691 for (m = head; m; m = m->next)
2692 if (!mstrcmp(m->name, tline->text, m->casesense))
2693 break;
2694 if (!m)
2695 return NULL;
2698 * OK, we have a potential macro. Count and demarcate the
2699 * parameters.
2701 count_mmac_params (tline->next, &nparam, &params);
2704 * So we know how many parameters we've got. Find the MMacro
2705 * structure that handles this number.
2707 while (m) {
2708 if (m->nparam_min <= nparam && (m->plus || nparam <= m->nparam_max)) {
2710 * This one is right. Just check if cycle removal
2711 * prohibits us using it before we actually celebrate...
2713 if (m->in_progress) {
2714 #if 0
2715 error (ERR_NONFATAL,
2716 "self-reference in multi-line macro `%s'",
2717 m->name);
2718 #endif
2719 nasm_free (params);
2720 return NULL;
2723 * It's right, and we can use it. Add its default
2724 * parameters to the end of our list if necessary.
2726 if (m->defaults && nparam < m->nparam_min + m->ndefs) {
2727 params = nasm_realloc (params, ((m->nparam_min+m->ndefs+1) *
2728 sizeof(*params)));
2729 while (nparam < m->nparam_min + m->ndefs) {
2730 params[nparam] = m->defaults[nparam - m->nparam_min];
2731 nparam++;
2735 * If we've gone over the maximum parameter count (and
2736 * we're in Plus mode), ignore parameters beyond
2737 * nparam_max.
2739 if (m->plus && nparam > m->nparam_max)
2740 nparam = m->nparam_max;
2742 * Then terminate the parameter list, and leave.
2744 if (!params) { /* need this special case */
2745 params = nasm_malloc(sizeof(*params));
2746 nparam = 0;
2748 params[nparam] = NULL;
2749 *params_array = params;
2750 return m;
2753 * This one wasn't right: look for the next one with the
2754 * same name.
2756 for (m = m->next; m; m = m->next)
2757 if (!mstrcmp(m->name, tline->text, m->casesense))
2758 break;
2762 * After all that, we didn't find one with the right number of
2763 * parameters. Issue a warning, and fail to expand the macro.
2765 error (ERR_WARNING|ERR_WARN_MNP,
2766 "macro `%s' exists, but not taking %d parameters",
2767 tline->text, nparam);
2768 nasm_free (params);
2769 return NULL;
2773 * Expand the multi-line macro call made by the given line, if
2774 * there is one to be expanded. If there is, push the expansion on
2775 * istk->expansion and return 1. Otherwise return 0.
2777 static int expand_mmacro (Token *tline)
2779 Token *startline = tline;
2780 Token *label = NULL;
2781 int dont_prepend = 0;
2782 Token **params, *t, *tt;
2783 MMacro *m;
2784 Line *l, *ll;
2785 int i, nparam, *paramlen;
2787 t = tline;
2788 skip_white_(t);
2789 if (!tok_type_(t, TOK_ID))
2790 return 0;
2791 m = is_mmacro (t, &params);
2792 if (!m) {
2793 Token *last;
2795 * We have an id which isn't a macro call. We'll assume
2796 * it might be a label; we'll also check to see if a
2797 * colon follows it. Then, if there's another id after
2798 * that lot, we'll check it again for macro-hood.
2800 label = last = t;
2801 t = t->next;
2802 if (tok_type_(t, TOK_WHITESPACE))
2803 last = t, t = t->next;
2804 if (tok_is_(t, ":")) {
2805 dont_prepend = 1;
2806 last = t, t = t->next;
2807 if (tok_type_(t, TOK_WHITESPACE))
2808 last = t, t = t->next;
2810 if (!tok_type_(t, TOK_ID) || (m = is_mmacro(t, &params)) == NULL)
2811 return 0;
2812 last->next = NULL;
2813 tline = t;
2817 * Fix up the parameters: this involves stripping leading and
2818 * trailing whitespace, then stripping braces if they are
2819 * present.
2821 for (nparam = 0; params[nparam]; nparam++)
2823 paramlen = nparam ? nasm_malloc(nparam*sizeof(*paramlen)) : NULL;
2825 for (i = 0; params[i]; i++) {
2826 int brace = FALSE;
2827 int comma = (!m->plus || i < nparam-1);
2829 t = params[i];
2830 skip_white_(t);
2831 if (tok_is_(t, "{"))
2832 t = t->next, brace = TRUE, comma = FALSE;
2833 params[i] = t;
2834 paramlen[i] = 0;
2835 while (t) {
2836 if (comma && t->type == TOK_OTHER && !strcmp(t->text, ","))
2837 break; /* ... because we have hit a comma */
2838 if (comma && t->type == TOK_WHITESPACE && tok_is_(t->next, ","))
2839 break; /* ... or a space then a comma */
2840 if (brace && t->type == TOK_OTHER && !strcmp(t->text, "}"))
2841 break; /* ... or a brace */
2842 t = t->next;
2843 paramlen[i]++;
2848 * OK, we have a MMacro structure together with a set of
2849 * parameters. We must now go through the expansion and push
2850 * copies of each Line on to istk->expansion. Substitution of
2851 * parameter tokens and macro-local tokens doesn't get done
2852 * until the single-line macro substitution process; this is
2853 * because delaying them allows us to change the semantics
2854 * later through %rotate.
2856 * First, push an end marker on to istk->expansion, mark this
2857 * macro as in progress, and set up its invocation-specific
2858 * variables.
2860 ll = nasm_malloc(sizeof(Line));
2861 ll->next = istk->expansion;
2862 ll->finishes = m;
2863 ll->first = NULL;
2864 istk->expansion = ll;
2866 m->in_progress = TRUE;
2867 m->params = params;
2868 m->iline = tline;
2869 m->nparam = nparam;
2870 m->rotate = 0;
2871 m->paramlen = paramlen;
2872 m->unique = unique++;
2873 m->lineno = 0;
2875 m->next_active = istk->mstk;
2876 istk->mstk = m;
2878 for (l = m->expansion; l; l = l->next) {
2879 Token **tail;
2881 ll = nasm_malloc(sizeof(Line));
2882 ll->finishes = NULL;
2883 ll->next = istk->expansion;
2884 istk->expansion = ll;
2885 tail = &ll->first;
2887 for (t = l->first; t; t = t->next) {
2888 Token *x = t;
2889 if (t->type == TOK_PREPROC_ID &&
2890 t->text[1]=='0' && t->text[2]=='0')
2892 dont_prepend = -1;
2893 x = label;
2894 if (!x)
2895 continue;
2897 tt = *tail = nasm_malloc(sizeof(Token));
2898 tail = &tt->next;
2899 tt->type = x->type;
2900 tt->text = nasm_strdup(x->text);
2901 tt->mac = NULL;
2903 *tail = NULL;
2907 * If we had a label, push it on as the first line of
2908 * the macro expansion.
2910 if (label) {
2911 if (dont_prepend<0)
2912 free_tlist(startline);
2913 else {
2914 ll = nasm_malloc(sizeof(Line));
2915 ll->finishes = NULL;
2916 ll->next = istk->expansion;
2917 istk->expansion = ll;
2918 ll->first = startline;
2919 if (!dont_prepend) {
2920 while (label->next)
2921 label = label->next;
2922 label->next = tt = nasm_malloc(sizeof(Token));
2923 tt->next = NULL;
2924 tt->mac = NULL;
2925 tt->type = TOK_OTHER;
2926 tt->text = nasm_strdup(":");
2931 list->uplevel (m->nolist ? LIST_MACRO_NOLIST : LIST_MACRO);
2933 return 1;
2937 * Since preprocessor always operate only on the line that didn't
2938 * arrived yet, we should always use ERR_OFFBY1. Also since user
2939 * won't want to see same error twice (preprocessing is done once
2940 * per pass) we will want to show errors only during pass one.
2942 static void error (int severity, char *fmt, ...)
2944 va_list arg;
2945 char buff [1024];
2947 /* If we're in a dead branch of IF or something like it, ignore the error */
2948 if (istk->conds && !emitting(istk->conds->state))
2949 return;
2951 va_start (arg, fmt);
2952 vsprintf (buff, fmt, arg);
2953 va_end (arg);
2955 if (istk->mstk && istk->mstk->name)
2956 __error (severity|ERR_PASS1, "(%s:%d) %s", istk->mstk->name,
2957 istk->mstk->lineno, buff);
2958 else
2959 __error (severity|ERR_PASS1, "%s", buff);
2962 static void pp_reset (char *file, int apass, efunc errfunc, evalfunc eval,
2963 ListGen *listgen)
2965 int h;
2967 __error = errfunc;
2968 cstk = NULL;
2969 istk = nasm_malloc(sizeof(Include));
2970 istk->next = NULL;
2971 istk->conds = NULL;
2972 istk->expansion = NULL;
2973 istk->mstk = NULL;
2974 istk->fp = fopen(file, "r");
2975 istk->fname = NULL;
2976 src_set_fname(nasm_strdup(file));
2977 src_set_linnum(0);
2978 istk->lineinc = 1;
2979 if (!istk->fp)
2980 error (ERR_FATAL|ERR_NOFILE, "unable to open input file `%s'", file);
2981 defining = NULL;
2982 for (h=0; h<NHASH; h++) {
2983 mmacros[h] = NULL;
2984 smacros[h] = NULL;
2986 unique = 0;
2987 stdmacpos = stdmac;
2988 any_extrastdmac = (extrastdmac != NULL);
2989 list = listgen;
2990 evaluate = eval;
2991 pass = apass;
2994 static char *pp_getline (void)
2996 char *line;
2997 Token *tline;
2998 int ret;
3000 while (1) {
3002 * Fetch a tokenised line, either from the macro-expansion
3003 * buffer or from the input file.
3005 tline = NULL;
3006 while (istk->expansion && istk->expansion->finishes) {
3007 Line *l = istk->expansion;
3008 if (!l->finishes->name && l->finishes->in_progress > 1) {
3009 Line *ll;
3012 * This is a macro-end marker for a macro with no
3013 * name, which means it's not really a macro at all
3014 * but a %rep block, and the `in_progress' field is
3015 * more than 1, meaning that we still need to
3016 * repeat. (1 means the natural last repetition; 0
3017 * means termination by %exitrep.) We have
3018 * therefore expanded up to the %endrep, and must
3019 * push the whole block on to the expansion buffer
3020 * again. We don't bother to remove the macro-end
3021 * marker: we'd only have to generate another one
3022 * if we did.
3024 l->finishes->in_progress--;
3025 for (l = l->finishes->expansion; l; l = l->next) {
3026 Token *t, *tt, **tail;
3028 ll = nasm_malloc(sizeof(Line));
3029 ll->next = istk->expansion;
3030 ll->finishes = NULL;
3031 ll->first = NULL;
3032 tail = &ll->first;
3034 for (t = l->first; t; t = t->next) {
3035 if (t->text) {
3036 tt = *tail = nasm_malloc(sizeof(Token));
3037 tt->next = NULL;
3038 tail = &tt->next;
3039 tt->type = t->type;
3040 tt->text = nasm_strdup(t->text);
3041 tt->mac = NULL;
3045 istk->expansion = ll;
3047 } else {
3049 * Check whether a `%rep' was started and not ended
3050 * within this macro expansion. This can happen and
3051 * should be detected. It's a fatal error because
3052 * I'm too confused to work out how to recover
3053 * sensibly from it.
3055 if (defining) {
3056 if (defining->name)
3057 error (ERR_PANIC,
3058 "defining with name in expansion");
3059 else if (istk->mstk->name)
3060 error (ERR_FATAL, "`%%rep' without `%%endrep' within"
3061 " expansion of macro `%s'", istk->mstk->name);
3065 * FIXME: investigate the relationship at this point between
3066 * istk->mstk and l->finishes
3069 MMacro *m = istk->mstk;
3070 istk->mstk = m->next_active;
3071 if (m->name) {
3073 * This was a real macro call, not a %rep, and
3074 * therefore the parameter information needs to
3075 * be freed.
3077 nasm_free(m->params);
3078 free_tlist(m->iline);
3079 nasm_free(m->paramlen);
3080 l->finishes->in_progress = FALSE;
3082 else
3083 free_mmacro(m);
3085 istk->expansion = l->next;
3086 nasm_free (l);
3087 list->downlevel (LIST_MACRO);
3090 while (1) { /* until we get a line we can use */
3092 if (istk->expansion) { /* from a macro expansion */
3093 char *p;
3094 Line *l = istk->expansion;
3095 if (istk->mstk)
3096 istk->mstk->lineno++;
3097 tline = l->first;
3098 istk->expansion = l->next;
3099 nasm_free (l);
3100 p = detoken (tline, FALSE);
3101 list->line (LIST_MACRO, p);
3102 nasm_free(p);
3103 break;
3105 line = read_line();
3106 if (line) { /* from the current input file */
3107 line = prepreproc(line);
3108 tline = tokenise(line);
3109 nasm_free (line);
3110 break;
3113 * The current file has ended; work down the istk
3116 Include *i = istk;
3117 fclose(i->fp);
3118 if (i->conds)
3119 error(ERR_FATAL, "expected `%%endif' before end of file");
3120 istk = i->next;
3121 list->downlevel (LIST_INCLUDE);
3122 src_set_linnum(i->lineno);
3123 nasm_free ( src_set_fname(i->fname) );
3124 nasm_free (i);
3125 if (!istk)
3126 return NULL;
3131 * We must expand MMacro parameters and MMacro-local labels
3132 * _before_ we plunge into directive processing, to cope
3133 * with things like `%define something %1' such as STRUC
3134 * uses. Unless we're _defining_ a MMacro, in which case
3135 * those tokens should be left alone to go into the
3136 * definition; and unless we're in a non-emitting
3137 * condition, in which case we don't want to meddle with
3138 * anything.
3140 if (!defining && !(istk->conds && !emitting(istk->conds->state)))
3141 tline = expand_mmac_params(tline);
3144 * Check the line to see if it's a preprocessor directive.
3146 ret = do_directive(tline);
3147 if (ret & 1) {
3148 continue;
3149 } else if (defining) {
3151 * We're defining a multi-line macro. We emit nothing
3152 * at all, and just
3153 * shove the tokenised line on to the macro definition.
3155 Line *l = nasm_malloc(sizeof(Line));
3156 l->next = defining->expansion;
3157 l->first = tline;
3158 l->finishes = FALSE;
3159 defining->expansion = l;
3160 continue;
3161 } else if (istk->conds && !emitting(istk->conds->state)) {
3163 * We're in a non-emitting branch of a condition block.
3164 * Emit nothing at all, not even a blank line: when we
3165 * emerge from the condition we'll give a line-number
3166 * directive so we keep our place correctly.
3168 free_tlist(tline);
3169 continue;
3170 } else if (istk->mstk && !istk->mstk->in_progress) {
3172 * We're in a %rep block which has been terminated, so
3173 * we're walking through to the %endrep without
3174 * emitting anything. Emit nothing at all, not even a
3175 * blank line: when we emerge from the %rep block we'll
3176 * give a line-number directive so we keep our place
3177 * correctly.
3179 free_tlist(tline);
3180 continue;
3181 } else {
3182 tline = expand_smacro(tline);
3183 ret = expand_mmacro(tline);
3184 if (!ret) {
3186 * De-tokenise the line again, and emit it.
3188 line = detoken(tline, TRUE);
3189 free_tlist (tline);
3190 break;
3191 } else {
3192 continue; /* expand_mmacro calls free_tlist */
3197 return line;
3200 static void pp_cleanup (void)
3202 int h;
3204 if (defining) {
3205 error (ERR_NONFATAL, "end of file while still defining macro `%s'",
3206 defining->name);
3207 free_mmacro (defining);
3209 while (cstk)
3210 ctx_pop();
3211 for (h=0; h<NHASH; h++) {
3212 while (mmacros[h]) {
3213 MMacro *m = mmacros[h];
3214 mmacros[h] = mmacros[h]->next;
3215 free_mmacro(m);
3217 while (smacros[h]) {
3218 SMacro *s = smacros[h];
3219 smacros[h] = smacros[h]->next;
3220 nasm_free (s->name);
3221 free_tlist (s->expansion);
3222 nasm_free (s);
3225 while (istk) {
3226 Include *i = istk;
3227 istk = istk->next;
3228 fclose(i->fp);
3229 nasm_free (i->fname);
3230 nasm_free (i);
3232 while (cstk)
3233 ctx_pop();
3236 void pp_include_path (char *path)
3238 IncPath *i;
3240 i = nasm_malloc(sizeof(IncPath));
3241 i->path = nasm_strdup(path);
3242 i->next = ipath;
3243 ipath = i;
3246 void pp_pre_include (char *fname)
3248 Token *inc, *space, *name;
3249 Line *l;
3251 inc = nasm_malloc(sizeof(Token));
3252 inc->next = space = nasm_malloc(sizeof(Token));
3253 space->next = name = nasm_malloc(sizeof(Token));
3254 name->next = NULL;
3256 inc->type = TOK_PREPROC_ID;
3257 inc->text = nasm_strdup("%include");
3258 space->type = TOK_WHITESPACE;
3259 space->text = nasm_strdup(" ");
3260 name->type = TOK_INTERNAL_STRING;
3261 name->text = nasm_strdup(fname);
3263 inc->mac = space->mac = name->mac = NULL;
3265 l = nasm_malloc(sizeof(Line));
3266 l->next = predef;
3267 l->first = inc;
3268 l->finishes = FALSE;
3269 predef = l;
3272 void pp_pre_define (char *definition)
3274 Token *def, *space;
3275 Line *l;
3276 char *equals;
3278 equals = strchr(definition, '=');
3280 def = nasm_malloc(sizeof(Token));
3281 def->next = space = nasm_malloc(sizeof(Token));
3282 if (equals)
3283 *equals = ' ';
3284 space->next = tokenise(definition);
3285 if (equals)
3286 *equals = '=';
3288 def->type = TOK_PREPROC_ID;
3289 def->text = nasm_strdup("%define");
3290 space->type = TOK_WHITESPACE;
3291 space->text = nasm_strdup(" ");
3293 def->mac = space->mac = NULL;
3295 l = nasm_malloc(sizeof(Line));
3296 l->next = predef;
3297 l->first = def;
3298 l->finishes = FALSE;
3299 predef = l;
3302 void pp_pre_undefine (char *definition)
3304 Token *def, *space;
3305 Line *l;
3307 def = nasm_malloc(sizeof(Token));
3308 def->next = space = nasm_malloc(sizeof(Token));
3309 space->next = tokenise(definition);
3311 def->type = TOK_PREPROC_ID;
3312 def->text = nasm_strdup("%undef");
3313 space->type = TOK_WHITESPACE;
3314 space->text = nasm_strdup(" ");
3316 def->mac = space->mac = NULL;
3318 l = nasm_malloc(sizeof(Line));
3319 l->next = predef;
3320 l->first = def;
3321 l->finishes = FALSE;
3322 predef = l;
3325 void pp_extra_stdmac (char **macros)
3327 extrastdmac = macros;
3330 static void make_tok_num(Token *tok, long val)
3332 char numbuf[20];
3333 sprintf(numbuf, "%ld", val);
3334 tok->text = nasm_strdup(numbuf);
3335 tok->type = TOK_NUMBER;
3338 Preproc nasmpp = {
3339 pp_reset,
3340 pp_getline,
3341 pp_cleanup