1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2014 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_SMAC_PARAM
, /* MUST BE LAST IN THE LIST!!! */
212 TOK_MAX
= INT_MAX
/* Keep compiler from reducing the range */
215 #define PP_CONCAT_MASK(x) (1 << (x))
216 #define PP_CONCAT_MATCH(t, mask) (PP_CONCAT_MASK((t)->type) & mask)
218 struct tokseq_match
{
227 SMacro
*mac
; /* associated macro for TOK_SMAC_END */
228 size_t len
; /* scratch length field */
229 } a
; /* Auxiliary data */
230 enum pp_token_type type
;
234 * Multi-line macro definitions are stored as a linked list of
235 * these, which is essentially a container to allow several linked
238 * Note that in this module, linked lists are treated as stacks
239 * wherever possible. For this reason, Lines are _pushed_ on to the
240 * `expansion' field in MMacro structures, so that the linked list,
241 * if walked, would give the macro lines in reverse order; this
242 * means that we can walk the list when expanding a macro, and thus
243 * push the lines on to the `expansion' field in _istk_ in reverse
244 * order (so that when popped back off they are in the right
245 * order). It may seem cockeyed, and it relies on my design having
246 * an even number of steps in, but it works...
248 * Some of these structures, rather than being actual lines, are
249 * markers delimiting the end of the expansion of a given macro.
250 * This is for use in the cycle-tracking and %rep-handling code.
251 * Such structures have `finishes' non-NULL, and `first' NULL. All
252 * others have `finishes' NULL, but `first' may still be NULL if
262 * To handle an arbitrary level of file inclusion, we maintain a
263 * stack (ie linked list) of these things.
272 MMacro
*mstk
; /* stack of active macros/reps */
276 * Include search path. This is simply a list of strings which get
277 * prepended, in turn, to the name of an include file, in an
278 * attempt to find the file if it's not in the current directory.
286 * Conditional assembly: we maintain a separate stack of these for
287 * each level of file inclusion. (The only reason we keep the
288 * stacks separate is to ensure that a stray `%endif' in a file
289 * included from within the true branch of a `%if' won't terminate
290 * it and cause confusion: instead, rightly, it'll cause an error.)
298 * These states are for use just after %if or %elif: IF_TRUE
299 * means the condition has evaluated to truth so we are
300 * currently emitting, whereas IF_FALSE means we are not
301 * currently emitting but will start doing so if a %else comes
302 * up. In these states, all directives are admissible: %elif,
303 * %else and %endif. (And of course %if.)
305 COND_IF_TRUE
, COND_IF_FALSE
,
307 * These states come up after a %else: ELSE_TRUE means we're
308 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
309 * any %elif or %else will cause an error.
311 COND_ELSE_TRUE
, COND_ELSE_FALSE
,
313 * These states mean that we're not emitting now, and also that
314 * nothing until %endif will be emitted at all. COND_DONE is
315 * used when we've had our moment of emission
316 * and have now started seeing %elifs. COND_NEVER is used when
317 * the condition construct in question is contained within a
318 * non-emitting branch of a larger condition construct,
319 * or if there is an error.
321 COND_DONE
, COND_NEVER
323 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
326 * These defines are used as the possible return values for do_directive
328 #define NO_DIRECTIVE_FOUND 0
329 #define DIRECTIVE_FOUND 1
332 * This define sets the upper limit for smacro and recursive mmacro
335 #define DEADMAN_LIMIT (1 << 20)
338 #define REP_LIMIT ((INT64_C(1) << 62))
341 * Condition codes. Note that we use c_ prefix not C_ because C_ is
342 * used in nasm.h for the "real" condition codes. At _this_ level,
343 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
344 * ones, so we need a different enum...
346 static const char * const conditions
[] = {
347 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
348 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
349 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
352 c_A
, c_AE
, c_B
, c_BE
, c_C
, c_CXZ
, c_E
, c_ECXZ
, c_G
, c_GE
, c_L
, c_LE
,
353 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, c_NE
, c_NG
, c_NGE
, c_NL
, c_NLE
, c_NO
,
354 c_NP
, c_NS
, c_NZ
, c_O
, c_P
, c_PE
, c_PO
, c_RCXZ
, c_S
, c_Z
,
357 static const enum pp_conds inverse_ccs
[] = {
358 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, -1, c_NE
, -1, c_NG
, c_NGE
, c_NL
, c_NLE
,
359 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
,
360 c_Z
, c_NO
, c_NP
, c_PO
, c_PE
, -1, c_NS
, c_NZ
366 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
367 static int is_condition(enum preproc_token arg
)
369 return PP_IS_COND(arg
) || (arg
== PP_ELSE
) || (arg
== PP_ENDIF
);
372 /* For TASM compatibility we need to be able to recognise TASM compatible
373 * conditional compilation directives. Using the NASM pre-processor does
374 * not work, so we look for them specifically from the following list and
375 * then jam in the equivalent NASM directive into the input stream.
379 TM_ARG
, TM_ELIF
, TM_ELSE
, TM_ENDIF
, TM_IF
, TM_IFDEF
, TM_IFDIFI
,
380 TM_IFNDEF
, TM_INCLUDE
, TM_LOCAL
383 static const char * const tasm_directives
[] = {
384 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
385 "ifndef", "include", "local"
388 static int StackSize
= 4;
389 static char *StackPointer
= "ebp";
390 static int ArgOffset
= 8;
391 static int LocalOffset
= 0;
393 static Context
*cstk
;
394 static Include
*istk
;
395 static IncPath
*ipath
= NULL
;
397 static int pass
; /* HACK: pass 0 = generate dependencies only */
398 static StrList
**dephead
, **deptail
; /* Dependency list */
400 static uint64_t unique
; /* unique identifier numbers */
402 static Line
*predef
= NULL
;
403 static bool do_predef
;
405 static ListGen
*list
;
408 * The current set of multi-line macros we have defined.
410 static struct hash_table mmacros
;
413 * The current set of single-line macros we have defined.
415 static struct hash_table smacros
;
418 * The multi-line macro we are currently defining, or the %rep
419 * block we are currently reading, if any.
421 static MMacro
*defining
;
423 static uint64_t nested_mac_count
;
424 static uint64_t nested_rep_count
;
427 * The number of macro parameters to allocate space for at a time.
429 #define PARAM_DELTA 16
432 * The standard macro set: defined in macros.c in the array nasm_stdmac.
433 * This gives our position in the macro set, when we're processing it.
435 static macros_t
*stdmacpos
;
438 * The extra standard macros that come from the object format, if
441 static macros_t
*extrastdmac
= NULL
;
442 static bool any_extrastdmac
;
445 * Tokens are allocated in blocks to improve speed
447 #define TOKEN_BLOCKSIZE 4096
448 static Token
*freeTokens
= NULL
;
454 static Blocks blocks
= { NULL
, NULL
};
457 * Forward declarations.
459 static Token
*expand_mmac_params(Token
* tline
);
460 static Token
*expand_smacro(Token
* tline
);
461 static Token
*expand_id(Token
* tline
);
462 static Context
*get_ctx(const char *name
, const char **namep
);
463 static void make_tok_num(Token
* tok
, int64_t val
);
464 static void error(int severity
, const char *fmt
, ...);
465 static void error_precond(int severity
, const char *fmt
, ...);
466 static void *new_Block(size_t size
);
467 static void delete_Blocks(void);
468 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
469 const char *text
, int txtlen
);
470 static Token
*delete_Token(Token
* t
);
473 * Macros for safe checking of token pointers, avoid *(NULL)
475 #define tok_type_(x,t) ((x) && (x)->type == (t))
476 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
477 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
478 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
481 * nasm_unquote with error if the string contains NUL characters.
482 * If the string contains NUL characters, issue an error and return
483 * the C len, i.e. truncate at the NUL.
485 static size_t nasm_unquote_cstr(char *qstr
, enum preproc_token directive
)
487 size_t len
= nasm_unquote(qstr
, NULL
);
488 size_t clen
= strlen(qstr
);
491 error(ERR_NONFATAL
, "NUL character in `%s' directive",
492 pp_directives
[directive
]);
498 * In-place reverse a list of tokens.
500 static Token
*reverse_tokens(Token
*t
)
516 * Handle TASM specific directives, which do not contain a % in
517 * front of them. We do it here because I could not find any other
518 * place to do it for the moment, and it is a hack (ideally it would
519 * be nice to be able to use the NASM pre-processor to do it).
521 static char *check_tasm_directive(char *line
)
523 int32_t i
, j
, k
, m
, len
;
524 char *p
, *q
, *oldline
, oldchar
;
526 p
= nasm_skip_spaces(line
);
528 /* Binary search for the directive name */
530 j
= ARRAY_SIZE(tasm_directives
);
531 q
= nasm_skip_word(p
);
538 m
= nasm_stricmp(p
, tasm_directives
[k
]);
540 /* We have found a directive, so jam a % in front of it
541 * so that NASM will then recognise it as one if it's own.
546 line
= nasm_malloc(len
+ 2);
548 if (k
== TM_IFDIFI
) {
550 * NASM does not recognise IFDIFI, so we convert
551 * it to %if 0. This is not used in NASM
552 * compatible code, but does need to parse for the
553 * TASM macro package.
555 strcpy(line
+ 1, "if 0");
557 memcpy(line
+ 1, p
, len
+ 1);
572 * The pre-preprocessing stage... This function translates line
573 * number indications as they emerge from GNU cpp (`# lineno "file"
574 * flags') into NASM preprocessor line number indications (`%line
577 static char *prepreproc(char *line
)
580 char *fname
, *oldline
;
582 if (line
[0] == '#' && line
[1] == ' ') {
585 lineno
= atoi(fname
);
586 fname
+= strspn(fname
, "0123456789 ");
589 fnlen
= strcspn(fname
, "\"");
590 line
= nasm_malloc(20 + fnlen
);
591 snprintf(line
, 20 + fnlen
, "%%line %d %.*s", lineno
, fnlen
, fname
);
594 if (tasm_compatible_mode
)
595 return check_tasm_directive(line
);
600 * Free a linked list of tokens.
602 static void free_tlist(Token
* list
)
605 list
= delete_Token(list
);
609 * Free a linked list of lines.
611 static void free_llist(Line
* list
)
614 list_for_each_safe(l
, tmp
, list
) {
615 free_tlist(l
->first
);
623 static void free_mmacro(MMacro
* m
)
626 free_tlist(m
->dlist
);
627 nasm_free(m
->defaults
);
628 free_llist(m
->expansion
);
633 * Free all currently defined macros, and free the hash tables
635 static void free_smacro_table(struct hash_table
*smt
)
639 struct hash_tbl_node
*it
= NULL
;
641 while ((s
= hash_iterate(smt
, &it
, &key
)) != NULL
) {
642 nasm_free((void *)key
);
643 list_for_each_safe(s
, tmp
, s
) {
645 free_tlist(s
->expansion
);
652 static void free_mmacro_table(struct hash_table
*mmt
)
656 struct hash_tbl_node
*it
= NULL
;
659 while ((m
= hash_iterate(mmt
, &it
, &key
)) != NULL
) {
660 nasm_free((void *)key
);
661 list_for_each_safe(m
,tmp
, m
)
667 static void free_macros(void)
669 free_smacro_table(&smacros
);
670 free_mmacro_table(&mmacros
);
674 * Initialize the hash tables
676 static void init_macros(void)
678 hash_init(&smacros
, HASH_LARGE
);
679 hash_init(&mmacros
, HASH_LARGE
);
683 * Pop the context stack.
685 static void ctx_pop(void)
690 free_smacro_table(&c
->localmac
);
696 * Search for a key in the hash index; adding it if necessary
697 * (in which case we initialize the data pointer to NULL.)
700 hash_findi_add(struct hash_table
*hash
, const char *str
)
702 struct hash_insert hi
;
706 r
= hash_findi(hash
, str
, &hi
);
710 strx
= nasm_strdup(str
); /* Use a more efficient allocator here? */
711 return hash_add(&hi
, strx
, NULL
);
715 * Like hash_findi, but returns the data element rather than a pointer
716 * to it. Used only when not adding a new element, hence no third
720 hash_findix(struct hash_table
*hash
, const char *str
)
724 p
= hash_findi(hash
, str
, NULL
);
725 return p
? *p
: NULL
;
729 * read line from standart macros set,
730 * if there no more left -- return NULL
732 static char *line_from_stdmac(void)
735 const unsigned char *p
= stdmacpos
;
744 len
+= pp_directives_len
[c
- 0x80] + 1;
749 line
= nasm_malloc(len
+ 1);
751 while ((c
= *stdmacpos
++)) {
753 memcpy(q
, pp_directives
[c
- 0x80], pp_directives_len
[c
- 0x80]);
754 q
+= pp_directives_len
[c
- 0x80];
764 /* This was the last of the standard macro chain... */
766 if (any_extrastdmac
) {
767 stdmacpos
= extrastdmac
;
768 any_extrastdmac
= false;
769 } else if (do_predef
) {
771 Token
*head
, **tail
, *t
;
774 * Nasty hack: here we push the contents of
775 * `predef' on to the top-level expansion stack,
776 * since this is the most convenient way to
777 * implement the pre-include and pre-define
780 list_for_each(pd
, predef
) {
783 list_for_each(t
, pd
->first
) {
784 *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
785 tail
= &(*tail
)->next
;
788 l
= nasm_malloc(sizeof(Line
));
789 l
->next
= istk
->expansion
;
802 static char *read_line(void)
804 unsigned int size
, c
, next
;
805 const unsigned int delta
= 512;
806 const unsigned int pad
= 8;
807 unsigned int nr_cont
= 0;
811 /* Standart macros set (predefined) goes first */
812 p
= line_from_stdmac();
817 p
= buffer
= nasm_malloc(size
);
821 if ((int)(c
) == EOF
) {
828 next
= fgetc(istk
->fp
);
830 ungetc(next
, istk
->fp
);
845 next
= fgetc(istk
->fp
);
846 ungetc(next
, istk
->fp
);
847 if (next
== '\r' || next
== '\n') {
855 if (c
== '\r' || c
== '\n') {
860 if (p
>= (buffer
+ size
- pad
)) {
861 buffer
= nasm_realloc(buffer
, size
+ delta
);
862 p
= buffer
+ size
- pad
;
866 *p
++ = (unsigned char)c
;
874 src_set_linnum(src_get_linnum() + istk
->lineinc
+
875 (nr_cont
* istk
->lineinc
));
878 * Handle spurious ^Z, which may be inserted into source files
879 * by some file transfer utilities.
881 buffer
[strcspn(buffer
, "\032")] = '\0';
883 list
->line(LIST_READ
, buffer
);
889 * Tokenize a line of text. This is a very simple process since we
890 * don't need to parse the value out of e.g. numeric tokens: we
891 * simply split one string into many.
893 static Token
*tokenize(char *line
)
896 enum pp_token_type type
;
898 Token
*t
, **tail
= &list
;
904 if (*p
== '+' && !nasm_isdigit(p
[1])) {
907 } else if (nasm_isdigit(*p
) ||
908 ((*p
== '-' || *p
== '+') && nasm_isdigit(p
[1]))) {
912 while (nasm_isdigit(*p
));
913 type
= TOK_PREPROC_ID
;
914 } else if (*p
== '{') {
923 error(ERR_WARNING
| ERR_PASS1
, "unterminated %{ construct");
927 type
= TOK_PREPROC_ID
;
928 } else if (*p
== '[') {
930 line
+= 2; /* Skip the leading %[ */
932 while (lvl
&& (c
= *p
++)) {
944 p
= nasm_skip_string(p
- 1) + 1;
954 error(ERR_NONFATAL
, "unterminated %[ construct");
956 } else if (*p
== '?') {
957 type
= TOK_PREPROC_Q
; /* %? */
960 type
= TOK_PREPROC_QQ
; /* %?? */
963 } else if (*p
== '!') {
964 type
= TOK_PREPROC_ID
;
970 while (isidchar(*p
));
971 } else if (*p
== '\'' || *p
== '\"' || *p
== '`') {
972 p
= nasm_skip_string(p
);
976 error(ERR_NONFATAL
|ERR_PASS1
, "unterminated %! string");
978 /* %! without string or identifier */
979 type
= TOK_OTHER
; /* Legacy behavior... */
981 } else if (isidchar(*p
) ||
982 ((*p
== '!' || *p
== '%' || *p
== '$') &&
987 while (isidchar(*p
));
988 type
= TOK_PREPROC_ID
;
994 } else if (isidstart(*p
) || (*p
== '$' && isidstart(p
[1]))) {
997 while (*p
&& isidchar(*p
))
999 } else if (*p
== '\'' || *p
== '"' || *p
== '`') {
1004 p
= nasm_skip_string(p
);
1009 error(ERR_WARNING
|ERR_PASS1
, "unterminated string");
1010 /* Handling unterminated strings by UNV */
1013 } else if (p
[0] == '$' && p
[1] == '$') {
1014 type
= TOK_OTHER
; /* TOKEN_BASE */
1016 } else if (isnumstart(*p
)) {
1017 bool is_hex
= false;
1018 bool is_float
= false;
1034 if (!is_hex
&& (c
== 'e' || c
== 'E')) {
1036 if (*p
== '+' || *p
== '-') {
1038 * e can only be followed by +/- if it is either a
1039 * prefixed hex number or a floating-point number
1044 } else if (c
== 'H' || c
== 'h' || c
== 'X' || c
== 'x') {
1046 } else if (c
== 'P' || c
== 'p') {
1048 if (*p
== '+' || *p
== '-')
1050 } else if (isnumchar(c
) || c
== '_')
1051 ; /* just advance */
1052 else if (c
== '.') {
1054 * we need to deal with consequences of the legacy
1055 * parser, like "1.nolist" being two tokens
1056 * (TOK_NUMBER, TOK_ID) here; at least give it
1057 * a shot for now. In the future, we probably need
1058 * a flex-based scanner with proper pattern matching
1059 * to do it as well as it can be done. Nothing in
1060 * the world is going to help the person who wants
1061 * 0x123.p16 interpreted as two tokens, though.
1067 if (nasm_isdigit(*r
) || (is_hex
&& nasm_isxdigit(*r
)) ||
1068 (!is_hex
&& (*r
== 'e' || *r
== 'E')) ||
1069 (*r
== 'p' || *r
== 'P')) {
1073 break; /* Terminate the token */
1077 p
--; /* Point to first character beyond number */
1079 if (p
== line
+1 && *line
== '$') {
1080 type
= TOK_OTHER
; /* TOKEN_HERE */
1082 if (has_e
&& !is_hex
) {
1083 /* 1e13 is floating-point, but 1e13h is not */
1087 type
= is_float
? TOK_FLOAT
: TOK_NUMBER
;
1089 } else if (nasm_isspace(*p
)) {
1090 type
= TOK_WHITESPACE
;
1091 p
= nasm_skip_spaces(p
);
1093 * Whitespace just before end-of-line is discarded by
1094 * pretending it's a comment; whitespace just before a
1095 * comment gets lumped into the comment.
1097 if (!*p
|| *p
== ';') {
1102 } else if (*p
== ';') {
1108 * Anything else is an operator of some kind. We check
1109 * for all the double-character operators (>>, <<, //,
1110 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1111 * else is a single-character operator.
1114 if ((p
[0] == '>' && p
[1] == '>') ||
1115 (p
[0] == '<' && p
[1] == '<') ||
1116 (p
[0] == '/' && p
[1] == '/') ||
1117 (p
[0] == '<' && p
[1] == '=') ||
1118 (p
[0] == '>' && p
[1] == '=') ||
1119 (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] == '^')) {
1130 /* Handling unterminated string by UNV */
1133 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1134 t->text[p-line] = *line;
1138 if (type
!= TOK_COMMENT
) {
1139 *tail
= t
= new_Token(NULL
, type
, line
, p
- line
);
1148 * this function allocates a new managed block of memory and
1149 * returns a pointer to the block. The managed blocks are
1150 * deleted only all at once by the delete_Blocks function.
1152 static void *new_Block(size_t size
)
1154 Blocks
*b
= &blocks
;
1156 /* first, get to the end of the linked list */
1159 /* now allocate the requested chunk */
1160 b
->chunk
= nasm_malloc(size
);
1162 /* now allocate a new block for the next request */
1163 b
->next
= nasm_zalloc(sizeof(Blocks
));
1168 * this function deletes all managed blocks of memory
1170 static void delete_Blocks(void)
1172 Blocks
*a
, *b
= &blocks
;
1175 * keep in mind that the first block, pointed to by blocks
1176 * is a static and not dynamically allocated, so we don't
1181 nasm_free(b
->chunk
);
1187 memset(&blocks
, 0, sizeof(blocks
));
1191 * this function creates a new Token and passes a pointer to it
1192 * back to the caller. It sets the type and text elements, and
1193 * also the a.mac and next elements to NULL.
1195 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
1196 const char *text
, int txtlen
)
1202 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1203 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1204 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1205 freeTokens
[i
].next
= NULL
;
1208 freeTokens
= t
->next
;
1212 if (type
== TOK_WHITESPACE
|| !text
) {
1216 txtlen
= strlen(text
);
1217 t
->text
= nasm_malloc(txtlen
+1);
1218 memcpy(t
->text
, text
, txtlen
);
1219 t
->text
[txtlen
] = '\0';
1224 static Token
*delete_Token(Token
* t
)
1226 Token
*next
= t
->next
;
1228 t
->next
= freeTokens
;
1234 * Convert a line of tokens back into text.
1235 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1236 * will be transformed into ..@ctxnum.xxx
1238 static char *detoken(Token
* tlist
, bool expand_locals
)
1245 list_for_each(t
, tlist
) {
1246 if (t
->type
== TOK_PREPROC_ID
&& t
->text
[1] == '!') {
1251 if (*v
== '\'' || *v
== '\"' || *v
== '`') {
1252 size_t len
= nasm_unquote(v
, NULL
);
1253 size_t clen
= strlen(v
);
1256 error(ERR_NONFATAL
| ERR_PASS1
,
1257 "NUL character in %! string");
1263 char *p
= getenv(v
);
1265 error(ERR_NONFATAL
| ERR_PASS1
,
1266 "nonexistent environment variable `%s'", v
);
1269 t
->text
= nasm_strdup(p
);
1274 /* Expand local macros here and not during preprocessing */
1275 if (expand_locals
&&
1276 t
->type
== TOK_PREPROC_ID
&& t
->text
&&
1277 t
->text
[0] == '%' && t
->text
[1] == '$') {
1280 Context
*ctx
= get_ctx(t
->text
, &q
);
1283 snprintf(buffer
, sizeof(buffer
), "..@%"PRIu32
".", ctx
->number
);
1284 p
= nasm_strcat(buffer
, q
);
1289 if (t
->type
== TOK_WHITESPACE
)
1292 len
+= strlen(t
->text
);
1295 p
= line
= nasm_malloc(len
+ 1);
1297 list_for_each(t
, tlist
) {
1298 if (t
->type
== TOK_WHITESPACE
) {
1300 } else if (t
->text
) {
1312 * A scanner, suitable for use by the expression evaluator, which
1313 * operates on a line of Tokens. Expects a pointer to a pointer to
1314 * the first token in the line to be passed in as its private_data
1317 * FIX: This really needs to be unified with stdscan.
1319 static int ppscan(void *private_data
, struct tokenval
*tokval
)
1321 Token
**tlineptr
= private_data
;
1323 char ourcopy
[MAX_KEYWORD
+1], *p
, *r
, *s
;
1327 *tlineptr
= tline
? tline
->next
: NULL
;
1328 } while (tline
&& (tline
->type
== TOK_WHITESPACE
||
1329 tline
->type
== TOK_COMMENT
));
1332 return tokval
->t_type
= TOKEN_EOS
;
1334 tokval
->t_charptr
= tline
->text
;
1336 if (tline
->text
[0] == '$' && !tline
->text
[1])
1337 return tokval
->t_type
= TOKEN_HERE
;
1338 if (tline
->text
[0] == '$' && tline
->text
[1] == '$' && !tline
->text
[2])
1339 return tokval
->t_type
= TOKEN_BASE
;
1341 if (tline
->type
== TOK_ID
) {
1342 p
= tokval
->t_charptr
= tline
->text
;
1344 tokval
->t_charptr
++;
1345 return tokval
->t_type
= TOKEN_ID
;
1348 for (r
= p
, s
= ourcopy
; *r
; r
++) {
1349 if (r
>= p
+MAX_KEYWORD
)
1350 return tokval
->t_type
= TOKEN_ID
; /* Not a keyword */
1351 *s
++ = nasm_tolower(*r
);
1354 /* right, so we have an identifier sitting in temp storage. now,
1355 * is it actually a register or instruction name, or what? */
1356 return nasm_token_hash(ourcopy
, tokval
);
1359 if (tline
->type
== TOK_NUMBER
) {
1361 tokval
->t_integer
= readnum(tline
->text
, &rn_error
);
1362 tokval
->t_charptr
= tline
->text
;
1364 return tokval
->t_type
= TOKEN_ERRNUM
;
1366 return tokval
->t_type
= TOKEN_NUM
;
1369 if (tline
->type
== TOK_FLOAT
) {
1370 return tokval
->t_type
= TOKEN_FLOAT
;
1373 if (tline
->type
== TOK_STRING
) {
1376 bq
= tline
->text
[0];
1377 tokval
->t_charptr
= tline
->text
;
1378 tokval
->t_inttwo
= nasm_unquote(tline
->text
, &ep
);
1380 if (ep
[0] != bq
|| ep
[1] != '\0')
1381 return tokval
->t_type
= TOKEN_ERRSTR
;
1383 return tokval
->t_type
= TOKEN_STR
;
1386 if (tline
->type
== TOK_OTHER
) {
1387 if (!strcmp(tline
->text
, "<<"))
1388 return tokval
->t_type
= TOKEN_SHL
;
1389 if (!strcmp(tline
->text
, ">>"))
1390 return tokval
->t_type
= TOKEN_SHR
;
1391 if (!strcmp(tline
->text
, "//"))
1392 return tokval
->t_type
= TOKEN_SDIV
;
1393 if (!strcmp(tline
->text
, "%%"))
1394 return tokval
->t_type
= TOKEN_SMOD
;
1395 if (!strcmp(tline
->text
, "=="))
1396 return tokval
->t_type
= TOKEN_EQ
;
1397 if (!strcmp(tline
->text
, "<>"))
1398 return tokval
->t_type
= TOKEN_NE
;
1399 if (!strcmp(tline
->text
, "!="))
1400 return tokval
->t_type
= TOKEN_NE
;
1401 if (!strcmp(tline
->text
, "<="))
1402 return tokval
->t_type
= TOKEN_LE
;
1403 if (!strcmp(tline
->text
, ">="))
1404 return tokval
->t_type
= TOKEN_GE
;
1405 if (!strcmp(tline
->text
, "&&"))
1406 return tokval
->t_type
= TOKEN_DBL_AND
;
1407 if (!strcmp(tline
->text
, "^^"))
1408 return tokval
->t_type
= TOKEN_DBL_XOR
;
1409 if (!strcmp(tline
->text
, "||"))
1410 return tokval
->t_type
= TOKEN_DBL_OR
;
1414 * We have no other options: just return the first character of
1417 return tokval
->t_type
= tline
->text
[0];
1421 * Compare a string to the name of an existing macro; this is a
1422 * simple wrapper which calls either strcmp or nasm_stricmp
1423 * depending on the value of the `casesense' parameter.
1425 static int mstrcmp(const char *p
, const char *q
, bool casesense
)
1427 return casesense
? strcmp(p
, q
) : nasm_stricmp(p
, q
);
1431 * Compare a string to the name of an existing macro; this is a
1432 * simple wrapper which calls either strcmp or nasm_stricmp
1433 * depending on the value of the `casesense' parameter.
1435 static int mmemcmp(const char *p
, const char *q
, size_t l
, bool casesense
)
1437 return casesense
? memcmp(p
, q
, l
) : nasm_memicmp(p
, q
, l
);
1441 * Return the Context structure associated with a %$ token. Return
1442 * NULL, having _already_ reported an error condition, if the
1443 * context stack isn't deep enough for the supplied number of $
1446 * If "namep" is non-NULL, set it to the pointer to the macro name
1447 * tail, i.e. the part beyond %$...
1449 static Context
*get_ctx(const char *name
, const char **namep
)
1457 if (!name
|| name
[0] != '%' || name
[1] != '$')
1461 error(ERR_NONFATAL
, "`%s': context stack is empty", name
);
1468 while (ctx
&& *name
== '$') {
1474 error(ERR_NONFATAL
, "`%s': context stack is only"
1475 " %d level%s deep", name
, i
, (i
== 1 ? "" : "s"));
1486 * Check to see if a file is already in a string list
1488 static bool in_list(const StrList
*list
, const char *str
)
1491 if (!strcmp(list
->str
, str
))
1499 * Open an include file. This routine must always return a valid
1500 * file pointer if it returns - it's responsible for throwing an
1501 * ERR_FATAL and bombing out completely if not. It should also try
1502 * the include path one by one until it finds the file or reaches
1503 * the end of the path.
1505 static FILE *inc_fopen(const char *file
, StrList
**dhead
, StrList
***dtail
,
1510 IncPath
*ip
= ipath
;
1511 int len
= strlen(file
);
1512 size_t prefix_len
= 0;
1516 sl
= nasm_malloc(prefix_len
+len
+1+sizeof sl
->next
);
1517 memcpy(sl
->str
, prefix
, prefix_len
);
1518 memcpy(sl
->str
+prefix_len
, file
, len
+1);
1519 fp
= fopen(sl
->str
, "r");
1520 if (fp
&& dhead
&& !in_list(*dhead
, sl
->str
)) {
1538 prefix_len
= strlen(prefix
);
1540 /* -MG given and file not found */
1541 if (dhead
&& !in_list(*dhead
, file
)) {
1542 sl
= nasm_malloc(len
+1+sizeof sl
->next
);
1544 strcpy(sl
->str
, file
);
1552 error(ERR_FATAL
, "unable to open include file `%s'", file
);
1557 * Determine if we should warn on defining a single-line macro of
1558 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1559 * return true if _any_ single-line macro of that name is defined.
1560 * Otherwise, will return true if a single-line macro with either
1561 * `nparam' or no parameters is defined.
1563 * If a macro with precisely the right number of parameters is
1564 * defined, or nparam is -1, the address of the definition structure
1565 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1566 * is NULL, no action will be taken regarding its contents, and no
1569 * Note that this is also called with nparam zero to resolve
1572 * If you already know which context macro belongs to, you can pass
1573 * the context pointer as first parameter; if you won't but name begins
1574 * with %$ the context will be automatically computed. If all_contexts
1575 * is true, macro will be searched in outer contexts as well.
1578 smacro_defined(Context
* ctx
, const char *name
, int nparam
, SMacro
** defn
,
1581 struct hash_table
*smtbl
;
1585 smtbl
= &ctx
->localmac
;
1586 } else if (name
[0] == '%' && name
[1] == '$') {
1588 ctx
= get_ctx(name
, &name
);
1590 return false; /* got to return _something_ */
1591 smtbl
= &ctx
->localmac
;
1595 m
= (SMacro
*) hash_findix(smtbl
, name
);
1598 if (!mstrcmp(m
->name
, name
, m
->casesense
&& nocase
) &&
1599 (nparam
<= 0 || m
->nparam
== 0 || nparam
== (int) m
->nparam
)) {
1601 if (nparam
== (int) m
->nparam
|| nparam
== -1)
1615 * Count and mark off the parameters in a multi-line macro call.
1616 * This is called both from within the multi-line macro expansion
1617 * code, and also to mark off the default parameters when provided
1618 * in a %macro definition line.
1620 static void count_mmac_params(Token
* t
, int *nparam
, Token
*** params
)
1622 int paramsize
, brace
;
1624 *nparam
= paramsize
= 0;
1627 /* +1: we need space for the final NULL */
1628 if (*nparam
+1 >= paramsize
) {
1629 paramsize
+= PARAM_DELTA
;
1630 *params
= nasm_realloc(*params
, sizeof(**params
) * paramsize
);
1634 if (tok_is_(t
, "{"))
1636 (*params
)[(*nparam
)++] = t
;
1638 while (brace
&& (t
= t
->next
) != NULL
) {
1639 if (tok_is_(t
, "{"))
1641 else if (tok_is_(t
, "}"))
1647 * Now we've found the closing brace, look further
1652 if (tok_isnt_(t
, ",")) {
1654 "braces do not enclose all of macro parameter");
1655 while (tok_isnt_(t
, ","))
1660 while (tok_isnt_(t
, ","))
1663 if (t
) { /* got a comma/brace */
1664 t
= t
->next
; /* eat the comma */
1670 * Determine whether one of the various `if' conditions is true or
1673 * We must free the tline we get passed.
1675 static bool if_condition(Token
* tline
, enum preproc_token ct
)
1677 enum pp_conditional i
= PP_COND(ct
);
1679 Token
*t
, *tt
, **tptr
, *origline
;
1680 struct tokenval tokval
;
1682 enum pp_token_type needtype
;
1689 j
= false; /* have we matched yet? */
1694 if (tline
->type
!= TOK_ID
) {
1696 "`%s' expects context identifiers", pp_directives
[ct
]);
1697 free_tlist(origline
);
1700 if (cstk
&& cstk
->name
&& !nasm_stricmp(tline
->text
, cstk
->name
))
1702 tline
= tline
->next
;
1707 j
= false; /* have we matched yet? */
1710 if (!tline
|| (tline
->type
!= TOK_ID
&&
1711 (tline
->type
!= TOK_PREPROC_ID
||
1712 tline
->text
[1] != '$'))) {
1714 "`%s' expects macro identifiers", pp_directives
[ct
]);
1717 if (smacro_defined(NULL
, tline
->text
, 0, NULL
, true))
1719 tline
= tline
->next
;
1724 tline
= expand_smacro(tline
);
1725 j
= false; /* have we matched yet? */
1728 if (!tline
|| (tline
->type
!= TOK_ID
&&
1729 tline
->type
!= TOK_STRING
&&
1730 (tline
->type
!= TOK_PREPROC_ID
||
1731 tline
->text
[1] != '!'))) {
1733 "`%s' expects environment variable names",
1738 if (tline
->type
== TOK_PREPROC_ID
)
1739 p
+= 2; /* Skip leading %! */
1740 if (*p
== '\'' || *p
== '\"' || *p
== '`')
1741 nasm_unquote_cstr(p
, ct
);
1744 tline
= tline
->next
;
1750 tline
= expand_smacro(tline
);
1752 while (tok_isnt_(tt
, ","))
1756 "`%s' expects two comma-separated arguments",
1761 j
= true; /* assume equality unless proved not */
1762 while ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) && tt
) {
1763 if (tt
->type
== TOK_OTHER
&& !strcmp(tt
->text
, ",")) {
1764 error(ERR_NONFATAL
, "`%s': more than one comma on line",
1768 if (t
->type
== TOK_WHITESPACE
) {
1772 if (tt
->type
== TOK_WHITESPACE
) {
1776 if (tt
->type
!= t
->type
) {
1777 j
= false; /* found mismatching tokens */
1780 /* When comparing strings, need to unquote them first */
1781 if (t
->type
== TOK_STRING
) {
1782 size_t l1
= nasm_unquote(t
->text
, NULL
);
1783 size_t l2
= nasm_unquote(tt
->text
, NULL
);
1789 if (mmemcmp(t
->text
, tt
->text
, l1
, i
== PPC_IFIDN
)) {
1793 } else if (mstrcmp(tt
->text
, t
->text
, i
== PPC_IFIDN
) != 0) {
1794 j
= false; /* found mismatching tokens */
1801 if ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) || tt
)
1802 j
= false; /* trailing gunk on one end or other */
1808 MMacro searching
, *mmac
;
1811 tline
= expand_id(tline
);
1812 if (!tok_type_(tline
, TOK_ID
)) {
1814 "`%s' expects a macro name", pp_directives
[ct
]);
1817 searching
.name
= nasm_strdup(tline
->text
);
1818 searching
.casesense
= true;
1819 searching
.plus
= false;
1820 searching
.nolist
= false;
1821 searching
.in_progress
= 0;
1822 searching
.max_depth
= 0;
1823 searching
.rep_nest
= NULL
;
1824 searching
.nparam_min
= 0;
1825 searching
.nparam_max
= INT_MAX
;
1826 tline
= expand_smacro(tline
->next
);
1829 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1831 "`%s' expects a parameter count or nothing",
1834 searching
.nparam_min
= searching
.nparam_max
=
1835 readnum(tline
->text
, &j
);
1838 "unable to parse parameter count `%s'",
1841 if (tline
&& tok_is_(tline
->next
, "-")) {
1842 tline
= tline
->next
->next
;
1843 if (tok_is_(tline
, "*"))
1844 searching
.nparam_max
= INT_MAX
;
1845 else if (!tok_type_(tline
, TOK_NUMBER
))
1847 "`%s' expects a parameter count after `-'",
1850 searching
.nparam_max
= readnum(tline
->text
, &j
);
1853 "unable to parse parameter count `%s'",
1855 if (searching
.nparam_min
> searching
.nparam_max
)
1857 "minimum parameter count exceeds maximum");
1860 if (tline
&& tok_is_(tline
->next
, "+")) {
1861 tline
= tline
->next
;
1862 searching
.plus
= true;
1864 mmac
= (MMacro
*) hash_findix(&mmacros
, searching
.name
);
1866 if (!strcmp(mmac
->name
, searching
.name
) &&
1867 (mmac
->nparam_min
<= searching
.nparam_max
1869 && (searching
.nparam_min
<= mmac
->nparam_max
1876 if (tline
&& tline
->next
)
1877 error(ERR_WARNING
|ERR_PASS1
,
1878 "trailing garbage after %%ifmacro ignored");
1879 nasm_free(searching
.name
);
1888 needtype
= TOK_NUMBER
;
1891 needtype
= TOK_STRING
;
1895 t
= tline
= expand_smacro(tline
);
1897 while (tok_type_(t
, TOK_WHITESPACE
) ||
1898 (needtype
== TOK_NUMBER
&&
1899 tok_type_(t
, TOK_OTHER
) &&
1900 (t
->text
[0] == '-' || t
->text
[0] == '+') &&
1904 j
= tok_type_(t
, needtype
);
1908 t
= tline
= expand_smacro(tline
);
1909 while (tok_type_(t
, TOK_WHITESPACE
))
1914 t
= t
->next
; /* Skip the actual token */
1915 while (tok_type_(t
, TOK_WHITESPACE
))
1917 j
= !t
; /* Should be nothing left */
1922 t
= tline
= expand_smacro(tline
);
1923 while (tok_type_(t
, TOK_WHITESPACE
))
1926 j
= !t
; /* Should be empty */
1930 t
= tline
= expand_smacro(tline
);
1932 tokval
.t_type
= TOKEN_INVALID
;
1933 evalresult
= evaluate(ppscan
, tptr
, &tokval
,
1934 NULL
, pass
| CRITICAL
, error
, NULL
);
1938 error(ERR_WARNING
|ERR_PASS1
,
1939 "trailing garbage after expression ignored");
1940 if (!is_simple(evalresult
)) {
1942 "non-constant value given to `%s'", pp_directives
[ct
]);
1945 j
= reloc_value(evalresult
) != 0;
1950 "preprocessor directive `%s' not yet implemented",
1955 free_tlist(origline
);
1956 return j
^ PP_NEGATIVE(ct
);
1959 free_tlist(origline
);
1964 * Common code for defining an smacro
1966 static bool define_smacro(Context
*ctx
, const char *mname
, bool casesense
,
1967 int nparam
, Token
*expansion
)
1969 SMacro
*smac
, **smhead
;
1970 struct hash_table
*smtbl
;
1972 if (smacro_defined(ctx
, mname
, nparam
, &smac
, casesense
)) {
1974 error(ERR_WARNING
|ERR_PASS1
,
1975 "single-line macro `%s' defined both with and"
1976 " without parameters", mname
);
1978 * Some instances of the old code considered this a failure,
1979 * some others didn't. What is the right thing to do here?
1981 free_tlist(expansion
);
1982 return false; /* Failure */
1985 * We're redefining, so we have to take over an
1986 * existing SMacro structure. This means freeing
1987 * what was already in it.
1989 nasm_free(smac
->name
);
1990 free_tlist(smac
->expansion
);
1993 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
1994 smhead
= (SMacro
**) hash_findi_add(smtbl
, mname
);
1995 smac
= nasm_malloc(sizeof(SMacro
));
1996 smac
->next
= *smhead
;
1999 smac
->name
= nasm_strdup(mname
);
2000 smac
->casesense
= casesense
;
2001 smac
->nparam
= nparam
;
2002 smac
->expansion
= expansion
;
2003 smac
->in_progress
= false;
2004 return true; /* Success */
2008 * Undefine an smacro
2010 static void undef_smacro(Context
*ctx
, const char *mname
)
2012 SMacro
**smhead
, *s
, **sp
;
2013 struct hash_table
*smtbl
;
2015 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2016 smhead
= (SMacro
**)hash_findi(smtbl
, mname
, NULL
);
2020 * We now have a macro name... go hunt for it.
2023 while ((s
= *sp
) != NULL
) {
2024 if (!mstrcmp(s
->name
, mname
, s
->casesense
)) {
2027 free_tlist(s
->expansion
);
2037 * Parse a mmacro specification.
2039 static bool parse_mmacro_spec(Token
*tline
, MMacro
*def
, const char *directive
)
2043 tline
= tline
->next
;
2045 tline
= expand_id(tline
);
2046 if (!tok_type_(tline
, TOK_ID
)) {
2047 error(ERR_NONFATAL
, "`%s' expects a macro name", directive
);
2052 def
->name
= nasm_strdup(tline
->text
);
2054 def
->nolist
= false;
2055 def
->in_progress
= 0;
2056 def
->rep_nest
= NULL
;
2057 def
->nparam_min
= 0;
2058 def
->nparam_max
= 0;
2060 tline
= expand_smacro(tline
->next
);
2062 if (!tok_type_(tline
, TOK_NUMBER
)) {
2063 error(ERR_NONFATAL
, "`%s' expects a parameter count", directive
);
2065 def
->nparam_min
= def
->nparam_max
=
2066 readnum(tline
->text
, &err
);
2069 "unable to parse parameter count `%s'", tline
->text
);
2071 if (tline
&& tok_is_(tline
->next
, "-")) {
2072 tline
= tline
->next
->next
;
2073 if (tok_is_(tline
, "*")) {
2074 def
->nparam_max
= INT_MAX
;
2075 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
2077 "`%s' expects a parameter count after `-'", directive
);
2079 def
->nparam_max
= readnum(tline
->text
, &err
);
2081 error(ERR_NONFATAL
, "unable to parse parameter count `%s'",
2084 if (def
->nparam_min
> def
->nparam_max
) {
2085 error(ERR_NONFATAL
, "minimum parameter count exceeds maximum");
2089 if (tline
&& tok_is_(tline
->next
, "+")) {
2090 tline
= tline
->next
;
2093 if (tline
&& tok_type_(tline
->next
, TOK_ID
) &&
2094 !nasm_stricmp(tline
->next
->text
, ".nolist")) {
2095 tline
= tline
->next
;
2100 * Handle default parameters.
2102 if (tline
&& tline
->next
) {
2103 def
->dlist
= tline
->next
;
2105 count_mmac_params(def
->dlist
, &def
->ndefs
, &def
->defaults
);
2108 def
->defaults
= NULL
;
2110 def
->expansion
= NULL
;
2112 if (def
->defaults
&& def
->ndefs
> def
->nparam_max
- def
->nparam_min
&&
2114 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MDP
,
2115 "too many default macro parameters");
2122 * Decode a size directive
2124 static int parse_size(const char *str
) {
2125 static const char *size_names
[] =
2126 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2127 static const int sizes
[] =
2128 { 0, 1, 4, 16, 8, 10, 2, 32 };
2130 return sizes
[bsii(str
, size_names
, ARRAY_SIZE(size_names
))+1];
2134 * find and process preprocessor directive in passed line
2135 * Find out if a line contains a preprocessor directive, and deal
2138 * If a directive _is_ found, it is the responsibility of this routine
2139 * (and not the caller) to free_tlist() the line.
2141 * @param tline a pointer to the current tokeninzed line linked list
2142 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2145 static int do_directive(Token
* tline
)
2147 enum preproc_token i
;
2160 MMacro
*mmac
, **mmhead
;
2161 Token
*t
= NULL
, *tt
, *param_start
, *macro_start
, *last
, **tptr
, *origline
;
2163 struct tokenval tokval
;
2165 MMacro
*tmp_defining
; /* Used when manipulating rep_nest */
2173 if (!tline
|| !tok_type_(tline
, TOK_PREPROC_ID
) ||
2174 (tline
->text
[1] == '%' || tline
->text
[1] == '$'
2175 || tline
->text
[1] == '!'))
2176 return NO_DIRECTIVE_FOUND
;
2178 i
= pp_token_hash(tline
->text
);
2181 * FIXME: We zap execution of PP_RMACRO, PP_IRMACRO, PP_EXITMACRO
2182 * since they are known to be buggy at moment, we need to fix them
2183 * in future release (2.09-2.10)
2185 if (i
== PP_RMACRO
|| i
== PP_IRMACRO
|| i
== PP_EXITMACRO
) {
2186 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2188 return NO_DIRECTIVE_FOUND
;
2192 * If we're in a non-emitting branch of a condition construct,
2193 * or walking to the end of an already terminated %rep block,
2194 * we should ignore all directives except for condition
2197 if (((istk
->conds
&& !emitting(istk
->conds
->state
)) ||
2198 (istk
->mstk
&& !istk
->mstk
->in_progress
)) && !is_condition(i
)) {
2199 return NO_DIRECTIVE_FOUND
;
2203 * If we're defining a macro or reading a %rep block, we should
2204 * ignore all directives except for %macro/%imacro (which nest),
2205 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2206 * If we're in a %rep block, another %rep nests, so should be let through.
2208 if (defining
&& i
!= PP_MACRO
&& i
!= PP_IMACRO
&&
2209 i
!= PP_RMACRO
&& i
!= PP_IRMACRO
&&
2210 i
!= PP_ENDMACRO
&& i
!= PP_ENDM
&&
2211 (defining
->name
|| (i
!= PP_ENDREP
&& i
!= PP_REP
))) {
2212 return NO_DIRECTIVE_FOUND
;
2216 if (i
== PP_MACRO
|| i
== PP_IMACRO
||
2217 i
== PP_RMACRO
|| i
== PP_IRMACRO
) {
2219 return NO_DIRECTIVE_FOUND
;
2220 } else if (nested_mac_count
> 0) {
2221 if (i
== PP_ENDMACRO
) {
2223 return NO_DIRECTIVE_FOUND
;
2226 if (!defining
->name
) {
2229 return NO_DIRECTIVE_FOUND
;
2230 } else if (nested_rep_count
> 0) {
2231 if (i
== PP_ENDREP
) {
2233 return NO_DIRECTIVE_FOUND
;
2241 error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2243 return NO_DIRECTIVE_FOUND
; /* didn't get it */
2246 /* Directive to tell NASM what the default stack size is. The
2247 * default is for a 16-bit stack, and this can be overriden with
2250 tline
= tline
->next
;
2251 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2252 tline
= tline
->next
;
2253 if (!tline
|| tline
->type
!= TOK_ID
) {
2254 error(ERR_NONFATAL
, "`%%stacksize' missing size parameter");
2255 free_tlist(origline
);
2256 return DIRECTIVE_FOUND
;
2258 if (nasm_stricmp(tline
->text
, "flat") == 0) {
2259 /* All subsequent ARG directives are for a 32-bit stack */
2261 StackPointer
= "ebp";
2264 } else if (nasm_stricmp(tline
->text
, "flat64") == 0) {
2265 /* All subsequent ARG directives are for a 64-bit stack */
2267 StackPointer
= "rbp";
2270 } else if (nasm_stricmp(tline
->text
, "large") == 0) {
2271 /* All subsequent ARG directives are for a 16-bit stack,
2272 * far function call.
2275 StackPointer
= "bp";
2278 } else if (nasm_stricmp(tline
->text
, "small") == 0) {
2279 /* All subsequent ARG directives are for a 16-bit stack,
2280 * far function call. We don't support near functions.
2283 StackPointer
= "bp";
2287 error(ERR_NONFATAL
, "`%%stacksize' invalid size type");
2288 free_tlist(origline
);
2289 return DIRECTIVE_FOUND
;
2291 free_tlist(origline
);
2292 return DIRECTIVE_FOUND
;
2295 /* TASM like ARG directive to define arguments to functions, in
2296 * the following form:
2298 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2302 char *arg
, directive
[256];
2303 int size
= StackSize
;
2305 /* Find the argument name */
2306 tline
= tline
->next
;
2307 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2308 tline
= tline
->next
;
2309 if (!tline
|| tline
->type
!= TOK_ID
) {
2310 error(ERR_NONFATAL
, "`%%arg' missing argument parameter");
2311 free_tlist(origline
);
2312 return DIRECTIVE_FOUND
;
2316 /* Find the argument size type */
2317 tline
= tline
->next
;
2318 if (!tline
|| tline
->type
!= TOK_OTHER
2319 || tline
->text
[0] != ':') {
2321 "Syntax error processing `%%arg' directive");
2322 free_tlist(origline
);
2323 return DIRECTIVE_FOUND
;
2325 tline
= tline
->next
;
2326 if (!tline
|| tline
->type
!= TOK_ID
) {
2327 error(ERR_NONFATAL
, "`%%arg' missing size type parameter");
2328 free_tlist(origline
);
2329 return DIRECTIVE_FOUND
;
2332 /* Allow macro expansion of type parameter */
2333 tt
= tokenize(tline
->text
);
2334 tt
= expand_smacro(tt
);
2335 size
= parse_size(tt
->text
);
2338 "Invalid size type for `%%arg' missing directive");
2340 free_tlist(origline
);
2341 return DIRECTIVE_FOUND
;
2345 /* Round up to even stack slots */
2346 size
= ALIGN(size
, StackSize
);
2348 /* Now define the macro for the argument */
2349 snprintf(directive
, sizeof(directive
), "%%define %s (%s+%d)",
2350 arg
, StackPointer
, offset
);
2351 do_directive(tokenize(directive
));
2354 /* Move to the next argument in the list */
2355 tline
= tline
->next
;
2356 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2357 tline
= tline
->next
;
2358 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2360 free_tlist(origline
);
2361 return DIRECTIVE_FOUND
;
2364 /* TASM like LOCAL directive to define local variables for a
2365 * function, in the following form:
2367 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2369 * The '= LocalSize' at the end is ignored by NASM, but is
2370 * required by TASM to define the local parameter size (and used
2371 * by the TASM macro package).
2373 offset
= LocalOffset
;
2375 char *local
, directive
[256];
2376 int size
= StackSize
;
2378 /* Find the argument name */
2379 tline
= tline
->next
;
2380 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2381 tline
= tline
->next
;
2382 if (!tline
|| tline
->type
!= TOK_ID
) {
2384 "`%%local' missing argument parameter");
2385 free_tlist(origline
);
2386 return DIRECTIVE_FOUND
;
2388 local
= tline
->text
;
2390 /* Find the argument size type */
2391 tline
= tline
->next
;
2392 if (!tline
|| tline
->type
!= TOK_OTHER
2393 || tline
->text
[0] != ':') {
2395 "Syntax error processing `%%local' directive");
2396 free_tlist(origline
);
2397 return DIRECTIVE_FOUND
;
2399 tline
= tline
->next
;
2400 if (!tline
|| tline
->type
!= TOK_ID
) {
2402 "`%%local' missing size type parameter");
2403 free_tlist(origline
);
2404 return DIRECTIVE_FOUND
;
2407 /* Allow macro expansion of type parameter */
2408 tt
= tokenize(tline
->text
);
2409 tt
= expand_smacro(tt
);
2410 size
= parse_size(tt
->text
);
2413 "Invalid size type for `%%local' missing directive");
2415 free_tlist(origline
);
2416 return DIRECTIVE_FOUND
;
2420 /* Round up to even stack slots */
2421 size
= ALIGN(size
, StackSize
);
2423 offset
+= size
; /* Negative offset, increment before */
2425 /* Now define the macro for the argument */
2426 snprintf(directive
, sizeof(directive
), "%%define %s (%s-%d)",
2427 local
, StackPointer
, offset
);
2428 do_directive(tokenize(directive
));
2430 /* Now define the assign to setup the enter_c macro correctly */
2431 snprintf(directive
, sizeof(directive
),
2432 "%%assign %%$localsize %%$localsize+%d", size
);
2433 do_directive(tokenize(directive
));
2435 /* Move to the next argument in the list */
2436 tline
= tline
->next
;
2437 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2438 tline
= tline
->next
;
2439 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2440 LocalOffset
= offset
;
2441 free_tlist(origline
);
2442 return DIRECTIVE_FOUND
;
2446 error(ERR_WARNING
|ERR_PASS1
,
2447 "trailing garbage after `%%clear' ignored");
2450 free_tlist(origline
);
2451 return DIRECTIVE_FOUND
;
2454 t
= tline
->next
= expand_smacro(tline
->next
);
2456 if (!t
|| (t
->type
!= TOK_STRING
&&
2457 t
->type
!= TOK_INTERNAL_STRING
)) {
2458 error(ERR_NONFATAL
, "`%%depend' expects a file name");
2459 free_tlist(origline
);
2460 return DIRECTIVE_FOUND
; /* but we did _something_ */
2463 error(ERR_WARNING
|ERR_PASS1
,
2464 "trailing garbage after `%%depend' ignored");
2466 if (t
->type
!= TOK_INTERNAL_STRING
)
2467 nasm_unquote_cstr(p
, i
);
2468 if (dephead
&& !in_list(*dephead
, p
)) {
2469 StrList
*sl
= nasm_malloc(strlen(p
)+1+sizeof sl
->next
);
2473 deptail
= &sl
->next
;
2475 free_tlist(origline
);
2476 return DIRECTIVE_FOUND
;
2479 t
= tline
->next
= expand_smacro(tline
->next
);
2482 if (!t
|| (t
->type
!= TOK_STRING
&&
2483 t
->type
!= TOK_INTERNAL_STRING
)) {
2484 error(ERR_NONFATAL
, "`%%include' expects a file name");
2485 free_tlist(origline
);
2486 return DIRECTIVE_FOUND
; /* but we did _something_ */
2489 error(ERR_WARNING
|ERR_PASS1
,
2490 "trailing garbage after `%%include' ignored");
2492 if (t
->type
!= TOK_INTERNAL_STRING
)
2493 nasm_unquote_cstr(p
, i
);
2494 inc
= nasm_malloc(sizeof(Include
));
2497 inc
->fp
= inc_fopen(p
, dephead
, &deptail
, pass
== 0);
2499 /* -MG given but file not found */
2502 inc
->fname
= src_set_fname(nasm_strdup(p
));
2503 inc
->lineno
= src_set_linnum(0);
2505 inc
->expansion
= NULL
;
2508 list
->uplevel(LIST_INCLUDE
);
2510 free_tlist(origline
);
2511 return DIRECTIVE_FOUND
;
2515 static macros_t
*use_pkg
;
2516 const char *pkg_macro
= NULL
;
2518 tline
= tline
->next
;
2520 tline
= expand_id(tline
);
2522 if (!tline
|| (tline
->type
!= TOK_STRING
&&
2523 tline
->type
!= TOK_INTERNAL_STRING
&&
2524 tline
->type
!= TOK_ID
)) {
2525 error(ERR_NONFATAL
, "`%%use' expects a package name");
2526 free_tlist(origline
);
2527 return DIRECTIVE_FOUND
; /* but we did _something_ */
2530 error(ERR_WARNING
|ERR_PASS1
,
2531 "trailing garbage after `%%use' ignored");
2532 if (tline
->type
== TOK_STRING
)
2533 nasm_unquote_cstr(tline
->text
, i
);
2534 use_pkg
= nasm_stdmac_find_package(tline
->text
);
2536 error(ERR_NONFATAL
, "unknown `%%use' package: %s", tline
->text
);
2538 pkg_macro
= (char *)use_pkg
+ 1; /* The first string will be <%define>__USE_*__ */
2539 if (use_pkg
&& ! smacro_defined(NULL
, pkg_macro
, 0, NULL
, true)) {
2540 /* Not already included, go ahead and include it */
2541 stdmacpos
= use_pkg
;
2543 free_tlist(origline
);
2544 return DIRECTIVE_FOUND
;
2549 tline
= tline
->next
;
2551 tline
= expand_id(tline
);
2553 if (!tok_type_(tline
, TOK_ID
)) {
2554 error(ERR_NONFATAL
, "`%s' expects a context identifier",
2556 free_tlist(origline
);
2557 return DIRECTIVE_FOUND
; /* but we did _something_ */
2560 error(ERR_WARNING
|ERR_PASS1
,
2561 "trailing garbage after `%s' ignored",
2563 p
= nasm_strdup(tline
->text
);
2565 p
= NULL
; /* Anonymous */
2569 ctx
= nasm_malloc(sizeof(Context
));
2571 hash_init(&ctx
->localmac
, HASH_SMALL
);
2573 ctx
->number
= unique
++;
2578 error(ERR_NONFATAL
, "`%s': context stack is empty",
2580 } else if (i
== PP_POP
) {
2581 if (p
&& (!cstk
->name
|| nasm_stricmp(p
, cstk
->name
)))
2582 error(ERR_NONFATAL
, "`%%pop' in wrong context: %s, "
2584 cstk
->name
? cstk
->name
: "anonymous", p
);
2589 nasm_free(cstk
->name
);
2595 free_tlist(origline
);
2596 return DIRECTIVE_FOUND
;
2598 severity
= ERR_FATAL
;
2601 severity
= ERR_NONFATAL
;
2604 severity
= ERR_WARNING
|ERR_WARN_USER
;
2609 /* Only error out if this is the final pass */
2610 if (pass
!= 2 && i
!= PP_FATAL
)
2611 return DIRECTIVE_FOUND
;
2613 tline
->next
= expand_smacro(tline
->next
);
2614 tline
= tline
->next
;
2616 t
= tline
? tline
->next
: NULL
;
2618 if (tok_type_(tline
, TOK_STRING
) && !t
) {
2619 /* The line contains only a quoted string */
2621 nasm_unquote(p
, NULL
); /* Ignore NUL character truncation */
2622 error(severity
, "%s", p
);
2624 /* Not a quoted string, or more than a quoted string */
2625 p
= detoken(tline
, false);
2626 error(severity
, "%s", p
);
2629 free_tlist(origline
);
2630 return DIRECTIVE_FOUND
;
2634 if (istk
->conds
&& !emitting(istk
->conds
->state
))
2637 j
= if_condition(tline
->next
, i
);
2638 tline
->next
= NULL
; /* it got freed */
2639 j
= j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2641 cond
= nasm_malloc(sizeof(Cond
));
2642 cond
->next
= istk
->conds
;
2646 istk
->mstk
->condcnt
++;
2647 free_tlist(origline
);
2648 return DIRECTIVE_FOUND
;
2652 error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2653 switch(istk
->conds
->state
) {
2655 istk
->conds
->state
= COND_DONE
;
2662 case COND_ELSE_TRUE
:
2663 case COND_ELSE_FALSE
:
2664 error_precond(ERR_WARNING
|ERR_PASS1
,
2665 "`%%elif' after `%%else' ignored");
2666 istk
->conds
->state
= COND_NEVER
;
2671 * IMPORTANT: In the case of %if, we will already have
2672 * called expand_mmac_params(); however, if we're
2673 * processing an %elif we must have been in a
2674 * non-emitting mode, which would have inhibited
2675 * the normal invocation of expand_mmac_params().
2676 * Therefore, we have to do it explicitly here.
2678 j
= if_condition(expand_mmac_params(tline
->next
), i
);
2679 tline
->next
= NULL
; /* it got freed */
2680 istk
->conds
->state
=
2681 j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2684 free_tlist(origline
);
2685 return DIRECTIVE_FOUND
;
2689 error_precond(ERR_WARNING
|ERR_PASS1
,
2690 "trailing garbage after `%%else' ignored");
2692 error(ERR_FATAL
, "`%%else': no matching `%%if'");
2693 switch(istk
->conds
->state
) {
2696 istk
->conds
->state
= COND_ELSE_FALSE
;
2703 istk
->conds
->state
= COND_ELSE_TRUE
;
2706 case COND_ELSE_TRUE
:
2707 case COND_ELSE_FALSE
:
2708 error_precond(ERR_WARNING
|ERR_PASS1
,
2709 "`%%else' after `%%else' ignored.");
2710 istk
->conds
->state
= COND_NEVER
;
2713 free_tlist(origline
);
2714 return DIRECTIVE_FOUND
;
2718 error_precond(ERR_WARNING
|ERR_PASS1
,
2719 "trailing garbage after `%%endif' ignored");
2721 error(ERR_FATAL
, "`%%endif': no matching `%%if'");
2723 istk
->conds
= cond
->next
;
2726 istk
->mstk
->condcnt
--;
2727 free_tlist(origline
);
2728 return DIRECTIVE_FOUND
;
2735 error(ERR_FATAL
, "`%s': already defining a macro",
2737 return DIRECTIVE_FOUND
;
2739 defining
= nasm_malloc(sizeof(MMacro
));
2740 defining
->max_depth
=
2741 (i
== PP_RMACRO
) || (i
== PP_IRMACRO
) ? DEADMAN_LIMIT
: 0;
2742 defining
->casesense
= (i
== PP_MACRO
) || (i
== PP_RMACRO
);
2743 if (!parse_mmacro_spec(tline
, defining
, pp_directives
[i
])) {
2744 nasm_free(defining
);
2746 return DIRECTIVE_FOUND
;
2749 mmac
= (MMacro
*) hash_findix(&mmacros
, defining
->name
);
2751 if (!strcmp(mmac
->name
, defining
->name
) &&
2752 (mmac
->nparam_min
<= defining
->nparam_max
2754 && (defining
->nparam_min
<= mmac
->nparam_max
2756 error(ERR_WARNING
|ERR_PASS1
,
2757 "redefining multi-line macro `%s'", defining
->name
);
2758 return DIRECTIVE_FOUND
;
2762 free_tlist(origline
);
2763 return DIRECTIVE_FOUND
;
2767 if (! (defining
&& defining
->name
)) {
2768 error(ERR_NONFATAL
, "`%s': not defining a macro", tline
->text
);
2769 return DIRECTIVE_FOUND
;
2771 mmhead
= (MMacro
**) hash_findi_add(&mmacros
, defining
->name
);
2772 defining
->next
= *mmhead
;
2775 free_tlist(origline
);
2776 return DIRECTIVE_FOUND
;
2780 * We must search along istk->expansion until we hit a
2781 * macro-end marker for a macro with a name. Then we
2782 * bypass all lines between exitmacro and endmacro.
2784 list_for_each(l
, istk
->expansion
)
2785 if (l
->finishes
&& l
->finishes
->name
)
2790 * Remove all conditional entries relative to this
2791 * macro invocation. (safe to do in this context)
2793 for ( ; l
->finishes
->condcnt
> 0; l
->finishes
->condcnt
--) {
2795 istk
->conds
= cond
->next
;
2798 istk
->expansion
= l
;
2800 error(ERR_NONFATAL
, "`%%exitmacro' not within `%%macro' block");
2802 free_tlist(origline
);
2803 return DIRECTIVE_FOUND
;
2811 spec
.casesense
= (i
== PP_UNMACRO
);
2812 if (!parse_mmacro_spec(tline
, &spec
, pp_directives
[i
])) {
2813 return DIRECTIVE_FOUND
;
2815 mmac_p
= (MMacro
**) hash_findi(&mmacros
, spec
.name
, NULL
);
2816 while (mmac_p
&& *mmac_p
) {
2818 if (mmac
->casesense
== spec
.casesense
&&
2819 !mstrcmp(mmac
->name
, spec
.name
, spec
.casesense
) &&
2820 mmac
->nparam_min
== spec
.nparam_min
&&
2821 mmac
->nparam_max
== spec
.nparam_max
&&
2822 mmac
->plus
== spec
.plus
) {
2823 *mmac_p
= mmac
->next
;
2826 mmac_p
= &mmac
->next
;
2829 free_tlist(origline
);
2830 free_tlist(spec
.dlist
);
2831 return DIRECTIVE_FOUND
;
2835 if (tline
->next
&& tline
->next
->type
== TOK_WHITESPACE
)
2836 tline
= tline
->next
;
2838 free_tlist(origline
);
2839 error(ERR_NONFATAL
, "`%%rotate' missing rotate count");
2840 return DIRECTIVE_FOUND
;
2842 t
= expand_smacro(tline
->next
);
2844 free_tlist(origline
);
2847 tokval
.t_type
= TOKEN_INVALID
;
2849 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2852 return DIRECTIVE_FOUND
;
2854 error(ERR_WARNING
|ERR_PASS1
,
2855 "trailing garbage after expression ignored");
2856 if (!is_simple(evalresult
)) {
2857 error(ERR_NONFATAL
, "non-constant value given to `%%rotate'");
2858 return DIRECTIVE_FOUND
;
2861 while (mmac
&& !mmac
->name
) /* avoid mistaking %reps for macros */
2862 mmac
= mmac
->next_active
;
2864 error(ERR_NONFATAL
, "`%%rotate' invoked outside a macro call");
2865 } else if (mmac
->nparam
== 0) {
2867 "`%%rotate' invoked within macro without parameters");
2869 int rotate
= mmac
->rotate
+ reloc_value(evalresult
);
2871 rotate
%= (int)mmac
->nparam
;
2873 rotate
+= mmac
->nparam
;
2875 mmac
->rotate
= rotate
;
2877 return DIRECTIVE_FOUND
;
2882 tline
= tline
->next
;
2883 } while (tok_type_(tline
, TOK_WHITESPACE
));
2885 if (tok_type_(tline
, TOK_ID
) &&
2886 nasm_stricmp(tline
->text
, ".nolist") == 0) {
2889 tline
= tline
->next
;
2890 } while (tok_type_(tline
, TOK_WHITESPACE
));
2894 t
= expand_smacro(tline
);
2896 tokval
.t_type
= TOKEN_INVALID
;
2898 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
2900 free_tlist(origline
);
2901 return DIRECTIVE_FOUND
;
2904 error(ERR_WARNING
|ERR_PASS1
,
2905 "trailing garbage after expression ignored");
2906 if (!is_simple(evalresult
)) {
2907 error(ERR_NONFATAL
, "non-constant value given to `%%rep'");
2908 return DIRECTIVE_FOUND
;
2910 count
= reloc_value(evalresult
);
2911 if (count
>= REP_LIMIT
) {
2912 error(ERR_NONFATAL
, "`%%rep' value exceeds limit");
2917 error(ERR_NONFATAL
, "`%%rep' expects a repeat count");
2920 free_tlist(origline
);
2922 tmp_defining
= defining
;
2923 defining
= nasm_malloc(sizeof(MMacro
));
2924 defining
->prev
= NULL
;
2925 defining
->name
= NULL
; /* flags this macro as a %rep block */
2926 defining
->casesense
= false;
2927 defining
->plus
= false;
2928 defining
->nolist
= nolist
;
2929 defining
->in_progress
= count
;
2930 defining
->max_depth
= 0;
2931 defining
->nparam_min
= defining
->nparam_max
= 0;
2932 defining
->defaults
= NULL
;
2933 defining
->dlist
= NULL
;
2934 defining
->expansion
= NULL
;
2935 defining
->next_active
= istk
->mstk
;
2936 defining
->rep_nest
= tmp_defining
;
2937 return DIRECTIVE_FOUND
;
2940 if (!defining
|| defining
->name
) {
2941 error(ERR_NONFATAL
, "`%%endrep': no matching `%%rep'");
2942 return DIRECTIVE_FOUND
;
2946 * Now we have a "macro" defined - although it has no name
2947 * and we won't be entering it in the hash tables - we must
2948 * push a macro-end marker for it on to istk->expansion.
2949 * After that, it will take care of propagating itself (a
2950 * macro-end marker line for a macro which is really a %rep
2951 * block will cause the macro to be re-expanded, complete
2952 * with another macro-end marker to ensure the process
2953 * continues) until the whole expansion is forcibly removed
2954 * from istk->expansion by a %exitrep.
2956 l
= nasm_malloc(sizeof(Line
));
2957 l
->next
= istk
->expansion
;
2958 l
->finishes
= defining
;
2960 istk
->expansion
= l
;
2962 istk
->mstk
= defining
;
2964 list
->uplevel(defining
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
2965 tmp_defining
= defining
;
2966 defining
= defining
->rep_nest
;
2967 free_tlist(origline
);
2968 return DIRECTIVE_FOUND
;
2972 * We must search along istk->expansion until we hit a
2973 * macro-end marker for a macro with no name. Then we set
2974 * its `in_progress' flag to 0.
2976 list_for_each(l
, istk
->expansion
)
2977 if (l
->finishes
&& !l
->finishes
->name
)
2981 l
->finishes
->in_progress
= 1;
2983 error(ERR_NONFATAL
, "`%%exitrep' not within `%%rep' block");
2984 free_tlist(origline
);
2985 return DIRECTIVE_FOUND
;
2991 casesense
= (i
== PP_DEFINE
|| i
== PP_XDEFINE
);
2993 tline
= tline
->next
;
2995 tline
= expand_id(tline
);
2996 if (!tline
|| (tline
->type
!= TOK_ID
&&
2997 (tline
->type
!= TOK_PREPROC_ID
||
2998 tline
->text
[1] != '$'))) {
2999 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3001 free_tlist(origline
);
3002 return DIRECTIVE_FOUND
;
3005 ctx
= get_ctx(tline
->text
, &mname
);
3007 param_start
= tline
= tline
->next
;
3010 /* Expand the macro definition now for %xdefine and %ixdefine */
3011 if ((i
== PP_XDEFINE
) || (i
== PP_IXDEFINE
))
3012 tline
= expand_smacro(tline
);
3014 if (tok_is_(tline
, "(")) {
3016 * This macro has parameters.
3019 tline
= tline
->next
;
3023 error(ERR_NONFATAL
, "parameter identifier expected");
3024 free_tlist(origline
);
3025 return DIRECTIVE_FOUND
;
3027 if (tline
->type
!= TOK_ID
) {
3029 "`%s': parameter identifier expected",
3031 free_tlist(origline
);
3032 return DIRECTIVE_FOUND
;
3034 tline
->type
= TOK_SMAC_PARAM
+ nparam
++;
3035 tline
= tline
->next
;
3037 if (tok_is_(tline
, ",")) {
3038 tline
= tline
->next
;
3040 if (!tok_is_(tline
, ")")) {
3042 "`)' expected to terminate macro template");
3043 free_tlist(origline
);
3044 return DIRECTIVE_FOUND
;
3050 tline
= tline
->next
;
3052 if (tok_type_(tline
, TOK_WHITESPACE
))
3053 last
= tline
, tline
= tline
->next
;
3058 if (t
->type
== TOK_ID
) {
3059 list_for_each(tt
, param_start
)
3060 if (tt
->type
>= TOK_SMAC_PARAM
&&
3061 !strcmp(tt
->text
, t
->text
))
3065 t
->next
= macro_start
;
3070 * Good. We now have a macro name, a parameter count, and a
3071 * token list (in reverse order) for an expansion. We ought
3072 * to be OK just to create an SMacro, store it, and let
3073 * free_tlist have the rest of the line (which we have
3074 * carefully re-terminated after chopping off the expansion
3077 define_smacro(ctx
, mname
, casesense
, nparam
, macro_start
);
3078 free_tlist(origline
);
3079 return DIRECTIVE_FOUND
;
3082 tline
= tline
->next
;
3084 tline
= expand_id(tline
);
3085 if (!tline
|| (tline
->type
!= TOK_ID
&&
3086 (tline
->type
!= TOK_PREPROC_ID
||
3087 tline
->text
[1] != '$'))) {
3088 error(ERR_NONFATAL
, "`%%undef' expects a macro identifier");
3089 free_tlist(origline
);
3090 return DIRECTIVE_FOUND
;
3093 error(ERR_WARNING
|ERR_PASS1
,
3094 "trailing garbage after macro name ignored");
3097 /* Find the context that symbol belongs to */
3098 ctx
= get_ctx(tline
->text
, &mname
);
3099 undef_smacro(ctx
, mname
);
3100 free_tlist(origline
);
3101 return DIRECTIVE_FOUND
;
3105 casesense
= (i
== PP_DEFSTR
);
3107 tline
= tline
->next
;
3109 tline
= expand_id(tline
);
3110 if (!tline
|| (tline
->type
!= TOK_ID
&&
3111 (tline
->type
!= TOK_PREPROC_ID
||
3112 tline
->text
[1] != '$'))) {
3113 error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3115 free_tlist(origline
);
3116 return DIRECTIVE_FOUND
;
3119 ctx
= get_ctx(tline
->text
, &mname
);
3121 tline
= expand_smacro(tline
->next
);
3124 while (tok_type_(tline
, TOK_WHITESPACE
))
3125 tline
= delete_Token(tline
);
3127 p
= detoken(tline
, false);
3128 macro_start
= nasm_malloc(sizeof(*macro_start
));
3129 macro_start
->next
= NULL
;
3130 macro_start
->text
= nasm_quote(p
, strlen(p
));
3131 macro_start
->type
= TOK_STRING
;
3132 macro_start
->a
.mac
= NULL
;
3136 * We now have a macro name, an implicit parameter count of
3137 * zero, and a string token to use as an expansion. Create
3138 * and store an SMacro.
3140 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3141 free_tlist(origline
);
3142 return DIRECTIVE_FOUND
;
3146 casesense
= (i
== PP_DEFTOK
);
3148 tline
= tline
->next
;
3150 tline
= expand_id(tline
);
3151 if (!tline
|| (tline
->type
!= TOK_ID
&&
3152 (tline
->type
!= TOK_PREPROC_ID
||
3153 tline
->text
[1] != '$'))) {
3155 "`%s' expects a macro identifier as first parameter",
3157 free_tlist(origline
);
3158 return DIRECTIVE_FOUND
;
3160 ctx
= get_ctx(tline
->text
, &mname
);
3162 tline
= expand_smacro(tline
->next
);
3166 while (tok_type_(t
, TOK_WHITESPACE
))
3168 /* t should now point to the string */
3169 if (!tok_type_(t
, TOK_STRING
)) {
3171 "`%s` requires string as second parameter",
3174 free_tlist(origline
);
3175 return DIRECTIVE_FOUND
;
3179 * Convert the string to a token stream. Note that smacros
3180 * are stored with the token stream reversed, so we have to
3181 * reverse the output of tokenize().
3183 nasm_unquote_cstr(t
->text
, i
);
3184 macro_start
= reverse_tokens(tokenize(t
->text
));
3187 * We now have a macro name, an implicit parameter count of
3188 * zero, and a numeric token to use as an expansion. Create
3189 * and store an SMacro.
3191 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3193 free_tlist(origline
);
3194 return DIRECTIVE_FOUND
;
3199 StrList
*xsl
= NULL
;
3200 StrList
**xst
= &xsl
;
3204 tline
= tline
->next
;
3206 tline
= expand_id(tline
);
3207 if (!tline
|| (tline
->type
!= TOK_ID
&&
3208 (tline
->type
!= TOK_PREPROC_ID
||
3209 tline
->text
[1] != '$'))) {
3211 "`%%pathsearch' expects a macro identifier as first parameter");
3212 free_tlist(origline
);
3213 return DIRECTIVE_FOUND
;
3215 ctx
= get_ctx(tline
->text
, &mname
);
3217 tline
= expand_smacro(tline
->next
);
3221 while (tok_type_(t
, TOK_WHITESPACE
))
3224 if (!t
|| (t
->type
!= TOK_STRING
&&
3225 t
->type
!= TOK_INTERNAL_STRING
)) {
3226 error(ERR_NONFATAL
, "`%%pathsearch' expects a file name");
3228 free_tlist(origline
);
3229 return DIRECTIVE_FOUND
; /* but we did _something_ */
3232 error(ERR_WARNING
|ERR_PASS1
,
3233 "trailing garbage after `%%pathsearch' ignored");
3235 if (t
->type
!= TOK_INTERNAL_STRING
)
3236 nasm_unquote(p
, NULL
);
3238 fp
= inc_fopen(p
, &xsl
, &xst
, true);
3241 fclose(fp
); /* Don't actually care about the file */
3243 macro_start
= nasm_malloc(sizeof(*macro_start
));
3244 macro_start
->next
= NULL
;
3245 macro_start
->text
= nasm_quote(p
, strlen(p
));
3246 macro_start
->type
= TOK_STRING
;
3247 macro_start
->a
.mac
= NULL
;
3252 * We now have a macro name, an implicit parameter count of
3253 * zero, and a string token to use as an expansion. Create
3254 * and store an SMacro.
3256 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3258 free_tlist(origline
);
3259 return DIRECTIVE_FOUND
;
3265 tline
= tline
->next
;
3267 tline
= expand_id(tline
);
3268 if (!tline
|| (tline
->type
!= TOK_ID
&&
3269 (tline
->type
!= TOK_PREPROC_ID
||
3270 tline
->text
[1] != '$'))) {
3272 "`%%strlen' expects a macro identifier as first parameter");
3273 free_tlist(origline
);
3274 return DIRECTIVE_FOUND
;
3276 ctx
= get_ctx(tline
->text
, &mname
);
3278 tline
= expand_smacro(tline
->next
);
3282 while (tok_type_(t
, TOK_WHITESPACE
))
3284 /* t should now point to the string */
3285 if (!tok_type_(t
, TOK_STRING
)) {
3287 "`%%strlen` requires string as second parameter");
3289 free_tlist(origline
);
3290 return DIRECTIVE_FOUND
;
3293 macro_start
= nasm_malloc(sizeof(*macro_start
));
3294 macro_start
->next
= NULL
;
3295 make_tok_num(macro_start
, nasm_unquote(t
->text
, NULL
));
3296 macro_start
->a
.mac
= NULL
;
3299 * We now have a macro name, an implicit parameter count of
3300 * zero, and a numeric token to use as an expansion. Create
3301 * and store an SMacro.
3303 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3305 free_tlist(origline
);
3306 return DIRECTIVE_FOUND
;
3311 tline
= tline
->next
;
3313 tline
= expand_id(tline
);
3314 if (!tline
|| (tline
->type
!= TOK_ID
&&
3315 (tline
->type
!= TOK_PREPROC_ID
||
3316 tline
->text
[1] != '$'))) {
3318 "`%%strcat' expects a macro identifier as first parameter");
3319 free_tlist(origline
);
3320 return DIRECTIVE_FOUND
;
3322 ctx
= get_ctx(tline
->text
, &mname
);
3324 tline
= expand_smacro(tline
->next
);
3328 list_for_each(t
, tline
) {
3330 case TOK_WHITESPACE
:
3333 len
+= t
->a
.len
= nasm_unquote(t
->text
, NULL
);
3336 if (!strcmp(t
->text
, ",")) /* permit comma separators */
3338 /* else fall through */
3341 "non-string passed to `%%strcat' (%d)", t
->type
);
3343 free_tlist(origline
);
3344 return DIRECTIVE_FOUND
;
3348 p
= pp
= nasm_malloc(len
);
3349 list_for_each(t
, tline
) {
3350 if (t
->type
== TOK_STRING
) {
3351 memcpy(p
, t
->text
, t
->a
.len
);
3357 * We now have a macro name, an implicit parameter count of
3358 * zero, and a numeric token to use as an expansion. Create
3359 * and store an SMacro.
3361 macro_start
= new_Token(NULL
, TOK_STRING
, NULL
, 0);
3362 macro_start
->text
= nasm_quote(pp
, len
);
3364 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3366 free_tlist(origline
);
3367 return DIRECTIVE_FOUND
;
3371 int64_t start
, count
;
3376 tline
= tline
->next
;
3378 tline
= expand_id(tline
);
3379 if (!tline
|| (tline
->type
!= TOK_ID
&&
3380 (tline
->type
!= TOK_PREPROC_ID
||
3381 tline
->text
[1] != '$'))) {
3383 "`%%substr' expects a macro identifier as first parameter");
3384 free_tlist(origline
);
3385 return DIRECTIVE_FOUND
;
3387 ctx
= get_ctx(tline
->text
, &mname
);
3389 tline
= expand_smacro(tline
->next
);
3392 if (tline
) /* skip expanded id */
3394 while (tok_type_(t
, TOK_WHITESPACE
))
3397 /* t should now point to the string */
3398 if (!tok_type_(t
, TOK_STRING
)) {
3400 "`%%substr` requires string as second parameter");
3402 free_tlist(origline
);
3403 return DIRECTIVE_FOUND
;
3408 tokval
.t_type
= TOKEN_INVALID
;
3409 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3413 free_tlist(origline
);
3414 return DIRECTIVE_FOUND
;
3415 } else if (!is_simple(evalresult
)) {
3416 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3418 free_tlist(origline
);
3419 return DIRECTIVE_FOUND
;
3421 start
= evalresult
->value
- 1;
3423 while (tok_type_(tt
, TOK_WHITESPACE
))
3426 count
= 1; /* Backwards compatibility: one character */
3428 tokval
.t_type
= TOKEN_INVALID
;
3429 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
,
3433 free_tlist(origline
);
3434 return DIRECTIVE_FOUND
;
3435 } else if (!is_simple(evalresult
)) {
3436 error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3438 free_tlist(origline
);
3439 return DIRECTIVE_FOUND
;
3441 count
= evalresult
->value
;
3444 len
= nasm_unquote(t
->text
, NULL
);
3446 /* make start and count being in range */
3450 count
= len
+ count
+ 1 - start
;
3451 if (start
+ count
> (int64_t)len
)
3452 count
= len
- start
;
3453 if (!len
|| count
< 0 || start
>=(int64_t)len
)
3454 start
= -1, count
= 0; /* empty string */
3456 macro_start
= nasm_malloc(sizeof(*macro_start
));
3457 macro_start
->next
= NULL
;
3458 macro_start
->text
= nasm_quote((start
< 0) ? "" : t
->text
+ start
, count
);
3459 macro_start
->type
= TOK_STRING
;
3460 macro_start
->a
.mac
= NULL
;
3463 * We now have a macro name, an implicit parameter count of
3464 * zero, and a numeric token to use as an expansion. Create
3465 * and store an SMacro.
3467 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3469 free_tlist(origline
);
3470 return DIRECTIVE_FOUND
;
3475 casesense
= (i
== PP_ASSIGN
);
3477 tline
= tline
->next
;
3479 tline
= expand_id(tline
);
3480 if (!tline
|| (tline
->type
!= TOK_ID
&&
3481 (tline
->type
!= TOK_PREPROC_ID
||
3482 tline
->text
[1] != '$'))) {
3484 "`%%%sassign' expects a macro identifier",
3485 (i
== PP_IASSIGN
? "i" : ""));
3486 free_tlist(origline
);
3487 return DIRECTIVE_FOUND
;
3489 ctx
= get_ctx(tline
->text
, &mname
);
3491 tline
= expand_smacro(tline
->next
);
3496 tokval
.t_type
= TOKEN_INVALID
;
3498 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, error
, NULL
);
3501 free_tlist(origline
);
3502 return DIRECTIVE_FOUND
;
3506 error(ERR_WARNING
|ERR_PASS1
,
3507 "trailing garbage after expression ignored");
3509 if (!is_simple(evalresult
)) {
3511 "non-constant value given to `%%%sassign'",
3512 (i
== PP_IASSIGN
? "i" : ""));
3513 free_tlist(origline
);
3514 return DIRECTIVE_FOUND
;
3517 macro_start
= nasm_malloc(sizeof(*macro_start
));
3518 macro_start
->next
= NULL
;
3519 make_tok_num(macro_start
, reloc_value(evalresult
));
3520 macro_start
->a
.mac
= NULL
;
3523 * We now have a macro name, an implicit parameter count of
3524 * zero, and a numeric token to use as an expansion. Create
3525 * and store an SMacro.
3527 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3528 free_tlist(origline
);
3529 return DIRECTIVE_FOUND
;
3533 * Syntax is `%line nnn[+mmm] [filename]'
3535 tline
= tline
->next
;
3537 if (!tok_type_(tline
, TOK_NUMBER
)) {
3538 error(ERR_NONFATAL
, "`%%line' expects line number");
3539 free_tlist(origline
);
3540 return DIRECTIVE_FOUND
;
3542 k
= readnum(tline
->text
, &err
);
3544 tline
= tline
->next
;
3545 if (tok_is_(tline
, "+")) {
3546 tline
= tline
->next
;
3547 if (!tok_type_(tline
, TOK_NUMBER
)) {
3548 error(ERR_NONFATAL
, "`%%line' expects line increment");
3549 free_tlist(origline
);
3550 return DIRECTIVE_FOUND
;
3552 m
= readnum(tline
->text
, &err
);
3553 tline
= tline
->next
;
3559 nasm_free(src_set_fname(detoken(tline
, false)));
3561 free_tlist(origline
);
3562 return DIRECTIVE_FOUND
;
3566 "preprocessor directive `%s' not yet implemented",
3568 return DIRECTIVE_FOUND
;
3573 * Ensure that a macro parameter contains a condition code and
3574 * nothing else. Return the condition code index if so, or -1
3577 static int find_cc(Token
* t
)
3582 return -1; /* Probably a %+ without a space */
3585 if (t
->type
!= TOK_ID
)
3589 if (tt
&& (tt
->type
!= TOK_OTHER
|| strcmp(tt
->text
, ",")))
3592 return bsii(t
->text
, (const char **)conditions
, ARRAY_SIZE(conditions
));
3596 * This routines walks over tokens strem and hadnles tokens
3597 * pasting, if @handle_explicit passed then explicit pasting
3598 * term is handled, otherwise -- implicit pastings only.
3600 static bool paste_tokens(Token
**head
, const struct tokseq_match
*m
,
3601 size_t mnum
, bool handle_explicit
)
3603 Token
*tok
, *next
, **prev_next
, **prev_nonspace
;
3604 bool pasted
= false;
3609 * The last token before pasting. We need it
3610 * to be able to connect new handled tokens.
3611 * In other words if there were a tokens stream
3615 * and we've joined tokens B and C, the resulting
3623 if (!tok_type_(tok
, TOK_WHITESPACE
) && !tok_type_(tok
, TOK_PASTE
))
3624 prev_nonspace
= head
;
3626 prev_nonspace
= NULL
;
3628 while (tok
&& (next
= tok
->next
)) {
3630 switch (tok
->type
) {
3631 case TOK_WHITESPACE
:
3632 /* Zap redundant whitespaces */
3633 while (tok_type_(next
, TOK_WHITESPACE
))
3634 next
= delete_Token(next
);
3639 /* Explicit pasting */
3640 if (!handle_explicit
)
3642 next
= delete_Token(tok
);
3644 while (tok_type_(next
, TOK_WHITESPACE
))
3645 next
= delete_Token(next
);
3650 /* Left pasting token is start of line */
3652 error(ERR_FATAL
, "No lvalue found on pasting");
3655 * No ending token, this might happen in two
3658 * 1) There indeed no right token at all
3659 * 2) There is a bare "%define ID" statement,
3660 * and @ID does expand to whitespace.
3662 * So technically we need to do a grammar analysis
3663 * in another stage of parsing, but for now lets don't
3664 * change the behaviour people used to. Simply allow
3665 * whitespace after paste token.
3669 * Zap ending space tokens and that's all.
3671 tok
= (*prev_nonspace
)->next
;
3672 while (tok_type_(tok
, TOK_WHITESPACE
))
3673 tok
= delete_Token(tok
);
3674 tok
= *prev_nonspace
;
3679 tok
= *prev_nonspace
;
3680 while (tok_type_(tok
, TOK_WHITESPACE
))
3681 tok
= delete_Token(tok
);
3682 len
= strlen(tok
->text
);
3683 len
+= strlen(next
->text
);
3685 p
= buf
= nasm_malloc(len
+ 1);
3686 strcpy(p
, tok
->text
);
3687 p
= strchr(p
, '\0');
3688 strcpy(p
, next
->text
);
3692 tok
= tokenize(buf
);
3695 *prev_nonspace
= tok
;
3696 while (tok
&& tok
->next
)
3699 tok
->next
= delete_Token(next
);
3701 /* Restart from pasted tokens head */
3702 tok
= *prev_nonspace
;
3706 /* implicit pasting */
3707 for (i
= 0; i
< mnum
; i
++) {
3708 if (!(PP_CONCAT_MATCH(tok
, m
[i
].mask_head
)))
3712 while (next
&& PP_CONCAT_MATCH(next
, m
[i
].mask_tail
)) {
3713 len
+= strlen(next
->text
);
3721 len
+= strlen(tok
->text
);
3722 p
= buf
= nasm_malloc(len
+ 1);
3724 while (tok
!= next
) {
3725 strcpy(p
, tok
->text
);
3726 p
= strchr(p
, '\0');
3727 tok
= delete_Token(tok
);
3730 tok
= tokenize(buf
);
3739 * Connect pasted into original stream,
3740 * ie A -> new-tokens -> B
3742 while (tok
&& tok
->next
)
3749 /* Restart from pasted tokens head */
3750 tok
= prev_next
? *prev_next
: *head
;
3756 prev_next
= &tok
->next
;
3759 !tok_type_(tok
->next
, TOK_WHITESPACE
) &&
3760 !tok_type_(tok
->next
, TOK_PASTE
))
3761 prev_nonspace
= prev_next
;
3770 * expands to a list of tokens from %{x:y}
3772 static Token
*expand_mmac_params_range(MMacro
*mac
, Token
*tline
, Token
***last
)
3774 Token
*t
= tline
, **tt
, *tm
, *head
;
3778 pos
= strchr(tline
->text
, ':');
3781 lst
= atoi(pos
+ 1);
3782 fst
= atoi(tline
->text
+ 1);
3785 * only macros params are accounted so
3786 * if someone passes %0 -- we reject such
3789 if (lst
== 0 || fst
== 0)
3792 /* the values should be sane */
3793 if ((fst
> (int)mac
->nparam
|| fst
< (-(int)mac
->nparam
)) ||
3794 (lst
> (int)mac
->nparam
|| lst
< (-(int)mac
->nparam
)))
3797 fst
= fst
< 0 ? fst
+ (int)mac
->nparam
+ 1: fst
;
3798 lst
= lst
< 0 ? lst
+ (int)mac
->nparam
+ 1: lst
;
3800 /* counted from zero */
3804 * It will be at least one token. Note we
3805 * need to scan params until separator, otherwise
3806 * only first token will be passed.
3808 tm
= mac
->params
[(fst
+ mac
->rotate
) % mac
->nparam
];
3809 head
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3810 tt
= &head
->next
, tm
= tm
->next
;
3811 while (tok_isnt_(tm
, ",")) {
3812 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3813 *tt
= t
, tt
= &t
->next
, tm
= tm
->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 while (tok_isnt_(tm
, ",")) {
3823 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3824 *tt
= t
, tt
= &t
->next
, tm
= tm
->next
;
3828 for (i
= fst
- 1; i
>= lst
; i
--) {
3829 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3830 *tt
= t
, tt
= &t
->next
;
3831 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3832 tm
= mac
->params
[j
];
3833 while (tok_isnt_(tm
, ",")) {
3834 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3835 *tt
= t
, tt
= &t
->next
, tm
= tm
->next
;
3844 error(ERR_NONFATAL
, "`%%{%s}': macro parameters out of range",
3850 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3851 * %-n) and MMacro-local identifiers (%%foo) as well as
3852 * macro indirection (%[...]) and range (%{..:..}).
3854 static Token
*expand_mmac_params(Token
* tline
)
3856 Token
*t
, *tt
, **tail
, *thead
;
3857 bool changed
= false;
3864 if (tline
->type
== TOK_PREPROC_ID
&&
3865 (((tline
->text
[1] == '+' || tline
->text
[1] == '-') && tline
->text
[2]) ||
3866 (tline
->text
[1] >= '0' && tline
->text
[1] <= '9') ||
3867 tline
->text
[1] == '%')) {
3869 int type
= 0, cc
; /* type = 0 to placate optimisers */
3876 tline
= tline
->next
;
3879 while (mac
&& !mac
->name
) /* avoid mistaking %reps for macros */
3880 mac
= mac
->next_active
;
3882 error(ERR_NONFATAL
, "`%s': not in a macro call", t
->text
);
3884 pos
= strchr(t
->text
, ':');
3886 switch (t
->text
[1]) {
3888 * We have to make a substitution of one of the
3889 * forms %1, %-1, %+1, %%foo, %0.
3893 snprintf(tmpbuf
, sizeof(tmpbuf
), "%d", mac
->nparam
);
3894 text
= nasm_strdup(tmpbuf
);
3898 snprintf(tmpbuf
, sizeof(tmpbuf
), "..@%"PRIu64
".",
3900 text
= nasm_strcat(tmpbuf
, t
->text
+ 2);
3903 n
= atoi(t
->text
+ 2) - 1;
3904 if (n
>= mac
->nparam
)
3907 if (mac
->nparam
> 1)
3908 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3909 tt
= mac
->params
[n
];
3914 "macro parameter %d is not a condition code",
3919 if (inverse_ccs
[cc
] == -1) {
3921 "condition code `%s' is not invertible",
3925 text
= nasm_strdup(conditions
[inverse_ccs
[cc
]]);
3929 n
= atoi(t
->text
+ 2) - 1;
3930 if (n
>= mac
->nparam
)
3933 if (mac
->nparam
> 1)
3934 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3935 tt
= mac
->params
[n
];
3940 "macro parameter %d is not a condition code",
3945 text
= nasm_strdup(conditions
[cc
]);
3949 n
= atoi(t
->text
+ 1) - 1;
3950 if (n
>= mac
->nparam
)
3953 if (mac
->nparam
> 1)
3954 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3955 tt
= mac
->params
[n
];
3958 for (i
= 0; i
< mac
->paramlen
[n
]; i
++) {
3959 *tail
= new_Token(NULL
, tt
->type
, tt
->text
, 0);
3960 tail
= &(*tail
)->next
;
3964 text
= NULL
; /* we've done it here */
3969 * seems we have a parameters range here
3971 Token
*head
, **last
;
3972 head
= expand_mmac_params_range(mac
, t
, &last
);
3993 } else if (tline
->type
== TOK_INDIRECT
) {
3995 tline
= tline
->next
;
3996 tt
= tokenize(t
->text
);
3997 tt
= expand_mmac_params(tt
);
3998 tt
= expand_smacro(tt
);
4001 tt
->a
.mac
= NULL
; /* Necessary? */
4009 tline
= tline
->next
;
4017 const struct tokseq_match t
[] = {
4019 PP_CONCAT_MASK(TOK_ID
) |
4020 PP_CONCAT_MASK(TOK_FLOAT
), /* head */
4021 PP_CONCAT_MASK(TOK_ID
) |
4022 PP_CONCAT_MASK(TOK_NUMBER
) |
4023 PP_CONCAT_MASK(TOK_FLOAT
) |
4024 PP_CONCAT_MASK(TOK_OTHER
) /* tail */
4027 PP_CONCAT_MASK(TOK_NUMBER
), /* head */
4028 PP_CONCAT_MASK(TOK_NUMBER
) /* tail */
4031 paste_tokens(&thead
, t
, ARRAY_SIZE(t
), false);
4038 * Expand all single-line macro calls made in the given line.
4039 * Return the expanded version of the line. The original is deemed
4040 * to be destroyed in the process. (In reality we'll just move
4041 * Tokens from input to output a lot of the time, rather than
4042 * actually bothering to destroy and replicate.)
4045 static Token
*expand_smacro(Token
* tline
)
4047 Token
*t
, *tt
, *mstart
, **tail
, *thead
;
4048 SMacro
*head
= NULL
, *m
;
4051 unsigned int nparam
, sparam
;
4053 Token
*org_tline
= tline
;
4056 int deadman
= DEADMAN_LIMIT
;
4060 * Trick: we should avoid changing the start token pointer since it can
4061 * be contained in "next" field of other token. Because of this
4062 * we allocate a copy of first token and work with it; at the end of
4063 * routine we copy it back
4066 tline
= new_Token(org_tline
->next
, org_tline
->type
,
4067 org_tline
->text
, 0);
4068 tline
->a
.mac
= org_tline
->a
.mac
;
4069 nasm_free(org_tline
->text
);
4070 org_tline
->text
= NULL
;
4073 expanded
= true; /* Always expand %+ at least once */
4079 while (tline
) { /* main token loop */
4081 error(ERR_NONFATAL
, "interminable macro recursion");
4085 if ((mname
= tline
->text
)) {
4086 /* if this token is a local macro, look in local context */
4087 if (tline
->type
== TOK_ID
) {
4088 head
= (SMacro
*)hash_findix(&smacros
, mname
);
4089 } else if (tline
->type
== TOK_PREPROC_ID
) {
4090 ctx
= get_ctx(mname
, &mname
);
4091 head
= ctx
? (SMacro
*)hash_findix(&ctx
->localmac
, mname
) : NULL
;
4096 * We've hit an identifier. As in is_mmacro below, we first
4097 * check whether the identifier is a single-line macro at
4098 * all, then think about checking for parameters if
4101 list_for_each(m
, head
)
4102 if (!mstrcmp(m
->name
, mname
, m
->casesense
))
4108 if (m
->nparam
== 0) {
4110 * Simple case: the macro is parameterless. Discard the
4111 * one token that the macro call took, and push the
4112 * expansion back on the to-do stack.
4114 if (!m
->expansion
) {
4115 if (!strcmp("__FILE__", m
->name
)) {
4118 src_get(&num
, &file
);
4119 tline
->text
= nasm_quote(file
, strlen(file
));
4120 tline
->type
= TOK_STRING
;
4124 if (!strcmp("__LINE__", m
->name
)) {
4125 nasm_free(tline
->text
);
4126 make_tok_num(tline
, src_get_linnum());
4129 if (!strcmp("__BITS__", m
->name
)) {
4130 nasm_free(tline
->text
);
4131 make_tok_num(tline
, globalbits
);
4134 tline
= delete_Token(tline
);
4139 * Complicated case: at least one macro with this name
4140 * exists and takes parameters. We must find the
4141 * parameters in the call, count them, find the SMacro
4142 * that corresponds to that form of the macro call, and
4143 * substitute for the parameters when we expand. What a
4146 /*tline = tline->next;
4147 skip_white_(tline); */
4150 while (tok_type_(t
, TOK_SMAC_END
)) {
4151 t
->a
.mac
->in_progress
= false;
4153 t
= tline
->next
= delete_Token(t
);
4156 } while (tok_type_(tline
, TOK_WHITESPACE
));
4157 if (!tok_is_(tline
, "(")) {
4159 * This macro wasn't called with parameters: ignore
4160 * the call. (Behaviour borrowed from gnu cpp.)
4169 sparam
= PARAM_DELTA
;
4170 params
= nasm_malloc(sparam
* sizeof(Token
*));
4171 params
[0] = tline
->next
;
4172 paramsize
= nasm_malloc(sparam
* sizeof(int));
4174 while (true) { /* parameter loop */
4176 * For some unusual expansions
4177 * which concatenates function call
4180 while (tok_type_(t
, TOK_SMAC_END
)) {
4181 t
->a
.mac
->in_progress
= false;
4183 t
= tline
->next
= delete_Token(t
);
4189 "macro call expects terminating `)'");
4192 if (tline
->type
== TOK_WHITESPACE
4194 if (paramsize
[nparam
])
4197 params
[nparam
] = tline
->next
;
4198 continue; /* parameter loop */
4200 if (tline
->type
== TOK_OTHER
4201 && tline
->text
[1] == 0) {
4202 char ch
= tline
->text
[0];
4203 if (ch
== ',' && !paren
&& brackets
<= 0) {
4204 if (++nparam
>= sparam
) {
4205 sparam
+= PARAM_DELTA
;
4206 params
= nasm_realloc(params
,
4207 sparam
* sizeof(Token
*));
4208 paramsize
= nasm_realloc(paramsize
,
4209 sparam
* sizeof(int));
4211 params
[nparam
] = tline
->next
;
4212 paramsize
[nparam
] = 0;
4214 continue; /* parameter loop */
4217 (brackets
> 0 || (brackets
== 0 &&
4218 !paramsize
[nparam
])))
4220 if (!(brackets
++)) {
4221 params
[nparam
] = tline
->next
;
4222 continue; /* parameter loop */
4225 if (ch
== '}' && brackets
> 0)
4226 if (--brackets
== 0) {
4228 continue; /* parameter loop */
4230 if (ch
== '(' && !brackets
)
4232 if (ch
== ')' && brackets
<= 0)
4238 error(ERR_NONFATAL
, "braces do not "
4239 "enclose all of macro parameter");
4241 paramsize
[nparam
] += white
+ 1;
4243 } /* parameter loop */
4245 while (m
&& (m
->nparam
!= nparam
||
4246 mstrcmp(m
->name
, mname
,
4250 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4251 "macro `%s' exists, "
4252 "but not taking %d parameters",
4253 mstart
->text
, nparam
);
4256 if (m
&& m
->in_progress
)
4258 if (!m
) { /* in progess or didn't find '(' or wrong nparam */
4260 * Design question: should we handle !tline, which
4261 * indicates missing ')' here, or expand those
4262 * macros anyway, which requires the (t) test a few
4266 nasm_free(paramsize
);
4270 * Expand the macro: we are placed on the last token of the
4271 * call, so that we can easily split the call from the
4272 * following tokens. We also start by pushing an SMAC_END
4273 * token for the cycle removal.
4280 tt
= new_Token(tline
, TOK_SMAC_END
, NULL
, 0);
4282 m
->in_progress
= true;
4284 list_for_each(t
, m
->expansion
) {
4285 if (t
->type
>= TOK_SMAC_PARAM
) {
4286 Token
*pcopy
= tline
, **ptail
= &pcopy
;
4290 ttt
= params
[t
->type
- TOK_SMAC_PARAM
];
4291 i
= paramsize
[t
->type
- TOK_SMAC_PARAM
];
4293 pt
= *ptail
= new_Token(tline
, ttt
->type
,
4299 } else if (t
->type
== TOK_PREPROC_Q
) {
4300 tt
= new_Token(tline
, TOK_ID
, mname
, 0);
4302 } else if (t
->type
== TOK_PREPROC_QQ
) {
4303 tt
= new_Token(tline
, TOK_ID
, m
->name
, 0);
4306 tt
= new_Token(tline
, t
->type
, t
->text
, 0);
4312 * Having done that, get rid of the macro call, and clean
4313 * up the parameters.
4316 nasm_free(paramsize
);
4319 continue; /* main token loop */
4324 if (tline
->type
== TOK_SMAC_END
) {
4325 tline
->a
.mac
->in_progress
= false;
4326 tline
= delete_Token(tline
);
4329 tline
= tline
->next
;
4337 * Now scan the entire line and look for successive TOK_IDs that resulted
4338 * after expansion (they can't be produced by tokenize()). The successive
4339 * TOK_IDs should be concatenated.
4340 * Also we look for %+ tokens and concatenate the tokens before and after
4341 * them (without white spaces in between).
4344 const struct tokseq_match t
[] = {
4346 PP_CONCAT_MASK(TOK_ID
) |
4347 PP_CONCAT_MASK(TOK_PREPROC_ID
), /* head */
4348 PP_CONCAT_MASK(TOK_ID
) |
4349 PP_CONCAT_MASK(TOK_PREPROC_ID
) |
4350 PP_CONCAT_MASK(TOK_NUMBER
) /* tail */
4353 if (paste_tokens(&thead
, t
, ARRAY_SIZE(t
), true)) {
4355 * If we concatenated something, *and* we had previously expanded
4356 * an actual macro, scan the lines again for macros...
4367 *org_tline
= *thead
;
4368 /* since we just gave text to org_line, don't free it */
4370 delete_Token(thead
);
4372 /* the expression expanded to empty line;
4373 we can't return NULL for some reasons
4374 we just set the line to a single WHITESPACE token. */
4375 memset(org_tline
, 0, sizeof(*org_tline
));
4376 org_tline
->text
= NULL
;
4377 org_tline
->type
= TOK_WHITESPACE
;
4386 * Similar to expand_smacro but used exclusively with macro identifiers
4387 * right before they are fetched in. The reason is that there can be
4388 * identifiers consisting of several subparts. We consider that if there
4389 * are more than one element forming the name, user wants a expansion,
4390 * otherwise it will be left as-is. Example:
4394 * the identifier %$abc will be left as-is so that the handler for %define
4395 * will suck it and define the corresponding value. Other case:
4397 * %define _%$abc cde
4399 * In this case user wants name to be expanded *before* %define starts
4400 * working, so we'll expand %$abc into something (if it has a value;
4401 * otherwise it will be left as-is) then concatenate all successive
4404 static Token
*expand_id(Token
* tline
)
4406 Token
*cur
, *oldnext
= NULL
;
4408 if (!tline
|| !tline
->next
)
4413 (cur
->next
->type
== TOK_ID
||
4414 cur
->next
->type
== TOK_PREPROC_ID
4415 || cur
->next
->type
== TOK_NUMBER
))
4418 /* If identifier consists of just one token, don't expand */
4423 oldnext
= cur
->next
; /* Detach the tail past identifier */
4424 cur
->next
= NULL
; /* so that expand_smacro stops here */
4427 tline
= expand_smacro(tline
);
4430 /* expand_smacro possibly changhed tline; re-scan for EOL */
4432 while (cur
&& cur
->next
)
4435 cur
->next
= oldnext
;
4442 * Determine whether the given line constitutes a multi-line macro
4443 * call, and return the MMacro structure called if so. Doesn't have
4444 * to check for an initial label - that's taken care of in
4445 * expand_mmacro - but must check numbers of parameters. Guaranteed
4446 * to be called with tline->type == TOK_ID, so the putative macro
4447 * name is easy to find.
4449 static MMacro
*is_mmacro(Token
* tline
, Token
*** params_array
)
4455 head
= (MMacro
*) hash_findix(&mmacros
, tline
->text
);
4458 * Efficiency: first we see if any macro exists with the given
4459 * name. If not, we can return NULL immediately. _Then_ we
4460 * count the parameters, and then we look further along the
4461 * list if necessary to find the proper MMacro.
4463 list_for_each(m
, head
)
4464 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4470 * OK, we have a potential macro. Count and demarcate the
4473 count_mmac_params(tline
->next
, &nparam
, ¶ms
);
4476 * So we know how many parameters we've got. Find the MMacro
4477 * structure that handles this number.
4480 if (m
->nparam_min
<= nparam
4481 && (m
->plus
|| nparam
<= m
->nparam_max
)) {
4483 * This one is right. Just check if cycle removal
4484 * prohibits us using it before we actually celebrate...
4486 if (m
->in_progress
> m
->max_depth
) {
4487 if (m
->max_depth
> 0) {
4489 "reached maximum recursion depth of %i",
4496 * It's right, and we can use it. Add its default
4497 * parameters to the end of our list if necessary.
4499 if (m
->defaults
&& nparam
< m
->nparam_min
+ m
->ndefs
) {
4501 nasm_realloc(params
,
4502 ((m
->nparam_min
+ m
->ndefs
+
4503 1) * sizeof(*params
)));
4504 while (nparam
< m
->nparam_min
+ m
->ndefs
) {
4505 params
[nparam
] = m
->defaults
[nparam
- m
->nparam_min
];
4510 * If we've gone over the maximum parameter count (and
4511 * we're in Plus mode), ignore parameters beyond
4514 if (m
->plus
&& nparam
> m
->nparam_max
)
4515 nparam
= m
->nparam_max
;
4517 * Then terminate the parameter list, and leave.
4519 if (!params
) { /* need this special case */
4520 params
= nasm_malloc(sizeof(*params
));
4523 params
[nparam
] = NULL
;
4524 *params_array
= params
;
4528 * This one wasn't right: look for the next one with the
4531 list_for_each(m
, m
->next
)
4532 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4537 * After all that, we didn't find one with the right number of
4538 * parameters. Issue a warning, and fail to expand the macro.
4540 error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4541 "macro `%s' exists, but not taking %d parameters",
4542 tline
->text
, nparam
);
4549 * Save MMacro invocation specific fields in
4550 * preparation for a recursive macro expansion
4552 static void push_mmacro(MMacro
*m
)
4554 MMacroInvocation
*i
;
4556 i
= nasm_malloc(sizeof(MMacroInvocation
));
4558 i
->params
= m
->params
;
4559 i
->iline
= m
->iline
;
4560 i
->nparam
= m
->nparam
;
4561 i
->rotate
= m
->rotate
;
4562 i
->paramlen
= m
->paramlen
;
4563 i
->unique
= m
->unique
;
4564 i
->condcnt
= m
->condcnt
;
4570 * Restore MMacro invocation specific fields that were
4571 * saved during a previous recursive macro expansion
4573 static void pop_mmacro(MMacro
*m
)
4575 MMacroInvocation
*i
;
4580 m
->params
= i
->params
;
4581 m
->iline
= i
->iline
;
4582 m
->nparam
= i
->nparam
;
4583 m
->rotate
= i
->rotate
;
4584 m
->paramlen
= i
->paramlen
;
4585 m
->unique
= i
->unique
;
4586 m
->condcnt
= i
->condcnt
;
4593 * Expand the multi-line macro call made by the given line, if
4594 * there is one to be expanded. If there is, push the expansion on
4595 * istk->expansion and return 1. Otherwise return 0.
4597 static int expand_mmacro(Token
* tline
)
4599 Token
*startline
= tline
;
4600 Token
*label
= NULL
;
4601 int dont_prepend
= 0;
4602 Token
**params
, *t
, *tt
;
4605 int i
, nparam
, *paramlen
;
4610 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4611 if (!tok_type_(t
, TOK_ID
) && !tok_type_(t
, TOK_PREPROC_ID
))
4613 m
= is_mmacro(t
, ¶ms
);
4619 * We have an id which isn't a macro call. We'll assume
4620 * it might be a label; we'll also check to see if a
4621 * colon follows it. Then, if there's another id after
4622 * that lot, we'll check it again for macro-hood.
4626 if (tok_type_(t
, TOK_WHITESPACE
))
4627 last
= t
, t
= t
->next
;
4628 if (tok_is_(t
, ":")) {
4630 last
= t
, t
= t
->next
;
4631 if (tok_type_(t
, TOK_WHITESPACE
))
4632 last
= t
, t
= t
->next
;
4634 if (!tok_type_(t
, TOK_ID
) || !(m
= is_mmacro(t
, ¶ms
)))
4642 * Fix up the parameters: this involves stripping leading and
4643 * trailing whitespace, then stripping braces if they are
4646 for (nparam
= 0; params
[nparam
]; nparam
++) ;
4647 paramlen
= nparam
? nasm_malloc(nparam
* sizeof(*paramlen
)) : NULL
;
4649 for (i
= 0; params
[i
]; i
++) {
4651 int comma
= (!m
->plus
|| i
< nparam
- 1);
4655 if (tok_is_(t
, "{"))
4656 t
= t
->next
, brace
++, comma
= false;
4660 if (comma
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, ","))
4661 break; /* ... because we have hit a comma */
4662 if (comma
&& t
->type
== TOK_WHITESPACE
4663 && tok_is_(t
->next
, ","))
4664 break; /* ... or a space then a comma */
4665 if (brace
&& t
->type
== TOK_OTHER
) {
4666 if (t
->text
[0] == '{')
4667 brace
++; /* ... or a nested opening brace */
4668 else if (t
->text
[0] == '}')
4670 break; /* ... or a brace */
4676 error(ERR_NONFATAL
, "macro params should be enclosed in braces");
4680 * OK, we have a MMacro structure together with a set of
4681 * parameters. We must now go through the expansion and push
4682 * copies of each Line on to istk->expansion. Substitution of
4683 * parameter tokens and macro-local tokens doesn't get done
4684 * until the single-line macro substitution process; this is
4685 * because delaying them allows us to change the semantics
4686 * later through %rotate.
4688 * First, push an end marker on to istk->expansion, mark this
4689 * macro as in progress, and set up its invocation-specific
4692 ll
= nasm_malloc(sizeof(Line
));
4693 ll
->next
= istk
->expansion
;
4696 istk
->expansion
= ll
;
4699 * Save the previous MMacro expansion in the case of
4702 if (m
->max_depth
&& m
->in_progress
)
4710 m
->paramlen
= paramlen
;
4711 m
->unique
= unique
++;
4715 m
->next_active
= istk
->mstk
;
4718 list_for_each(l
, m
->expansion
) {
4721 ll
= nasm_malloc(sizeof(Line
));
4722 ll
->finishes
= NULL
;
4723 ll
->next
= istk
->expansion
;
4724 istk
->expansion
= ll
;
4727 list_for_each(t
, l
->first
) {
4731 tt
= *tail
= new_Token(NULL
, TOK_ID
, mname
, 0);
4733 case TOK_PREPROC_QQ
:
4734 tt
= *tail
= new_Token(NULL
, TOK_ID
, m
->name
, 0);
4736 case TOK_PREPROC_ID
:
4737 if (t
->text
[1] == '0' && t
->text
[2] == '0') {
4745 tt
= *tail
= new_Token(NULL
, x
->type
, x
->text
, 0);
4754 * If we had a label, push it on as the first line of
4755 * the macro expansion.
4758 if (dont_prepend
< 0)
4759 free_tlist(startline
);
4761 ll
= nasm_malloc(sizeof(Line
));
4762 ll
->finishes
= NULL
;
4763 ll
->next
= istk
->expansion
;
4764 istk
->expansion
= ll
;
4765 ll
->first
= startline
;
4766 if (!dont_prepend
) {
4768 label
= label
->next
;
4769 label
->next
= tt
= new_Token(NULL
, TOK_OTHER
, ":", 0);
4774 list
->uplevel(m
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
4779 /* The function that actually does the error reporting */
4780 static void verror(int severity
, const char *fmt
, va_list arg
)
4783 MMacro
*mmac
= NULL
;
4786 vsnprintf(buff
, sizeof(buff
), fmt
, arg
);
4788 /* get %macro name */
4789 if (istk
&& istk
->mstk
) {
4791 /* but %rep blocks should be skipped */
4792 while (mmac
&& !mmac
->name
)
4793 mmac
= mmac
->next_active
, delta
++;
4797 nasm_error(severity
, "(%s:%d) %s",
4798 mmac
->name
, mmac
->lineno
- delta
, buff
);
4800 nasm_error(severity
, "%s", buff
);
4804 * Since preprocessor always operate only on the line that didn't
4805 * arrived yet, we should always use ERR_OFFBY1.
4807 static void error(int severity
, const char *fmt
, ...)
4811 /* If we're in a dead branch of IF or something like it, ignore the error */
4812 if (istk
&& istk
->conds
&& !emitting(istk
->conds
->state
))
4816 verror(severity
, fmt
, arg
);
4821 * Because %else etc are evaluated in the state context
4822 * of the previous branch, errors might get lost with error():
4823 * %if 0 ... %else trailing garbage ... %endif
4824 * So %else etc should report errors with this function.
4826 static void error_precond(int severity
, const char *fmt
, ...)
4830 /* Only ignore the error if it's really in a dead branch */
4831 if (istk
&& istk
->conds
&& istk
->conds
->state
== COND_NEVER
)
4835 verror(severity
, fmt
, arg
);
4840 pp_reset(char *file
, int apass
, ListGen
* listgen
, StrList
**deplist
)
4845 istk
= nasm_malloc(sizeof(Include
));
4848 istk
->expansion
= NULL
;
4850 istk
->fp
= fopen(file
, "r");
4852 src_set_fname(nasm_strdup(file
));
4856 error(ERR_FATAL
|ERR_NOFILE
, "unable to open input file `%s'",
4859 nested_mac_count
= 0;
4860 nested_rep_count
= 0;
4863 if (tasm_compatible_mode
) {
4864 stdmacpos
= nasm_stdmac
;
4866 stdmacpos
= nasm_stdmac_after_tasm
;
4868 any_extrastdmac
= extrastdmac
&& *extrastdmac
;
4873 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4874 * The caller, however, will also pass in 3 for preprocess-only so
4875 * we can set __PASS__ accordingly.
4877 pass
= apass
> 2 ? 2 : apass
;
4879 dephead
= deptail
= deplist
;
4881 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
4883 strcpy(sl
->str
, file
);
4885 deptail
= &sl
->next
;
4889 * Define the __PASS__ macro. This is defined here unlike
4890 * all the other builtins, because it is special -- it varies between
4893 t
= nasm_malloc(sizeof(*t
));
4895 make_tok_num(t
, apass
);
4897 define_smacro(NULL
, "__PASS__", true, 0, t
);
4900 static char *pp_getline(void)
4907 * Fetch a tokenized line, either from the macro-expansion
4908 * buffer or from the input file.
4911 while (istk
->expansion
&& istk
->expansion
->finishes
) {
4912 Line
*l
= istk
->expansion
;
4913 if (!l
->finishes
->name
&& l
->finishes
->in_progress
> 1) {
4917 * This is a macro-end marker for a macro with no
4918 * name, which means it's not really a macro at all
4919 * but a %rep block, and the `in_progress' field is
4920 * more than 1, meaning that we still need to
4921 * repeat. (1 means the natural last repetition; 0
4922 * means termination by %exitrep.) We have
4923 * therefore expanded up to the %endrep, and must
4924 * push the whole block on to the expansion buffer
4925 * again. We don't bother to remove the macro-end
4926 * marker: we'd only have to generate another one
4929 l
->finishes
->in_progress
--;
4930 list_for_each(l
, l
->finishes
->expansion
) {
4931 Token
*t
, *tt
, **tail
;
4933 ll
= nasm_malloc(sizeof(Line
));
4934 ll
->next
= istk
->expansion
;
4935 ll
->finishes
= NULL
;
4939 list_for_each(t
, l
->first
) {
4940 if (t
->text
|| t
->type
== TOK_WHITESPACE
) {
4941 tt
= *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
4946 istk
->expansion
= ll
;
4950 * Check whether a `%rep' was started and not ended
4951 * within this macro expansion. This can happen and
4952 * should be detected. It's a fatal error because
4953 * I'm too confused to work out how to recover
4959 "defining with name in expansion");
4960 else if (istk
->mstk
->name
)
4962 "`%%rep' without `%%endrep' within"
4963 " expansion of macro `%s'",
4968 * FIXME: investigate the relationship at this point between
4969 * istk->mstk and l->finishes
4972 MMacro
*m
= istk
->mstk
;
4973 istk
->mstk
= m
->next_active
;
4976 * This was a real macro call, not a %rep, and
4977 * therefore the parameter information needs to
4982 l
->finishes
->in_progress
--;
4984 nasm_free(m
->params
);
4985 free_tlist(m
->iline
);
4986 nasm_free(m
->paramlen
);
4987 l
->finishes
->in_progress
= 0;
4992 istk
->expansion
= l
->next
;
4994 list
->downlevel(LIST_MACRO
);
4997 while (1) { /* until we get a line we can use */
4999 if (istk
->expansion
) { /* from a macro expansion */
5001 Line
*l
= istk
->expansion
;
5003 istk
->mstk
->lineno
++;
5005 istk
->expansion
= l
->next
;
5007 p
= detoken(tline
, false);
5008 list
->line(LIST_MACRO
, p
);
5013 if (line
) { /* from the current input file */
5014 line
= prepreproc(line
);
5015 tline
= tokenize(line
);
5020 * The current file has ended; work down the istk
5026 /* nasm_error can't be conditionally suppressed */
5027 nasm_error(ERR_FATAL
,
5028 "expected `%%endif' before end of file");
5030 /* only set line and file name if there's a next node */
5032 src_set_linnum(i
->lineno
);
5033 nasm_free(src_set_fname(nasm_strdup(i
->fname
)));
5036 list
->downlevel(LIST_INCLUDE
);
5040 if (istk
->expansion
&& istk
->expansion
->finishes
)
5046 * We must expand MMacro parameters and MMacro-local labels
5047 * _before_ we plunge into directive processing, to cope
5048 * with things like `%define something %1' such as STRUC
5049 * uses. Unless we're _defining_ a MMacro, in which case
5050 * those tokens should be left alone to go into the
5051 * definition; and unless we're in a non-emitting
5052 * condition, in which case we don't want to meddle with
5055 if (!defining
&& !(istk
->conds
&& !emitting(istk
->conds
->state
))
5056 && !(istk
->mstk
&& !istk
->mstk
->in_progress
)) {
5057 tline
= expand_mmac_params(tline
);
5061 * Check the line to see if it's a preprocessor directive.
5063 if (do_directive(tline
) == DIRECTIVE_FOUND
) {
5065 } else if (defining
) {
5067 * We're defining a multi-line macro. We emit nothing
5069 * shove the tokenized line on to the macro definition.
5071 Line
*l
= nasm_malloc(sizeof(Line
));
5072 l
->next
= defining
->expansion
;
5075 defining
->expansion
= l
;
5077 } else if (istk
->conds
&& !emitting(istk
->conds
->state
)) {
5079 * We're in a non-emitting branch of a condition block.
5080 * Emit nothing at all, not even a blank line: when we
5081 * emerge from the condition we'll give a line-number
5082 * directive so we keep our place correctly.
5086 } else if (istk
->mstk
&& !istk
->mstk
->in_progress
) {
5088 * We're in a %rep block which has been terminated, so
5089 * we're walking through to the %endrep without
5090 * emitting anything. Emit nothing at all, not even a
5091 * blank line: when we emerge from the %rep block we'll
5092 * give a line-number directive so we keep our place
5098 tline
= expand_smacro(tline
);
5099 if (!expand_mmacro(tline
)) {
5101 * De-tokenize the line again, and emit it.
5103 line
= detoken(tline
, true);
5107 continue; /* expand_mmacro calls free_tlist */
5115 static void pp_cleanup(int pass
)
5118 if (defining
->name
) {
5120 "end of file while still defining macro `%s'",
5123 error(ERR_NONFATAL
, "end of file while still in %%rep");
5126 free_mmacro(defining
);
5136 nasm_free(i
->fname
);
5141 nasm_free(src_set_fname(NULL
));
5148 while ((i
= ipath
)) {
5157 static void pp_include_path(char *path
)
5161 i
= nasm_malloc(sizeof(IncPath
));
5162 i
->path
= path
? nasm_strdup(path
) : NULL
;
5175 static void pp_pre_include(char *fname
)
5177 Token
*inc
, *space
, *name
;
5180 name
= new_Token(NULL
, TOK_INTERNAL_STRING
, fname
, 0);
5181 space
= new_Token(name
, TOK_WHITESPACE
, NULL
, 0);
5182 inc
= new_Token(space
, TOK_PREPROC_ID
, "%include", 0);
5184 l
= nasm_malloc(sizeof(Line
));
5191 static void pp_pre_define(char *definition
)
5197 equals
= strchr(definition
, '=');
5198 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5199 def
= new_Token(space
, TOK_PREPROC_ID
, "%define", 0);
5202 space
->next
= tokenize(definition
);
5206 if (space
->next
->type
!= TOK_PREPROC_ID
&&
5207 space
->next
->type
!= TOK_ID
)
5208 error(ERR_WARNING
, "pre-defining non ID `%s\'\n", definition
);
5210 l
= nasm_malloc(sizeof(Line
));
5217 static void pp_pre_undefine(char *definition
)
5222 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5223 def
= new_Token(space
, TOK_PREPROC_ID
, "%undef", 0);
5224 space
->next
= tokenize(definition
);
5226 l
= nasm_malloc(sizeof(Line
));
5233 static void pp_extra_stdmac(macros_t
*macros
)
5235 extrastdmac
= macros
;
5238 static void make_tok_num(Token
* tok
, int64_t val
)
5241 snprintf(numbuf
, sizeof(numbuf
), "%"PRId64
"", val
);
5242 tok
->text
= nasm_strdup(numbuf
);
5243 tok
->type
= TOK_NUMBER
;
5246 struct preproc_ops nasmpp
= {