1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2012 The NASM Authors - All Rights Reserved
4 * See the file AUTHORS included with the NASM distribution for
5 * the specific copyright holders.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above
14 * copyright notice, this list of conditions and the following
15 * disclaimer in the documentation and/or other materials provided
16 * with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * ----------------------------------------------------------------------- */
35 * preproc.c macro preprocessor for the Netwide Assembler
38 /* Typical flow of text through preproc
40 * pp_getline gets tokenized lines, either
42 * from a macro expansion
46 * read_line gets raw text from stdmacpos, or predef, or current input file
47 * tokenize converts to tokens
50 * expand_mmac_params is used to expand %1 etc., unless a macro is being
51 * defined or a false conditional is being processed
52 * (%0, %1, %+1, %-1, %%foo
54 * do_directive checks for directives
56 * expand_smacro is used to expand single line macros
58 * expand_mmacro is used to expand multi-line macros
60 * detoken is used to convert the line back to text
84 typedef struct SMacro SMacro
;
85 typedef struct MMacro MMacro
;
86 typedef struct MMacroInvocation MMacroInvocation
;
87 typedef struct Context Context
;
88 typedef struct Token Token
;
89 typedef struct Blocks Blocks
;
90 typedef struct Line Line
;
91 typedef struct Include Include
;
92 typedef struct Cond Cond
;
93 typedef struct IncPath IncPath
;
96 * Note on the storage of both SMacro and MMacros: the hash table
97 * indexes them case-insensitively, and we then have to go through a
98 * linked list of potential case aliases (and, for MMacros, parameter
99 * ranges); this is to preserve the matching semantics of the earlier
100 * code. If the number of case aliases for a specific macro is a
101 * performance issue, you may want to reconsider your coding style.
105 * Store the definition of a single-line macro.
117 * Store the definition of a multi-line macro. This is also used to
118 * store the interiors of `%rep...%endrep' blocks, which are
119 * effectively self-re-invoking multi-line macros which simply
120 * don't have a name or bother to appear in the hash tables. %rep
121 * blocks are signified by having a NULL `name' field.
123 * In a MMacro describing a `%rep' block, the `in_progress' field
124 * isn't merely boolean, but gives the number of repeats left to
127 * The `next' field is used for storing MMacros in hash tables; the
128 * `next_active' field is for stacking them on istk entries.
130 * When a MMacro is being expanded, `params', `iline', `nparam',
131 * `paramlen', `rotate' and `unique' are local to the invocation.
135 MMacroInvocation
*prev
; /* previous invocation */
137 int nparam_min
, nparam_max
;
139 bool plus
; /* is the last parameter greedy? */
140 bool nolist
; /* is this macro listing-inhibited? */
141 int64_t in_progress
; /* is this macro currently being expanded? */
142 int32_t max_depth
; /* maximum number of recursive expansions allowed */
143 Token
*dlist
; /* All defaults as one list */
144 Token
**defaults
; /* Parameter default pointers */
145 int ndefs
; /* number of default parameters */
149 MMacro
*rep_nest
; /* used for nesting %rep */
150 Token
**params
; /* actual parameters */
151 Token
*iline
; /* invocation line */
152 unsigned int nparam
, rotate
;
155 int lineno
; /* Current line number on expansion */
156 uint64_t condcnt
; /* number of if blocks... */
160 /* Store the definition of a multi-line macro, as defined in a
161 * previous recursive macro expansion.
163 struct MMacroInvocation
{
164 MMacroInvocation
*prev
; /* previous invocation */
165 Token
**params
; /* actual parameters */
166 Token
*iline
; /* invocation line */
167 unsigned int nparam
, rotate
;
175 * The context stack is composed of a linked list of these.
180 struct hash_table localmac
;
185 * This is the internal form which we break input lines up into.
186 * Typically stored in linked lists.
188 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
189 * necessarily used as-is, but is intended to denote the number of
190 * the substituted parameter. So in the definition
192 * %define a(x,y) ( (x) & ~(y) )
194 * the token representing `x' will have its type changed to
195 * TOK_SMAC_PARAM, but the one representing `y' will be
198 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
199 * which doesn't need quotes around it. Used in the pre-include
200 * mechanism as an alternative to trying to find a sensible type of
201 * quote to use on the filename we were passed.
204 TOK_NONE
= 0, TOK_WHITESPACE
, TOK_COMMENT
, TOK_ID
,
205 TOK_PREPROC_ID
, TOK_STRING
,
206 TOK_NUMBER
, TOK_FLOAT
, TOK_SMAC_END
, TOK_OTHER
,
208 TOK_PREPROC_Q
, TOK_PREPROC_QQ
,
210 TOK_INDIRECT
, /* %[...] */
211 TOK_BRACE
, /* \{...\} */
212 TOK_SMAC_PARAM
, /* MUST BE LAST IN THE LIST!!! */
213 TOK_MAX
= INT_MAX
/* Keep compiler from reducing the range */
216 #define PP_CONCAT_MASK(x) (1 << (x))
217 #define PP_CONCAT_MATCH(t, mask) (PP_CONCAT_MASK((t)->type) & mask)
219 struct tokseq_match
{
228 SMacro
*mac
; /* associated macro for TOK_SMAC_END */
229 size_t len
; /* scratch length field */
230 } a
; /* Auxiliary data */
231 enum pp_token_type type
;
235 * Multi-line macro definitions are stored as a linked list of
236 * these, which is essentially a container to allow several linked
239 * Note that in this module, linked lists are treated as stacks
240 * wherever possible. For this reason, Lines are _pushed_ on to the
241 * `expansion' field in MMacro structures, so that the linked list,
242 * if walked, would give the macro lines in reverse order; this
243 * means that we can walk the list when expanding a macro, and thus
244 * push the lines on to the `expansion' field in _istk_ in reverse
245 * order (so that when popped back off they are in the right
246 * order). It may seem cockeyed, and it relies on my design having
247 * an even number of steps in, but it works...
249 * Some of these structures, rather than being actual lines, are
250 * markers delimiting the end of the expansion of a given macro.
251 * This is for use in the cycle-tracking and %rep-handling code.
252 * Such structures have `finishes' non-NULL, and `first' NULL. All
253 * others have `finishes' NULL, but `first' may still be NULL if
263 * To handle an arbitrary level of file inclusion, we maintain a
264 * stack (ie linked list) of these things.
273 MMacro
*mstk
; /* stack of active macros/reps */
277 * Include search path. This is simply a list of strings which get
278 * prepended, in turn, to the name of an include file, in an
279 * attempt to find the file if it's not in the current directory.
287 * Conditional assembly: we maintain a separate stack of these for
288 * each level of file inclusion. (The only reason we keep the
289 * stacks separate is to ensure that a stray `%endif' in a file
290 * included from within the true branch of a `%if' won't terminate
291 * it and cause confusion: instead, rightly, it'll cause an error.)
299 * These states are for use just after %if or %elif: IF_TRUE
300 * means the condition has evaluated to truth so we are
301 * currently emitting, whereas IF_FALSE means we are not
302 * currently emitting but will start doing so if a %else comes
303 * up. In these states, all directives are admissible: %elif,
304 * %else and %endif. (And of course %if.)
306 COND_IF_TRUE
, COND_IF_FALSE
,
308 * These states come up after a %else: ELSE_TRUE means we're
309 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
310 * any %elif or %else will cause an error.
312 COND_ELSE_TRUE
, COND_ELSE_FALSE
,
314 * These states mean that we're not emitting now, and also that
315 * nothing until %endif will be emitted at all. COND_DONE is
316 * used when we've had our moment of emission
317 * and have now started seeing %elifs. COND_NEVER is used when
318 * the condition construct in question is contained within a
319 * non-emitting branch of a larger condition construct,
320 * or if there is an error.
322 COND_DONE
, COND_NEVER
324 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
327 * These defines are used as the possible return values for do_directive
329 #define NO_DIRECTIVE_FOUND 0
330 #define DIRECTIVE_FOUND 1
333 * This define sets the upper limit for smacro and recursive mmacro
336 #define DEADMAN_LIMIT (1 << 20)
339 #define REP_LIMIT ((INT64_C(1) << 62))
342 * Condition codes. Note that we use c_ prefix not C_ because C_ is
343 * used in nasm.h for the "real" condition codes. At _this_ level,
344 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
345 * ones, so we need a different enum...
347 static const char * const conditions
[] = {
348 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
349 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
350 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
353 c_A
, c_AE
, c_B
, c_BE
, c_C
, c_CXZ
, c_E
, c_ECXZ
, c_G
, c_GE
, c_L
, c_LE
,
354 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, c_NE
, c_NG
, c_NGE
, c_NL
, c_NLE
, c_NO
,
355 c_NP
, c_NS
, c_NZ
, c_O
, c_P
, c_PE
, c_PO
, c_RCXZ
, c_S
, c_Z
,
358 static const enum pp_conds inverse_ccs
[] = {
359 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, -1, c_NE
, -1, c_NG
, c_NGE
, c_NL
, c_NLE
,
360 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
,
361 c_Z
, c_NO
, c_NP
, c_PO
, c_PE
, -1, c_NS
, c_NZ
367 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
368 static int is_condition(enum preproc_token arg
)
370 return PP_IS_COND(arg
) || (arg
== PP_ELSE
) || (arg
== PP_ENDIF
);
373 /* For TASM compatibility we need to be able to recognise TASM compatible
374 * conditional compilation directives. Using the NASM pre-processor does
375 * not work, so we look for them specifically from the following list and
376 * then jam in the equivalent NASM directive into the input stream.
380 TM_ARG
, TM_ELIF
, TM_ELSE
, TM_ENDIF
, TM_IF
, TM_IFDEF
, TM_IFDIFI
,
381 TM_IFNDEF
, TM_INCLUDE
, TM_LOCAL
384 static const char * const tasm_directives
[] = {
385 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
386 "ifndef", "include", "local"
389 static int StackSize
= 4;
390 static char *StackPointer
= "ebp";
391 static int ArgOffset
= 8;
392 static int LocalOffset
= 0;
394 static Context
*cstk
;
395 static Include
*istk
;
396 static IncPath
*ipath
= NULL
;
398 static int pass
; /* HACK: pass 0 = generate dependencies only */
399 static StrList
**dephead
, **deptail
; /* Dependency list */
401 static uint64_t unique
; /* unique identifier numbers */
403 static Line
*predef
= NULL
;
404 static bool do_predef
;
406 static ListGen
*list
;
409 * The current set of multi-line macros we have defined.
411 static struct hash_table mmacros
;
414 * The current set of single-line macros we have defined.
416 static struct hash_table smacros
;
419 * The multi-line macro we are currently defining, or the %rep
420 * block we are currently reading, if any.
422 static MMacro
*defining
;
424 static uint64_t nested_mac_count
;
425 static uint64_t nested_rep_count
;
428 * The number of macro parameters to allocate space for at a time.
430 #define PARAM_DELTA 16
433 * The standard macro set: defined in macros.c in the array nasm_stdmac.
434 * This gives our position in the macro set, when we're processing it.
436 static macros_t
*stdmacpos
;
439 * The extra standard macros that come from the object format, if
442 static macros_t
*extrastdmac
= NULL
;
443 static bool any_extrastdmac
;
446 * Tokens are allocated in blocks to improve speed
448 #define TOKEN_BLOCKSIZE 4096
449 static Token
*freeTokens
= NULL
;
455 static Blocks blocks
= { NULL
, NULL
};
458 * Forward declarations.
460 static Token
*expand_mmac_params(Token
* tline
);
461 static Token
*expand_smacro(Token
* tline
);
462 static Token
*expand_id(Token
* tline
);
463 static Context
*get_ctx(const char *name
, const char **namep
);
464 static void make_tok_num(Token
* tok
, int64_t val
);
465 static void error(int severity
, const char *fmt
, ...);
466 static void error_precond(int severity
, const char *fmt
, ...);
467 static void *new_Block(size_t size
);
468 static void delete_Blocks(void);
469 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
470 const char *text
, int txtlen
);
471 static Token
*delete_Token(Token
* t
);
474 * Macros for safe checking of token pointers, avoid *(NULL)
476 #define tok_type_(x,t) ((x) && (x)->type == (t))
477 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
478 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
479 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
482 * nasm_unquote with error if the string contains NUL characters.
483 * If the string contains NUL characters, issue an error and return
484 * the C len, i.e. truncate at the NUL.
486 static size_t nasm_unquote_cstr(char *qstr
, enum preproc_token directive
)
488 size_t len
= nasm_unquote(qstr
, NULL
);
489 size_t clen
= strlen(qstr
);
492 error(ERR_NONFATAL
, "NUL character in `%s' directive",
493 pp_directives
[directive
]);
499 * In-place reverse a list of tokens.
501 static Token
*reverse_tokens(Token
*t
)
517 * Handle TASM specific directives, which do not contain a % in
518 * front of them. We do it here because I could not find any other
519 * place to do it for the moment, and it is a hack (ideally it would
520 * be nice to be able to use the NASM pre-processor to do it).
522 static char *check_tasm_directive(char *line
)
524 int32_t i
, j
, k
, m
, len
;
525 char *p
, *q
, *oldline
, oldchar
;
527 p
= nasm_skip_spaces(line
);
529 /* Binary search for the directive name */
531 j
= ARRAY_SIZE(tasm_directives
);
532 q
= nasm_skip_word(p
);
539 m
= nasm_stricmp(p
, tasm_directives
[k
]);
541 /* We have found a directive, so jam a % in front of it
542 * so that NASM will then recognise it as one if it's own.
547 line
= nasm_malloc(len
+ 2);
549 if (k
== TM_IFDIFI
) {
551 * NASM does not recognise IFDIFI, so we convert
552 * it to %if 0. This is not used in NASM
553 * compatible code, but does need to parse for the
554 * TASM macro package.
556 strcpy(line
+ 1, "if 0");
558 memcpy(line
+ 1, p
, len
+ 1);
573 * The pre-preprocessing stage... This function translates line
574 * number indications as they emerge from GNU cpp (`# lineno "file"
575 * flags') into NASM preprocessor line number indications (`%line
578 static char *prepreproc(char *line
)
581 char *fname
, *oldline
;
583 if (line
[0] == '#' && line
[1] == ' ') {
586 lineno
= atoi(fname
);
587 fname
+= strspn(fname
, "0123456789 ");
590 fnlen
= strcspn(fname
, "\"");
591 line
= nasm_malloc(20 + fnlen
);
592 snprintf(line
, 20 + fnlen
, "%%line %d %.*s", lineno
, fnlen
, fname
);
595 if (tasm_compatible_mode
)
596 return check_tasm_directive(line
);
601 * Free a linked list of tokens.
603 static void free_tlist(Token
* list
)
606 list
= delete_Token(list
);
610 * Free a linked list of lines.
612 static void free_llist(Line
* list
)
615 list_for_each_safe(l
, tmp
, list
) {
616 free_tlist(l
->first
);
624 static void free_mmacro(MMacro
* m
)
627 free_tlist(m
->dlist
);
628 nasm_free(m
->defaults
);
629 free_llist(m
->expansion
);
634 * Free all currently defined macros, and free the hash tables
636 static void free_smacro_table(struct hash_table
*smt
)
640 struct hash_tbl_node
*it
= NULL
;
642 while ((s
= hash_iterate(smt
, &it
, &key
)) != NULL
) {
643 nasm_free((void *)key
);
644 list_for_each_safe(s
, tmp
, s
) {
646 free_tlist(s
->expansion
);
653 static void free_mmacro_table(struct hash_table
*mmt
)
657 struct hash_tbl_node
*it
= NULL
;
660 while ((m
= hash_iterate(mmt
, &it
, &key
)) != NULL
) {
661 nasm_free((void *)key
);
662 list_for_each_safe(m
,tmp
, m
)
668 static void free_macros(void)
670 free_smacro_table(&smacros
);
671 free_mmacro_table(&mmacros
);
675 * Initialize the hash tables
677 static void init_macros(void)
679 hash_init(&smacros
, HASH_LARGE
);
680 hash_init(&mmacros
, HASH_LARGE
);
684 * Pop the context stack.
686 static void ctx_pop(void)
691 free_smacro_table(&c
->localmac
);
697 * Search for a key in the hash index; adding it if necessary
698 * (in which case we initialize the data pointer to NULL.)
701 hash_findi_add(struct hash_table
*hash
, const char *str
)
703 struct hash_insert hi
;
707 r
= hash_findi(hash
, str
, &hi
);
711 strx
= nasm_strdup(str
); /* Use a more efficient allocator here? */
712 return hash_add(&hi
, strx
, NULL
);
716 * Like hash_findi, but returns the data element rather than a pointer
717 * to it. Used only when not adding a new element, hence no third
721 hash_findix(struct hash_table
*hash
, const char *str
)
725 p
= hash_findi(hash
, str
, NULL
);
726 return p
? *p
: NULL
;
730 * read line from standart macros set,
731 * if there no more left -- return NULL
733 static char *line_from_stdmac(void)
736 const unsigned char *p
= stdmacpos
;
745 len
+= pp_directives_len
[c
- 0x80] + 1;
750 line
= nasm_malloc(len
+ 1);
752 while ((c
= *stdmacpos
++)) {
754 memcpy(q
, pp_directives
[c
- 0x80], pp_directives_len
[c
- 0x80]);
755 q
+= pp_directives_len
[c
- 0x80];
765 /* This was the last of the standard macro chain... */
767 if (any_extrastdmac
) {
768 stdmacpos
= extrastdmac
;
769 any_extrastdmac
= false;
770 } else if (do_predef
) {
772 Token
*head
, **tail
, *t
;
775 * Nasty hack: here we push the contents of
776 * `predef' on to the top-level expansion stack,
777 * since this is the most convenient way to
778 * implement the pre-include and pre-define
781 list_for_each(pd
, predef
) {
784 list_for_each(t
, pd
->first
) {
785 *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
786 tail
= &(*tail
)->next
;
789 l
= nasm_malloc(sizeof(Line
));
790 l
->next
= istk
->expansion
;
803 static char *read_line(void)
805 unsigned int size
, c
, next
;
806 const unsigned int delta
= 512;
807 const unsigned int pad
= 8;
808 unsigned int nr_cont
= 0;
812 /* Standart macros set (predefined) goes first */
813 p
= line_from_stdmac();
818 p
= buffer
= nasm_malloc(size
);
822 if ((int)(c
) == EOF
) {
829 next
= fgetc(istk
->fp
);
831 ungetc(next
, istk
->fp
);
846 next
= fgetc(istk
->fp
);
847 ungetc(next
, istk
->fp
);
848 if (next
== '\r' || next
== '\n') {
856 if (c
== '\r' || c
== '\n') {
861 if (p
>= (buffer
+ size
- pad
)) {
862 buffer
= nasm_realloc(buffer
, size
+ delta
);
863 p
= buffer
+ size
- pad
;
867 *p
++ = (unsigned char)c
;
875 src_set_linnum(src_get_linnum() + istk
->lineinc
+
876 (nr_cont
* istk
->lineinc
));
879 * Handle spurious ^Z, which may be inserted into source files
880 * by some file transfer utilities.
882 buffer
[strcspn(buffer
, "\032")] = '\0';
884 list
->line(LIST_READ
, buffer
);
890 * Tokenize a line of text. This is a very simple process since we
891 * don't need to parse the value out of e.g. numeric tokens: we
892 * simply split one string into many.
894 static Token
*tokenize(char *line
)
897 enum pp_token_type type
;
899 Token
*t
, **tail
= &list
;
905 if (*p
== '+' && !nasm_isdigit(p
[1])) {
908 } else if (nasm_isdigit(*p
) ||
909 ((*p
== '-' || *p
== '+') && nasm_isdigit(p
[1]))) {
913 while (nasm_isdigit(*p
));
914 type
= TOK_PREPROC_ID
;
915 } else if (*p
== '{') {
924 error(ERR_WARNING
| ERR_PASS1
, "unterminated %{ construct");
928 type
= TOK_PREPROC_ID
;
929 } else if (*p
== '[') {
931 line
+= 2; /* Skip the leading %[ */
933 while (lvl
&& (c
= *p
++)) {
945 p
= nasm_skip_string(p
- 1) + 1;
955 error(ERR_NONFATAL
, "unterminated %[ construct");
957 } else if (*p
== '?') {
958 type
= TOK_PREPROC_Q
; /* %? */
961 type
= TOK_PREPROC_QQ
; /* %?? */
964 } else if (*p
== '!') {
965 type
= TOK_PREPROC_ID
;
971 while (isidchar(*p
));
972 } else if (*p
== '\'' || *p
== '\"' || *p
== '`') {
973 p
= nasm_skip_string(p
);
977 error(ERR_NONFATAL
|ERR_PASS1
, "unterminated %! string");
979 /* %! without string or identifier */
980 type
= TOK_OTHER
; /* Legacy behavior... */
982 } else if (isidchar(*p
) ||
983 ((*p
== '!' || *p
== '%' || *p
== '$') &&
988 while (isidchar(*p
));
989 type
= TOK_PREPROC_ID
;
995 } else if (isidstart(*p
) || (*p
== '$' && isidstart(p
[1]))) {
998 while (*p
&& isidchar(*p
))
1000 } else if (*p
== '\'' || *p
== '"' || *p
== '`') {
1005 p
= nasm_skip_string(p
);
1010 error(ERR_WARNING
|ERR_PASS1
, "unterminated string");
1011 /* Handling unterminated strings by UNV */
1014 } else if (p
[0] == '$' && p
[1] == '$') {
1015 type
= TOK_OTHER
; /* TOKEN_BASE */
1017 } else if (isnumstart(*p
)) {
1018 bool is_hex
= false;
1019 bool is_float
= false;
1035 if (!is_hex
&& (c
== 'e' || c
== 'E')) {
1037 if (*p
== '+' || *p
== '-') {
1039 * e can only be followed by +/- if it is either a
1040 * prefixed hex number or a floating-point number
1045 } else if (c
== 'H' || c
== 'h' || c
== 'X' || c
== 'x') {
1047 } else if (c
== 'P' || c
== 'p') {
1049 if (*p
== '+' || *p
== '-')
1051 } else if (isnumchar(c
) || c
== '_')
1052 ; /* just advance */
1053 else if (c
== '.') {
1055 * we need to deal with consequences of the legacy
1056 * parser, like "1.nolist" being two tokens
1057 * (TOK_NUMBER, TOK_ID) here; at least give it
1058 * a shot for now. In the future, we probably need
1059 * a flex-based scanner with proper pattern matching
1060 * to do it as well as it can be done. Nothing in
1061 * the world is going to help the person who wants
1062 * 0x123.p16 interpreted as two tokens, though.
1068 if (nasm_isdigit(*r
) || (is_hex
&& nasm_isxdigit(*r
)) ||
1069 (!is_hex
&& (*r
== 'e' || *r
== 'E')) ||
1070 (*r
== 'p' || *r
== 'P')) {
1074 break; /* Terminate the token */
1078 p
--; /* Point to first character beyond number */
1080 if (p
== line
+1 && *line
== '$') {
1081 type
= TOK_OTHER
; /* TOKEN_HERE */
1083 if (has_e
&& !is_hex
) {
1084 /* 1e13 is floating-point, but 1e13h is not */
1088 type
= is_float
? TOK_FLOAT
: TOK_NUMBER
;
1090 } else if (nasm_isspace(*p
)) {
1091 type
= TOK_WHITESPACE
;
1092 p
= nasm_skip_spaces(p
);
1094 * Whitespace just before end-of-line is discarded by
1095 * pretending it's a comment; whitespace just before a
1096 * comment gets lumped into the comment.
1098 if (!*p
|| *p
== ';') {
1103 } else if (*p
== ';') {
1107 } else if (p
[0] == '\\' && (p
[1] == '{' || p
[1] == '}')) {
1113 * Anything else is an operator of some kind. We check
1114 * for all the double-character operators (>>, <<, //,
1115 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1116 * else is a single-character operator.
1119 if ((p
[0] == '>' && p
[1] == '>') ||
1120 (p
[0] == '<' && p
[1] == '<') ||
1121 (p
[0] == '/' && p
[1] == '/') ||
1122 (p
[0] == '<' && p
[1] == '=') ||
1123 (p
[0] == '>' && p
[1] == '=') ||
1124 (p
[0] == '=' && p
[1] == '=') ||
1125 (p
[0] == '!' && p
[1] == '=') ||
1126 (p
[0] == '<' && p
[1] == '>') ||
1127 (p
[0] == '&' && p
[1] == '&') ||
1128 (p
[0] == '|' && p
[1] == '|') ||
1129 (p
[0] == '^' && p
[1] == '^')) {
1135 /* Handling unterminated string by UNV */
1138 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1139 t->text[p-line] = *line;
1143 if (type
!= TOK_COMMENT
) {
1144 *tail
= t
= new_Token(NULL
, type
, line
, p
- line
);
1153 * this function allocates a new managed block of memory and
1154 * returns a pointer to the block. The managed blocks are
1155 * deleted only all at once by the delete_Blocks function.
1157 static void *new_Block(size_t size
)
1159 Blocks
*b
= &blocks
;
1161 /* first, get to the end of the linked list */
1164 /* now allocate the requested chunk */
1165 b
->chunk
= nasm_malloc(size
);
1167 /* now allocate a new block for the next request */
1168 b
->next
= nasm_malloc(sizeof(Blocks
));
1169 /* and initialize the contents of the new block */
1170 b
->next
->next
= NULL
;
1171 b
->next
->chunk
= NULL
;
1176 * this function deletes all managed blocks of memory
1178 static void delete_Blocks(void)
1180 Blocks
*a
, *b
= &blocks
;
1183 * keep in mind that the first block, pointed to by blocks
1184 * is a static and not dynamically allocated, so we don't
1189 nasm_free(b
->chunk
);
1198 * this function creates a new Token and passes a pointer to it
1199 * back to the caller. It sets the type and text elements, and
1200 * also the a.mac and next elements to NULL.
1202 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
1203 const char *text
, int txtlen
)
1209 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1210 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1211 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1212 freeTokens
[i
].next
= NULL
;
1215 freeTokens
= t
->next
;
1219 if (type
== TOK_WHITESPACE
|| !text
) {
1223 txtlen
= strlen(text
);
1224 t
->text
= nasm_malloc(txtlen
+1);
1225 memcpy(t
->text
, text
, txtlen
);
1226 t
->text
[txtlen
] = '\0';
1231 static Token
*delete_Token(Token
* t
)
1233 Token
*next
= t
->next
;
1235 t
->next
= freeTokens
;
1241 * Convert a line of tokens back into text.
1242 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1243 * will be transformed into ..@ctxnum.xxx
1245 static char *detoken(Token
* tlist
, bool expand_locals
)
1252 list_for_each(t
, tlist
) {
1253 if (t
->type
== TOK_PREPROC_ID
&& t
->text
[1] == '!') {
1258 if (*v
== '\'' || *v
== '\"' || *v
== '`') {
1259 size_t len
= nasm_unquote(v
, NULL
);
1260 size_t clen
= strlen(v
);
1263 error(ERR_NONFATAL
| ERR_PASS1
,
1264 "NUL character in %! string");
1270 char *p
= getenv(v
);
1272 error(ERR_NONFATAL
| ERR_PASS1
,
1273 "nonexistent environment variable `%s'", v
);
1276 t
->text
= nasm_strdup(p
);
1281 /* Expand local macros here and not during preprocessing */
1282 if (expand_locals
&&
1283 t
->type
== TOK_PREPROC_ID
&& t
->text
&&
1284 t
->text
[0] == '%' && t
->text
[1] == '$') {
1287 Context
*ctx
= get_ctx(t
->text
, &q
);
1290 snprintf(buffer
, sizeof(buffer
), "..@%"PRIu32
".", ctx
->number
);
1291 p
= nasm_strcat(buffer
, q
);
1296 if (t
->type
== TOK_WHITESPACE
)
1299 len
+= strlen(t
->text
);
1302 p
= line
= nasm_malloc(len
+ 1);
1304 list_for_each(t
, tlist
) {
1305 if (t
->type
== TOK_WHITESPACE
) {
1307 } else if (t
->text
) {
1319 * A scanner, suitable for use by the expression evaluator, which
1320 * operates on a line of Tokens. Expects a pointer to a pointer to
1321 * the first token in the line to be passed in as its private_data
1324 * FIX: This really needs to be unified with stdscan.
1326 static int ppscan(void *private_data
, struct tokenval
*tokval
)
1328 Token
**tlineptr
= private_data
;
1330 char ourcopy
[MAX_KEYWORD
+1], *p
, *r
, *s
;
1334 *tlineptr
= tline
? tline
->next
: NULL
;
1335 } while (tline
&& (tline
->type
== TOK_WHITESPACE
||
1336 tline
->type
== TOK_COMMENT
));
1339 return tokval
->t_type
= TOKEN_EOS
;
1341 tokval
->t_charptr
= tline
->text
;
1343 if (tline
->text
[0] == '$' && !tline
->text
[1])
1344 return tokval
->t_type
= TOKEN_HERE
;
1345 if (tline
->text
[0] == '$' && tline
->text
[1] == '$' && !tline
->text
[2])
1346 return tokval
->t_type
= TOKEN_BASE
;
1348 if (tline
->type
== TOK_ID
) {
1349 p
= tokval
->t_charptr
= tline
->text
;
1351 tokval
->t_charptr
++;
1352 return tokval
->t_type
= TOKEN_ID
;
1355 for (r
= p
, s
= ourcopy
; *r
; r
++) {
1356 if (r
>= p
+MAX_KEYWORD
)
1357 return tokval
->t_type
= TOKEN_ID
; /* Not a keyword */
1358 *s
++ = nasm_tolower(*r
);
1361 /* right, so we have an identifier sitting in temp storage. now,
1362 * is it actually a register or instruction name, or what? */
1363 return nasm_token_hash(ourcopy
, tokval
);
1366 if (tline
->type
== TOK_NUMBER
) {
1368 tokval
->t_integer
= readnum(tline
->text
, &rn_error
);
1369 tokval
->t_charptr
= tline
->text
;
1371 return tokval
->t_type
= TOKEN_ERRNUM
;
1373 return tokval
->t_type
= TOKEN_NUM
;
1376 if (tline
->type
== TOK_FLOAT
) {
1377 return tokval
->t_type
= TOKEN_FLOAT
;
1380 if (tline
->type
== TOK_STRING
) {
1383 bq
= tline
->text
[0];
1384 tokval
->t_charptr
= tline
->text
;
1385 tokval
->t_inttwo
= nasm_unquote(tline
->text
, &ep
);
1387 if (ep
[0] != bq
|| ep
[1] != '\0')
1388 return tokval
->t_type
= TOKEN_ERRSTR
;
1390 return tokval
->t_type
= TOKEN_STR
;
1393 if (tline
->type
== TOK_OTHER
) {
1394 if (!strcmp(tline
->text
, "<<"))
1395 return tokval
->t_type
= TOKEN_SHL
;
1396 if (!strcmp(tline
->text
, ">>"))
1397 return tokval
->t_type
= TOKEN_SHR
;
1398 if (!strcmp(tline
->text
, "//"))
1399 return tokval
->t_type
= TOKEN_SDIV
;
1400 if (!strcmp(tline
->text
, "%%"))
1401 return tokval
->t_type
= TOKEN_SMOD
;
1402 if (!strcmp(tline
->text
, "=="))
1403 return tokval
->t_type
= TOKEN_EQ
;
1404 if (!strcmp(tline
->text
, "<>"))
1405 return tokval
->t_type
= TOKEN_NE
;
1406 if (!strcmp(tline
->text
, "!="))
1407 return tokval
->t_type
= TOKEN_NE
;
1408 if (!strcmp(tline
->text
, "<="))
1409 return tokval
->t_type
= TOKEN_LE
;
1410 if (!strcmp(tline
->text
, ">="))
1411 return tokval
->t_type
= TOKEN_GE
;
1412 if (!strcmp(tline
->text
, "&&"))
1413 return tokval
->t_type
= TOKEN_DBL_AND
;
1414 if (!strcmp(tline
->text
, "^^"))
1415 return tokval
->t_type
= TOKEN_DBL_XOR
;
1416 if (!strcmp(tline
->text
, "||"))
1417 return tokval
->t_type
= TOKEN_DBL_OR
;
1421 * We have no other options: just return the first character of
1424 return tokval
->t_type
= tline
->text
[0];
1428 * Compare a string to the name of an existing macro; this is a
1429 * simple wrapper which calls either strcmp or nasm_stricmp
1430 * depending on the value of the `casesense' parameter.
1432 static int mstrcmp(const char *p
, const char *q
, bool casesense
)
1434 return casesense
? strcmp(p
, q
) : nasm_stricmp(p
, q
);
1438 * Compare a string to the name of an existing macro; this is a
1439 * simple wrapper which calls either strcmp or nasm_stricmp
1440 * depending on the value of the `casesense' parameter.
1442 static int mmemcmp(const char *p
, const char *q
, size_t l
, bool casesense
)
1444 return casesense
? memcmp(p
, q
, l
) : nasm_memicmp(p
, q
, l
);
1448 * Return the Context structure associated with a %$ token. Return
1449 * NULL, having _already_ reported an error condition, if the
1450 * context stack isn't deep enough for the supplied number of $
1453 * If "namep" is non-NULL, set it to the pointer to the macro name
1454 * tail, i.e. the part beyond %$...
1456 static Context
*get_ctx(const char *name
, const char **namep
)
1464 if (!name
|| name
[0] != '%' || name
[1] != '$')
1468 error(ERR_NONFATAL
, "`%s': context stack is empty", name
);
1475 while (ctx
&& *name
== '$') {
1481 error(ERR_NONFATAL
, "`%s': context stack is only"
1482 " %d level%s deep", name
, i
, (i
== 1 ? "" : "s"));
1493 * Check to see if a file is already in a string list
1495 static bool in_list(const StrList
*list
, const char *str
)
1498 if (!strcmp(list
->str
, str
))
1506 * Open an include file. This routine must always return a valid
1507 * file pointer if it returns - it's responsible for throwing an
1508 * ERR_FATAL and bombing out completely if not. It should also try
1509 * the include path one by one until it finds the file or reaches
1510 * the end of the path.
1512 static FILE *inc_fopen(const char *file
, StrList
**dhead
, StrList
***dtail
,
1517 IncPath
*ip
= ipath
;
1518 int len
= strlen(file
);
1519 size_t prefix_len
= 0;
1523 sl
= nasm_malloc(prefix_len
+len
+1+sizeof sl
->next
);
1524 memcpy(sl
->str
, prefix
, prefix_len
);
1525 memcpy(sl
->str
+prefix_len
, file
, len
+1);
1526 fp
= fopen(sl
->str
, "r");
1527 if (fp
&& dhead
&& !in_list(*dhead
, sl
->str
)) {
1545 prefix_len
= strlen(prefix
);
1547 /* -MG given and file not found */
1548 if (dhead
&& !in_list(*dhead
, file
)) {
1549 sl
= nasm_malloc(len
+1+sizeof sl
->next
);
1551 strcpy(sl
->str
, file
);
1559 error(ERR_FATAL
, "unable to open include file `%s'", file
);
1564 * Determine if we should warn on defining a single-line macro of
1565 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1566 * return true if _any_ single-line macro of that name is defined.
1567 * Otherwise, will return true if a single-line macro with either
1568 * `nparam' or no parameters is defined.
1570 * If a macro with precisely the right number of parameters is
1571 * defined, or nparam is -1, the address of the definition structure
1572 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1573 * is NULL, no action will be taken regarding its contents, and no
1576 * Note that this is also called with nparam zero to resolve
1579 * If you already know which context macro belongs to, you can pass
1580 * the context pointer as first parameter; if you won't but name begins
1581 * with %$ the context will be automatically computed. If all_contexts
1582 * is true, macro will be searched in outer contexts as well.
1585 smacro_defined(Context
* ctx
, const char *name
, int nparam
, SMacro
** defn
,
1588 struct hash_table
*smtbl
;
1592 smtbl
= &ctx
->localmac
;
1593 } else if (name
[0] == '%' && name
[1] == '$') {
1595 ctx
= get_ctx(name
, &name
);
1597 return false; /* got to return _something_ */
1598 smtbl
= &ctx
->localmac
;
1602 m
= (SMacro
*) hash_findix(smtbl
, name
);
1605 if (!mstrcmp(m
->name
, name
, m
->casesense
&& nocase
) &&
1606 (nparam
<= 0 || m
->nparam
== 0 || nparam
== (int) m
->nparam
)) {
1608 if (nparam
== (int) m
->nparam
|| nparam
== -1)
1622 * Count and mark off the parameters in a multi-line macro call.
1623 * This is called both from within the multi-line macro expansion
1624 * code, and also to mark off the default parameters when provided
1625 * in a %macro definition line.
1627 static void count_mmac_params(Token
* t
, int *nparam
, Token
*** params
)
1629 int paramsize
, brace
;
1631 *nparam
= paramsize
= 0;
1634 /* +1: we need space for the final NULL */
1635 if (*nparam
+1 >= paramsize
) {
1636 paramsize
+= PARAM_DELTA
;
1637 *params
= nasm_realloc(*params
, sizeof(**params
) * paramsize
);
1641 if (tok_is_(t
, "{"))
1643 (*params
)[(*nparam
)++] = t
;
1644 while (tok_isnt_(t
, brace
? "}" : ","))
1646 if (t
) { /* got a comma/brace */
1650 * Now we've found the closing brace, look further
1654 if (tok_isnt_(t
, ",")) {
1656 "braces do not enclose all of macro parameter");
1657 while (tok_isnt_(t
, ","))
1661 t
= t
->next
; /* eat the comma */
1668 * Determine whether one of the various `if' conditions is true or
1671 * We must free the tline we get passed.
1673 static bool if_condition(Token
* tline
, enum preproc_token ct
)
1675 enum pp_conditional i
= PP_COND(ct
);
1677 Token
*t
, *tt
, **tptr
, *origline
;
1678 struct tokenval tokval
;
1680 enum pp_token_type needtype
;
1687 j
= false; /* have we matched yet? */
1692 if (tline
->type
!= TOK_ID
) {
1694 "`%s' expects context identifiers", pp_directives
[ct
]);
1695 free_tlist(origline
);
1698 if (cstk
&& cstk
->name
&& !nasm_stricmp(tline
->text
, cstk
->name
))
1700 tline
= tline
->next
;
1705 j
= false; /* have we matched yet? */
1708 if (!tline
|| (tline
->type
!= TOK_ID
&&
1709 (tline
->type
!= TOK_PREPROC_ID
||
1710 tline
->text
[1] != '$'))) {
1712 "`%s' expects macro identifiers", pp_directives
[ct
]);
1715 if (smacro_defined(NULL
, tline
->text
, 0, NULL
, true))
1717 tline
= tline
->next
;
1722 tline
= expand_smacro(tline
);
1723 j
= false; /* have we matched yet? */
1726 if (!tline
|| (tline
->type
!= TOK_ID
&&
1727 tline
->type
!= TOK_STRING
&&
1728 (tline
->type
!= TOK_PREPROC_ID
||
1729 tline
->text
[1] != '!'))) {
1731 "`%s' expects environment variable names",
1736 if (tline
->type
== TOK_PREPROC_ID
)
1737 p
+= 2; /* Skip leading %! */
1738 if (*p
== '\'' || *p
== '\"' || *p
== '`')
1739 nasm_unquote_cstr(p
, ct
);
1742 tline
= tline
->next
;
1748 tline
= expand_smacro(tline
);
1750 while (tok_isnt_(tt
, ","))
1754 "`%s' expects two comma-separated arguments",
1759 j
= true; /* assume equality unless proved not */
1760 while ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) && tt
) {
1761 if (tt
->type
== TOK_OTHER
&& !strcmp(tt
->text
, ",")) {
1762 error(ERR_NONFATAL
, "`%s': more than one comma on line",
1766 if (t
->type
== TOK_WHITESPACE
) {
1770 if (tt
->type
== TOK_WHITESPACE
) {
1774 if (tt
->type
!= t
->type
) {
1775 j
= false; /* found mismatching tokens */
1778 /* When comparing strings, need to unquote them first */
1779 if (t
->type
== TOK_STRING
) {
1780 size_t l1
= nasm_unquote(t
->text
, NULL
);
1781 size_t l2
= nasm_unquote(tt
->text
, NULL
);
1787 if (mmemcmp(t
->text
, tt
->text
, l1
, i
== PPC_IFIDN
)) {
1791 } else if (mstrcmp(tt
->text
, t
->text
, i
== PPC_IFIDN
) != 0) {
1792 j
= false; /* found mismatching tokens */
1799 if ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) || tt
)
1800 j
= false; /* trailing gunk on one end or other */
1806 MMacro searching
, *mmac
;
1809 tline
= expand_id(tline
);
1810 if (!tok_type_(tline
, TOK_ID
)) {
1812 "`%s' expects a macro name", pp_directives
[ct
]);
1815 searching
.name
= nasm_strdup(tline
->text
);
1816 searching
.casesense
= true;
1817 searching
.plus
= false;
1818 searching
.nolist
= false;
1819 searching
.in_progress
= 0;
1820 searching
.max_depth
= 0;
1821 searching
.rep_nest
= NULL
;
1822 searching
.nparam_min
= 0;
1823 searching
.nparam_max
= INT_MAX
;
1824 tline
= expand_smacro(tline
->next
);
1827 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1829 "`%s' expects a parameter count or nothing",
1832 searching
.nparam_min
= searching
.nparam_max
=
1833 readnum(tline
->text
, &j
);
1836 "unable to parse parameter count `%s'",
1839 if (tline
&& tok_is_(tline
->next
, "-")) {
1840 tline
= tline
->next
->next
;
1841 if (tok_is_(tline
, "*"))
1842 searching
.nparam_max
= INT_MAX
;
1843 else if (!tok_type_(tline
, TOK_NUMBER
))
1845 "`%s' expects a parameter count after `-'",
1848 searching
.nparam_max
= readnum(tline
->text
, &j
);
1851 "unable to parse parameter count `%s'",
1853 if (searching
.nparam_min
> searching
.nparam_max
)
1855 "minimum parameter count exceeds maximum");
1858 if (tline
&& tok_is_(tline
->next
, "+")) {
1859 tline
= tline
->next
;
1860 searching
.plus
= true;
1862 mmac
= (MMacro
*) hash_findix(&mmacros
, searching
.name
);
1864 if (!strcmp(mmac
->name
, searching
.name
) &&
1865 (mmac
->nparam_min
<= searching
.nparam_max
1867 && (searching
.nparam_min
<= mmac
->nparam_max
1874 if (tline
&& tline
->next
)
1875 error(ERR_WARNING
|ERR_PASS1
,
1876 "trailing garbage after %%ifmacro ignored");
1877 nasm_free(searching
.name
);
1886 needtype
= TOK_NUMBER
;
1889 needtype
= TOK_STRING
;
1893 t
= tline
= expand_smacro(tline
);
1895 while (tok_type_(t
, TOK_WHITESPACE
) ||
1896 (needtype
== TOK_NUMBER
&&
1897 tok_type_(t
, TOK_OTHER
) &&
1898 (t
->text
[0] == '-' || t
->text
[0] == '+') &&
1902 j
= tok_type_(t
, needtype
);
1906 t
= tline
= expand_smacro(tline
);
1907 while (tok_type_(t
, TOK_WHITESPACE
))
1912 t
= t
->next
; /* Skip the actual token */
1913 while (tok_type_(t
, TOK_WHITESPACE
))
1915 j
= !t
; /* Should be nothing left */
1920 t
= tline
= expand_smacro(tline
);
1921 while (tok_type_(t
, TOK_WHITESPACE
))
1924 j
= !t
; /* Should be empty */
1928 t
= tline
= expand_smacro(tline
);
1930 tokval
.t_type
= TOKEN_INVALID
;
1931 evalresult
= evaluate(ppscan
, tptr
, &tokval
,
1932 NULL
, pass
| CRITICAL
, error
, NULL
);
1936 error(ERR_WARNING
|ERR_PASS1
,
1937 "trailing garbage after expression ignored");
1938 if (!is_simple(evalresult
)) {
1940 "non-constant value given to `%s'", pp_directives
[ct
]);
1943 j
= reloc_value(evalresult
) != 0;
1948 "preprocessor directive `%s' not yet implemented",
1953 free_tlist(origline
);
1954 return j
^ PP_NEGATIVE(ct
);
1957 free_tlist(origline
);
1962 * Common code for defining an smacro
1964 static bool define_smacro(Context
*ctx
, const char *mname
, bool casesense
,
1965 int nparam
, Token
*expansion
)
1967 SMacro
*smac
, **smhead
;
1968 struct hash_table
*smtbl
;
1970 if (smacro_defined(ctx
, mname
, nparam
, &smac
, casesense
)) {
1972 error(ERR_WARNING
|ERR_PASS1
,
1973 "single-line macro `%s' defined both with and"
1974 " without parameters", mname
);
1976 * Some instances of the old code considered this a failure,
1977 * some others didn't. What is the right thing to do here?
1979 free_tlist(expansion
);
1980 return false; /* Failure */
1983 * We're redefining, so we have to take over an
1984 * existing SMacro structure. This means freeing
1985 * what was already in it.
1987 nasm_free(smac
->name
);
1988 free_tlist(smac
->expansion
);
1991 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
1992 smhead
= (SMacro
**) hash_findi_add(smtbl
, mname
);
1993 smac
= nasm_malloc(sizeof(SMacro
));
1994 smac
->next
= *smhead
;
1997 smac
->name
= nasm_strdup(mname
);
1998 smac
->casesense
= casesense
;
1999 smac
->nparam
= nparam
;
2000 smac
->expansion
= expansion
;
2001 smac
->in_progress
= false;
2002 return true; /* Success */
2006 * Undefine an smacro
2008 static void undef_smacro(Context
*ctx
, const char *mname
)
2010 SMacro
**smhead
, *s
, **sp
;
2011 struct hash_table
*smtbl
;
2013 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2014 smhead
= (SMacro
**)hash_findi(smtbl
, mname
, NULL
);
2018 * We now have a macro name... go hunt for it.
2021 while ((s
= *sp
) != NULL
) {
2022 if (!mstrcmp(s
->name
, mname
, s
->casesense
)) {
2025 free_tlist(s
->expansion
);
2035 * Parse a mmacro specification.
2037 static bool parse_mmacro_spec(Token
*tline
, MMacro
*def
, const char *directive
)
2041 tline
= tline
->next
;
2043 tline
= expand_id(tline
);
2044 if (!tok_type_(tline
, TOK_ID
)) {
2045 error(ERR_NONFATAL
, "`%s' expects a macro name", directive
);
2050 def
->name
= nasm_strdup(tline
->text
);
2052 def
->nolist
= false;
2053 def
->in_progress
= 0;
2054 def
->rep_nest
= NULL
;
2055 def
->nparam_min
= 0;
2056 def
->nparam_max
= 0;
2058 tline
= expand_smacro(tline
->next
);
2060 if (!tok_type_(tline
, TOK_NUMBER
)) {
2061 error(ERR_NONFATAL
, "`%s' expects a parameter count", directive
);
2063 def
->nparam_min
= def
->nparam_max
=
2064 readnum(tline
->text
, &err
);
2067 "unable to parse parameter count `%s'", tline
->text
);
2069 if (tline
&& tok_is_(tline
->next
, "-")) {
2070 tline
= tline
->next
->next
;
2071 if (tok_is_(tline
, "*")) {
2072 def
->nparam_max
= INT_MAX
;
2073 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
2075 "`%s' expects a parameter count after `-'", directive
);
2077 def
->nparam_max
= readnum(tline
->text
, &err
);
2079 error(ERR_NONFATAL
, "unable to parse parameter count `%s'",
2082 if (def
->nparam_min
> def
->nparam_max
) {
2083 error(ERR_NONFATAL
, "minimum parameter count exceeds maximum");
2087 if (tline
&& tok_is_(tline
->next
, "+")) {
2088 tline
= tline
->next
;
2091 if (tline
&& tok_type_(tline
->next
, TOK_ID
) &&
2092 !nasm_stricmp(tline
->next
->text
, ".nolist")) {
2093 tline
= tline
->next
;
2098 * Handle default parameters.
2100 if (tline
&& tline
->next
) {
2101 def
->dlist
= tline
->next
;
2103 count_mmac_params(def
->dlist
, &def
->ndefs
, &def
->defaults
);
2106 def
->defaults
= NULL
;
2108 def
->expansion
= NULL
;
2110 if (def
->defaults
&& def
->ndefs
> def
->nparam_max
- def
->nparam_min
&&
2112 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MDP
,
2113 "too many default macro parameters");
2120 * Decode a size directive
2122 static int parse_size(const char *str
) {
2123 static const char *size_names
[] =
2124 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2125 static const int sizes
[] =
2126 { 0, 1, 4, 16, 8, 10, 2, 32 };
2128 return sizes
[bsii(str
, size_names
, ARRAY_SIZE(size_names
))+1];
2132 * find and process preprocessor directive in passed line
2133 * Find out if a line contains a preprocessor directive, and deal
2136 * If a directive _is_ found, it is the responsibility of this routine
2137 * (and not the caller) to free_tlist() the line.
2139 * @param tline a pointer to the current tokeninzed line linked list
2140 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2143 static int do_directive(Token
* tline
)
2145 enum preproc_token i
;
2158 MMacro
*mmac
, **mmhead
;
2159 Token
*t
, *tt
, *param_start
, *macro_start
, *last
, **tptr
, *origline
;
2161 struct tokenval tokval
;
2163 MMacro
*tmp_defining
; /* Used when manipulating rep_nest */
2171 if (!tline
|| !tok_type_(tline
, TOK_PREPROC_ID
) ||
2172 (tline
->text
[1] == '%' || tline
->text
[1] == '$'
2173 || tline
->text
[1] == '!'))
2174 return NO_DIRECTIVE_FOUND
;
2176 i
= pp_token_hash(tline
->text
);
2179 * FIXME: We zap execution of PP_RMACRO, PP_IRMACRO, PP_EXITMACRO
2180 * since they are known to be buggy at moment, we need to fix them
2181 * in future release (2.09-2.10)
2183 if (i
== PP_RMACRO
|| i
== PP_IRMACRO
|| i
== PP_EXITMACRO
) {
2184 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2186 return NO_DIRECTIVE_FOUND
;
2190 * If we're in a non-emitting branch of a condition construct,
2191 * or walking to the end of an already terminated %rep block,
2192 * we should ignore all directives except for condition
2195 if (((istk
->conds
&& !emitting(istk
->conds
->state
)) ||
2196 (istk
->mstk
&& !istk
->mstk
->in_progress
)) && !is_condition(i
)) {
2197 return NO_DIRECTIVE_FOUND
;
2201 * If we're defining a macro or reading a %rep block, we should
2202 * ignore all directives except for %macro/%imacro (which nest),
2203 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2204 * If we're in a %rep block, another %rep nests, so should be let through.
2206 if (defining
&& i
!= PP_MACRO
&& i
!= PP_IMACRO
&&
2207 i
!= PP_RMACRO
&& i
!= PP_IRMACRO
&&
2208 i
!= PP_ENDMACRO
&& i
!= PP_ENDM
&&
2209 (defining
->name
|| (i
!= PP_ENDREP
&& i
!= PP_REP
))) {
2210 return NO_DIRECTIVE_FOUND
;
2214 if (i
== PP_MACRO
|| i
== PP_IMACRO
||
2215 i
== PP_RMACRO
|| i
== PP_IRMACRO
) {
2217 return NO_DIRECTIVE_FOUND
;
2218 } else if (nested_mac_count
> 0) {
2219 if (i
== PP_ENDMACRO
) {
2221 return NO_DIRECTIVE_FOUND
;
2224 if (!defining
->name
) {
2227 return NO_DIRECTIVE_FOUND
;
2228 } else if (nested_rep_count
> 0) {
2229 if (i
== PP_ENDREP
) {
2231 return NO_DIRECTIVE_FOUND
;
2239 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2241 return NO_DIRECTIVE_FOUND
; /* didn't get it */
2244 /* Directive to tell NASM what the default stack size is. The
2245 * default is for a 16-bit stack, and this can be overriden with
2248 tline
= tline
->next
;
2249 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2250 tline
= tline
->next
;
2251 if (!tline
|| tline
->type
!= TOK_ID
) {
2252 error(ERR_NONFATAL
, "`%%stacksize' missing size parameter");
2253 free_tlist(origline
);
2254 return DIRECTIVE_FOUND
;
2256 if (nasm_stricmp(tline
->text
, "flat") == 0) {
2257 /* All subsequent ARG directives are for a 32-bit stack */
2259 StackPointer
= "ebp";
2262 } else if (nasm_stricmp(tline
->text
, "flat64") == 0) {
2263 /* All subsequent ARG directives are for a 64-bit stack */
2265 StackPointer
= "rbp";
2268 } else if (nasm_stricmp(tline
->text
, "large") == 0) {
2269 /* All subsequent ARG directives are for a 16-bit stack,
2270 * far function call.
2273 StackPointer
= "bp";
2276 } else if (nasm_stricmp(tline
->text
, "small") == 0) {
2277 /* All subsequent ARG directives are for a 16-bit stack,
2278 * far function call. We don't support near functions.
2281 StackPointer
= "bp";
2285 error(ERR_NONFATAL
, "`%%stacksize' invalid size type");
2286 free_tlist(origline
);
2287 return DIRECTIVE_FOUND
;
2289 free_tlist(origline
);
2290 return DIRECTIVE_FOUND
;
2293 /* TASM like ARG directive to define arguments to functions, in
2294 * the following form:
2296 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2300 char *arg
, directive
[256];
2301 int size
= StackSize
;
2303 /* Find the argument name */
2304 tline
= tline
->next
;
2305 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2306 tline
= tline
->next
;
2307 if (!tline
|| tline
->type
!= TOK_ID
) {
2308 error(ERR_NONFATAL
, "`%%arg' missing argument parameter");
2309 free_tlist(origline
);
2310 return DIRECTIVE_FOUND
;
2314 /* Find the argument size type */
2315 tline
= tline
->next
;
2316 if (!tline
|| tline
->type
!= TOK_OTHER
2317 || tline
->text
[0] != ':') {
2319 "Syntax error processing `%%arg' directive");
2320 free_tlist(origline
);
2321 return DIRECTIVE_FOUND
;
2323 tline
= tline
->next
;
2324 if (!tline
|| tline
->type
!= TOK_ID
) {
2325 error(ERR_NONFATAL
, "`%%arg' missing size type parameter");
2326 free_tlist(origline
);
2327 return DIRECTIVE_FOUND
;
2330 /* Allow macro expansion of type parameter */
2331 tt
= tokenize(tline
->text
);
2332 tt
= expand_smacro(tt
);
2333 size
= parse_size(tt
->text
);
2336 "Invalid size type for `%%arg' missing directive");
2338 free_tlist(origline
);
2339 return DIRECTIVE_FOUND
;
2343 /* Round up to even stack slots */
2344 size
= ALIGN(size
, StackSize
);
2346 /* Now define the macro for the argument */
2347 snprintf(directive
, sizeof(directive
), "%%define %s (%s+%d)",
2348 arg
, StackPointer
, offset
);
2349 do_directive(tokenize(directive
));
2352 /* Move to the next argument in the list */
2353 tline
= tline
->next
;
2354 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2355 tline
= tline
->next
;
2356 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2358 free_tlist(origline
);
2359 return DIRECTIVE_FOUND
;
2362 /* TASM like LOCAL directive to define local variables for a
2363 * function, in the following form:
2365 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2367 * The '= LocalSize' at the end is ignored by NASM, but is
2368 * required by TASM to define the local parameter size (and used
2369 * by the TASM macro package).
2371 offset
= LocalOffset
;
2373 char *local
, directive
[256];
2374 int size
= StackSize
;
2376 /* Find the argument name */
2377 tline
= tline
->next
;
2378 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2379 tline
= tline
->next
;
2380 if (!tline
|| tline
->type
!= TOK_ID
) {
2382 "`%%local' missing argument parameter");
2383 free_tlist(origline
);
2384 return DIRECTIVE_FOUND
;
2386 local
= tline
->text
;
2388 /* Find the argument size type */
2389 tline
= tline
->next
;
2390 if (!tline
|| tline
->type
!= TOK_OTHER
2391 || tline
->text
[0] != ':') {
2393 "Syntax error processing `%%local' directive");
2394 free_tlist(origline
);
2395 return DIRECTIVE_FOUND
;
2397 tline
= tline
->next
;
2398 if (!tline
|| tline
->type
!= TOK_ID
) {
2400 "`%%local' missing size type parameter");
2401 free_tlist(origline
);
2402 return DIRECTIVE_FOUND
;
2405 /* Allow macro expansion of type parameter */
2406 tt
= tokenize(tline
->text
);
2407 tt
= expand_smacro(tt
);
2408 size
= parse_size(tt
->text
);
2411 "Invalid size type for `%%local' missing directive");
2413 free_tlist(origline
);
2414 return DIRECTIVE_FOUND
;
2418 /* Round up to even stack slots */
2419 size
= ALIGN(size
, StackSize
);
2421 offset
+= size
; /* Negative offset, increment before */
2423 /* Now define the macro for the argument */
2424 snprintf(directive
, sizeof(directive
), "%%define %s (%s-%d)",
2425 local
, StackPointer
, offset
);
2426 do_directive(tokenize(directive
));
2428 /* Now define the assign to setup the enter_c macro correctly */
2429 snprintf(directive
, sizeof(directive
),
2430 "%%assign %%$localsize %%$localsize+%d", size
);
2431 do_directive(tokenize(directive
));
2433 /* Move to the next argument in the list */
2434 tline
= tline
->next
;
2435 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2436 tline
= tline
->next
;
2437 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2438 LocalOffset
= offset
;
2439 free_tlist(origline
);
2440 return DIRECTIVE_FOUND
;
2444 error(ERR_WARNING
|ERR_PASS1
,
2445 "trailing garbage after `%%clear' ignored");
2448 free_tlist(origline
);
2449 return DIRECTIVE_FOUND
;
2452 t
= tline
->next
= expand_smacro(tline
->next
);
2454 if (!t
|| (t
->type
!= TOK_STRING
&&
2455 t
->type
!= TOK_INTERNAL_STRING
)) {
2456 error(ERR_NONFATAL
, "`%%depend' expects a file name");
2457 free_tlist(origline
);
2458 return DIRECTIVE_FOUND
; /* but we did _something_ */
2461 error(ERR_WARNING
|ERR_PASS1
,
2462 "trailing garbage after `%%depend' ignored");
2464 if (t
->type
!= TOK_INTERNAL_STRING
)
2465 nasm_unquote_cstr(p
, i
);
2466 if (dephead
&& !in_list(*dephead
, p
)) {
2467 StrList
*sl
= nasm_malloc(strlen(p
)+1+sizeof sl
->next
);
2471 deptail
= &sl
->next
;
2473 free_tlist(origline
);
2474 return DIRECTIVE_FOUND
;
2477 t
= tline
->next
= expand_smacro(tline
->next
);
2480 if (!t
|| (t
->type
!= TOK_STRING
&&
2481 t
->type
!= TOK_INTERNAL_STRING
)) {
2482 error(ERR_NONFATAL
, "`%%include' expects a file name");
2483 free_tlist(origline
);
2484 return DIRECTIVE_FOUND
; /* but we did _something_ */
2487 error(ERR_WARNING
|ERR_PASS1
,
2488 "trailing garbage after `%%include' ignored");
2490 if (t
->type
!= TOK_INTERNAL_STRING
)
2491 nasm_unquote_cstr(p
, i
);
2492 inc
= nasm_malloc(sizeof(Include
));
2495 inc
->fp
= inc_fopen(p
, dephead
, &deptail
, pass
== 0);
2497 /* -MG given but file not found */
2500 inc
->fname
= src_set_fname(nasm_strdup(p
));
2501 inc
->lineno
= src_set_linnum(0);
2503 inc
->expansion
= NULL
;
2506 list
->uplevel(LIST_INCLUDE
);
2508 free_tlist(origline
);
2509 return DIRECTIVE_FOUND
;
2513 static macros_t
*use_pkg
;
2514 const char *pkg_macro
= NULL
;
2516 tline
= tline
->next
;
2518 tline
= expand_id(tline
);
2520 if (!tline
|| (tline
->type
!= TOK_STRING
&&
2521 tline
->type
!= TOK_INTERNAL_STRING
&&
2522 tline
->type
!= TOK_ID
)) {
2523 error(ERR_NONFATAL
, "`%%use' expects a package name");
2524 free_tlist(origline
);
2525 return DIRECTIVE_FOUND
; /* but we did _something_ */
2528 error(ERR_WARNING
|ERR_PASS1
,
2529 "trailing garbage after `%%use' ignored");
2530 if (tline
->type
== TOK_STRING
)
2531 nasm_unquote_cstr(tline
->text
, i
);
2532 use_pkg
= nasm_stdmac_find_package(tline
->text
);
2534 error(ERR_NONFATAL
, "unknown `%%use' package: %s", tline
->text
);
2536 pkg_macro
= (char *)use_pkg
+ 1; /* The first string will be <%define>__USE_*__ */
2537 if (use_pkg
&& ! smacro_defined(NULL
, pkg_macro
, 0, NULL
, true)) {
2538 /* Not already included, go ahead and include it */
2539 stdmacpos
= use_pkg
;
2541 free_tlist(origline
);
2542 return DIRECTIVE_FOUND
;
2547 tline
= tline
->next
;
2549 tline
= expand_id(tline
);
2551 if (!tok_type_(tline
, TOK_ID
)) {
2552 error(ERR_NONFATAL
, "`%s' expects a context identifier",
2554 free_tlist(origline
);
2555 return DIRECTIVE_FOUND
; /* but we did _something_ */
2558 error(ERR_WARNING
|ERR_PASS1
,
2559 "trailing garbage after `%s' ignored",
2561 p
= nasm_strdup(tline
->text
);
2563 p
= NULL
; /* Anonymous */
2567 ctx
= nasm_malloc(sizeof(Context
));
2569 hash_init(&ctx
->localmac
, HASH_SMALL
);
2571 ctx
->number
= unique
++;
2576 error(ERR_NONFATAL
, "`%s': context stack is empty",
2578 } else if (i
== PP_POP
) {
2579 if (p
&& (!cstk
->name
|| nasm_stricmp(p
, cstk
->name
)))
2580 error(ERR_NONFATAL
, "`%%pop' in wrong context: %s, "
2582 cstk
->name
? cstk
->name
: "anonymous", p
);
2587 nasm_free(cstk
->name
);
2593 free_tlist(origline
);
2594 return DIRECTIVE_FOUND
;
2596 severity
= ERR_FATAL
;
2599 severity
= ERR_NONFATAL
;
2602 severity
= ERR_WARNING
|ERR_WARN_USER
;
2607 /* Only error out if this is the final pass */
2608 if (pass
!= 2 && i
!= PP_FATAL
)
2609 return DIRECTIVE_FOUND
;
2611 tline
->next
= expand_smacro(tline
->next
);
2612 tline
= tline
->next
;
2614 t
= tline
? tline
->next
: NULL
;
2616 if (tok_type_(tline
, TOK_STRING
) && !t
) {
2617 /* The line contains only a quoted string */
2619 nasm_unquote(p
, NULL
); /* Ignore NUL character truncation */
2620 error(severity
, "%s", p
);
2622 /* Not a quoted string, or more than a quoted string */
2623 p
= detoken(tline
, false);
2624 error(severity
, "%s", p
);
2627 free_tlist(origline
);
2628 return DIRECTIVE_FOUND
;
2632 if (istk
->conds
&& !emitting(istk
->conds
->state
))
2635 j
= if_condition(tline
->next
, i
);
2636 tline
->next
= NULL
; /* it got freed */
2637 j
= j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2639 cond
= nasm_malloc(sizeof(Cond
));
2640 cond
->next
= istk
->conds
;
2644 istk
->mstk
->condcnt
++;
2645 free_tlist(origline
);
2646 return DIRECTIVE_FOUND
;
2650 error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2651 switch(istk
->conds
->state
) {
2653 istk
->conds
->state
= COND_DONE
;
2660 case COND_ELSE_TRUE
:
2661 case COND_ELSE_FALSE
:
2662 error_precond(ERR_WARNING
|ERR_PASS1
,
2663 "`%%elif' after `%%else' ignored");
2664 istk
->conds
->state
= COND_NEVER
;
2669 * IMPORTANT: In the case of %if, we will already have
2670 * called expand_mmac_params(); however, if we're
2671 * processing an %elif we must have been in a
2672 * non-emitting mode, which would have inhibited
2673 * the normal invocation of expand_mmac_params().
2674 * Therefore, we have to do it explicitly here.
2676 j
= if_condition(expand_mmac_params(tline
->next
), i
);
2677 tline
->next
= NULL
; /* it got freed */
2678 istk
->conds
->state
=
2679 j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2682 free_tlist(origline
);
2683 return DIRECTIVE_FOUND
;
2687 error_precond(ERR_WARNING
|ERR_PASS1
,
2688 "trailing garbage after `%%else' ignored");
2690 error(ERR_FATAL
, "`%%else': no matching `%%if'");
2691 switch(istk
->conds
->state
) {
2694 istk
->conds
->state
= COND_ELSE_FALSE
;
2701 istk
->conds
->state
= COND_ELSE_TRUE
;
2704 case COND_ELSE_TRUE
:
2705 case COND_ELSE_FALSE
:
2706 error_precond(ERR_WARNING
|ERR_PASS1
,
2707 "`%%else' after `%%else' ignored.");
2708 istk
->conds
->state
= COND_NEVER
;
2711 free_tlist(origline
);
2712 return DIRECTIVE_FOUND
;
2716 error_precond(ERR_WARNING
|ERR_PASS1
,
2717 "trailing garbage after `%%endif' ignored");
2719 error(ERR_FATAL
, "`%%endif': no matching `%%if'");
2721 istk
->conds
= cond
->next
;
2724 istk
->mstk
->condcnt
--;
2725 free_tlist(origline
);
2726 return DIRECTIVE_FOUND
;
2733 error(ERR_FATAL
, "`%s': already defining a macro",
2735 return DIRECTIVE_FOUND
;
2737 defining
= nasm_malloc(sizeof(MMacro
));
2738 defining
->max_depth
=
2739 (i
== PP_RMACRO
) || (i
== PP_IRMACRO
) ? DEADMAN_LIMIT
: 0;
2740 defining
->casesense
= (i
== PP_MACRO
) || (i
== PP_RMACRO
);
2741 if (!parse_mmacro_spec(tline
, defining
, pp_directives
[i
])) {
2742 nasm_free(defining
);
2744 return DIRECTIVE_FOUND
;
2747 mmac
= (MMacro
*) hash_findix(&mmacros
, defining
->name
);
2749 if (!strcmp(mmac
->name
, defining
->name
) &&
2750 (mmac
->nparam_min
<= defining
->nparam_max
2752 && (defining
->nparam_min
<= mmac
->nparam_max
2754 error(ERR_WARNING
|ERR_PASS1
,
2755 "redefining multi-line macro `%s'", defining
->name
);
2756 return DIRECTIVE_FOUND
;
2760 free_tlist(origline
);
2761 return DIRECTIVE_FOUND
;
2765 if (! (defining
&& defining
->name
)) {
2766 error(ERR_NONFATAL
, "`%s': not defining a macro", tline
->text
);
2767 return DIRECTIVE_FOUND
;
2769 mmhead
= (MMacro
**) hash_findi_add(&mmacros
, defining
->name
);
2770 defining
->next
= *mmhead
;
2773 free_tlist(origline
);
2774 return DIRECTIVE_FOUND
;
2778 * We must search along istk->expansion until we hit a
2779 * macro-end marker for a macro with a name. Then we
2780 * bypass all lines between exitmacro and endmacro.
2782 list_for_each(l
, istk
->expansion
)
2783 if (l
->finishes
&& l
->finishes
->name
)
2788 * Remove all conditional entries relative to this
2789 * macro invocation. (safe to do in this context)
2791 for ( ; l
->finishes
->condcnt
> 0; l
->finishes
->condcnt
--) {
2793 istk
->conds
= cond
->next
;
2796 istk
->expansion
= l
;
2798 error(ERR_NONFATAL
, "`%%exitmacro' not within `%%macro' block");
2800 free_tlist(origline
);
2801 return DIRECTIVE_FOUND
;
2809 spec
.casesense
= (i
== PP_UNMACRO
);
2810 if (!parse_mmacro_spec(tline
, &spec
, pp_directives
[i
])) {
2811 return DIRECTIVE_FOUND
;
2813 mmac_p
= (MMacro
**) hash_findi(&mmacros
, spec
.name
, NULL
);
2814 while (mmac_p
&& *mmac_p
) {
2816 if (mmac
->casesense
== spec
.casesense
&&
2817 !mstrcmp(mmac
->name
, spec
.name
, spec
.casesense
) &&
2818 mmac
->nparam_min
== spec
.nparam_min
&&
2819 mmac
->nparam_max
== spec
.nparam_max
&&
2820 mmac
->plus
== spec
.plus
) {
2821 *mmac_p
= mmac
->next
;
2824 mmac_p
= &mmac
->next
;
2827 free_tlist(origline
);
2828 free_tlist(spec
.dlist
);
2829 return DIRECTIVE_FOUND
;
2833 if (tline
->next
&& tline
->next
->type
== TOK_WHITESPACE
)
2834 tline
= tline
->next
;
2836 free_tlist(origline
);
2837 error(ERR_NONFATAL
, "`%%rotate' missing rotate count");
2838 return DIRECTIVE_FOUND
;
2840 t
= expand_smacro(tline
->next
);
2842 free_tlist(origline
);
2845 tokval
.t_type
= TOKEN_INVALID
;
2847 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2850 return DIRECTIVE_FOUND
;
2852 error(ERR_WARNING
|ERR_PASS1
,
2853 "trailing garbage after expression ignored");
2854 if (!is_simple(evalresult
)) {
2855 error(ERR_NONFATAL
, "non-constant value given to `%%rotate'");
2856 return DIRECTIVE_FOUND
;
2859 while (mmac
&& !mmac
->name
) /* avoid mistaking %reps for macros */
2860 mmac
= mmac
->next_active
;
2862 error(ERR_NONFATAL
, "`%%rotate' invoked outside a macro call");
2863 } else if (mmac
->nparam
== 0) {
2865 "`%%rotate' invoked within macro without parameters");
2867 int rotate
= mmac
->rotate
+ reloc_value(evalresult
);
2869 rotate
%= (int)mmac
->nparam
;
2871 rotate
+= mmac
->nparam
;
2873 mmac
->rotate
= rotate
;
2875 return DIRECTIVE_FOUND
;
2880 tline
= tline
->next
;
2881 } while (tok_type_(tline
, TOK_WHITESPACE
));
2883 if (tok_type_(tline
, TOK_ID
) &&
2884 nasm_stricmp(tline
->text
, ".nolist") == 0) {
2887 tline
= tline
->next
;
2888 } while (tok_type_(tline
, TOK_WHITESPACE
));
2892 t
= expand_smacro(tline
);
2894 tokval
.t_type
= TOKEN_INVALID
;
2896 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2898 free_tlist(origline
);
2899 return DIRECTIVE_FOUND
;
2902 error(ERR_WARNING
|ERR_PASS1
,
2903 "trailing garbage after expression ignored");
2904 if (!is_simple(evalresult
)) {
2905 error(ERR_NONFATAL
, "non-constant value given to `%%rep'");
2906 return DIRECTIVE_FOUND
;
2908 count
= reloc_value(evalresult
);
2909 if (count
>= REP_LIMIT
) {
2910 error(ERR_NONFATAL
, "`%%rep' value exceeds limit");
2915 error(ERR_NONFATAL
, "`%%rep' expects a repeat count");
2918 free_tlist(origline
);
2920 tmp_defining
= defining
;
2921 defining
= nasm_malloc(sizeof(MMacro
));
2922 defining
->prev
= NULL
;
2923 defining
->name
= NULL
; /* flags this macro as a %rep block */
2924 defining
->casesense
= false;
2925 defining
->plus
= false;
2926 defining
->nolist
= nolist
;
2927 defining
->in_progress
= count
;
2928 defining
->max_depth
= 0;
2929 defining
->nparam_min
= defining
->nparam_max
= 0;
2930 defining
->defaults
= NULL
;
2931 defining
->dlist
= NULL
;
2932 defining
->expansion
= NULL
;
2933 defining
->next_active
= istk
->mstk
;
2934 defining
->rep_nest
= tmp_defining
;
2935 return DIRECTIVE_FOUND
;
2938 if (!defining
|| defining
->name
) {
2939 error(ERR_NONFATAL
, "`%%endrep': no matching `%%rep'");
2940 return DIRECTIVE_FOUND
;
2944 * Now we have a "macro" defined - although it has no name
2945 * and we won't be entering it in the hash tables - we must
2946 * push a macro-end marker for it on to istk->expansion.
2947 * After that, it will take care of propagating itself (a
2948 * macro-end marker line for a macro which is really a %rep
2949 * block will cause the macro to be re-expanded, complete
2950 * with another macro-end marker to ensure the process
2951 * continues) until the whole expansion is forcibly removed
2952 * from istk->expansion by a %exitrep.
2954 l
= nasm_malloc(sizeof(Line
));
2955 l
->next
= istk
->expansion
;
2956 l
->finishes
= defining
;
2958 istk
->expansion
= l
;
2960 istk
->mstk
= defining
;
2962 list
->uplevel(defining
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
2963 tmp_defining
= defining
;
2964 defining
= defining
->rep_nest
;
2965 free_tlist(origline
);
2966 return DIRECTIVE_FOUND
;
2970 * We must search along istk->expansion until we hit a
2971 * macro-end marker for a macro with no name. Then we set
2972 * its `in_progress' flag to 0.
2974 list_for_each(l
, istk
->expansion
)
2975 if (l
->finishes
&& !l
->finishes
->name
)
2979 l
->finishes
->in_progress
= 1;
2981 error(ERR_NONFATAL
, "`%%exitrep' not within `%%rep' block");
2982 free_tlist(origline
);
2983 return DIRECTIVE_FOUND
;
2989 casesense
= (i
== PP_DEFINE
|| i
== PP_XDEFINE
);
2991 tline
= tline
->next
;
2993 tline
= expand_id(tline
);
2994 if (!tline
|| (tline
->type
!= TOK_ID
&&
2995 (tline
->type
!= TOK_PREPROC_ID
||
2996 tline
->text
[1] != '$'))) {
2997 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
2999 free_tlist(origline
);
3000 return DIRECTIVE_FOUND
;
3003 ctx
= get_ctx(tline
->text
, &mname
);
3005 param_start
= tline
= tline
->next
;
3008 /* Expand the macro definition now for %xdefine and %ixdefine */
3009 if ((i
== PP_XDEFINE
) || (i
== PP_IXDEFINE
))
3010 tline
= expand_smacro(tline
);
3012 if (tok_is_(tline
, "(")) {
3014 * This macro has parameters.
3017 tline
= tline
->next
;
3021 error(ERR_NONFATAL
, "parameter identifier expected");
3022 free_tlist(origline
);
3023 return DIRECTIVE_FOUND
;
3025 if (tline
->type
!= TOK_ID
) {
3027 "`%s': parameter identifier expected",
3029 free_tlist(origline
);
3030 return DIRECTIVE_FOUND
;
3032 tline
->type
= TOK_SMAC_PARAM
+ nparam
++;
3033 tline
= tline
->next
;
3035 if (tok_is_(tline
, ",")) {
3036 tline
= tline
->next
;
3038 if (!tok_is_(tline
, ")")) {
3040 "`)' expected to terminate macro template");
3041 free_tlist(origline
);
3042 return DIRECTIVE_FOUND
;
3048 tline
= tline
->next
;
3050 if (tok_type_(tline
, TOK_WHITESPACE
))
3051 last
= tline
, tline
= tline
->next
;
3056 if (t
->type
== TOK_ID
) {
3057 list_for_each(tt
, param_start
)
3058 if (tt
->type
>= TOK_SMAC_PARAM
&&
3059 !strcmp(tt
->text
, t
->text
))
3063 t
->next
= macro_start
;
3068 * Good. We now have a macro name, a parameter count, and a
3069 * token list (in reverse order) for an expansion. We ought
3070 * to be OK just to create an SMacro, store it, and let
3071 * free_tlist have the rest of the line (which we have
3072 * carefully re-terminated after chopping off the expansion
3075 define_smacro(ctx
, mname
, casesense
, nparam
, macro_start
);
3076 free_tlist(origline
);
3077 return DIRECTIVE_FOUND
;
3080 tline
= tline
->next
;
3082 tline
= expand_id(tline
);
3083 if (!tline
|| (tline
->type
!= TOK_ID
&&
3084 (tline
->type
!= TOK_PREPROC_ID
||
3085 tline
->text
[1] != '$'))) {
3086 error(ERR_NONFATAL
, "`%%undef' expects a macro identifier");
3087 free_tlist(origline
);
3088 return DIRECTIVE_FOUND
;
3091 error(ERR_WARNING
|ERR_PASS1
,
3092 "trailing garbage after macro name ignored");
3095 /* Find the context that symbol belongs to */
3096 ctx
= get_ctx(tline
->text
, &mname
);
3097 undef_smacro(ctx
, mname
);
3098 free_tlist(origline
);
3099 return DIRECTIVE_FOUND
;
3103 casesense
= (i
== PP_DEFSTR
);
3105 tline
= tline
->next
;
3107 tline
= expand_id(tline
);
3108 if (!tline
|| (tline
->type
!= TOK_ID
&&
3109 (tline
->type
!= TOK_PREPROC_ID
||
3110 tline
->text
[1] != '$'))) {
3111 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3113 free_tlist(origline
);
3114 return DIRECTIVE_FOUND
;
3117 ctx
= get_ctx(tline
->text
, &mname
);
3119 tline
= expand_smacro(tline
->next
);
3122 while (tok_type_(tline
, TOK_WHITESPACE
))
3123 tline
= delete_Token(tline
);
3125 p
= detoken(tline
, false);
3126 macro_start
= nasm_malloc(sizeof(*macro_start
));
3127 macro_start
->next
= NULL
;
3128 macro_start
->text
= nasm_quote(p
, strlen(p
));
3129 macro_start
->type
= TOK_STRING
;
3130 macro_start
->a
.mac
= NULL
;
3134 * We now have a macro name, an implicit parameter count of
3135 * zero, and a string token to use as an expansion. Create
3136 * and store an SMacro.
3138 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3139 free_tlist(origline
);
3140 return DIRECTIVE_FOUND
;
3144 casesense
= (i
== PP_DEFTOK
);
3146 tline
= tline
->next
;
3148 tline
= expand_id(tline
);
3149 if (!tline
|| (tline
->type
!= TOK_ID
&&
3150 (tline
->type
!= TOK_PREPROC_ID
||
3151 tline
->text
[1] != '$'))) {
3153 "`%s' expects a macro identifier as first parameter",
3155 free_tlist(origline
);
3156 return DIRECTIVE_FOUND
;
3158 ctx
= get_ctx(tline
->text
, &mname
);
3160 tline
= expand_smacro(tline
->next
);
3164 while (tok_type_(t
, TOK_WHITESPACE
))
3166 /* t should now point to the string */
3167 if (!tok_type_(t
, TOK_STRING
)) {
3169 "`%s` requires string as second parameter",
3172 free_tlist(origline
);
3173 return DIRECTIVE_FOUND
;
3177 * Convert the string to a token stream. Note that smacros
3178 * are stored with the token stream reversed, so we have to
3179 * reverse the output of tokenize().
3181 nasm_unquote_cstr(t
->text
, i
);
3182 macro_start
= reverse_tokens(tokenize(t
->text
));
3185 * We now have a macro name, an implicit parameter count of
3186 * zero, and a numeric token to use as an expansion. Create
3187 * and store an SMacro.
3189 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3191 free_tlist(origline
);
3192 return DIRECTIVE_FOUND
;
3197 StrList
*xsl
= NULL
;
3198 StrList
**xst
= &xsl
;
3202 tline
= tline
->next
;
3204 tline
= expand_id(tline
);
3205 if (!tline
|| (tline
->type
!= TOK_ID
&&
3206 (tline
->type
!= TOK_PREPROC_ID
||
3207 tline
->text
[1] != '$'))) {
3209 "`%%pathsearch' expects a macro identifier as first parameter");
3210 free_tlist(origline
);
3211 return DIRECTIVE_FOUND
;
3213 ctx
= get_ctx(tline
->text
, &mname
);
3215 tline
= expand_smacro(tline
->next
);
3219 while (tok_type_(t
, TOK_WHITESPACE
))
3222 if (!t
|| (t
->type
!= TOK_STRING
&&
3223 t
->type
!= TOK_INTERNAL_STRING
)) {
3224 error(ERR_NONFATAL
, "`%%pathsearch' expects a file name");
3226 free_tlist(origline
);
3227 return DIRECTIVE_FOUND
; /* but we did _something_ */
3230 error(ERR_WARNING
|ERR_PASS1
,
3231 "trailing garbage after `%%pathsearch' ignored");
3233 if (t
->type
!= TOK_INTERNAL_STRING
)
3234 nasm_unquote(p
, NULL
);
3236 fp
= inc_fopen(p
, &xsl
, &xst
, true);
3239 fclose(fp
); /* Don't actually care about the file */
3241 macro_start
= nasm_malloc(sizeof(*macro_start
));
3242 macro_start
->next
= NULL
;
3243 macro_start
->text
= nasm_quote(p
, strlen(p
));
3244 macro_start
->type
= TOK_STRING
;
3245 macro_start
->a
.mac
= NULL
;
3250 * We now have a macro name, an implicit parameter count of
3251 * zero, and a string token to use as an expansion. Create
3252 * and store an SMacro.
3254 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3256 free_tlist(origline
);
3257 return DIRECTIVE_FOUND
;
3263 tline
= tline
->next
;
3265 tline
= expand_id(tline
);
3266 if (!tline
|| (tline
->type
!= TOK_ID
&&
3267 (tline
->type
!= TOK_PREPROC_ID
||
3268 tline
->text
[1] != '$'))) {
3270 "`%%strlen' expects a macro identifier as first parameter");
3271 free_tlist(origline
);
3272 return DIRECTIVE_FOUND
;
3274 ctx
= get_ctx(tline
->text
, &mname
);
3276 tline
= expand_smacro(tline
->next
);
3280 while (tok_type_(t
, TOK_WHITESPACE
))
3282 /* t should now point to the string */
3283 if (!tok_type_(t
, TOK_STRING
)) {
3285 "`%%strlen` requires string as second parameter");
3287 free_tlist(origline
);
3288 return DIRECTIVE_FOUND
;
3291 macro_start
= nasm_malloc(sizeof(*macro_start
));
3292 macro_start
->next
= NULL
;
3293 make_tok_num(macro_start
, nasm_unquote(t
->text
, NULL
));
3294 macro_start
->a
.mac
= NULL
;
3297 * We now have a macro name, an implicit parameter count of
3298 * zero, and a numeric token to use as an expansion. Create
3299 * and store an SMacro.
3301 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3303 free_tlist(origline
);
3304 return DIRECTIVE_FOUND
;
3309 tline
= tline
->next
;
3311 tline
= expand_id(tline
);
3312 if (!tline
|| (tline
->type
!= TOK_ID
&&
3313 (tline
->type
!= TOK_PREPROC_ID
||
3314 tline
->text
[1] != '$'))) {
3316 "`%%strcat' expects a macro identifier as first parameter");
3317 free_tlist(origline
);
3318 return DIRECTIVE_FOUND
;
3320 ctx
= get_ctx(tline
->text
, &mname
);
3322 tline
= expand_smacro(tline
->next
);
3326 list_for_each(t
, tline
) {
3328 case TOK_WHITESPACE
:
3331 len
+= t
->a
.len
= nasm_unquote(t
->text
, NULL
);
3334 if (!strcmp(t
->text
, ",")) /* permit comma separators */
3336 /* else fall through */
3339 "non-string passed to `%%strcat' (%d)", t
->type
);
3341 free_tlist(origline
);
3342 return DIRECTIVE_FOUND
;
3346 p
= pp
= nasm_malloc(len
);
3347 list_for_each(t
, tline
) {
3348 if (t
->type
== TOK_STRING
) {
3349 memcpy(p
, t
->text
, t
->a
.len
);
3355 * We now have a macro name, an implicit parameter count of
3356 * zero, and a numeric token to use as an expansion. Create
3357 * and store an SMacro.
3359 macro_start
= new_Token(NULL
, TOK_STRING
, NULL
, 0);
3360 macro_start
->text
= nasm_quote(pp
, len
);
3362 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3364 free_tlist(origline
);
3365 return DIRECTIVE_FOUND
;
3369 int64_t start
, count
;
3374 tline
= tline
->next
;
3376 tline
= expand_id(tline
);
3377 if (!tline
|| (tline
->type
!= TOK_ID
&&
3378 (tline
->type
!= TOK_PREPROC_ID
||
3379 tline
->text
[1] != '$'))) {
3381 "`%%substr' expects a macro identifier as first parameter");
3382 free_tlist(origline
);
3383 return DIRECTIVE_FOUND
;
3385 ctx
= get_ctx(tline
->text
, &mname
);
3387 tline
= expand_smacro(tline
->next
);
3390 if (tline
) /* skip expanded id */
3392 while (tok_type_(t
, TOK_WHITESPACE
))
3395 /* t should now point to the string */
3396 if (!tok_type_(t
, TOK_STRING
)) {
3398 "`%%substr` requires string as second parameter");
3400 free_tlist(origline
);
3401 return DIRECTIVE_FOUND
;
3406 tokval
.t_type
= TOKEN_INVALID
;
3407 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3411 free_tlist(origline
);
3412 return DIRECTIVE_FOUND
;
3413 } else if (!is_simple(evalresult
)) {
3414 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3416 free_tlist(origline
);
3417 return DIRECTIVE_FOUND
;
3419 start
= evalresult
->value
- 1;
3421 while (tok_type_(tt
, TOK_WHITESPACE
))
3424 count
= 1; /* Backwards compatibility: one character */
3426 tokval
.t_type
= TOKEN_INVALID
;
3427 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3431 free_tlist(origline
);
3432 return DIRECTIVE_FOUND
;
3433 } else if (!is_simple(evalresult
)) {
3434 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3436 free_tlist(origline
);
3437 return DIRECTIVE_FOUND
;
3439 count
= evalresult
->value
;
3442 len
= nasm_unquote(t
->text
, NULL
);
3444 /* make start and count being in range */
3448 count
= len
+ count
+ 1 - start
;
3449 if (start
+ count
> (int64_t)len
)
3450 count
= len
- start
;
3451 if (!len
|| count
< 0 || start
>=(int64_t)len
)
3452 start
= -1, count
= 0; /* empty string */
3454 macro_start
= nasm_malloc(sizeof(*macro_start
));
3455 macro_start
->next
= NULL
;
3456 macro_start
->text
= nasm_quote((start
< 0) ? "" : t
->text
+ start
, count
);
3457 macro_start
->type
= TOK_STRING
;
3458 macro_start
->a
.mac
= NULL
;
3461 * We now have a macro name, an implicit parameter count of
3462 * zero, and a numeric token to use as an expansion. Create
3463 * and store an SMacro.
3465 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3467 free_tlist(origline
);
3468 return DIRECTIVE_FOUND
;
3473 casesense
= (i
== PP_ASSIGN
);
3475 tline
= tline
->next
;
3477 tline
= expand_id(tline
);
3478 if (!tline
|| (tline
->type
!= TOK_ID
&&
3479 (tline
->type
!= TOK_PREPROC_ID
||
3480 tline
->text
[1] != '$'))) {
3482 "`%%%sassign' expects a macro identifier",
3483 (i
== PP_IASSIGN
? "i" : ""));
3484 free_tlist(origline
);
3485 return DIRECTIVE_FOUND
;
3487 ctx
= get_ctx(tline
->text
, &mname
);
3489 tline
= expand_smacro(tline
->next
);
3494 tokval
.t_type
= TOKEN_INVALID
;
3496 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
3499 free_tlist(origline
);
3500 return DIRECTIVE_FOUND
;
3504 error(ERR_WARNING
|ERR_PASS1
,
3505 "trailing garbage after expression ignored");
3507 if (!is_simple(evalresult
)) {
3509 "non-constant value given to `%%%sassign'",
3510 (i
== PP_IASSIGN
? "i" : ""));
3511 free_tlist(origline
);
3512 return DIRECTIVE_FOUND
;
3515 macro_start
= nasm_malloc(sizeof(*macro_start
));
3516 macro_start
->next
= NULL
;
3517 make_tok_num(macro_start
, reloc_value(evalresult
));
3518 macro_start
->a
.mac
= NULL
;
3521 * We now have a macro name, an implicit parameter count of
3522 * zero, and a numeric token to use as an expansion. Create
3523 * and store an SMacro.
3525 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3526 free_tlist(origline
);
3527 return DIRECTIVE_FOUND
;
3531 * Syntax is `%line nnn[+mmm] [filename]'
3533 tline
= tline
->next
;
3535 if (!tok_type_(tline
, TOK_NUMBER
)) {
3536 error(ERR_NONFATAL
, "`%%line' expects line number");
3537 free_tlist(origline
);
3538 return DIRECTIVE_FOUND
;
3540 k
= readnum(tline
->text
, &err
);
3542 tline
= tline
->next
;
3543 if (tok_is_(tline
, "+")) {
3544 tline
= tline
->next
;
3545 if (!tok_type_(tline
, TOK_NUMBER
)) {
3546 error(ERR_NONFATAL
, "`%%line' expects line increment");
3547 free_tlist(origline
);
3548 return DIRECTIVE_FOUND
;
3550 m
= readnum(tline
->text
, &err
);
3551 tline
= tline
->next
;
3557 nasm_free(src_set_fname(detoken(tline
, false)));
3559 free_tlist(origline
);
3560 return DIRECTIVE_FOUND
;
3564 "preprocessor directive `%s' not yet implemented",
3566 return DIRECTIVE_FOUND
;
3571 * Ensure that a macro parameter contains a condition code and
3572 * nothing else. Return the condition code index if so, or -1
3575 static int find_cc(Token
* t
)
3580 return -1; /* Probably a %+ without a space */
3583 if (t
->type
!= TOK_ID
)
3587 if (tt
&& (tt
->type
!= TOK_OTHER
|| strcmp(tt
->text
, ",")))
3590 return bsii(t
->text
, (const char **)conditions
, ARRAY_SIZE(conditions
));
3594 * This routines walks over tokens strem and hadnles tokens
3595 * pasting, if @handle_explicit passed then explicit pasting
3596 * term is handled, otherwise -- implicit pastings only.
3598 static bool paste_tokens(Token
**head
, const struct tokseq_match
*m
,
3599 size_t mnum
, bool handle_explicit
)
3601 Token
*tok
, *next
, **prev_next
, **prev_nonspace
;
3602 bool pasted
= false;
3607 * The last token before pasting. We need it
3608 * to be able to connect new handled tokens.
3609 * In other words if there were a tokens stream
3613 * and we've joined tokens B and C, the resulting
3621 if (!tok_type_(tok
, TOK_WHITESPACE
) && !tok_type_(tok
, TOK_PASTE
))
3622 prev_nonspace
= head
;
3624 prev_nonspace
= NULL
;
3626 while (tok
&& (next
= tok
->next
)) {
3628 switch (tok
->type
) {
3629 case TOK_WHITESPACE
:
3630 /* Zap redundant whitespaces */
3631 while (tok_type_(next
, TOK_WHITESPACE
))
3632 next
= delete_Token(next
);
3637 /* Explicit pasting */
3638 if (!handle_explicit
)
3640 next
= delete_Token(tok
);
3642 while (tok_type_(next
, TOK_WHITESPACE
))
3643 next
= delete_Token(next
);
3648 /* Left pasting token is start of line */
3650 error(ERR_FATAL
, "No lvalue found on pasting");
3653 * No ending token, this might happen in two
3656 * 1) There indeed no right token at all
3657 * 2) There is a bare "%define ID" statement,
3658 * and @ID does expand to whitespace.
3660 * So technically we need to do a grammar analysis
3661 * in another stage of parsing, but for now lets don't
3662 * change the behaviour people used to. Simply allow
3663 * whitespace after paste token.
3667 * Zap ending space tokens and that's all.
3669 tok
= (*prev_nonspace
)->next
;
3670 while (tok_type_(tok
, TOK_WHITESPACE
))
3671 tok
= delete_Token(tok
);
3672 tok
= *prev_nonspace
;
3677 tok
= *prev_nonspace
;
3678 while (tok_type_(tok
, TOK_WHITESPACE
))
3679 tok
= delete_Token(tok
);
3680 len
= strlen(tok
->text
);
3681 len
+= strlen(next
->text
);
3683 p
= buf
= nasm_malloc(len
+ 1);
3684 strcpy(p
, tok
->text
);
3685 p
= strchr(p
, '\0');
3686 strcpy(p
, next
->text
);
3690 tok
= tokenize(buf
);
3693 *prev_nonspace
= tok
;
3694 while (tok
&& tok
->next
)
3697 tok
->next
= delete_Token(next
);
3699 /* Restart from pasted tokens head */
3700 tok
= *prev_nonspace
;
3704 /* implicit pasting */
3705 for (i
= 0; i
< mnum
; i
++) {
3706 if (!(PP_CONCAT_MATCH(tok
, m
[i
].mask_head
)))
3710 while (next
&& PP_CONCAT_MATCH(next
, m
[i
].mask_tail
)) {
3711 len
+= strlen(next
->text
);
3719 len
+= strlen(tok
->text
);
3720 p
= buf
= nasm_malloc(len
+ 1);
3722 while (tok
!= next
) {
3723 strcpy(p
, tok
->text
);
3724 p
= strchr(p
, '\0');
3725 tok
= delete_Token(tok
);
3728 tok
= tokenize(buf
);
3737 * Connect pasted into original stream,
3738 * ie A -> new-tokens -> B
3740 while (tok
&& tok
->next
)
3747 /* Restart from pasted tokens head */
3748 tok
= prev_next
? *prev_next
: *head
;
3754 prev_next
= &tok
->next
;
3757 !tok_type_(tok
->next
, TOK_WHITESPACE
) &&
3758 !tok_type_(tok
->next
, TOK_PASTE
))
3759 prev_nonspace
= prev_next
;
3768 * expands to a list of tokens from %{x:y}
3770 static Token
*expand_mmac_params_range(MMacro
*mac
, Token
*tline
, Token
***last
)
3772 Token
*t
= tline
, **tt
, *tm
, *head
;
3776 pos
= strchr(tline
->text
, ':');
3779 lst
= atoi(pos
+ 1);
3780 fst
= atoi(tline
->text
+ 1);
3783 * only macros params are accounted so
3784 * if someone passes %0 -- we reject such
3787 if (lst
== 0 || fst
== 0)
3790 /* the values should be sane */
3791 if ((fst
> (int)mac
->nparam
|| fst
< (-(int)mac
->nparam
)) ||
3792 (lst
> (int)mac
->nparam
|| lst
< (-(int)mac
->nparam
)))
3795 fst
= fst
< 0 ? fst
+ (int)mac
->nparam
+ 1: fst
;
3796 lst
= lst
< 0 ? lst
+ (int)mac
->nparam
+ 1: lst
;
3798 /* counted from zero */
3802 * it will be at least one token
3804 tm
= mac
->params
[(fst
+ mac
->rotate
) % mac
->nparam
];
3805 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3806 head
= t
, tt
= &t
->next
;
3808 for (i
= fst
+ 1; i
<= lst
; i
++) {
3809 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3810 *tt
= t
, tt
= &t
->next
;
3811 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3812 tm
= mac
->params
[j
];
3813 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3814 *tt
= t
, tt
= &t
->next
;
3817 for (i
= fst
- 1; i
>= lst
; i
--) {
3818 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3819 *tt
= t
, tt
= &t
->next
;
3820 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3821 tm
= mac
->params
[j
];
3822 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3823 *tt
= t
, tt
= &t
->next
;
3831 error(ERR_NONFATAL
, "`%%{%s}': macro parameters out of range",
3837 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3838 * %-n) and MMacro-local identifiers (%%foo) as well as
3839 * macro indirection (%[...]) and range (%{..:..}).
3841 static Token
*expand_mmac_params(Token
* tline
)
3843 Token
*t
, *tt
, **tail
, *thead
;
3844 bool changed
= false;
3851 if (tline
->type
== TOK_PREPROC_ID
&&
3852 (((tline
->text
[1] == '+' || tline
->text
[1] == '-') && tline
->text
[2]) ||
3853 (tline
->text
[1] >= '0' && tline
->text
[1] <= '9') ||
3854 tline
->text
[1] == '%')) {
3856 int type
= 0, cc
; /* type = 0 to placate optimisers */
3863 tline
= tline
->next
;
3866 while (mac
&& !mac
->name
) /* avoid mistaking %reps for macros */
3867 mac
= mac
->next_active
;
3869 error(ERR_NONFATAL
, "`%s': not in a macro call", t
->text
);
3871 pos
= strchr(t
->text
, ':');
3873 switch (t
->text
[1]) {
3875 * We have to make a substitution of one of the
3876 * forms %1, %-1, %+1, %%foo, %0.
3880 snprintf(tmpbuf
, sizeof(tmpbuf
), "%d", mac
->nparam
);
3881 text
= nasm_strdup(tmpbuf
);
3885 snprintf(tmpbuf
, sizeof(tmpbuf
), "..@%"PRIu64
".",
3887 text
= nasm_strcat(tmpbuf
, t
->text
+ 2);
3890 n
= atoi(t
->text
+ 2) - 1;
3891 if (n
>= mac
->nparam
)
3894 if (mac
->nparam
> 1)
3895 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3896 tt
= mac
->params
[n
];
3901 "macro parameter %d is not a condition code",
3906 if (inverse_ccs
[cc
] == -1) {
3908 "condition code `%s' is not invertible",
3912 text
= nasm_strdup(conditions
[inverse_ccs
[cc
]]);
3916 n
= atoi(t
->text
+ 2) - 1;
3917 if (n
>= mac
->nparam
)
3920 if (mac
->nparam
> 1)
3921 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3922 tt
= mac
->params
[n
];
3927 "macro parameter %d is not a condition code",
3932 text
= nasm_strdup(conditions
[cc
]);
3936 n
= atoi(t
->text
+ 1) - 1;
3937 if (n
>= mac
->nparam
)
3940 if (mac
->nparam
> 1)
3941 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3942 tt
= mac
->params
[n
];
3945 for (i
= 0; i
< mac
->paramlen
[n
]; i
++) {
3946 *tail
= new_Token(NULL
, tt
->type
, tt
->text
, 0);
3947 tail
= &(*tail
)->next
;
3951 text
= NULL
; /* we've done it here */
3956 * seems we have a parameters range here
3958 Token
*head
, **last
;
3959 head
= expand_mmac_params_range(mac
, t
, &last
);
3980 } else if (tline
->type
== TOK_INDIRECT
) {
3982 tline
= tline
->next
;
3983 tt
= tokenize(t
->text
);
3984 tt
= expand_mmac_params(tt
);
3985 tt
= expand_smacro(tt
);
3988 tt
->a
.mac
= NULL
; /* Necessary? */
3996 tline
= tline
->next
;
4004 const struct tokseq_match t
[] = {
4006 PP_CONCAT_MASK(TOK_ID
) |
4007 PP_CONCAT_MASK(TOK_FLOAT
), /* head */
4008 PP_CONCAT_MASK(TOK_ID
) |
4009 PP_CONCAT_MASK(TOK_NUMBER
) |
4010 PP_CONCAT_MASK(TOK_FLOAT
) |
4011 PP_CONCAT_MASK(TOK_OTHER
) /* tail */
4014 PP_CONCAT_MASK(TOK_NUMBER
), /* head */
4015 PP_CONCAT_MASK(TOK_NUMBER
) /* tail */
4018 paste_tokens(&thead
, t
, ARRAY_SIZE(t
), false);
4025 * Expand all single-line macro calls made in the given line.
4026 * Return the expanded version of the line. The original is deemed
4027 * to be destroyed in the process. (In reality we'll just move
4028 * Tokens from input to output a lot of the time, rather than
4029 * actually bothering to destroy and replicate.)
4032 static Token
*expand_smacro(Token
* tline
)
4034 Token
*t
, *tt
, *mstart
, **tail
, *thead
;
4035 SMacro
*head
= NULL
, *m
;
4038 unsigned int nparam
, sparam
;
4040 Token
*org_tline
= tline
;
4043 int deadman
= DEADMAN_LIMIT
;
4047 * Trick: we should avoid changing the start token pointer since it can
4048 * be contained in "next" field of other token. Because of this
4049 * we allocate a copy of first token and work with it; at the end of
4050 * routine we copy it back
4053 tline
= new_Token(org_tline
->next
, org_tline
->type
,
4054 org_tline
->text
, 0);
4055 tline
->a
.mac
= org_tline
->a
.mac
;
4056 nasm_free(org_tline
->text
);
4057 org_tline
->text
= NULL
;
4060 expanded
= true; /* Always expand %+ at least once */
4066 while (tline
) { /* main token loop */
4068 error(ERR_NONFATAL
, "interminable macro recursion");
4072 if ((mname
= tline
->text
)) {
4073 /* if this token is a local macro, look in local context */
4074 if (tline
->type
== TOK_ID
) {
4075 head
= (SMacro
*)hash_findix(&smacros
, mname
);
4076 } else if (tline
->type
== TOK_PREPROC_ID
) {
4077 ctx
= get_ctx(mname
, &mname
);
4078 head
= ctx
? (SMacro
*)hash_findix(&ctx
->localmac
, mname
) : NULL
;
4083 * We've hit an identifier. As in is_mmacro below, we first
4084 * check whether the identifier is a single-line macro at
4085 * all, then think about checking for parameters if
4088 list_for_each(m
, head
)
4089 if (!mstrcmp(m
->name
, mname
, m
->casesense
))
4095 if (m
->nparam
== 0) {
4097 * Simple case: the macro is parameterless. Discard the
4098 * one token that the macro call took, and push the
4099 * expansion back on the to-do stack.
4101 if (!m
->expansion
) {
4102 if (!strcmp("__FILE__", m
->name
)) {
4105 src_get(&num
, &file
);
4106 tline
->text
= nasm_quote(file
, strlen(file
));
4107 tline
->type
= TOK_STRING
;
4111 if (!strcmp("__LINE__", m
->name
)) {
4112 nasm_free(tline
->text
);
4113 make_tok_num(tline
, src_get_linnum());
4116 if (!strcmp("__BITS__", m
->name
)) {
4117 nasm_free(tline
->text
);
4118 make_tok_num(tline
, globalbits
);
4121 tline
= delete_Token(tline
);
4126 * Complicated case: at least one macro with this name
4127 * exists and takes parameters. We must find the
4128 * parameters in the call, count them, find the SMacro
4129 * that corresponds to that form of the macro call, and
4130 * substitute for the parameters when we expand. What a
4133 /*tline = tline->next;
4134 skip_white_(tline); */
4137 while (tok_type_(t
, TOK_SMAC_END
)) {
4138 t
->a
.mac
->in_progress
= false;
4140 t
= tline
->next
= delete_Token(t
);
4143 } while (tok_type_(tline
, TOK_WHITESPACE
));
4144 if (!tok_is_(tline
, "(")) {
4146 * This macro wasn't called with parameters: ignore
4147 * the call. (Behaviour borrowed from gnu cpp.)
4156 sparam
= PARAM_DELTA
;
4157 params
= nasm_malloc(sparam
* sizeof(Token
*));
4158 params
[0] = tline
->next
;
4159 paramsize
= nasm_malloc(sparam
* sizeof(int));
4161 while (true) { /* parameter loop */
4163 * For some unusual expansions
4164 * which concatenates function call
4167 while (tok_type_(t
, TOK_SMAC_END
)) {
4168 t
->a
.mac
->in_progress
= false;
4170 t
= tline
->next
= delete_Token(t
);
4176 "macro call expects terminating `)'");
4179 if (tline
->type
== TOK_WHITESPACE
4181 if (paramsize
[nparam
])
4184 params
[nparam
] = tline
->next
;
4185 continue; /* parameter loop */
4187 if (tline
->type
== TOK_OTHER
4188 && tline
->text
[1] == 0) {
4189 char ch
= tline
->text
[0];
4190 if (ch
== ',' && !paren
&& brackets
<= 0) {
4191 if (++nparam
>= sparam
) {
4192 sparam
+= PARAM_DELTA
;
4193 params
= nasm_realloc(params
,
4194 sparam
* sizeof(Token
*));
4195 paramsize
= nasm_realloc(paramsize
,
4196 sparam
* sizeof(int));
4198 params
[nparam
] = tline
->next
;
4199 paramsize
[nparam
] = 0;
4201 continue; /* parameter loop */
4204 (brackets
> 0 || (brackets
== 0 &&
4205 !paramsize
[nparam
])))
4207 if (!(brackets
++)) {
4208 params
[nparam
] = tline
->next
;
4209 continue; /* parameter loop */
4212 if (ch
== '}' && brackets
> 0)
4213 if (--brackets
== 0) {
4215 continue; /* parameter loop */
4217 if (ch
== '(' && !brackets
)
4219 if (ch
== ')' && brackets
<= 0)
4225 error(ERR_NONFATAL
, "braces do not "
4226 "enclose all of macro parameter");
4228 paramsize
[nparam
] += white
+ 1;
4230 } /* parameter loop */
4232 while (m
&& (m
->nparam
!= nparam
||
4233 mstrcmp(m
->name
, mname
,
4237 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4238 "macro `%s' exists, "
4239 "but not taking %d parameters",
4240 mstart
->text
, nparam
);
4243 if (m
&& m
->in_progress
)
4245 if (!m
) { /* in progess or didn't find '(' or wrong nparam */
4247 * Design question: should we handle !tline, which
4248 * indicates missing ')' here, or expand those
4249 * macros anyway, which requires the (t) test a few
4253 nasm_free(paramsize
);
4257 * Expand the macro: we are placed on the last token of the
4258 * call, so that we can easily split the call from the
4259 * following tokens. We also start by pushing an SMAC_END
4260 * token for the cycle removal.
4267 tt
= new_Token(tline
, TOK_SMAC_END
, NULL
, 0);
4269 m
->in_progress
= true;
4271 list_for_each(t
, m
->expansion
) {
4272 if (t
->type
>= TOK_SMAC_PARAM
) {
4273 Token
*pcopy
= tline
, **ptail
= &pcopy
;
4277 ttt
= params
[t
->type
- TOK_SMAC_PARAM
];
4278 i
= paramsize
[t
->type
- TOK_SMAC_PARAM
];
4280 pt
= *ptail
= new_Token(tline
, ttt
->type
,
4286 } else if (t
->type
== TOK_PREPROC_Q
) {
4287 tt
= new_Token(tline
, TOK_ID
, mname
, 0);
4289 } else if (t
->type
== TOK_PREPROC_QQ
) {
4290 tt
= new_Token(tline
, TOK_ID
, m
->name
, 0);
4293 tt
= new_Token(tline
, t
->type
, t
->text
, 0);
4299 * Having done that, get rid of the macro call, and clean
4300 * up the parameters.
4303 nasm_free(paramsize
);
4306 continue; /* main token loop */
4311 if (tline
->type
== TOK_SMAC_END
) {
4312 tline
->a
.mac
->in_progress
= false;
4313 tline
= delete_Token(tline
);
4316 tline
= tline
->next
;
4324 * Now scan the entire line and look for successive TOK_IDs that resulted
4325 * after expansion (they can't be produced by tokenize()). The successive
4326 * TOK_IDs should be concatenated.
4327 * Also we look for %+ tokens and concatenate the tokens before and after
4328 * them (without white spaces in between).
4331 const struct tokseq_match t
[] = {
4333 PP_CONCAT_MASK(TOK_ID
) |
4334 PP_CONCAT_MASK(TOK_PREPROC_ID
), /* head */
4335 PP_CONCAT_MASK(TOK_ID
) |
4336 PP_CONCAT_MASK(TOK_PREPROC_ID
) |
4337 PP_CONCAT_MASK(TOK_NUMBER
) /* tail */
4340 if (paste_tokens(&thead
, t
, ARRAY_SIZE(t
), true)) {
4342 * If we concatenated something, *and* we had previously expanded
4343 * an actual macro, scan the lines again for macros...
4354 *org_tline
= *thead
;
4355 /* since we just gave text to org_line, don't free it */
4357 delete_Token(thead
);
4359 /* the expression expanded to empty line;
4360 we can't return NULL for some reasons
4361 we just set the line to a single WHITESPACE token. */
4362 memset(org_tline
, 0, sizeof(*org_tline
));
4363 org_tline
->text
= NULL
;
4364 org_tline
->type
= TOK_WHITESPACE
;
4373 * Similar to expand_smacro but used exclusively with macro identifiers
4374 * right before they are fetched in. The reason is that there can be
4375 * identifiers consisting of several subparts. We consider that if there
4376 * are more than one element forming the name, user wants a expansion,
4377 * otherwise it will be left as-is. Example:
4381 * the identifier %$abc will be left as-is so that the handler for %define
4382 * will suck it and define the corresponding value. Other case:
4384 * %define _%$abc cde
4386 * In this case user wants name to be expanded *before* %define starts
4387 * working, so we'll expand %$abc into something (if it has a value;
4388 * otherwise it will be left as-is) then concatenate all successive
4391 static Token
*expand_id(Token
* tline
)
4393 Token
*cur
, *oldnext
= NULL
;
4395 if (!tline
|| !tline
->next
)
4400 (cur
->next
->type
== TOK_ID
||
4401 cur
->next
->type
== TOK_PREPROC_ID
4402 || cur
->next
->type
== TOK_NUMBER
))
4405 /* If identifier consists of just one token, don't expand */
4410 oldnext
= cur
->next
; /* Detach the tail past identifier */
4411 cur
->next
= NULL
; /* so that expand_smacro stops here */
4414 tline
= expand_smacro(tline
);
4417 /* expand_smacro possibly changhed tline; re-scan for EOL */
4419 while (cur
&& cur
->next
)
4422 cur
->next
= oldnext
;
4429 * Determine whether the given line constitutes a multi-line macro
4430 * call, and return the MMacro structure called if so. Doesn't have
4431 * to check for an initial label - that's taken care of in
4432 * expand_mmacro - but must check numbers of parameters. Guaranteed
4433 * to be called with tline->type == TOK_ID, so the putative macro
4434 * name is easy to find.
4436 static MMacro
*is_mmacro(Token
* tline
, Token
*** params_array
)
4442 head
= (MMacro
*) hash_findix(&mmacros
, tline
->text
);
4445 * Efficiency: first we see if any macro exists with the given
4446 * name. If not, we can return NULL immediately. _Then_ we
4447 * count the parameters, and then we look further along the
4448 * list if necessary to find the proper MMacro.
4450 list_for_each(m
, head
)
4451 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4457 * OK, we have a potential macro. Count and demarcate the
4460 count_mmac_params(tline
->next
, &nparam
, ¶ms
);
4463 * So we know how many parameters we've got. Find the MMacro
4464 * structure that handles this number.
4467 if (m
->nparam_min
<= nparam
4468 && (m
->plus
|| nparam
<= m
->nparam_max
)) {
4470 * This one is right. Just check if cycle removal
4471 * prohibits us using it before we actually celebrate...
4473 if (m
->in_progress
> m
->max_depth
) {
4474 if (m
->max_depth
> 0) {
4476 "reached maximum recursion depth of %i",
4483 * It's right, and we can use it. Add its default
4484 * parameters to the end of our list if necessary.
4486 if (m
->defaults
&& nparam
< m
->nparam_min
+ m
->ndefs
) {
4488 nasm_realloc(params
,
4489 ((m
->nparam_min
+ m
->ndefs
+
4490 1) * sizeof(*params
)));
4491 while (nparam
< m
->nparam_min
+ m
->ndefs
) {
4492 params
[nparam
] = m
->defaults
[nparam
- m
->nparam_min
];
4497 * If we've gone over the maximum parameter count (and
4498 * we're in Plus mode), ignore parameters beyond
4501 if (m
->plus
&& nparam
> m
->nparam_max
)
4502 nparam
= m
->nparam_max
;
4504 * Then terminate the parameter list, and leave.
4506 if (!params
) { /* need this special case */
4507 params
= nasm_malloc(sizeof(*params
));
4510 params
[nparam
] = NULL
;
4511 *params_array
= params
;
4515 * This one wasn't right: look for the next one with the
4518 list_for_each(m
, m
->next
)
4519 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4524 * After all that, we didn't find one with the right number of
4525 * parameters. Issue a warning, and fail to expand the macro.
4527 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4528 "macro `%s' exists, but not taking %d parameters",
4529 tline
->text
, nparam
);
4536 * Save MMacro invocation specific fields in
4537 * preparation for a recursive macro expansion
4539 static void push_mmacro(MMacro
*m
)
4541 MMacroInvocation
*i
;
4543 i
= nasm_malloc(sizeof(MMacroInvocation
));
4545 i
->params
= m
->params
;
4546 i
->iline
= m
->iline
;
4547 i
->nparam
= m
->nparam
;
4548 i
->rotate
= m
->rotate
;
4549 i
->paramlen
= m
->paramlen
;
4550 i
->unique
= m
->unique
;
4551 i
->condcnt
= m
->condcnt
;
4557 * Restore MMacro invocation specific fields that were
4558 * saved during a previous recursive macro expansion
4560 static void pop_mmacro(MMacro
*m
)
4562 MMacroInvocation
*i
;
4567 m
->params
= i
->params
;
4568 m
->iline
= i
->iline
;
4569 m
->nparam
= i
->nparam
;
4570 m
->rotate
= i
->rotate
;
4571 m
->paramlen
= i
->paramlen
;
4572 m
->unique
= i
->unique
;
4573 m
->condcnt
= i
->condcnt
;
4580 * Expand the multi-line macro call made by the given line, if
4581 * there is one to be expanded. If there is, push the expansion on
4582 * istk->expansion and return 1. Otherwise return 0.
4584 static int expand_mmacro(Token
* tline
)
4586 Token
*startline
= tline
;
4587 Token
*label
= NULL
;
4588 int dont_prepend
= 0;
4589 Token
**params
, *t
, *tt
;
4592 int i
, nparam
, *paramlen
;
4597 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4598 if (!tok_type_(t
, TOK_ID
) && !tok_type_(t
, TOK_PREPROC_ID
))
4600 m
= is_mmacro(t
, ¶ms
);
4606 * We have an id which isn't a macro call. We'll assume
4607 * it might be a label; we'll also check to see if a
4608 * colon follows it. Then, if there's another id after
4609 * that lot, we'll check it again for macro-hood.
4613 if (tok_type_(t
, TOK_WHITESPACE
))
4614 last
= t
, t
= t
->next
;
4615 if (tok_is_(t
, ":")) {
4617 last
= t
, t
= t
->next
;
4618 if (tok_type_(t
, TOK_WHITESPACE
))
4619 last
= t
, t
= t
->next
;
4621 if (!tok_type_(t
, TOK_ID
) || !(m
= is_mmacro(t
, ¶ms
)))
4629 * Fix up the parameters: this involves stripping leading and
4630 * trailing whitespace, then stripping braces if they are
4633 for (nparam
= 0; params
[nparam
]; nparam
++) ;
4634 paramlen
= nparam
? nasm_malloc(nparam
* sizeof(*paramlen
)) : NULL
;
4636 for (i
= 0; params
[i
]; i
++) {
4638 int comma
= (!m
->plus
|| i
< nparam
- 1);
4642 if (tok_is_(t
, "{"))
4643 t
= t
->next
, brace
= true, comma
= false;
4647 if (comma
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, ","))
4648 break; /* ... because we have hit a comma */
4649 if (comma
&& t
->type
== TOK_WHITESPACE
4650 && tok_is_(t
->next
, ","))
4651 break; /* ... or a space then a comma */
4652 if (brace
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, "}"))
4653 break; /* ... or a brace */
4660 * OK, we have a MMacro structure together with a set of
4661 * parameters. We must now go through the expansion and push
4662 * copies of each Line on to istk->expansion. Substitution of
4663 * parameter tokens and macro-local tokens doesn't get done
4664 * until the single-line macro substitution process; this is
4665 * because delaying them allows us to change the semantics
4666 * later through %rotate.
4668 * First, push an end marker on to istk->expansion, mark this
4669 * macro as in progress, and set up its invocation-specific
4672 ll
= nasm_malloc(sizeof(Line
));
4673 ll
->next
= istk
->expansion
;
4676 istk
->expansion
= ll
;
4679 * Save the previous MMacro expansion in the case of
4682 if (m
->max_depth
&& m
->in_progress
)
4690 m
->paramlen
= paramlen
;
4691 m
->unique
= unique
++;
4695 m
->next_active
= istk
->mstk
;
4698 list_for_each(l
, m
->expansion
) {
4701 ll
= nasm_malloc(sizeof(Line
));
4702 ll
->finishes
= NULL
;
4703 ll
->next
= istk
->expansion
;
4704 istk
->expansion
= ll
;
4707 list_for_each(t
, l
->first
) {
4711 tt
= *tail
= new_Token(NULL
, TOK_ID
, mname
, 0);
4713 case TOK_PREPROC_QQ
:
4714 tt
= *tail
= new_Token(NULL
, TOK_ID
, m
->name
, 0);
4716 case TOK_PREPROC_ID
:
4717 if (t
->text
[1] == '0' && t
->text
[2] == '0') {
4725 tt
= *tail
= new_Token(NULL
, x
->type
, x
->text
, 0);
4734 * If we had a label, push it on as the first line of
4735 * the macro expansion.
4738 if (dont_prepend
< 0)
4739 free_tlist(startline
);
4741 ll
= nasm_malloc(sizeof(Line
));
4742 ll
->finishes
= NULL
;
4743 ll
->next
= istk
->expansion
;
4744 istk
->expansion
= ll
;
4745 ll
->first
= startline
;
4746 if (!dont_prepend
) {
4748 label
= label
->next
;
4749 label
->next
= tt
= new_Token(NULL
, TOK_OTHER
, ":", 0);
4754 list
->uplevel(m
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
4759 /* The function that actually does the error reporting */
4760 static void verror(int severity
, const char *fmt
, va_list arg
)
4763 MMacro
*mmac
= NULL
;
4766 vsnprintf(buff
, sizeof(buff
), fmt
, arg
);
4768 /* get %macro name */
4769 if (istk
&& istk
->mstk
) {
4771 /* but %rep blocks should be skipped */
4772 while (mmac
&& !mmac
->name
)
4773 mmac
= mmac
->next_active
, delta
++;
4777 nasm_error(severity
, "(%s:%d) %s",
4778 mmac
->name
, mmac
->lineno
- delta
, buff
);
4780 nasm_error(severity
, "%s", buff
);
4784 * Since preprocessor always operate only on the line that didn't
4785 * arrived yet, we should always use ERR_OFFBY1.
4787 static void error(int severity
, const char *fmt
, ...)
4791 /* If we're in a dead branch of IF or something like it, ignore the error */
4792 if (istk
&& istk
->conds
&& !emitting(istk
->conds
->state
))
4796 verror(severity
, fmt
, arg
);
4801 * Because %else etc are evaluated in the state context
4802 * of the previous branch, errors might get lost with error():
4803 * %if 0 ... %else trailing garbage ... %endif
4804 * So %else etc should report errors with this function.
4806 static void error_precond(int severity
, const char *fmt
, ...)
4810 /* Only ignore the error if it's really in a dead branch */
4811 if (istk
&& istk
->conds
&& istk
->conds
->state
== COND_NEVER
)
4815 verror(severity
, fmt
, arg
);
4820 pp_reset(char *file
, int apass
, ListGen
* listgen
, StrList
**deplist
)
4825 istk
= nasm_malloc(sizeof(Include
));
4828 istk
->expansion
= NULL
;
4830 istk
->fp
= fopen(file
, "r");
4832 src_set_fname(nasm_strdup(file
));
4836 error(ERR_FATAL
|ERR_NOFILE
, "unable to open input file `%s'",
4839 nested_mac_count
= 0;
4840 nested_rep_count
= 0;
4843 if (tasm_compatible_mode
) {
4844 stdmacpos
= nasm_stdmac
;
4846 stdmacpos
= nasm_stdmac_after_tasm
;
4848 any_extrastdmac
= extrastdmac
&& *extrastdmac
;
4853 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4854 * The caller, however, will also pass in 3 for preprocess-only so
4855 * we can set __PASS__ accordingly.
4857 pass
= apass
> 2 ? 2 : apass
;
4859 dephead
= deptail
= deplist
;
4861 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
4863 strcpy(sl
->str
, file
);
4865 deptail
= &sl
->next
;
4869 * Define the __PASS__ macro. This is defined here unlike
4870 * all the other builtins, because it is special -- it varies between
4873 t
= nasm_malloc(sizeof(*t
));
4875 make_tok_num(t
, apass
);
4877 define_smacro(NULL
, "__PASS__", true, 0, t
);
4880 static char *pp_getline(void)
4887 * Fetch a tokenized line, either from the macro-expansion
4888 * buffer or from the input file.
4891 while (istk
->expansion
&& istk
->expansion
->finishes
) {
4892 Line
*l
= istk
->expansion
;
4893 if (!l
->finishes
->name
&& l
->finishes
->in_progress
> 1) {
4897 * This is a macro-end marker for a macro with no
4898 * name, which means it's not really a macro at all
4899 * but a %rep block, and the `in_progress' field is
4900 * more than 1, meaning that we still need to
4901 * repeat. (1 means the natural last repetition; 0
4902 * means termination by %exitrep.) We have
4903 * therefore expanded up to the %endrep, and must
4904 * push the whole block on to the expansion buffer
4905 * again. We don't bother to remove the macro-end
4906 * marker: we'd only have to generate another one
4909 l
->finishes
->in_progress
--;
4910 list_for_each(l
, l
->finishes
->expansion
) {
4911 Token
*t
, *tt
, **tail
;
4913 ll
= nasm_malloc(sizeof(Line
));
4914 ll
->next
= istk
->expansion
;
4915 ll
->finishes
= NULL
;
4919 list_for_each(t
, l
->first
) {
4920 if (t
->text
|| t
->type
== TOK_WHITESPACE
) {
4921 tt
= *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
4926 istk
->expansion
= ll
;
4930 * Check whether a `%rep' was started and not ended
4931 * within this macro expansion. This can happen and
4932 * should be detected. It's a fatal error because
4933 * I'm too confused to work out how to recover
4939 "defining with name in expansion");
4940 else if (istk
->mstk
->name
)
4942 "`%%rep' without `%%endrep' within"
4943 " expansion of macro `%s'",
4948 * FIXME: investigate the relationship at this point between
4949 * istk->mstk and l->finishes
4952 MMacro
*m
= istk
->mstk
;
4953 istk
->mstk
= m
->next_active
;
4956 * This was a real macro call, not a %rep, and
4957 * therefore the parameter information needs to
4962 l
->finishes
->in_progress
--;
4964 nasm_free(m
->params
);
4965 free_tlist(m
->iline
);
4966 nasm_free(m
->paramlen
);
4967 l
->finishes
->in_progress
= 0;
4972 istk
->expansion
= l
->next
;
4974 list
->downlevel(LIST_MACRO
);
4977 while (1) { /* until we get a line we can use */
4979 if (istk
->expansion
) { /* from a macro expansion */
4981 Line
*l
= istk
->expansion
;
4983 istk
->mstk
->lineno
++;
4985 istk
->expansion
= l
->next
;
4987 p
= detoken(tline
, false);
4988 list
->line(LIST_MACRO
, p
);
4993 if (line
) { /* from the current input file */
4994 line
= prepreproc(line
);
4995 tline
= tokenize(line
);
5000 * The current file has ended; work down the istk
5006 /* nasm_error can't be conditionally suppressed */
5007 nasm_error(ERR_FATAL
,
5008 "expected `%%endif' before end of file");
5010 /* only set line and file name if there's a next node */
5012 src_set_linnum(i
->lineno
);
5013 nasm_free(src_set_fname(nasm_strdup(i
->fname
)));
5016 list
->downlevel(LIST_INCLUDE
);
5020 if (istk
->expansion
&& istk
->expansion
->finishes
)
5026 * We must expand MMacro parameters and MMacro-local labels
5027 * _before_ we plunge into directive processing, to cope
5028 * with things like `%define something %1' such as STRUC
5029 * uses. Unless we're _defining_ a MMacro, in which case
5030 * those tokens should be left alone to go into the
5031 * definition; and unless we're in a non-emitting
5032 * condition, in which case we don't want to meddle with
5035 if (!defining
&& !(istk
->conds
&& !emitting(istk
->conds
->state
))
5036 && !(istk
->mstk
&& !istk
->mstk
->in_progress
)) {
5037 tline
= expand_mmac_params(tline
);
5041 * Check the line to see if it's a preprocessor directive.
5043 if (do_directive(tline
) == DIRECTIVE_FOUND
) {
5045 } else if (defining
) {
5047 * We're defining a multi-line macro. We emit nothing
5049 * shove the tokenized line on to the macro definition.
5051 Line
*l
= nasm_malloc(sizeof(Line
));
5052 l
->next
= defining
->expansion
;
5055 defining
->expansion
= l
;
5057 } else if (istk
->conds
&& !emitting(istk
->conds
->state
)) {
5059 * We're in a non-emitting branch of a condition block.
5060 * Emit nothing at all, not even a blank line: when we
5061 * emerge from the condition we'll give a line-number
5062 * directive so we keep our place correctly.
5066 } else if (istk
->mstk
&& !istk
->mstk
->in_progress
) {
5068 * We're in a %rep block which has been terminated, so
5069 * we're walking through to the %endrep without
5070 * emitting anything. Emit nothing at all, not even a
5071 * blank line: when we emerge from the %rep block we'll
5072 * give a line-number directive so we keep our place
5078 tline
= expand_smacro(tline
);
5079 if (!expand_mmacro(tline
)) {
5081 * De-tokenize the line again, and emit it.
5083 line
= detoken(tline
, true);
5087 continue; /* expand_mmacro calls free_tlist */
5095 static void pp_cleanup(int pass
)
5098 if (defining
->name
) {
5100 "end of file while still defining macro `%s'",
5103 error(ERR_NONFATAL
, "end of file while still in %%rep");
5106 free_mmacro(defining
);
5116 nasm_free(i
->fname
);
5121 nasm_free(src_set_fname(NULL
));
5126 while ((i
= ipath
)) {
5135 static void pp_include_path(char *path
)
5139 i
= nasm_malloc(sizeof(IncPath
));
5140 i
->path
= path
? nasm_strdup(path
) : NULL
;
5153 static void pp_pre_include(char *fname
)
5155 Token
*inc
, *space
, *name
;
5158 name
= new_Token(NULL
, TOK_INTERNAL_STRING
, fname
, 0);
5159 space
= new_Token(name
, TOK_WHITESPACE
, NULL
, 0);
5160 inc
= new_Token(space
, TOK_PREPROC_ID
, "%include", 0);
5162 l
= nasm_malloc(sizeof(Line
));
5169 static void pp_pre_define(char *definition
)
5175 equals
= strchr(definition
, '=');
5176 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5177 def
= new_Token(space
, TOK_PREPROC_ID
, "%define", 0);
5180 space
->next
= tokenize(definition
);
5184 l
= nasm_malloc(sizeof(Line
));
5191 static void pp_pre_undefine(char *definition
)
5196 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5197 def
= new_Token(space
, TOK_PREPROC_ID
, "%undef", 0);
5198 space
->next
= tokenize(definition
);
5200 l
= nasm_malloc(sizeof(Line
));
5207 static void pp_extra_stdmac(macros_t
*macros
)
5209 extrastdmac
= macros
;
5212 static void make_tok_num(Token
* tok
, int64_t val
)
5215 snprintf(numbuf
, sizeof(numbuf
), "%"PRId64
"", val
);
5216 tok
->text
= nasm_strdup(numbuf
);
5217 tok
->type
= TOK_NUMBER
;
5220 struct preproc_ops nasmpp
= {