1 /* ----------------------------------------------------------------------- *
3 * Copyright 1996-2016 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
85 typedef struct SMacro SMacro
;
86 typedef struct MMacro MMacro
;
87 typedef struct MMacroInvocation MMacroInvocation
;
88 typedef struct Context Context
;
89 typedef struct Token Token
;
90 typedef struct Blocks Blocks
;
91 typedef struct Line Line
;
92 typedef struct Include Include
;
93 typedef struct Cond Cond
;
94 typedef struct IncPath IncPath
;
97 * Note on the storage of both SMacro and MMacros: the hash table
98 * indexes them case-insensitively, and we then have to go through a
99 * linked list of potential case aliases (and, for MMacros, parameter
100 * ranges); this is to preserve the matching semantics of the earlier
101 * code. If the number of case aliases for a specific macro is a
102 * performance issue, you may want to reconsider your coding style.
106 * Store the definition of a single-line macro.
118 * Store the definition of a multi-line macro. This is also used to
119 * store the interiors of `%rep...%endrep' blocks, which are
120 * effectively self-re-invoking multi-line macros which simply
121 * don't have a name or bother to appear in the hash tables. %rep
122 * blocks are signified by having a NULL `name' field.
124 * In a MMacro describing a `%rep' block, the `in_progress' field
125 * isn't merely boolean, but gives the number of repeats left to
128 * The `next' field is used for storing MMacros in hash tables; the
129 * `next_active' field is for stacking them on istk entries.
131 * When a MMacro is being expanded, `params', `iline', `nparam',
132 * `paramlen', `rotate' and `unique' are local to the invocation.
136 MMacroInvocation
*prev
; /* previous invocation */
138 int nparam_min
, nparam_max
;
140 bool plus
; /* is the last parameter greedy? */
141 bool nolist
; /* is this macro listing-inhibited? */
142 int64_t in_progress
; /* is this macro currently being expanded? */
143 int32_t max_depth
; /* maximum number of recursive expansions allowed */
144 Token
*dlist
; /* All defaults as one list */
145 Token
**defaults
; /* Parameter default pointers */
146 int ndefs
; /* number of default parameters */
150 MMacro
*rep_nest
; /* used for nesting %rep */
151 Token
**params
; /* actual parameters */
152 Token
*iline
; /* invocation line */
153 unsigned int nparam
, rotate
;
156 int lineno
; /* Current line number on expansion */
157 uint64_t condcnt
; /* number of if blocks... */
159 char *fname
; /* File where defined */
160 int32_t xline
; /* First line in macro */
164 /* Store the definition of a multi-line macro, as defined in a
165 * previous recursive macro expansion.
167 struct MMacroInvocation
{
168 MMacroInvocation
*prev
; /* previous invocation */
169 Token
**params
; /* actual parameters */
170 Token
*iline
; /* invocation line */
171 unsigned int nparam
, rotate
;
179 * The context stack is composed of a linked list of these.
184 struct hash_table localmac
;
189 * This is the internal form which we break input lines up into.
190 * Typically stored in linked lists.
192 * Note that `type' serves a double meaning: TOK_SMAC_PARAM is not
193 * necessarily used as-is, but is intended to denote the number of
194 * the substituted parameter. So in the definition
196 * %define a(x,y) ( (x) & ~(y) )
198 * the token representing `x' will have its type changed to
199 * TOK_SMAC_PARAM, but the one representing `y' will be
202 * TOK_INTERNAL_STRING is a dirty hack: it's a single string token
203 * which doesn't need quotes around it. Used in the pre-include
204 * mechanism as an alternative to trying to find a sensible type of
205 * quote to use on the filename we were passed.
208 TOK_NONE
= 0, TOK_WHITESPACE
, TOK_COMMENT
, TOK_ID
,
209 TOK_PREPROC_ID
, TOK_STRING
,
210 TOK_NUMBER
, TOK_FLOAT
, TOK_SMAC_END
, TOK_OTHER
,
212 TOK_PREPROC_Q
, TOK_PREPROC_QQ
,
214 TOK_INDIRECT
, /* %[...] */
215 TOK_SMAC_PARAM
, /* MUST BE LAST IN THE LIST!!! */
216 TOK_MAX
= INT_MAX
/* Keep compiler from reducing the range */
219 #define PP_CONCAT_MASK(x) (1 << (x))
220 #define PP_CONCAT_MATCH(t, mask) (PP_CONCAT_MASK((t)->type) & mask)
222 struct tokseq_match
{
231 SMacro
*mac
; /* associated macro for TOK_SMAC_END */
232 size_t len
; /* scratch length field */
233 } a
; /* Auxiliary data */
234 enum pp_token_type type
;
238 * Multi-line macro definitions are stored as a linked list of
239 * these, which is essentially a container to allow several linked
242 * Note that in this module, linked lists are treated as stacks
243 * wherever possible. For this reason, Lines are _pushed_ on to the
244 * `expansion' field in MMacro structures, so that the linked list,
245 * if walked, would give the macro lines in reverse order; this
246 * means that we can walk the list when expanding a macro, and thus
247 * push the lines on to the `expansion' field in _istk_ in reverse
248 * order (so that when popped back off they are in the right
249 * order). It may seem cockeyed, and it relies on my design having
250 * an even number of steps in, but it works...
252 * Some of these structures, rather than being actual lines, are
253 * markers delimiting the end of the expansion of a given macro.
254 * This is for use in the cycle-tracking and %rep-handling code.
255 * Such structures have `finishes' non-NULL, and `first' NULL. All
256 * others have `finishes' NULL, but `first' may still be NULL if
266 * To handle an arbitrary level of file inclusion, we maintain a
267 * stack (ie linked list) of these things.
276 MMacro
*mstk
; /* stack of active macros/reps */
280 * Include search path. This is simply a list of strings which get
281 * prepended, in turn, to the name of an include file, in an
282 * attempt to find the file if it's not in the current directory.
290 * Conditional assembly: we maintain a separate stack of these for
291 * each level of file inclusion. (The only reason we keep the
292 * stacks separate is to ensure that a stray `%endif' in a file
293 * included from within the true branch of a `%if' won't terminate
294 * it and cause confusion: instead, rightly, it'll cause an error.)
302 * These states are for use just after %if or %elif: IF_TRUE
303 * means the condition has evaluated to truth so we are
304 * currently emitting, whereas IF_FALSE means we are not
305 * currently emitting but will start doing so if a %else comes
306 * up. In these states, all directives are admissible: %elif,
307 * %else and %endif. (And of course %if.)
309 COND_IF_TRUE
, COND_IF_FALSE
,
311 * These states come up after a %else: ELSE_TRUE means we're
312 * emitting, and ELSE_FALSE means we're not. In ELSE_* states,
313 * any %elif or %else will cause an error.
315 COND_ELSE_TRUE
, COND_ELSE_FALSE
,
317 * These states mean that we're not emitting now, and also that
318 * nothing until %endif will be emitted at all. COND_DONE is
319 * used when we've had our moment of emission
320 * and have now started seeing %elifs. COND_NEVER is used when
321 * the condition construct in question is contained within a
322 * non-emitting branch of a larger condition construct,
323 * or if there is an error.
325 COND_DONE
, COND_NEVER
327 #define emitting(x) ( (x) == COND_IF_TRUE || (x) == COND_ELSE_TRUE )
330 * These defines are used as the possible return values for do_directive
332 #define NO_DIRECTIVE_FOUND 0
333 #define DIRECTIVE_FOUND 1
336 * This define sets the upper limit for smacro and recursive mmacro
339 #define DEADMAN_LIMIT (1 << 20)
342 #define REP_LIMIT ((INT64_C(1) << 62))
345 * Condition codes. Note that we use c_ prefix not C_ because C_ is
346 * used in nasm.h for the "real" condition codes. At _this_ level,
347 * we treat CXZ and ECXZ as condition codes, albeit non-invertible
348 * ones, so we need a different enum...
350 static const char * const conditions
[] = {
351 "a", "ae", "b", "be", "c", "cxz", "e", "ecxz", "g", "ge", "l", "le",
352 "na", "nae", "nb", "nbe", "nc", "ne", "ng", "nge", "nl", "nle", "no",
353 "np", "ns", "nz", "o", "p", "pe", "po", "rcxz", "s", "z"
356 c_A
, c_AE
, c_B
, c_BE
, c_C
, c_CXZ
, c_E
, c_ECXZ
, c_G
, c_GE
, c_L
, c_LE
,
357 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, c_NE
, c_NG
, c_NGE
, c_NL
, c_NLE
, c_NO
,
358 c_NP
, c_NS
, c_NZ
, c_O
, c_P
, c_PE
, c_PO
, c_RCXZ
, c_S
, c_Z
,
361 static const enum pp_conds inverse_ccs
[] = {
362 c_NA
, c_NAE
, c_NB
, c_NBE
, c_NC
, -1, c_NE
, -1, c_NG
, c_NGE
, c_NL
, c_NLE
,
363 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
,
364 c_Z
, c_NO
, c_NP
, c_PO
, c_PE
, -1, c_NS
, c_NZ
370 /* If this is a an IF, ELIF, ELSE or ENDIF keyword */
371 static int is_condition(enum preproc_token arg
)
373 return PP_IS_COND(arg
) || (arg
== PP_ELSE
) || (arg
== PP_ENDIF
);
376 /* For TASM compatibility we need to be able to recognise TASM compatible
377 * conditional compilation directives. Using the NASM pre-processor does
378 * not work, so we look for them specifically from the following list and
379 * then jam in the equivalent NASM directive into the input stream.
383 TM_ARG
, TM_ELIF
, TM_ELSE
, TM_ENDIF
, TM_IF
, TM_IFDEF
, TM_IFDIFI
,
384 TM_IFNDEF
, TM_INCLUDE
, TM_LOCAL
387 static const char * const tasm_directives
[] = {
388 "arg", "elif", "else", "endif", "if", "ifdef", "ifdifi",
389 "ifndef", "include", "local"
392 static int StackSize
= 4;
393 static char *StackPointer
= "ebp";
394 static int ArgOffset
= 8;
395 static int LocalOffset
= 0;
397 static Context
*cstk
;
398 static Include
*istk
;
399 static IncPath
*ipath
= NULL
;
401 static int pass
; /* HACK: pass 0 = generate dependencies only */
402 static StrList
**dephead
, **deptail
; /* Dependency list */
404 static uint64_t unique
; /* unique identifier numbers */
406 static Line
*predef
= NULL
;
407 static bool do_predef
;
410 * The current set of multi-line macros we have defined.
412 static struct hash_table mmacros
;
415 * The current set of single-line macros we have defined.
417 static struct hash_table smacros
;
420 * The multi-line macro we are currently defining, or the %rep
421 * block we are currently reading, if any.
423 static MMacro
*defining
;
425 static uint64_t nested_mac_count
;
426 static uint64_t nested_rep_count
;
429 * The number of macro parameters to allocate space for at a time.
431 #define PARAM_DELTA 16
434 * The standard macro set: defined in macros.c in the array nasm_stdmac.
435 * This gives our position in the macro set, when we're processing it.
437 static macros_t
*stdmacpos
;
440 * The extra standard macros that come from the object format, if
443 static macros_t
*extrastdmac
= NULL
;
444 static bool any_extrastdmac
;
447 * Tokens are allocated in blocks to improve speed
449 #define TOKEN_BLOCKSIZE 4096
450 static Token
*freeTokens
= NULL
;
456 static Blocks blocks
= { NULL
, NULL
};
459 * Forward declarations.
461 static Token
*expand_mmac_params(Token
* tline
);
462 static Token
*expand_smacro(Token
* tline
);
463 static Token
*expand_id(Token
* tline
);
464 static Context
*get_ctx(const char *name
, const char **namep
);
465 static void make_tok_num(Token
* tok
, int64_t val
);
466 static void pp_verror(int severity
, const char *fmt
, va_list ap
);
467 static vefunc real_verror
;
468 static void *new_Block(size_t size
);
469 static void delete_Blocks(void);
470 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
471 const char *text
, int txtlen
);
472 static Token
*delete_Token(Token
* t
);
475 * Macros for safe checking of token pointers, avoid *(NULL)
477 #define tok_type_(x,t) ((x) && (x)->type == (t))
478 #define skip_white_(x) if (tok_type_((x), TOK_WHITESPACE)) (x)=(x)->next
479 #define tok_is_(x,v) (tok_type_((x), TOK_OTHER) && !strcmp((x)->text,(v)))
480 #define tok_isnt_(x,v) ((x) && ((x)->type!=TOK_OTHER || strcmp((x)->text,(v))))
483 * nasm_unquote with error if the string contains NUL characters.
484 * If the string contains NUL characters, issue an error and return
485 * the C len, i.e. truncate at the NUL.
487 static size_t nasm_unquote_cstr(char *qstr
, enum preproc_token directive
)
489 size_t len
= nasm_unquote(qstr
, NULL
);
490 size_t clen
= strlen(qstr
);
493 nasm_error(ERR_NONFATAL
, "NUL character in `%s' directive",
494 pp_directives
[directive
]);
500 * In-place reverse a list of tokens.
502 static Token
*reverse_tokens(Token
*t
)
518 * Handle TASM specific directives, which do not contain a % in
519 * front of them. We do it here because I could not find any other
520 * place to do it for the moment, and it is a hack (ideally it would
521 * be nice to be able to use the NASM pre-processor to do it).
523 static char *check_tasm_directive(char *line
)
525 int32_t i
, j
, k
, m
, len
;
526 char *p
, *q
, *oldline
, oldchar
;
528 p
= nasm_skip_spaces(line
);
530 /* Binary search for the directive name */
532 j
= ARRAY_SIZE(tasm_directives
);
533 q
= nasm_skip_word(p
);
540 m
= nasm_stricmp(p
, tasm_directives
[k
]);
542 /* We have found a directive, so jam a % in front of it
543 * so that NASM will then recognise it as one if it's own.
548 line
= nasm_malloc(len
+ 2);
550 if (k
== TM_IFDIFI
) {
552 * NASM does not recognise IFDIFI, so we convert
553 * it to %if 0. This is not used in NASM
554 * compatible code, but does need to parse for the
555 * TASM macro package.
557 strcpy(line
+ 1, "if 0");
559 memcpy(line
+ 1, p
, len
+ 1);
574 * The pre-preprocessing stage... This function translates line
575 * number indications as they emerge from GNU cpp (`# lineno "file"
576 * flags') into NASM preprocessor line number indications (`%line
579 static char *prepreproc(char *line
)
582 char *fname
, *oldline
;
584 if (line
[0] == '#' && line
[1] == ' ') {
587 lineno
= atoi(fname
);
588 fname
+= strspn(fname
, "0123456789 ");
591 fnlen
= strcspn(fname
, "\"");
592 line
= nasm_malloc(20 + fnlen
);
593 snprintf(line
, 20 + fnlen
, "%%line %d %.*s", lineno
, fnlen
, fname
);
596 if (tasm_compatible_mode
)
597 return check_tasm_directive(line
);
602 * Free a linked list of tokens.
604 static void free_tlist(Token
* list
)
607 list
= delete_Token(list
);
611 * Free a linked list of lines.
613 static void free_llist(Line
* list
)
616 list_for_each_safe(l
, tmp
, list
) {
617 free_tlist(l
->first
);
625 static void free_mmacro(MMacro
* m
)
628 free_tlist(m
->dlist
);
629 nasm_free(m
->defaults
);
630 free_llist(m
->expansion
);
636 * Free all currently defined macros, and free the hash tables
638 static void free_smacro_table(struct hash_table
*smt
)
642 struct hash_tbl_node
*it
= NULL
;
644 while ((s
= hash_iterate(smt
, &it
, &key
)) != NULL
) {
645 nasm_free((void *)key
);
646 list_for_each_safe(s
, tmp
, s
) {
648 free_tlist(s
->expansion
);
655 static void free_mmacro_table(struct hash_table
*mmt
)
659 struct hash_tbl_node
*it
= NULL
;
662 while ((m
= hash_iterate(mmt
, &it
, &key
)) != NULL
) {
663 nasm_free((void *)key
);
664 list_for_each_safe(m
,tmp
, m
)
670 static void free_macros(void)
672 free_smacro_table(&smacros
);
673 free_mmacro_table(&mmacros
);
677 * Initialize the hash tables
679 static void init_macros(void)
681 hash_init(&smacros
, HASH_LARGE
);
682 hash_init(&mmacros
, HASH_LARGE
);
686 * Pop the context stack.
688 static void ctx_pop(void)
693 free_smacro_table(&c
->localmac
);
699 * Search for a key in the hash index; adding it if necessary
700 * (in which case we initialize the data pointer to NULL.)
703 hash_findi_add(struct hash_table
*hash
, const char *str
)
705 struct hash_insert hi
;
709 r
= hash_findi(hash
, str
, &hi
);
713 strx
= nasm_strdup(str
); /* Use a more efficient allocator here? */
714 return hash_add(&hi
, strx
, NULL
);
718 * Like hash_findi, but returns the data element rather than a pointer
719 * to it. Used only when not adding a new element, hence no third
723 hash_findix(struct hash_table
*hash
, const char *str
)
727 p
= hash_findi(hash
, str
, NULL
);
728 return p
? *p
: NULL
;
732 * read line from standart macros set,
733 * if there no more left -- return NULL
735 static char *line_from_stdmac(void)
738 const unsigned char *p
= stdmacpos
;
747 len
+= pp_directives_len
[c
- 0x80] + 1;
752 line
= nasm_malloc(len
+ 1);
754 while ((c
= *stdmacpos
++)) {
756 memcpy(q
, pp_directives
[c
- 0x80], pp_directives_len
[c
- 0x80]);
757 q
+= pp_directives_len
[c
- 0x80];
767 /* This was the last of the standard macro chain... */
769 if (any_extrastdmac
) {
770 stdmacpos
= extrastdmac
;
771 any_extrastdmac
= false;
772 } else if (do_predef
) {
774 Token
*head
, **tail
, *t
;
777 * Nasty hack: here we push the contents of
778 * `predef' on to the top-level expansion stack,
779 * since this is the most convenient way to
780 * implement the pre-include and pre-define
783 list_for_each(pd
, predef
) {
786 list_for_each(t
, pd
->first
) {
787 *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
788 tail
= &(*tail
)->next
;
791 l
= nasm_malloc(sizeof(Line
));
792 l
->next
= istk
->expansion
;
805 static char *read_line(void)
807 unsigned int size
, c
, next
;
808 const unsigned int delta
= 512;
809 const unsigned int pad
= 8;
810 unsigned int nr_cont
= 0;
814 /* Standart macros set (predefined) goes first */
815 p
= line_from_stdmac();
820 p
= buffer
= nasm_malloc(size
);
824 if ((int)(c
) == EOF
) {
831 next
= fgetc(istk
->fp
);
833 ungetc(next
, istk
->fp
);
848 next
= fgetc(istk
->fp
);
849 ungetc(next
, istk
->fp
);
850 if (next
== '\r' || next
== '\n') {
858 if (c
== '\r' || c
== '\n') {
863 if (p
>= (buffer
+ size
- pad
)) {
864 buffer
= nasm_realloc(buffer
, size
+ delta
);
865 p
= buffer
+ size
- pad
;
869 *p
++ = (unsigned char)c
;
877 src_set_linnum(src_get_linnum() + istk
->lineinc
+
878 (nr_cont
* istk
->lineinc
));
881 * Handle spurious ^Z, which may be inserted into source files
882 * by some file transfer utilities.
884 buffer
[strcspn(buffer
, "\032")] = '\0';
886 lfmt
->line(LIST_READ
, buffer
);
892 * Tokenize a line of text. This is a very simple process since we
893 * don't need to parse the value out of e.g. numeric tokens: we
894 * simply split one string into many.
896 static Token
*tokenize(char *line
)
899 enum pp_token_type type
;
901 Token
*t
, **tail
= &list
;
907 if (*p
== '+' && !nasm_isdigit(p
[1])) {
910 } else if (nasm_isdigit(*p
) ||
911 ((*p
== '-' || *p
== '+') && nasm_isdigit(p
[1]))) {
915 while (nasm_isdigit(*p
));
916 type
= TOK_PREPROC_ID
;
917 } else if (*p
== '{') {
926 nasm_error(ERR_WARNING
| ERR_PASS1
,
927 "unterminated %%{ construct");
931 type
= TOK_PREPROC_ID
;
932 } else if (*p
== '[') {
934 line
+= 2; /* Skip the leading %[ */
936 while (lvl
&& (c
= *p
++)) {
948 p
= nasm_skip_string(p
- 1) + 1;
958 nasm_error(ERR_NONFATAL
|ERR_PASS1
,
959 "unterminated %%[ construct");
961 } else if (*p
== '?') {
962 type
= TOK_PREPROC_Q
; /* %? */
965 type
= TOK_PREPROC_QQ
; /* %?? */
968 } else if (*p
== '!') {
969 type
= TOK_PREPROC_ID
;
975 while (isidchar(*p
));
976 } else if (*p
== '\'' || *p
== '\"' || *p
== '`') {
977 p
= nasm_skip_string(p
);
981 nasm_error(ERR_NONFATAL
|ERR_PASS1
,
982 "unterminated %%! string");
984 /* %! without string or identifier */
985 type
= TOK_OTHER
; /* Legacy behavior... */
987 } else if (isidchar(*p
) ||
988 ((*p
== '!' || *p
== '%' || *p
== '$') &&
993 while (isidchar(*p
));
994 type
= TOK_PREPROC_ID
;
1000 } else if (isidstart(*p
) || (*p
== '$' && isidstart(p
[1]))) {
1003 while (*p
&& isidchar(*p
))
1005 } else if (*p
== '\'' || *p
== '"' || *p
== '`') {
1010 p
= nasm_skip_string(p
);
1015 nasm_error(ERR_WARNING
|ERR_PASS1
, "unterminated string");
1016 /* Handling unterminated strings by UNV */
1019 } else if (p
[0] == '$' && p
[1] == '$') {
1020 type
= TOK_OTHER
; /* TOKEN_BASE */
1022 } else if (isnumstart(*p
)) {
1023 bool is_hex
= false;
1024 bool is_float
= false;
1040 if (!is_hex
&& (c
== 'e' || c
== 'E')) {
1042 if (*p
== '+' || *p
== '-') {
1044 * e can only be followed by +/- if it is either a
1045 * prefixed hex number or a floating-point number
1050 } else if (c
== 'H' || c
== 'h' || c
== 'X' || c
== 'x') {
1052 } else if (c
== 'P' || c
== 'p') {
1054 if (*p
== '+' || *p
== '-')
1056 } else if (isnumchar(c
) || c
== '_')
1057 ; /* just advance */
1058 else if (c
== '.') {
1060 * we need to deal with consequences of the legacy
1061 * parser, like "1.nolist" being two tokens
1062 * (TOK_NUMBER, TOK_ID) here; at least give it
1063 * a shot for now. In the future, we probably need
1064 * a flex-based scanner with proper pattern matching
1065 * to do it as well as it can be done. Nothing in
1066 * the world is going to help the person who wants
1067 * 0x123.p16 interpreted as two tokens, though.
1073 if (nasm_isdigit(*r
) || (is_hex
&& nasm_isxdigit(*r
)) ||
1074 (!is_hex
&& (*r
== 'e' || *r
== 'E')) ||
1075 (*r
== 'p' || *r
== 'P')) {
1079 break; /* Terminate the token */
1083 p
--; /* Point to first character beyond number */
1085 if (p
== line
+1 && *line
== '$') {
1086 type
= TOK_OTHER
; /* TOKEN_HERE */
1088 if (has_e
&& !is_hex
) {
1089 /* 1e13 is floating-point, but 1e13h is not */
1093 type
= is_float
? TOK_FLOAT
: TOK_NUMBER
;
1095 } else if (nasm_isspace(*p
)) {
1096 type
= TOK_WHITESPACE
;
1097 p
= nasm_skip_spaces(p
);
1099 * Whitespace just before end-of-line is discarded by
1100 * pretending it's a comment; whitespace just before a
1101 * comment gets lumped into the comment.
1103 if (!*p
|| *p
== ';') {
1108 } else if (*p
== ';') {
1114 * Anything else is an operator of some kind. We check
1115 * for all the double-character operators (>>, <<, //,
1116 * %%, <=, >=, ==, !=, <>, &&, ||, ^^), but anything
1117 * else is a single-character operator.
1120 if ((p
[0] == '>' && p
[1] == '>') ||
1121 (p
[0] == '<' && p
[1] == '<') ||
1122 (p
[0] == '/' && p
[1] == '/') ||
1123 (p
[0] == '<' && p
[1] == '=') ||
1124 (p
[0] == '>' && p
[1] == '=') ||
1125 (p
[0] == '=' && p
[1] == '=') ||
1126 (p
[0] == '!' && p
[1] == '=') ||
1127 (p
[0] == '<' && p
[1] == '>') ||
1128 (p
[0] == '&' && p
[1] == '&') ||
1129 (p
[0] == '|' && p
[1] == '|') ||
1130 (p
[0] == '^' && p
[1] == '^')) {
1136 /* Handling unterminated string by UNV */
1139 *tail = t = new_Token(NULL, TOK_STRING, line, p-line+1);
1140 t->text[p-line] = *line;
1144 if (type
!= TOK_COMMENT
) {
1145 *tail
= t
= new_Token(NULL
, type
, line
, p
- line
);
1154 * this function allocates a new managed block of memory and
1155 * returns a pointer to the block. The managed blocks are
1156 * deleted only all at once by the delete_Blocks function.
1158 static void *new_Block(size_t size
)
1160 Blocks
*b
= &blocks
;
1162 /* first, get to the end of the linked list */
1165 /* now allocate the requested chunk */
1166 b
->chunk
= nasm_malloc(size
);
1168 /* now allocate a new block for the next request */
1169 b
->next
= nasm_zalloc(sizeof(Blocks
));
1174 * this function deletes all managed blocks of memory
1176 static void delete_Blocks(void)
1178 Blocks
*a
, *b
= &blocks
;
1181 * keep in mind that the first block, pointed to by blocks
1182 * is a static and not dynamically allocated, so we don't
1187 nasm_free(b
->chunk
);
1193 memset(&blocks
, 0, sizeof(blocks
));
1197 * this function creates a new Token and passes a pointer to it
1198 * back to the caller. It sets the type and text elements, and
1199 * also the a.mac and next elements to NULL.
1201 static Token
*new_Token(Token
* next
, enum pp_token_type type
,
1202 const char *text
, int txtlen
)
1208 freeTokens
= (Token
*) new_Block(TOKEN_BLOCKSIZE
* sizeof(Token
));
1209 for (i
= 0; i
< TOKEN_BLOCKSIZE
- 1; i
++)
1210 freeTokens
[i
].next
= &freeTokens
[i
+ 1];
1211 freeTokens
[i
].next
= NULL
;
1214 freeTokens
= t
->next
;
1218 if (type
== TOK_WHITESPACE
|| !text
) {
1222 txtlen
= strlen(text
);
1223 t
->text
= nasm_malloc(txtlen
+1);
1224 memcpy(t
->text
, text
, txtlen
);
1225 t
->text
[txtlen
] = '\0';
1230 static Token
*delete_Token(Token
* t
)
1232 Token
*next
= t
->next
;
1234 t
->next
= freeTokens
;
1240 * Convert a line of tokens back into text.
1241 * If expand_locals is not zero, identifiers of the form "%$*xxx"
1242 * will be transformed into ..@ctxnum.xxx
1244 static char *detoken(Token
* tlist
, bool expand_locals
)
1251 list_for_each(t
, tlist
) {
1252 if (t
->type
== TOK_PREPROC_ID
&& t
->text
[1] == '!') {
1257 if (*v
== '\'' || *v
== '\"' || *v
== '`') {
1258 size_t len
= nasm_unquote(v
, NULL
);
1259 size_t clen
= strlen(v
);
1262 nasm_error(ERR_NONFATAL
| ERR_PASS1
,
1263 "NUL character in %%! string");
1269 char *p
= getenv(v
);
1271 nasm_error(ERR_NONFATAL
| ERR_PASS1
,
1272 "nonexistent environment variable `%s'", v
);
1275 t
->text
= nasm_strdup(p
);
1280 /* Expand local macros here and not during preprocessing */
1281 if (expand_locals
&&
1282 t
->type
== TOK_PREPROC_ID
&& t
->text
&&
1283 t
->text
[0] == '%' && t
->text
[1] == '$') {
1286 Context
*ctx
= get_ctx(t
->text
, &q
);
1289 snprintf(buffer
, sizeof(buffer
), "..@%"PRIu32
".", ctx
->number
);
1290 p
= nasm_strcat(buffer
, q
);
1295 if (t
->type
== TOK_WHITESPACE
)
1298 len
+= strlen(t
->text
);
1301 p
= line
= nasm_malloc(len
+ 1);
1303 list_for_each(t
, tlist
) {
1304 if (t
->type
== TOK_WHITESPACE
) {
1306 } else if (t
->text
) {
1318 * A scanner, suitable for use by the expression evaluator, which
1319 * operates on a line of Tokens. Expects a pointer to a pointer to
1320 * the first token in the line to be passed in as its private_data
1323 * FIX: This really needs to be unified with stdscan.
1325 static int ppscan(void *private_data
, struct tokenval
*tokval
)
1327 Token
**tlineptr
= private_data
;
1329 char ourcopy
[MAX_KEYWORD
+1], *p
, *r
, *s
;
1333 *tlineptr
= tline
? tline
->next
: NULL
;
1334 } while (tline
&& (tline
->type
== TOK_WHITESPACE
||
1335 tline
->type
== TOK_COMMENT
));
1338 return tokval
->t_type
= TOKEN_EOS
;
1340 tokval
->t_charptr
= tline
->text
;
1342 if (tline
->text
[0] == '$' && !tline
->text
[1])
1343 return tokval
->t_type
= TOKEN_HERE
;
1344 if (tline
->text
[0] == '$' && tline
->text
[1] == '$' && !tline
->text
[2])
1345 return tokval
->t_type
= TOKEN_BASE
;
1347 if (tline
->type
== TOK_ID
) {
1348 p
= tokval
->t_charptr
= tline
->text
;
1350 tokval
->t_charptr
++;
1351 return tokval
->t_type
= TOKEN_ID
;
1354 for (r
= p
, s
= ourcopy
; *r
; r
++) {
1355 if (r
>= p
+MAX_KEYWORD
)
1356 return tokval
->t_type
= TOKEN_ID
; /* Not a keyword */
1357 *s
++ = nasm_tolower(*r
);
1360 /* right, so we have an identifier sitting in temp storage. now,
1361 * is it actually a register or instruction name, or what? */
1362 return nasm_token_hash(ourcopy
, tokval
);
1365 if (tline
->type
== TOK_NUMBER
) {
1367 tokval
->t_integer
= readnum(tline
->text
, &rn_error
);
1368 tokval
->t_charptr
= tline
->text
;
1370 return tokval
->t_type
= TOKEN_ERRNUM
;
1372 return tokval
->t_type
= TOKEN_NUM
;
1375 if (tline
->type
== TOK_FLOAT
) {
1376 return tokval
->t_type
= TOKEN_FLOAT
;
1379 if (tline
->type
== TOK_STRING
) {
1382 bq
= tline
->text
[0];
1383 tokval
->t_charptr
= tline
->text
;
1384 tokval
->t_inttwo
= nasm_unquote(tline
->text
, &ep
);
1386 if (ep
[0] != bq
|| ep
[1] != '\0')
1387 return tokval
->t_type
= TOKEN_ERRSTR
;
1389 return tokval
->t_type
= TOKEN_STR
;
1392 if (tline
->type
== TOK_OTHER
) {
1393 if (!strcmp(tline
->text
, "<<"))
1394 return tokval
->t_type
= TOKEN_SHL
;
1395 if (!strcmp(tline
->text
, ">>"))
1396 return tokval
->t_type
= TOKEN_SHR
;
1397 if (!strcmp(tline
->text
, "//"))
1398 return tokval
->t_type
= TOKEN_SDIV
;
1399 if (!strcmp(tline
->text
, "%%"))
1400 return tokval
->t_type
= TOKEN_SMOD
;
1401 if (!strcmp(tline
->text
, "=="))
1402 return tokval
->t_type
= TOKEN_EQ
;
1403 if (!strcmp(tline
->text
, "<>"))
1404 return tokval
->t_type
= TOKEN_NE
;
1405 if (!strcmp(tline
->text
, "!="))
1406 return tokval
->t_type
= TOKEN_NE
;
1407 if (!strcmp(tline
->text
, "<="))
1408 return tokval
->t_type
= TOKEN_LE
;
1409 if (!strcmp(tline
->text
, ">="))
1410 return tokval
->t_type
= TOKEN_GE
;
1411 if (!strcmp(tline
->text
, "&&"))
1412 return tokval
->t_type
= TOKEN_DBL_AND
;
1413 if (!strcmp(tline
->text
, "^^"))
1414 return tokval
->t_type
= TOKEN_DBL_XOR
;
1415 if (!strcmp(tline
->text
, "||"))
1416 return tokval
->t_type
= TOKEN_DBL_OR
;
1420 * We have no other options: just return the first character of
1423 return tokval
->t_type
= tline
->text
[0];
1427 * Compare a string to the name of an existing macro; this is a
1428 * simple wrapper which calls either strcmp or nasm_stricmp
1429 * depending on the value of the `casesense' parameter.
1431 static int mstrcmp(const char *p
, const char *q
, bool casesense
)
1433 return casesense
? strcmp(p
, q
) : nasm_stricmp(p
, q
);
1437 * Compare a string to the name of an existing macro; this is a
1438 * simple wrapper which calls either strcmp or nasm_stricmp
1439 * depending on the value of the `casesense' parameter.
1441 static int mmemcmp(const char *p
, const char *q
, size_t l
, bool casesense
)
1443 return casesense
? memcmp(p
, q
, l
) : nasm_memicmp(p
, q
, l
);
1447 * Return the Context structure associated with a %$ token. Return
1448 * NULL, having _already_ reported an error condition, if the
1449 * context stack isn't deep enough for the supplied number of $
1452 * If "namep" is non-NULL, set it to the pointer to the macro name
1453 * tail, i.e. the part beyond %$...
1455 static Context
*get_ctx(const char *name
, const char **namep
)
1463 if (!name
|| name
[0] != '%' || name
[1] != '$')
1467 nasm_error(ERR_NONFATAL
, "`%s': context stack is empty", name
);
1474 while (ctx
&& *name
== '$') {
1480 nasm_error(ERR_NONFATAL
, "`%s': context stack is only"
1481 " %d level%s deep", name
, i
, (i
== 1 ? "" : "s"));
1492 * Check to see if a file is already in a string list
1494 static bool in_list(const StrList
*list
, const char *str
)
1497 if (!strcmp(list
->str
, str
))
1505 * Open an include file. This routine must always return a valid
1506 * file pointer if it returns - it's responsible for throwing an
1507 * ERR_FATAL and bombing out completely if not. It should also try
1508 * the include path one by one until it finds the file or reaches
1509 * the end of the path.
1511 static FILE *inc_fopen(const char *file
, StrList
**dhead
, StrList
***dtail
,
1516 IncPath
*ip
= ipath
;
1517 int len
= strlen(file
);
1518 size_t prefix_len
= 0;
1522 sl
= nasm_malloc(prefix_len
+len
+1+sizeof sl
->next
);
1523 memcpy(sl
->str
, prefix
, prefix_len
);
1524 memcpy(sl
->str
+prefix_len
, file
, len
+1);
1525 fp
= fopen(sl
->str
, "r");
1526 if (fp
&& dhead
&& !in_list(*dhead
, sl
->str
)) {
1544 prefix_len
= strlen(prefix
);
1546 /* -MG given and file not found */
1547 if (dhead
&& !in_list(*dhead
, file
)) {
1548 sl
= nasm_malloc(len
+1+sizeof sl
->next
);
1550 strcpy(sl
->str
, file
);
1558 nasm_error(ERR_FATAL
, "unable to open include file `%s'", file
);
1563 * Determine if we should warn on defining a single-line macro of
1564 * name `name', with `nparam' parameters. If nparam is 0 or -1, will
1565 * return true if _any_ single-line macro of that name is defined.
1566 * Otherwise, will return true if a single-line macro with either
1567 * `nparam' or no parameters is defined.
1569 * If a macro with precisely the right number of parameters is
1570 * defined, or nparam is -1, the address of the definition structure
1571 * will be returned in `defn'; otherwise NULL will be returned. If `defn'
1572 * is NULL, no action will be taken regarding its contents, and no
1575 * Note that this is also called with nparam zero to resolve
1578 * If you already know which context macro belongs to, you can pass
1579 * the context pointer as first parameter; if you won't but name begins
1580 * with %$ the context will be automatically computed. If all_contexts
1581 * is true, macro will be searched in outer contexts as well.
1584 smacro_defined(Context
* ctx
, const char *name
, int nparam
, SMacro
** defn
,
1587 struct hash_table
*smtbl
;
1591 smtbl
= &ctx
->localmac
;
1592 } else if (name
[0] == '%' && name
[1] == '$') {
1594 ctx
= get_ctx(name
, &name
);
1596 return false; /* got to return _something_ */
1597 smtbl
= &ctx
->localmac
;
1601 m
= (SMacro
*) hash_findix(smtbl
, name
);
1604 if (!mstrcmp(m
->name
, name
, m
->casesense
&& nocase
) &&
1605 (nparam
<= 0 || m
->nparam
== 0 || nparam
== (int) m
->nparam
)) {
1607 if (nparam
== (int) m
->nparam
|| nparam
== -1)
1621 * Count and mark off the parameters in a multi-line macro call.
1622 * This is called both from within the multi-line macro expansion
1623 * code, and also to mark off the default parameters when provided
1624 * in a %macro definition line.
1626 static void count_mmac_params(Token
* t
, int *nparam
, Token
*** params
)
1628 int paramsize
, brace
;
1630 *nparam
= paramsize
= 0;
1633 /* +1: we need space for the final NULL */
1634 if (*nparam
+1 >= paramsize
) {
1635 paramsize
+= PARAM_DELTA
;
1636 *params
= nasm_realloc(*params
, sizeof(**params
) * paramsize
);
1640 if (tok_is_(t
, "{"))
1642 (*params
)[(*nparam
)++] = t
;
1644 while (brace
&& (t
= t
->next
) != NULL
) {
1645 if (tok_is_(t
, "{"))
1647 else if (tok_is_(t
, "}"))
1653 * Now we've found the closing brace, look further
1658 if (tok_isnt_(t
, ",")) {
1659 nasm_error(ERR_NONFATAL
,
1660 "braces do not enclose all of macro parameter");
1661 while (tok_isnt_(t
, ","))
1666 while (tok_isnt_(t
, ","))
1669 if (t
) { /* got a comma/brace */
1670 t
= t
->next
; /* eat the comma */
1676 * Determine whether one of the various `if' conditions is true or
1679 * We must free the tline we get passed.
1681 static bool if_condition(Token
* tline
, enum preproc_token ct
)
1683 enum pp_conditional i
= PP_COND(ct
);
1685 Token
*t
, *tt
, **tptr
, *origline
;
1686 struct tokenval tokval
;
1688 enum pp_token_type needtype
;
1695 j
= false; /* have we matched yet? */
1700 if (tline
->type
!= TOK_ID
) {
1701 nasm_error(ERR_NONFATAL
,
1702 "`%s' expects context identifiers", pp_directives
[ct
]);
1703 free_tlist(origline
);
1706 if (cstk
&& cstk
->name
&& !nasm_stricmp(tline
->text
, cstk
->name
))
1708 tline
= tline
->next
;
1713 j
= false; /* have we matched yet? */
1716 if (!tline
|| (tline
->type
!= TOK_ID
&&
1717 (tline
->type
!= TOK_PREPROC_ID
||
1718 tline
->text
[1] != '$'))) {
1719 nasm_error(ERR_NONFATAL
,
1720 "`%s' expects macro identifiers", pp_directives
[ct
]);
1723 if (smacro_defined(NULL
, tline
->text
, 0, NULL
, true))
1725 tline
= tline
->next
;
1730 tline
= expand_smacro(tline
);
1731 j
= false; /* have we matched yet? */
1734 if (!tline
|| (tline
->type
!= TOK_ID
&&
1735 tline
->type
!= TOK_STRING
&&
1736 (tline
->type
!= TOK_PREPROC_ID
||
1737 tline
->text
[1] != '!'))) {
1738 nasm_error(ERR_NONFATAL
,
1739 "`%s' expects environment variable names",
1744 if (tline
->type
== TOK_PREPROC_ID
)
1745 p
+= 2; /* Skip leading %! */
1746 if (*p
== '\'' || *p
== '\"' || *p
== '`')
1747 nasm_unquote_cstr(p
, ct
);
1750 tline
= tline
->next
;
1756 tline
= expand_smacro(tline
);
1758 while (tok_isnt_(tt
, ","))
1761 nasm_error(ERR_NONFATAL
,
1762 "`%s' expects two comma-separated arguments",
1767 j
= true; /* assume equality unless proved not */
1768 while ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) && tt
) {
1769 if (tt
->type
== TOK_OTHER
&& !strcmp(tt
->text
, ",")) {
1770 nasm_error(ERR_NONFATAL
, "`%s': more than one comma on line",
1774 if (t
->type
== TOK_WHITESPACE
) {
1778 if (tt
->type
== TOK_WHITESPACE
) {
1782 if (tt
->type
!= t
->type
) {
1783 j
= false; /* found mismatching tokens */
1786 /* When comparing strings, need to unquote them first */
1787 if (t
->type
== TOK_STRING
) {
1788 size_t l1
= nasm_unquote(t
->text
, NULL
);
1789 size_t l2
= nasm_unquote(tt
->text
, NULL
);
1795 if (mmemcmp(t
->text
, tt
->text
, l1
, i
== PPC_IFIDN
)) {
1799 } else if (mstrcmp(tt
->text
, t
->text
, i
== PPC_IFIDN
) != 0) {
1800 j
= false; /* found mismatching tokens */
1807 if ((t
->type
!= TOK_OTHER
|| strcmp(t
->text
, ",")) || tt
)
1808 j
= false; /* trailing gunk on one end or other */
1814 MMacro searching
, *mmac
;
1817 tline
= expand_id(tline
);
1818 if (!tok_type_(tline
, TOK_ID
)) {
1819 nasm_error(ERR_NONFATAL
,
1820 "`%s' expects a macro name", pp_directives
[ct
]);
1823 searching
.name
= nasm_strdup(tline
->text
);
1824 searching
.casesense
= true;
1825 searching
.plus
= false;
1826 searching
.nolist
= false;
1827 searching
.in_progress
= 0;
1828 searching
.max_depth
= 0;
1829 searching
.rep_nest
= NULL
;
1830 searching
.nparam_min
= 0;
1831 searching
.nparam_max
= INT_MAX
;
1832 tline
= expand_smacro(tline
->next
);
1835 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
1836 nasm_error(ERR_NONFATAL
,
1837 "`%s' expects a parameter count or nothing",
1840 searching
.nparam_min
= searching
.nparam_max
=
1841 readnum(tline
->text
, &j
);
1843 nasm_error(ERR_NONFATAL
,
1844 "unable to parse parameter count `%s'",
1847 if (tline
&& tok_is_(tline
->next
, "-")) {
1848 tline
= tline
->next
->next
;
1849 if (tok_is_(tline
, "*"))
1850 searching
.nparam_max
= INT_MAX
;
1851 else if (!tok_type_(tline
, TOK_NUMBER
))
1852 nasm_error(ERR_NONFATAL
,
1853 "`%s' expects a parameter count after `-'",
1856 searching
.nparam_max
= readnum(tline
->text
, &j
);
1858 nasm_error(ERR_NONFATAL
,
1859 "unable to parse parameter count `%s'",
1861 if (searching
.nparam_min
> searching
.nparam_max
)
1862 nasm_error(ERR_NONFATAL
,
1863 "minimum parameter count exceeds maximum");
1866 if (tline
&& tok_is_(tline
->next
, "+")) {
1867 tline
= tline
->next
;
1868 searching
.plus
= true;
1870 mmac
= (MMacro
*) hash_findix(&mmacros
, searching
.name
);
1872 if (!strcmp(mmac
->name
, searching
.name
) &&
1873 (mmac
->nparam_min
<= searching
.nparam_max
1875 && (searching
.nparam_min
<= mmac
->nparam_max
1882 if (tline
&& tline
->next
)
1883 nasm_error(ERR_WARNING
|ERR_PASS1
,
1884 "trailing garbage after %%ifmacro ignored");
1885 nasm_free(searching
.name
);
1894 needtype
= TOK_NUMBER
;
1897 needtype
= TOK_STRING
;
1901 t
= tline
= expand_smacro(tline
);
1903 while (tok_type_(t
, TOK_WHITESPACE
) ||
1904 (needtype
== TOK_NUMBER
&&
1905 tok_type_(t
, TOK_OTHER
) &&
1906 (t
->text
[0] == '-' || t
->text
[0] == '+') &&
1910 j
= tok_type_(t
, needtype
);
1914 t
= tline
= expand_smacro(tline
);
1915 while (tok_type_(t
, TOK_WHITESPACE
))
1920 t
= t
->next
; /* Skip the actual token */
1921 while (tok_type_(t
, TOK_WHITESPACE
))
1923 j
= !t
; /* Should be nothing left */
1928 t
= tline
= expand_smacro(tline
);
1929 while (tok_type_(t
, TOK_WHITESPACE
))
1932 j
= !t
; /* Should be empty */
1936 t
= tline
= expand_smacro(tline
);
1938 tokval
.t_type
= TOKEN_INVALID
;
1939 evalresult
= evaluate(ppscan
, tptr
, &tokval
,
1940 NULL
, pass
| CRITICAL
, NULL
);
1944 nasm_error(ERR_WARNING
|ERR_PASS1
,
1945 "trailing garbage after expression ignored");
1946 if (!is_simple(evalresult
)) {
1947 nasm_error(ERR_NONFATAL
,
1948 "non-constant value given to `%s'", pp_directives
[ct
]);
1951 j
= reloc_value(evalresult
) != 0;
1955 nasm_error(ERR_FATAL
,
1956 "preprocessor directive `%s' not yet implemented",
1961 free_tlist(origline
);
1962 return j
^ PP_NEGATIVE(ct
);
1965 free_tlist(origline
);
1970 * Common code for defining an smacro
1972 static bool define_smacro(Context
*ctx
, const char *mname
, bool casesense
,
1973 int nparam
, Token
*expansion
)
1975 SMacro
*smac
, **smhead
;
1976 struct hash_table
*smtbl
;
1978 if (smacro_defined(ctx
, mname
, nparam
, &smac
, casesense
)) {
1980 nasm_error(ERR_WARNING
|ERR_PASS1
,
1981 "single-line macro `%s' defined both with and"
1982 " without parameters", mname
);
1984 * Some instances of the old code considered this a failure,
1985 * some others didn't. What is the right thing to do here?
1987 free_tlist(expansion
);
1988 return false; /* Failure */
1991 * We're redefining, so we have to take over an
1992 * existing SMacro structure. This means freeing
1993 * what was already in it.
1995 nasm_free(smac
->name
);
1996 free_tlist(smac
->expansion
);
1999 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2000 smhead
= (SMacro
**) hash_findi_add(smtbl
, mname
);
2001 smac
= nasm_malloc(sizeof(SMacro
));
2002 smac
->next
= *smhead
;
2005 smac
->name
= nasm_strdup(mname
);
2006 smac
->casesense
= casesense
;
2007 smac
->nparam
= nparam
;
2008 smac
->expansion
= expansion
;
2009 smac
->in_progress
= false;
2010 return true; /* Success */
2014 * Undefine an smacro
2016 static void undef_smacro(Context
*ctx
, const char *mname
)
2018 SMacro
**smhead
, *s
, **sp
;
2019 struct hash_table
*smtbl
;
2021 smtbl
= ctx
? &ctx
->localmac
: &smacros
;
2022 smhead
= (SMacro
**)hash_findi(smtbl
, mname
, NULL
);
2026 * We now have a macro name... go hunt for it.
2029 while ((s
= *sp
) != NULL
) {
2030 if (!mstrcmp(s
->name
, mname
, s
->casesense
)) {
2033 free_tlist(s
->expansion
);
2043 * Parse a mmacro specification.
2045 static bool parse_mmacro_spec(Token
*tline
, MMacro
*def
, const char *directive
)
2049 tline
= tline
->next
;
2051 tline
= expand_id(tline
);
2052 if (!tok_type_(tline
, TOK_ID
)) {
2053 nasm_error(ERR_NONFATAL
, "`%s' expects a macro name", directive
);
2058 def
->name
= nasm_strdup(tline
->text
);
2060 def
->nolist
= false;
2061 def
->in_progress
= 0;
2062 def
->rep_nest
= NULL
;
2063 def
->nparam_min
= 0;
2064 def
->nparam_max
= 0;
2066 tline
= expand_smacro(tline
->next
);
2068 if (!tok_type_(tline
, TOK_NUMBER
)) {
2069 nasm_error(ERR_NONFATAL
, "`%s' expects a parameter count", directive
);
2071 def
->nparam_min
= def
->nparam_max
=
2072 readnum(tline
->text
, &err
);
2074 nasm_error(ERR_NONFATAL
,
2075 "unable to parse parameter count `%s'", tline
->text
);
2077 if (tline
&& tok_is_(tline
->next
, "-")) {
2078 tline
= tline
->next
->next
;
2079 if (tok_is_(tline
, "*")) {
2080 def
->nparam_max
= INT_MAX
;
2081 } else if (!tok_type_(tline
, TOK_NUMBER
)) {
2082 nasm_error(ERR_NONFATAL
,
2083 "`%s' expects a parameter count after `-'", directive
);
2085 def
->nparam_max
= readnum(tline
->text
, &err
);
2087 nasm_error(ERR_NONFATAL
, "unable to parse parameter count `%s'",
2090 if (def
->nparam_min
> def
->nparam_max
) {
2091 nasm_error(ERR_NONFATAL
, "minimum parameter count exceeds maximum");
2095 if (tline
&& tok_is_(tline
->next
, "+")) {
2096 tline
= tline
->next
;
2099 if (tline
&& tok_type_(tline
->next
, TOK_ID
) &&
2100 !nasm_stricmp(tline
->next
->text
, ".nolist")) {
2101 tline
= tline
->next
;
2106 * Handle default parameters.
2108 if (tline
&& tline
->next
) {
2109 def
->dlist
= tline
->next
;
2111 count_mmac_params(def
->dlist
, &def
->ndefs
, &def
->defaults
);
2114 def
->defaults
= NULL
;
2116 def
->expansion
= NULL
;
2118 if (def
->defaults
&& def
->ndefs
> def
->nparam_max
- def
->nparam_min
&&
2120 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MDP
,
2121 "too many default macro parameters");
2128 * Decode a size directive
2130 static int parse_size(const char *str
) {
2131 static const char *size_names
[] =
2132 { "byte", "dword", "oword", "qword", "tword", "word", "yword" };
2133 static const int sizes
[] =
2134 { 0, 1, 4, 16, 8, 10, 2, 32 };
2136 return sizes
[bsii(str
, size_names
, ARRAY_SIZE(size_names
))+1];
2140 * find and process preprocessor directive in passed line
2141 * Find out if a line contains a preprocessor directive, and deal
2144 * If a directive _is_ found, it is the responsibility of this routine
2145 * (and not the caller) to free_tlist() the line.
2147 * @param tline a pointer to the current tokeninzed line linked list
2148 * @return DIRECTIVE_FOUND or NO_DIRECTIVE_FOUND
2151 static int do_directive(Token
* tline
)
2153 enum preproc_token i
;
2166 MMacro
*mmac
, **mmhead
;
2167 Token
*t
= NULL
, *tt
, *param_start
, *macro_start
, *last
, **tptr
, *origline
;
2169 struct tokenval tokval
;
2171 MMacro
*tmp_defining
; /* Used when manipulating rep_nest */
2179 if (!tline
|| !tok_type_(tline
, TOK_PREPROC_ID
) ||
2180 (tline
->text
[1] == '%' || tline
->text
[1] == '$'
2181 || tline
->text
[1] == '!'))
2182 return NO_DIRECTIVE_FOUND
;
2184 i
= pp_token_hash(tline
->text
);
2187 * FIXME: We zap execution of PP_RMACRO, PP_IRMACRO, PP_EXITMACRO
2188 * since they are known to be buggy at moment, we need to fix them
2189 * in future release (2.09-2.10)
2191 if (i
== PP_RMACRO
|| i
== PP_IRMACRO
|| i
== PP_EXITMACRO
) {
2192 nasm_error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2194 return NO_DIRECTIVE_FOUND
;
2198 * If we're in a non-emitting branch of a condition construct,
2199 * or walking to the end of an already terminated %rep block,
2200 * we should ignore all directives except for condition
2203 if (((istk
->conds
&& !emitting(istk
->conds
->state
)) ||
2204 (istk
->mstk
&& !istk
->mstk
->in_progress
)) && !is_condition(i
)) {
2205 return NO_DIRECTIVE_FOUND
;
2209 * If we're defining a macro or reading a %rep block, we should
2210 * ignore all directives except for %macro/%imacro (which nest),
2211 * %endm/%endmacro, and (only if we're in a %rep block) %endrep.
2212 * If we're in a %rep block, another %rep nests, so should be let through.
2214 if (defining
&& i
!= PP_MACRO
&& i
!= PP_IMACRO
&&
2215 i
!= PP_RMACRO
&& i
!= PP_IRMACRO
&&
2216 i
!= PP_ENDMACRO
&& i
!= PP_ENDM
&&
2217 (defining
->name
|| (i
!= PP_ENDREP
&& i
!= PP_REP
))) {
2218 return NO_DIRECTIVE_FOUND
;
2222 if (i
== PP_MACRO
|| i
== PP_IMACRO
||
2223 i
== PP_RMACRO
|| i
== PP_IRMACRO
) {
2225 return NO_DIRECTIVE_FOUND
;
2226 } else if (nested_mac_count
> 0) {
2227 if (i
== PP_ENDMACRO
) {
2229 return NO_DIRECTIVE_FOUND
;
2232 if (!defining
->name
) {
2235 return NO_DIRECTIVE_FOUND
;
2236 } else if (nested_rep_count
> 0) {
2237 if (i
== PP_ENDREP
) {
2239 return NO_DIRECTIVE_FOUND
;
2247 nasm_error(ERR_NONFATAL
, "unknown preprocessor directive `%s'",
2249 return NO_DIRECTIVE_FOUND
; /* didn't get it */
2252 /* Directive to tell NASM what the default stack size is. The
2253 * default is for a 16-bit stack, and this can be overriden with
2256 tline
= tline
->next
;
2257 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2258 tline
= tline
->next
;
2259 if (!tline
|| tline
->type
!= TOK_ID
) {
2260 nasm_error(ERR_NONFATAL
, "`%%stacksize' missing size parameter");
2261 free_tlist(origline
);
2262 return DIRECTIVE_FOUND
;
2264 if (nasm_stricmp(tline
->text
, "flat") == 0) {
2265 /* All subsequent ARG directives are for a 32-bit stack */
2267 StackPointer
= "ebp";
2270 } else if (nasm_stricmp(tline
->text
, "flat64") == 0) {
2271 /* All subsequent ARG directives are for a 64-bit stack */
2273 StackPointer
= "rbp";
2276 } else if (nasm_stricmp(tline
->text
, "large") == 0) {
2277 /* All subsequent ARG directives are for a 16-bit stack,
2278 * far function call.
2281 StackPointer
= "bp";
2284 } else if (nasm_stricmp(tline
->text
, "small") == 0) {
2285 /* All subsequent ARG directives are for a 16-bit stack,
2286 * far function call. We don't support near functions.
2289 StackPointer
= "bp";
2293 nasm_error(ERR_NONFATAL
, "`%%stacksize' invalid size type");
2294 free_tlist(origline
);
2295 return DIRECTIVE_FOUND
;
2297 free_tlist(origline
);
2298 return DIRECTIVE_FOUND
;
2301 /* TASM like ARG directive to define arguments to functions, in
2302 * the following form:
2304 * ARG arg1:WORD, arg2:DWORD, arg4:QWORD
2308 char *arg
, directive
[256];
2309 int size
= StackSize
;
2311 /* Find the argument name */
2312 tline
= tline
->next
;
2313 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2314 tline
= tline
->next
;
2315 if (!tline
|| tline
->type
!= TOK_ID
) {
2316 nasm_error(ERR_NONFATAL
, "`%%arg' missing argument parameter");
2317 free_tlist(origline
);
2318 return DIRECTIVE_FOUND
;
2322 /* Find the argument size type */
2323 tline
= tline
->next
;
2324 if (!tline
|| tline
->type
!= TOK_OTHER
2325 || tline
->text
[0] != ':') {
2326 nasm_error(ERR_NONFATAL
,
2327 "Syntax error processing `%%arg' directive");
2328 free_tlist(origline
);
2329 return DIRECTIVE_FOUND
;
2331 tline
= tline
->next
;
2332 if (!tline
|| tline
->type
!= TOK_ID
) {
2333 nasm_error(ERR_NONFATAL
, "`%%arg' missing size type parameter");
2334 free_tlist(origline
);
2335 return DIRECTIVE_FOUND
;
2338 /* Allow macro expansion of type parameter */
2339 tt
= tokenize(tline
->text
);
2340 tt
= expand_smacro(tt
);
2341 size
= parse_size(tt
->text
);
2343 nasm_error(ERR_NONFATAL
,
2344 "Invalid size type for `%%arg' missing directive");
2346 free_tlist(origline
);
2347 return DIRECTIVE_FOUND
;
2351 /* Round up to even stack slots */
2352 size
= ALIGN(size
, StackSize
);
2354 /* Now define the macro for the argument */
2355 snprintf(directive
, sizeof(directive
), "%%define %s (%s+%d)",
2356 arg
, StackPointer
, offset
);
2357 do_directive(tokenize(directive
));
2360 /* Move to the next argument in the list */
2361 tline
= tline
->next
;
2362 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2363 tline
= tline
->next
;
2364 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2366 free_tlist(origline
);
2367 return DIRECTIVE_FOUND
;
2370 /* TASM like LOCAL directive to define local variables for a
2371 * function, in the following form:
2373 * LOCAL local1:WORD, local2:DWORD, local4:QWORD = LocalSize
2375 * The '= LocalSize' at the end is ignored by NASM, but is
2376 * required by TASM to define the local parameter size (and used
2377 * by the TASM macro package).
2379 offset
= LocalOffset
;
2381 char *local
, directive
[256];
2382 int size
= StackSize
;
2384 /* Find the argument name */
2385 tline
= tline
->next
;
2386 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2387 tline
= tline
->next
;
2388 if (!tline
|| tline
->type
!= TOK_ID
) {
2389 nasm_error(ERR_NONFATAL
,
2390 "`%%local' missing argument parameter");
2391 free_tlist(origline
);
2392 return DIRECTIVE_FOUND
;
2394 local
= tline
->text
;
2396 /* Find the argument size type */
2397 tline
= tline
->next
;
2398 if (!tline
|| tline
->type
!= TOK_OTHER
2399 || tline
->text
[0] != ':') {
2400 nasm_error(ERR_NONFATAL
,
2401 "Syntax error processing `%%local' directive");
2402 free_tlist(origline
);
2403 return DIRECTIVE_FOUND
;
2405 tline
= tline
->next
;
2406 if (!tline
|| tline
->type
!= TOK_ID
) {
2407 nasm_error(ERR_NONFATAL
,
2408 "`%%local' missing size type parameter");
2409 free_tlist(origline
);
2410 return DIRECTIVE_FOUND
;
2413 /* Allow macro expansion of type parameter */
2414 tt
= tokenize(tline
->text
);
2415 tt
= expand_smacro(tt
);
2416 size
= parse_size(tt
->text
);
2418 nasm_error(ERR_NONFATAL
,
2419 "Invalid size type for `%%local' missing directive");
2421 free_tlist(origline
);
2422 return DIRECTIVE_FOUND
;
2426 /* Round up to even stack slots */
2427 size
= ALIGN(size
, StackSize
);
2429 offset
+= size
; /* Negative offset, increment before */
2431 /* Now define the macro for the argument */
2432 snprintf(directive
, sizeof(directive
), "%%define %s (%s-%d)",
2433 local
, StackPointer
, offset
);
2434 do_directive(tokenize(directive
));
2436 /* Now define the assign to setup the enter_c macro correctly */
2437 snprintf(directive
, sizeof(directive
),
2438 "%%assign %%$localsize %%$localsize+%d", size
);
2439 do_directive(tokenize(directive
));
2441 /* Move to the next argument in the list */
2442 tline
= tline
->next
;
2443 if (tline
&& tline
->type
== TOK_WHITESPACE
)
2444 tline
= tline
->next
;
2445 } while (tline
&& tline
->type
== TOK_OTHER
&& tline
->text
[0] == ',');
2446 LocalOffset
= offset
;
2447 free_tlist(origline
);
2448 return DIRECTIVE_FOUND
;
2452 nasm_error(ERR_WARNING
|ERR_PASS1
,
2453 "trailing garbage after `%%clear' ignored");
2456 free_tlist(origline
);
2457 return DIRECTIVE_FOUND
;
2460 t
= tline
->next
= expand_smacro(tline
->next
);
2462 if (!t
|| (t
->type
!= TOK_STRING
&&
2463 t
->type
!= TOK_INTERNAL_STRING
)) {
2464 nasm_error(ERR_NONFATAL
, "`%%depend' expects a file name");
2465 free_tlist(origline
);
2466 return DIRECTIVE_FOUND
; /* but we did _something_ */
2469 nasm_error(ERR_WARNING
|ERR_PASS1
,
2470 "trailing garbage after `%%depend' ignored");
2472 if (t
->type
!= TOK_INTERNAL_STRING
)
2473 nasm_unquote_cstr(p
, i
);
2474 if (dephead
&& !in_list(*dephead
, p
)) {
2475 StrList
*sl
= nasm_malloc(strlen(p
)+1+sizeof sl
->next
);
2479 deptail
= &sl
->next
;
2481 free_tlist(origline
);
2482 return DIRECTIVE_FOUND
;
2485 t
= tline
->next
= expand_smacro(tline
->next
);
2488 if (!t
|| (t
->type
!= TOK_STRING
&&
2489 t
->type
!= TOK_INTERNAL_STRING
)) {
2490 nasm_error(ERR_NONFATAL
, "`%%include' expects a file name");
2491 free_tlist(origline
);
2492 return DIRECTIVE_FOUND
; /* but we did _something_ */
2495 nasm_error(ERR_WARNING
|ERR_PASS1
,
2496 "trailing garbage after `%%include' ignored");
2498 if (t
->type
!= TOK_INTERNAL_STRING
)
2499 nasm_unquote_cstr(p
, i
);
2500 inc
= nasm_malloc(sizeof(Include
));
2503 inc
->fp
= inc_fopen(p
, dephead
, &deptail
, pass
== 0);
2505 /* -MG given but file not found */
2508 inc
->fname
= src_set_fname(nasm_strdup(p
));
2509 inc
->lineno
= src_set_linnum(0);
2511 inc
->expansion
= NULL
;
2514 lfmt
->uplevel(LIST_INCLUDE
);
2516 free_tlist(origline
);
2517 return DIRECTIVE_FOUND
;
2521 static macros_t
*use_pkg
;
2522 const char *pkg_macro
= NULL
;
2524 tline
= tline
->next
;
2526 tline
= expand_id(tline
);
2528 if (!tline
|| (tline
->type
!= TOK_STRING
&&
2529 tline
->type
!= TOK_INTERNAL_STRING
&&
2530 tline
->type
!= TOK_ID
)) {
2531 nasm_error(ERR_NONFATAL
, "`%%use' expects a package name");
2532 free_tlist(origline
);
2533 return DIRECTIVE_FOUND
; /* but we did _something_ */
2536 nasm_error(ERR_WARNING
|ERR_PASS1
,
2537 "trailing garbage after `%%use' ignored");
2538 if (tline
->type
== TOK_STRING
)
2539 nasm_unquote_cstr(tline
->text
, i
);
2540 use_pkg
= nasm_stdmac_find_package(tline
->text
);
2542 nasm_error(ERR_NONFATAL
, "unknown `%%use' package: %s", tline
->text
);
2544 pkg_macro
= (char *)use_pkg
+ 1; /* The first string will be <%define>__USE_*__ */
2545 if (use_pkg
&& ! smacro_defined(NULL
, pkg_macro
, 0, NULL
, true)) {
2546 /* Not already included, go ahead and include it */
2547 stdmacpos
= use_pkg
;
2549 free_tlist(origline
);
2550 return DIRECTIVE_FOUND
;
2555 tline
= tline
->next
;
2557 tline
= expand_id(tline
);
2559 if (!tok_type_(tline
, TOK_ID
)) {
2560 nasm_error(ERR_NONFATAL
, "`%s' expects a context identifier",
2562 free_tlist(origline
);
2563 return DIRECTIVE_FOUND
; /* but we did _something_ */
2566 nasm_error(ERR_WARNING
|ERR_PASS1
,
2567 "trailing garbage after `%s' ignored",
2569 p
= nasm_strdup(tline
->text
);
2571 p
= NULL
; /* Anonymous */
2575 ctx
= nasm_malloc(sizeof(Context
));
2577 hash_init(&ctx
->localmac
, HASH_SMALL
);
2579 ctx
->number
= unique
++;
2584 nasm_error(ERR_NONFATAL
, "`%s': context stack is empty",
2586 } else if (i
== PP_POP
) {
2587 if (p
&& (!cstk
->name
|| nasm_stricmp(p
, cstk
->name
)))
2588 nasm_error(ERR_NONFATAL
, "`%%pop' in wrong context: %s, "
2590 cstk
->name
? cstk
->name
: "anonymous", p
);
2595 nasm_free(cstk
->name
);
2601 free_tlist(origline
);
2602 return DIRECTIVE_FOUND
;
2604 severity
= ERR_FATAL
;
2607 severity
= ERR_NONFATAL
;
2610 severity
= ERR_WARNING
|ERR_WARN_USER
;
2615 /* Only error out if this is the final pass */
2616 if (pass
!= 2 && i
!= PP_FATAL
)
2617 return DIRECTIVE_FOUND
;
2619 tline
->next
= expand_smacro(tline
->next
);
2620 tline
= tline
->next
;
2622 t
= tline
? tline
->next
: NULL
;
2624 if (tok_type_(tline
, TOK_STRING
) && !t
) {
2625 /* The line contains only a quoted string */
2627 nasm_unquote(p
, NULL
); /* Ignore NUL character truncation */
2628 nasm_error(severity
, "%s", p
);
2630 /* Not a quoted string, or more than a quoted string */
2631 p
= detoken(tline
, false);
2632 nasm_error(severity
, "%s", p
);
2635 free_tlist(origline
);
2636 return DIRECTIVE_FOUND
;
2640 if (istk
->conds
&& !emitting(istk
->conds
->state
))
2643 j
= if_condition(tline
->next
, i
);
2644 tline
->next
= NULL
; /* it got freed */
2645 j
= j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2647 cond
= nasm_malloc(sizeof(Cond
));
2648 cond
->next
= istk
->conds
;
2652 istk
->mstk
->condcnt
++;
2653 free_tlist(origline
);
2654 return DIRECTIVE_FOUND
;
2658 nasm_error(ERR_FATAL
, "`%s': no matching `%%if'", pp_directives
[i
]);
2659 switch(istk
->conds
->state
) {
2661 istk
->conds
->state
= COND_DONE
;
2668 case COND_ELSE_TRUE
:
2669 case COND_ELSE_FALSE
:
2670 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_PP_PRECOND
,
2671 "`%%elif' after `%%else' ignored");
2672 istk
->conds
->state
= COND_NEVER
;
2677 * IMPORTANT: In the case of %if, we will already have
2678 * called expand_mmac_params(); however, if we're
2679 * processing an %elif we must have been in a
2680 * non-emitting mode, which would have inhibited
2681 * the normal invocation of expand_mmac_params().
2682 * Therefore, we have to do it explicitly here.
2684 j
= if_condition(expand_mmac_params(tline
->next
), i
);
2685 tline
->next
= NULL
; /* it got freed */
2686 istk
->conds
->state
=
2687 j
< 0 ? COND_NEVER
: j
? COND_IF_TRUE
: COND_IF_FALSE
;
2690 free_tlist(origline
);
2691 return DIRECTIVE_FOUND
;
2695 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_PP_PRECOND
,
2696 "trailing garbage after `%%else' ignored");
2698 nasm_fatal(0, "`%%else: no matching `%%if'");
2699 switch(istk
->conds
->state
) {
2702 istk
->conds
->state
= COND_ELSE_FALSE
;
2709 istk
->conds
->state
= COND_ELSE_TRUE
;
2712 case COND_ELSE_TRUE
:
2713 case COND_ELSE_FALSE
:
2714 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_PP_PRECOND
,
2715 "`%%else' after `%%else' ignored.");
2716 istk
->conds
->state
= COND_NEVER
;
2719 free_tlist(origline
);
2720 return DIRECTIVE_FOUND
;
2724 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_PP_PRECOND
,
2725 "trailing garbage after `%%endif' ignored");
2727 nasm_error(ERR_FATAL
, "`%%endif': no matching `%%if'");
2729 istk
->conds
= cond
->next
;
2732 istk
->mstk
->condcnt
--;
2733 free_tlist(origline
);
2734 return DIRECTIVE_FOUND
;
2741 nasm_error(ERR_FATAL
, "`%s': already defining a macro",
2743 return DIRECTIVE_FOUND
;
2745 defining
= nasm_zalloc(sizeof(MMacro
));
2746 defining
->max_depth
=
2747 (i
== PP_RMACRO
) || (i
== PP_IRMACRO
) ? DEADMAN_LIMIT
: 0;
2748 defining
->casesense
= (i
== PP_MACRO
) || (i
== PP_RMACRO
);
2749 if (!parse_mmacro_spec(tline
, defining
, pp_directives
[i
])) {
2750 nasm_free(defining
);
2752 return DIRECTIVE_FOUND
;
2755 src_get(&defining
->xline
, &defining
->fname
);
2757 mmac
= (MMacro
*) hash_findix(&mmacros
, defining
->name
);
2759 if (!strcmp(mmac
->name
, defining
->name
) &&
2760 (mmac
->nparam_min
<= defining
->nparam_max
2762 && (defining
->nparam_min
<= mmac
->nparam_max
2764 nasm_error(ERR_WARNING
|ERR_PASS1
,
2765 "redefining multi-line macro `%s'", defining
->name
);
2766 return DIRECTIVE_FOUND
;
2770 free_tlist(origline
);
2771 return DIRECTIVE_FOUND
;
2775 if (! (defining
&& defining
->name
)) {
2776 nasm_error(ERR_NONFATAL
, "`%s': not defining a macro", tline
->text
);
2777 return DIRECTIVE_FOUND
;
2779 mmhead
= (MMacro
**) hash_findi_add(&mmacros
, defining
->name
);
2780 defining
->next
= *mmhead
;
2783 free_tlist(origline
);
2784 return DIRECTIVE_FOUND
;
2788 * We must search along istk->expansion until we hit a
2789 * macro-end marker for a macro with a name. Then we
2790 * bypass all lines between exitmacro and endmacro.
2792 list_for_each(l
, istk
->expansion
)
2793 if (l
->finishes
&& l
->finishes
->name
)
2798 * Remove all conditional entries relative to this
2799 * macro invocation. (safe to do in this context)
2801 for ( ; l
->finishes
->condcnt
> 0; l
->finishes
->condcnt
--) {
2803 istk
->conds
= cond
->next
;
2806 istk
->expansion
= l
;
2808 nasm_error(ERR_NONFATAL
, "`%%exitmacro' not within `%%macro' block");
2810 free_tlist(origline
);
2811 return DIRECTIVE_FOUND
;
2819 spec
.casesense
= (i
== PP_UNMACRO
);
2820 if (!parse_mmacro_spec(tline
, &spec
, pp_directives
[i
])) {
2821 return DIRECTIVE_FOUND
;
2823 mmac_p
= (MMacro
**) hash_findi(&mmacros
, spec
.name
, NULL
);
2824 while (mmac_p
&& *mmac_p
) {
2826 if (mmac
->casesense
== spec
.casesense
&&
2827 !mstrcmp(mmac
->name
, spec
.name
, spec
.casesense
) &&
2828 mmac
->nparam_min
== spec
.nparam_min
&&
2829 mmac
->nparam_max
== spec
.nparam_max
&&
2830 mmac
->plus
== spec
.plus
) {
2831 *mmac_p
= mmac
->next
;
2834 mmac_p
= &mmac
->next
;
2837 free_tlist(origline
);
2838 free_tlist(spec
.dlist
);
2839 return DIRECTIVE_FOUND
;
2843 if (tline
->next
&& tline
->next
->type
== TOK_WHITESPACE
)
2844 tline
= tline
->next
;
2846 free_tlist(origline
);
2847 nasm_error(ERR_NONFATAL
, "`%%rotate' missing rotate count");
2848 return DIRECTIVE_FOUND
;
2850 t
= expand_smacro(tline
->next
);
2852 free_tlist(origline
);
2855 tokval
.t_type
= TOKEN_INVALID
;
2857 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, NULL
);
2860 return DIRECTIVE_FOUND
;
2862 nasm_error(ERR_WARNING
|ERR_PASS1
,
2863 "trailing garbage after expression ignored");
2864 if (!is_simple(evalresult
)) {
2865 nasm_error(ERR_NONFATAL
, "non-constant value given to `%%rotate'");
2866 return DIRECTIVE_FOUND
;
2869 while (mmac
&& !mmac
->name
) /* avoid mistaking %reps for macros */
2870 mmac
= mmac
->next_active
;
2872 nasm_error(ERR_NONFATAL
, "`%%rotate' invoked outside a macro call");
2873 } else if (mmac
->nparam
== 0) {
2874 nasm_error(ERR_NONFATAL
,
2875 "`%%rotate' invoked within macro without parameters");
2877 int rotate
= mmac
->rotate
+ reloc_value(evalresult
);
2879 rotate
%= (int)mmac
->nparam
;
2881 rotate
+= mmac
->nparam
;
2883 mmac
->rotate
= rotate
;
2885 return DIRECTIVE_FOUND
;
2890 tline
= tline
->next
;
2891 } while (tok_type_(tline
, TOK_WHITESPACE
));
2893 if (tok_type_(tline
, TOK_ID
) &&
2894 nasm_stricmp(tline
->text
, ".nolist") == 0) {
2897 tline
= tline
->next
;
2898 } while (tok_type_(tline
, TOK_WHITESPACE
));
2902 t
= expand_smacro(tline
);
2904 tokval
.t_type
= TOKEN_INVALID
;
2906 evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, NULL
);
2908 free_tlist(origline
);
2909 return DIRECTIVE_FOUND
;
2912 nasm_error(ERR_WARNING
|ERR_PASS1
,
2913 "trailing garbage after expression ignored");
2914 if (!is_simple(evalresult
)) {
2915 nasm_error(ERR_NONFATAL
, "non-constant value given to `%%rep'");
2916 return DIRECTIVE_FOUND
;
2918 count
= reloc_value(evalresult
);
2919 if (count
>= REP_LIMIT
) {
2920 nasm_error(ERR_NONFATAL
, "`%%rep' value exceeds limit");
2925 nasm_error(ERR_NONFATAL
, "`%%rep' expects a repeat count");
2928 free_tlist(origline
);
2930 tmp_defining
= defining
;
2931 defining
= nasm_malloc(sizeof(MMacro
));
2932 defining
->prev
= NULL
;
2933 defining
->name
= NULL
; /* flags this macro as a %rep block */
2934 defining
->casesense
= false;
2935 defining
->plus
= false;
2936 defining
->nolist
= nolist
;
2937 defining
->in_progress
= count
;
2938 defining
->max_depth
= 0;
2939 defining
->nparam_min
= defining
->nparam_max
= 0;
2940 defining
->defaults
= NULL
;
2941 defining
->dlist
= NULL
;
2942 defining
->expansion
= NULL
;
2943 defining
->next_active
= istk
->mstk
;
2944 defining
->rep_nest
= tmp_defining
;
2945 return DIRECTIVE_FOUND
;
2948 if (!defining
|| defining
->name
) {
2949 nasm_error(ERR_NONFATAL
, "`%%endrep': no matching `%%rep'");
2950 return DIRECTIVE_FOUND
;
2954 * Now we have a "macro" defined - although it has no name
2955 * and we won't be entering it in the hash tables - we must
2956 * push a macro-end marker for it on to istk->expansion.
2957 * After that, it will take care of propagating itself (a
2958 * macro-end marker line for a macro which is really a %rep
2959 * block will cause the macro to be re-expanded, complete
2960 * with another macro-end marker to ensure the process
2961 * continues) until the whole expansion is forcibly removed
2962 * from istk->expansion by a %exitrep.
2964 l
= nasm_malloc(sizeof(Line
));
2965 l
->next
= istk
->expansion
;
2966 l
->finishes
= defining
;
2968 istk
->expansion
= l
;
2970 istk
->mstk
= defining
;
2972 lfmt
->uplevel(defining
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
2973 tmp_defining
= defining
;
2974 defining
= defining
->rep_nest
;
2975 free_tlist(origline
);
2976 return DIRECTIVE_FOUND
;
2980 * We must search along istk->expansion until we hit a
2981 * macro-end marker for a macro with no name. Then we set
2982 * its `in_progress' flag to 0.
2984 list_for_each(l
, istk
->expansion
)
2985 if (l
->finishes
&& !l
->finishes
->name
)
2989 l
->finishes
->in_progress
= 1;
2991 nasm_error(ERR_NONFATAL
, "`%%exitrep' not within `%%rep' block");
2992 free_tlist(origline
);
2993 return DIRECTIVE_FOUND
;
2999 casesense
= (i
== PP_DEFINE
|| i
== PP_XDEFINE
);
3001 tline
= tline
->next
;
3003 tline
= expand_id(tline
);
3004 if (!tline
|| (tline
->type
!= TOK_ID
&&
3005 (tline
->type
!= TOK_PREPROC_ID
||
3006 tline
->text
[1] != '$'))) {
3007 nasm_error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3009 free_tlist(origline
);
3010 return DIRECTIVE_FOUND
;
3013 ctx
= get_ctx(tline
->text
, &mname
);
3015 param_start
= tline
= tline
->next
;
3018 /* Expand the macro definition now for %xdefine and %ixdefine */
3019 if ((i
== PP_XDEFINE
) || (i
== PP_IXDEFINE
))
3020 tline
= expand_smacro(tline
);
3022 if (tok_is_(tline
, "(")) {
3024 * This macro has parameters.
3027 tline
= tline
->next
;
3031 nasm_error(ERR_NONFATAL
, "parameter identifier expected");
3032 free_tlist(origline
);
3033 return DIRECTIVE_FOUND
;
3035 if (tline
->type
!= TOK_ID
) {
3036 nasm_error(ERR_NONFATAL
,
3037 "`%s': parameter identifier expected",
3039 free_tlist(origline
);
3040 return DIRECTIVE_FOUND
;
3042 tline
->type
= TOK_SMAC_PARAM
+ nparam
++;
3043 tline
= tline
->next
;
3045 if (tok_is_(tline
, ",")) {
3046 tline
= tline
->next
;
3048 if (!tok_is_(tline
, ")")) {
3049 nasm_error(ERR_NONFATAL
,
3050 "`)' expected to terminate macro template");
3051 free_tlist(origline
);
3052 return DIRECTIVE_FOUND
;
3058 tline
= tline
->next
;
3060 if (tok_type_(tline
, TOK_WHITESPACE
))
3061 last
= tline
, tline
= tline
->next
;
3066 if (t
->type
== TOK_ID
) {
3067 list_for_each(tt
, param_start
)
3068 if (tt
->type
>= TOK_SMAC_PARAM
&&
3069 !strcmp(tt
->text
, t
->text
))
3073 t
->next
= macro_start
;
3078 * Good. We now have a macro name, a parameter count, and a
3079 * token list (in reverse order) for an expansion. We ought
3080 * to be OK just to create an SMacro, store it, and let
3081 * free_tlist have the rest of the line (which we have
3082 * carefully re-terminated after chopping off the expansion
3085 define_smacro(ctx
, mname
, casesense
, nparam
, macro_start
);
3086 free_tlist(origline
);
3087 return DIRECTIVE_FOUND
;
3090 tline
= tline
->next
;
3092 tline
= expand_id(tline
);
3093 if (!tline
|| (tline
->type
!= TOK_ID
&&
3094 (tline
->type
!= TOK_PREPROC_ID
||
3095 tline
->text
[1] != '$'))) {
3096 nasm_error(ERR_NONFATAL
, "`%%undef' expects a macro identifier");
3097 free_tlist(origline
);
3098 return DIRECTIVE_FOUND
;
3101 nasm_error(ERR_WARNING
|ERR_PASS1
,
3102 "trailing garbage after macro name ignored");
3105 /* Find the context that symbol belongs to */
3106 ctx
= get_ctx(tline
->text
, &mname
);
3107 undef_smacro(ctx
, mname
);
3108 free_tlist(origline
);
3109 return DIRECTIVE_FOUND
;
3113 casesense
= (i
== PP_DEFSTR
);
3115 tline
= tline
->next
;
3117 tline
= expand_id(tline
);
3118 if (!tline
|| (tline
->type
!= TOK_ID
&&
3119 (tline
->type
!= TOK_PREPROC_ID
||
3120 tline
->text
[1] != '$'))) {
3121 nasm_error(ERR_NONFATAL
, "`%s' expects a macro identifier",
3123 free_tlist(origline
);
3124 return DIRECTIVE_FOUND
;
3127 ctx
= get_ctx(tline
->text
, &mname
);
3129 tline
= expand_smacro(tline
->next
);
3132 while (tok_type_(tline
, TOK_WHITESPACE
))
3133 tline
= delete_Token(tline
);
3135 p
= detoken(tline
, false);
3136 macro_start
= nasm_malloc(sizeof(*macro_start
));
3137 macro_start
->next
= NULL
;
3138 macro_start
->text
= nasm_quote(p
, strlen(p
));
3139 macro_start
->type
= TOK_STRING
;
3140 macro_start
->a
.mac
= NULL
;
3144 * We now have a macro name, an implicit parameter count of
3145 * zero, and a string token to use as an expansion. Create
3146 * and store an SMacro.
3148 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3149 free_tlist(origline
);
3150 return DIRECTIVE_FOUND
;
3154 casesense
= (i
== PP_DEFTOK
);
3156 tline
= tline
->next
;
3158 tline
= expand_id(tline
);
3159 if (!tline
|| (tline
->type
!= TOK_ID
&&
3160 (tline
->type
!= TOK_PREPROC_ID
||
3161 tline
->text
[1] != '$'))) {
3162 nasm_error(ERR_NONFATAL
,
3163 "`%s' expects a macro identifier as first parameter",
3165 free_tlist(origline
);
3166 return DIRECTIVE_FOUND
;
3168 ctx
= get_ctx(tline
->text
, &mname
);
3170 tline
= expand_smacro(tline
->next
);
3174 while (tok_type_(t
, TOK_WHITESPACE
))
3176 /* t should now point to the string */
3177 if (!tok_type_(t
, TOK_STRING
)) {
3178 nasm_error(ERR_NONFATAL
,
3179 "`%s` requires string as second parameter",
3182 free_tlist(origline
);
3183 return DIRECTIVE_FOUND
;
3187 * Convert the string to a token stream. Note that smacros
3188 * are stored with the token stream reversed, so we have to
3189 * reverse the output of tokenize().
3191 nasm_unquote_cstr(t
->text
, i
);
3192 macro_start
= reverse_tokens(tokenize(t
->text
));
3195 * We now have a macro name, an implicit parameter count of
3196 * zero, and a numeric token to use as an expansion. Create
3197 * and store an SMacro.
3199 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3201 free_tlist(origline
);
3202 return DIRECTIVE_FOUND
;
3207 StrList
*xsl
= NULL
;
3208 StrList
**xst
= &xsl
;
3212 tline
= tline
->next
;
3214 tline
= expand_id(tline
);
3215 if (!tline
|| (tline
->type
!= TOK_ID
&&
3216 (tline
->type
!= TOK_PREPROC_ID
||
3217 tline
->text
[1] != '$'))) {
3218 nasm_error(ERR_NONFATAL
,
3219 "`%%pathsearch' expects a macro identifier as first parameter");
3220 free_tlist(origline
);
3221 return DIRECTIVE_FOUND
;
3223 ctx
= get_ctx(tline
->text
, &mname
);
3225 tline
= expand_smacro(tline
->next
);
3229 while (tok_type_(t
, TOK_WHITESPACE
))
3232 if (!t
|| (t
->type
!= TOK_STRING
&&
3233 t
->type
!= TOK_INTERNAL_STRING
)) {
3234 nasm_error(ERR_NONFATAL
, "`%%pathsearch' expects a file name");
3236 free_tlist(origline
);
3237 return DIRECTIVE_FOUND
; /* but we did _something_ */
3240 nasm_error(ERR_WARNING
|ERR_PASS1
,
3241 "trailing garbage after `%%pathsearch' ignored");
3243 if (t
->type
!= TOK_INTERNAL_STRING
)
3244 nasm_unquote(p
, NULL
);
3246 fp
= inc_fopen(p
, &xsl
, &xst
, true);
3249 fclose(fp
); /* Don't actually care about the file */
3251 macro_start
= nasm_malloc(sizeof(*macro_start
));
3252 macro_start
->next
= NULL
;
3253 macro_start
->text
= nasm_quote(p
, strlen(p
));
3254 macro_start
->type
= TOK_STRING
;
3255 macro_start
->a
.mac
= NULL
;
3260 * We now have a macro name, an implicit parameter count of
3261 * zero, and a string token to use as an expansion. Create
3262 * and store an SMacro.
3264 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3266 free_tlist(origline
);
3267 return DIRECTIVE_FOUND
;
3273 tline
= tline
->next
;
3275 tline
= expand_id(tline
);
3276 if (!tline
|| (tline
->type
!= TOK_ID
&&
3277 (tline
->type
!= TOK_PREPROC_ID
||
3278 tline
->text
[1] != '$'))) {
3279 nasm_error(ERR_NONFATAL
,
3280 "`%%strlen' expects a macro identifier as first parameter");
3281 free_tlist(origline
);
3282 return DIRECTIVE_FOUND
;
3284 ctx
= get_ctx(tline
->text
, &mname
);
3286 tline
= expand_smacro(tline
->next
);
3290 while (tok_type_(t
, TOK_WHITESPACE
))
3292 /* t should now point to the string */
3293 if (!tok_type_(t
, TOK_STRING
)) {
3294 nasm_error(ERR_NONFATAL
,
3295 "`%%strlen` requires string as second parameter");
3297 free_tlist(origline
);
3298 return DIRECTIVE_FOUND
;
3301 macro_start
= nasm_malloc(sizeof(*macro_start
));
3302 macro_start
->next
= NULL
;
3303 make_tok_num(macro_start
, nasm_unquote(t
->text
, NULL
));
3304 macro_start
->a
.mac
= NULL
;
3307 * We now have a macro name, an implicit parameter count of
3308 * zero, and a numeric token to use as an expansion. Create
3309 * and store an SMacro.
3311 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3313 free_tlist(origline
);
3314 return DIRECTIVE_FOUND
;
3319 tline
= tline
->next
;
3321 tline
= expand_id(tline
);
3322 if (!tline
|| (tline
->type
!= TOK_ID
&&
3323 (tline
->type
!= TOK_PREPROC_ID
||
3324 tline
->text
[1] != '$'))) {
3325 nasm_error(ERR_NONFATAL
,
3326 "`%%strcat' expects a macro identifier as first parameter");
3327 free_tlist(origline
);
3328 return DIRECTIVE_FOUND
;
3330 ctx
= get_ctx(tline
->text
, &mname
);
3332 tline
= expand_smacro(tline
->next
);
3336 list_for_each(t
, tline
) {
3338 case TOK_WHITESPACE
:
3341 len
+= t
->a
.len
= nasm_unquote(t
->text
, NULL
);
3344 if (!strcmp(t
->text
, ",")) /* permit comma separators */
3346 /* else fall through */
3348 nasm_error(ERR_NONFATAL
,
3349 "non-string passed to `%%strcat' (%d)", t
->type
);
3351 free_tlist(origline
);
3352 return DIRECTIVE_FOUND
;
3356 p
= pp
= nasm_malloc(len
);
3357 list_for_each(t
, tline
) {
3358 if (t
->type
== TOK_STRING
) {
3359 memcpy(p
, t
->text
, t
->a
.len
);
3365 * We now have a macro name, an implicit parameter count of
3366 * zero, and a numeric token to use as an expansion. Create
3367 * and store an SMacro.
3369 macro_start
= new_Token(NULL
, TOK_STRING
, NULL
, 0);
3370 macro_start
->text
= nasm_quote(pp
, len
);
3372 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3374 free_tlist(origline
);
3375 return DIRECTIVE_FOUND
;
3379 int64_t start
, count
;
3384 tline
= tline
->next
;
3386 tline
= expand_id(tline
);
3387 if (!tline
|| (tline
->type
!= TOK_ID
&&
3388 (tline
->type
!= TOK_PREPROC_ID
||
3389 tline
->text
[1] != '$'))) {
3390 nasm_error(ERR_NONFATAL
,
3391 "`%%substr' expects a macro identifier as first parameter");
3392 free_tlist(origline
);
3393 return DIRECTIVE_FOUND
;
3395 ctx
= get_ctx(tline
->text
, &mname
);
3397 tline
= expand_smacro(tline
->next
);
3400 if (tline
) /* skip expanded id */
3402 while (tok_type_(t
, TOK_WHITESPACE
))
3405 /* t should now point to the string */
3406 if (!tok_type_(t
, TOK_STRING
)) {
3407 nasm_error(ERR_NONFATAL
,
3408 "`%%substr` requires string as second parameter");
3410 free_tlist(origline
);
3411 return DIRECTIVE_FOUND
;
3416 tokval
.t_type
= TOKEN_INVALID
;
3417 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, NULL
);
3420 free_tlist(origline
);
3421 return DIRECTIVE_FOUND
;
3422 } else if (!is_simple(evalresult
)) {
3423 nasm_error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3425 free_tlist(origline
);
3426 return DIRECTIVE_FOUND
;
3428 start
= evalresult
->value
- 1;
3430 while (tok_type_(tt
, TOK_WHITESPACE
))
3433 count
= 1; /* Backwards compatibility: one character */
3435 tokval
.t_type
= TOKEN_INVALID
;
3436 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, NULL
);
3439 free_tlist(origline
);
3440 return DIRECTIVE_FOUND
;
3441 } else if (!is_simple(evalresult
)) {
3442 nasm_error(ERR_NONFATAL
, "non-constant value given to `%%substr`");
3444 free_tlist(origline
);
3445 return DIRECTIVE_FOUND
;
3447 count
= evalresult
->value
;
3450 len
= nasm_unquote(t
->text
, NULL
);
3452 /* make start and count being in range */
3456 count
= len
+ count
+ 1 - start
;
3457 if (start
+ count
> (int64_t)len
)
3458 count
= len
- start
;
3459 if (!len
|| count
< 0 || start
>=(int64_t)len
)
3460 start
= -1, count
= 0; /* empty string */
3462 macro_start
= nasm_malloc(sizeof(*macro_start
));
3463 macro_start
->next
= NULL
;
3464 macro_start
->text
= nasm_quote((start
< 0) ? "" : t
->text
+ start
, count
);
3465 macro_start
->type
= TOK_STRING
;
3466 macro_start
->a
.mac
= NULL
;
3469 * We now have a macro name, an implicit parameter count of
3470 * zero, and a numeric token to use as an expansion. Create
3471 * and store an SMacro.
3473 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3475 free_tlist(origline
);
3476 return DIRECTIVE_FOUND
;
3481 casesense
= (i
== PP_ASSIGN
);
3483 tline
= tline
->next
;
3485 tline
= expand_id(tline
);
3486 if (!tline
|| (tline
->type
!= TOK_ID
&&
3487 (tline
->type
!= TOK_PREPROC_ID
||
3488 tline
->text
[1] != '$'))) {
3489 nasm_error(ERR_NONFATAL
,
3490 "`%%%sassign' expects a macro identifier",
3491 (i
== PP_IASSIGN
? "i" : ""));
3492 free_tlist(origline
);
3493 return DIRECTIVE_FOUND
;
3495 ctx
= get_ctx(tline
->text
, &mname
);
3497 tline
= expand_smacro(tline
->next
);
3502 tokval
.t_type
= TOKEN_INVALID
;
3503 evalresult
= evaluate(ppscan
, tptr
, &tokval
, NULL
, pass
, NULL
);
3506 free_tlist(origline
);
3507 return DIRECTIVE_FOUND
;
3511 nasm_error(ERR_WARNING
|ERR_PASS1
,
3512 "trailing garbage after expression ignored");
3514 if (!is_simple(evalresult
)) {
3515 nasm_error(ERR_NONFATAL
,
3516 "non-constant value given to `%%%sassign'",
3517 (i
== PP_IASSIGN
? "i" : ""));
3518 free_tlist(origline
);
3519 return DIRECTIVE_FOUND
;
3522 macro_start
= nasm_malloc(sizeof(*macro_start
));
3523 macro_start
->next
= NULL
;
3524 make_tok_num(macro_start
, reloc_value(evalresult
));
3525 macro_start
->a
.mac
= NULL
;
3528 * We now have a macro name, an implicit parameter count of
3529 * zero, and a numeric token to use as an expansion. Create
3530 * and store an SMacro.
3532 define_smacro(ctx
, mname
, casesense
, 0, macro_start
);
3533 free_tlist(origline
);
3534 return DIRECTIVE_FOUND
;
3538 * Syntax is `%line nnn[+mmm] [filename]'
3540 tline
= tline
->next
;
3542 if (!tok_type_(tline
, TOK_NUMBER
)) {
3543 nasm_error(ERR_NONFATAL
, "`%%line' expects line number");
3544 free_tlist(origline
);
3545 return DIRECTIVE_FOUND
;
3547 k
= readnum(tline
->text
, &err
);
3549 tline
= tline
->next
;
3550 if (tok_is_(tline
, "+")) {
3551 tline
= tline
->next
;
3552 if (!tok_type_(tline
, TOK_NUMBER
)) {
3553 nasm_error(ERR_NONFATAL
, "`%%line' expects line increment");
3554 free_tlist(origline
);
3555 return DIRECTIVE_FOUND
;
3557 m
= readnum(tline
->text
, &err
);
3558 tline
= tline
->next
;
3564 nasm_free(src_set_fname(detoken(tline
, false)));
3566 free_tlist(origline
);
3567 return DIRECTIVE_FOUND
;
3570 nasm_error(ERR_FATAL
,
3571 "preprocessor directive `%s' not yet implemented",
3573 return DIRECTIVE_FOUND
;
3578 * Ensure that a macro parameter contains a condition code and
3579 * nothing else. Return the condition code index if so, or -1
3582 static int find_cc(Token
* t
)
3587 return -1; /* Probably a %+ without a space */
3590 if (t
->type
!= TOK_ID
)
3594 if (tt
&& (tt
->type
!= TOK_OTHER
|| strcmp(tt
->text
, ",")))
3597 return bsii(t
->text
, (const char **)conditions
, ARRAY_SIZE(conditions
));
3601 * This routines walks over tokens strem and hadnles tokens
3602 * pasting, if @handle_explicit passed then explicit pasting
3603 * term is handled, otherwise -- implicit pastings only.
3605 static bool paste_tokens(Token
**head
, const struct tokseq_match
*m
,
3606 size_t mnum
, bool handle_explicit
)
3608 Token
*tok
, *next
, **prev_next
, **prev_nonspace
;
3609 bool pasted
= false;
3614 * The last token before pasting. We need it
3615 * to be able to connect new handled tokens.
3616 * In other words if there were a tokens stream
3620 * and we've joined tokens B and C, the resulting
3628 if (!tok_type_(tok
, TOK_WHITESPACE
) && !tok_type_(tok
, TOK_PASTE
))
3629 prev_nonspace
= head
;
3631 prev_nonspace
= NULL
;
3633 while (tok
&& (next
= tok
->next
)) {
3635 switch (tok
->type
) {
3636 case TOK_WHITESPACE
:
3637 /* Zap redundant whitespaces */
3638 while (tok_type_(next
, TOK_WHITESPACE
))
3639 next
= delete_Token(next
);
3644 /* Explicit pasting */
3645 if (!handle_explicit
)
3647 next
= delete_Token(tok
);
3649 while (tok_type_(next
, TOK_WHITESPACE
))
3650 next
= delete_Token(next
);
3655 /* Left pasting token is start of line */
3657 nasm_error(ERR_FATAL
, "No lvalue found on pasting");
3660 * No ending token, this might happen in two
3663 * 1) There indeed no right token at all
3664 * 2) There is a bare "%define ID" statement,
3665 * and @ID does expand to whitespace.
3667 * So technically we need to do a grammar analysis
3668 * in another stage of parsing, but for now lets don't
3669 * change the behaviour people used to. Simply allow
3670 * whitespace after paste token.
3674 * Zap ending space tokens and that's all.
3676 tok
= (*prev_nonspace
)->next
;
3677 while (tok_type_(tok
, TOK_WHITESPACE
))
3678 tok
= delete_Token(tok
);
3679 tok
= *prev_nonspace
;
3684 tok
= *prev_nonspace
;
3685 while (tok_type_(tok
, TOK_WHITESPACE
))
3686 tok
= delete_Token(tok
);
3687 len
= strlen(tok
->text
);
3688 len
+= strlen(next
->text
);
3690 p
= buf
= nasm_malloc(len
+ 1);
3691 strcpy(p
, tok
->text
);
3692 p
= strchr(p
, '\0');
3693 strcpy(p
, next
->text
);
3697 tok
= tokenize(buf
);
3700 *prev_nonspace
= tok
;
3701 while (tok
&& tok
->next
)
3704 tok
->next
= delete_Token(next
);
3706 /* Restart from pasted tokens head */
3707 tok
= *prev_nonspace
;
3711 /* implicit pasting */
3712 for (i
= 0; i
< mnum
; i
++) {
3713 if (!(PP_CONCAT_MATCH(tok
, m
[i
].mask_head
)))
3717 while (next
&& PP_CONCAT_MATCH(next
, m
[i
].mask_tail
)) {
3718 len
+= strlen(next
->text
);
3726 len
+= strlen(tok
->text
);
3727 p
= buf
= nasm_malloc(len
+ 1);
3729 while (tok
!= next
) {
3730 strcpy(p
, tok
->text
);
3731 p
= strchr(p
, '\0');
3732 tok
= delete_Token(tok
);
3735 tok
= tokenize(buf
);
3744 * Connect pasted into original stream,
3745 * ie A -> new-tokens -> B
3747 while (tok
&& tok
->next
)
3754 /* Restart from pasted tokens head */
3755 tok
= prev_next
? *prev_next
: *head
;
3761 prev_next
= &tok
->next
;
3764 !tok_type_(tok
->next
, TOK_WHITESPACE
) &&
3765 !tok_type_(tok
->next
, TOK_PASTE
))
3766 prev_nonspace
= prev_next
;
3775 * expands to a list of tokens from %{x:y}
3777 static Token
*expand_mmac_params_range(MMacro
*mac
, Token
*tline
, Token
***last
)
3779 Token
*t
= tline
, **tt
, *tm
, *head
;
3783 pos
= strchr(tline
->text
, ':');
3786 lst
= atoi(pos
+ 1);
3787 fst
= atoi(tline
->text
+ 1);
3790 * only macros params are accounted so
3791 * if someone passes %0 -- we reject such
3794 if (lst
== 0 || fst
== 0)
3797 /* the values should be sane */
3798 if ((fst
> (int)mac
->nparam
|| fst
< (-(int)mac
->nparam
)) ||
3799 (lst
> (int)mac
->nparam
|| lst
< (-(int)mac
->nparam
)))
3802 fst
= fst
< 0 ? fst
+ (int)mac
->nparam
+ 1: fst
;
3803 lst
= lst
< 0 ? lst
+ (int)mac
->nparam
+ 1: lst
;
3805 /* counted from zero */
3809 * It will be at least one token. Note we
3810 * need to scan params until separator, otherwise
3811 * only first token will be passed.
3813 tm
= mac
->params
[(fst
+ mac
->rotate
) % mac
->nparam
];
3814 head
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3815 tt
= &head
->next
, tm
= tm
->next
;
3816 while (tok_isnt_(tm
, ",")) {
3817 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3818 *tt
= t
, tt
= &t
->next
, tm
= tm
->next
;
3822 for (i
= fst
+ 1; i
<= lst
; i
++) {
3823 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3824 *tt
= t
, tt
= &t
->next
;
3825 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3826 tm
= mac
->params
[j
];
3827 while (tok_isnt_(tm
, ",")) {
3828 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3829 *tt
= t
, tt
= &t
->next
, tm
= tm
->next
;
3833 for (i
= fst
- 1; i
>= lst
; i
--) {
3834 t
= new_Token(NULL
, TOK_OTHER
, ",", 0);
3835 *tt
= t
, tt
= &t
->next
;
3836 j
= (i
+ mac
->rotate
) % mac
->nparam
;
3837 tm
= mac
->params
[j
];
3838 while (tok_isnt_(tm
, ",")) {
3839 t
= new_Token(NULL
, tm
->type
, tm
->text
, 0);
3840 *tt
= t
, tt
= &t
->next
, tm
= tm
->next
;
3849 nasm_error(ERR_NONFATAL
, "`%%{%s}': macro parameters out of range",
3855 * Expand MMacro-local things: parameter references (%0, %n, %+n,
3856 * %-n) and MMacro-local identifiers (%%foo) as well as
3857 * macro indirection (%[...]) and range (%{..:..}).
3859 static Token
*expand_mmac_params(Token
* tline
)
3861 Token
*t
, *tt
, **tail
, *thead
;
3862 bool changed
= false;
3869 if (tline
->type
== TOK_PREPROC_ID
&&
3870 (((tline
->text
[1] == '+' || tline
->text
[1] == '-') && tline
->text
[2]) ||
3871 (tline
->text
[1] >= '0' && tline
->text
[1] <= '9') ||
3872 tline
->text
[1] == '%')) {
3874 int type
= 0, cc
; /* type = 0 to placate optimisers */
3881 tline
= tline
->next
;
3884 while (mac
&& !mac
->name
) /* avoid mistaking %reps for macros */
3885 mac
= mac
->next_active
;
3887 nasm_error(ERR_NONFATAL
, "`%s': not in a macro call", t
->text
);
3889 pos
= strchr(t
->text
, ':');
3891 switch (t
->text
[1]) {
3893 * We have to make a substitution of one of the
3894 * forms %1, %-1, %+1, %%foo, %0.
3898 snprintf(tmpbuf
, sizeof(tmpbuf
), "%d", mac
->nparam
);
3899 text
= nasm_strdup(tmpbuf
);
3903 snprintf(tmpbuf
, sizeof(tmpbuf
), "..@%"PRIu64
".",
3905 text
= nasm_strcat(tmpbuf
, t
->text
+ 2);
3908 n
= atoi(t
->text
+ 2) - 1;
3909 if (n
>= mac
->nparam
)
3912 if (mac
->nparam
> 1)
3913 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3914 tt
= mac
->params
[n
];
3918 nasm_error(ERR_NONFATAL
,
3919 "macro parameter %d is not a condition code",
3924 if (inverse_ccs
[cc
] == -1) {
3925 nasm_error(ERR_NONFATAL
,
3926 "condition code `%s' is not invertible",
3930 text
= nasm_strdup(conditions
[inverse_ccs
[cc
]]);
3934 n
= atoi(t
->text
+ 2) - 1;
3935 if (n
>= mac
->nparam
)
3938 if (mac
->nparam
> 1)
3939 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3940 tt
= mac
->params
[n
];
3944 nasm_error(ERR_NONFATAL
,
3945 "macro parameter %d is not a condition code",
3950 text
= nasm_strdup(conditions
[cc
]);
3954 n
= atoi(t
->text
+ 1) - 1;
3955 if (n
>= mac
->nparam
)
3958 if (mac
->nparam
> 1)
3959 n
= (n
+ mac
->rotate
) % mac
->nparam
;
3960 tt
= mac
->params
[n
];
3963 for (i
= 0; i
< mac
->paramlen
[n
]; i
++) {
3964 *tail
= new_Token(NULL
, tt
->type
, tt
->text
, 0);
3965 tail
= &(*tail
)->next
;
3969 text
= NULL
; /* we've done it here */
3974 * seems we have a parameters range here
3976 Token
*head
, **last
;
3977 head
= expand_mmac_params_range(mac
, t
, &last
);
3998 } else if (tline
->type
== TOK_INDIRECT
) {
4000 tline
= tline
->next
;
4001 tt
= tokenize(t
->text
);
4002 tt
= expand_mmac_params(tt
);
4003 tt
= expand_smacro(tt
);
4006 tt
->a
.mac
= NULL
; /* Necessary? */
4014 tline
= tline
->next
;
4022 const struct tokseq_match t
[] = {
4024 PP_CONCAT_MASK(TOK_ID
) |
4025 PP_CONCAT_MASK(TOK_FLOAT
), /* head */
4026 PP_CONCAT_MASK(TOK_ID
) |
4027 PP_CONCAT_MASK(TOK_NUMBER
) |
4028 PP_CONCAT_MASK(TOK_FLOAT
) |
4029 PP_CONCAT_MASK(TOK_OTHER
) /* tail */
4032 PP_CONCAT_MASK(TOK_NUMBER
), /* head */
4033 PP_CONCAT_MASK(TOK_NUMBER
) /* tail */
4036 paste_tokens(&thead
, t
, ARRAY_SIZE(t
), false);
4043 * Expand all single-line macro calls made in the given line.
4044 * Return the expanded version of the line. The original is deemed
4045 * to be destroyed in the process. (In reality we'll just move
4046 * Tokens from input to output a lot of the time, rather than
4047 * actually bothering to destroy and replicate.)
4050 static Token
*expand_smacro(Token
* tline
)
4052 Token
*t
, *tt
, *mstart
, **tail
, *thead
;
4053 SMacro
*head
= NULL
, *m
;
4056 unsigned int nparam
, sparam
;
4058 Token
*org_tline
= tline
;
4061 int deadman
= DEADMAN_LIMIT
;
4065 * Trick: we should avoid changing the start token pointer since it can
4066 * be contained in "next" field of other token. Because of this
4067 * we allocate a copy of first token and work with it; at the end of
4068 * routine we copy it back
4071 tline
= new_Token(org_tline
->next
, org_tline
->type
,
4072 org_tline
->text
, 0);
4073 tline
->a
.mac
= org_tline
->a
.mac
;
4074 nasm_free(org_tline
->text
);
4075 org_tline
->text
= NULL
;
4078 expanded
= true; /* Always expand %+ at least once */
4084 while (tline
) { /* main token loop */
4086 nasm_error(ERR_NONFATAL
, "interminable macro recursion");
4090 if ((mname
= tline
->text
)) {
4091 /* if this token is a local macro, look in local context */
4092 if (tline
->type
== TOK_ID
) {
4093 head
= (SMacro
*)hash_findix(&smacros
, mname
);
4094 } else if (tline
->type
== TOK_PREPROC_ID
) {
4095 ctx
= get_ctx(mname
, &mname
);
4096 head
= ctx
? (SMacro
*)hash_findix(&ctx
->localmac
, mname
) : NULL
;
4101 * We've hit an identifier. As in is_mmacro below, we first
4102 * check whether the identifier is a single-line macro at
4103 * all, then think about checking for parameters if
4106 list_for_each(m
, head
)
4107 if (!mstrcmp(m
->name
, mname
, m
->casesense
))
4113 if (m
->nparam
== 0) {
4115 * Simple case: the macro is parameterless. Discard the
4116 * one token that the macro call took, and push the
4117 * expansion back on the to-do stack.
4119 if (!m
->expansion
) {
4120 if (!strcmp("__FILE__", m
->name
)) {
4123 src_get(&num
, &file
);
4124 tline
->text
= nasm_quote(file
, strlen(file
));
4125 tline
->type
= TOK_STRING
;
4129 if (!strcmp("__LINE__", m
->name
)) {
4130 nasm_free(tline
->text
);
4131 make_tok_num(tline
, src_get_linnum());
4134 if (!strcmp("__BITS__", m
->name
)) {
4135 nasm_free(tline
->text
);
4136 make_tok_num(tline
, globalbits
);
4139 tline
= delete_Token(tline
);
4144 * Complicated case: at least one macro with this name
4145 * exists and takes parameters. We must find the
4146 * parameters in the call, count them, find the SMacro
4147 * that corresponds to that form of the macro call, and
4148 * substitute for the parameters when we expand. What a
4151 /*tline = tline->next;
4152 skip_white_(tline); */
4155 while (tok_type_(t
, TOK_SMAC_END
)) {
4156 t
->a
.mac
->in_progress
= false;
4158 t
= tline
->next
= delete_Token(t
);
4161 } while (tok_type_(tline
, TOK_WHITESPACE
));
4162 if (!tok_is_(tline
, "(")) {
4164 * This macro wasn't called with parameters: ignore
4165 * the call. (Behaviour borrowed from gnu cpp.)
4174 sparam
= PARAM_DELTA
;
4175 params
= nasm_malloc(sparam
* sizeof(Token
*));
4176 params
[0] = tline
->next
;
4177 paramsize
= nasm_malloc(sparam
* sizeof(int));
4179 while (true) { /* parameter loop */
4181 * For some unusual expansions
4182 * which concatenates function call
4185 while (tok_type_(t
, TOK_SMAC_END
)) {
4186 t
->a
.mac
->in_progress
= false;
4188 t
= tline
->next
= delete_Token(t
);
4193 nasm_error(ERR_NONFATAL
,
4194 "macro call expects terminating `)'");
4197 if (tline
->type
== TOK_WHITESPACE
4199 if (paramsize
[nparam
])
4202 params
[nparam
] = tline
->next
;
4203 continue; /* parameter loop */
4205 if (tline
->type
== TOK_OTHER
4206 && tline
->text
[1] == 0) {
4207 char ch
= tline
->text
[0];
4208 if (ch
== ',' && !paren
&& brackets
<= 0) {
4209 if (++nparam
>= sparam
) {
4210 sparam
+= PARAM_DELTA
;
4211 params
= nasm_realloc(params
,
4212 sparam
* sizeof(Token
*));
4213 paramsize
= nasm_realloc(paramsize
,
4214 sparam
* sizeof(int));
4216 params
[nparam
] = tline
->next
;
4217 paramsize
[nparam
] = 0;
4219 continue; /* parameter loop */
4222 (brackets
> 0 || (brackets
== 0 &&
4223 !paramsize
[nparam
])))
4225 if (!(brackets
++)) {
4226 params
[nparam
] = tline
->next
;
4227 continue; /* parameter loop */
4230 if (ch
== '}' && brackets
> 0)
4231 if (--brackets
== 0) {
4233 continue; /* parameter loop */
4235 if (ch
== '(' && !brackets
)
4237 if (ch
== ')' && brackets
<= 0)
4243 nasm_error(ERR_NONFATAL
, "braces do not "
4244 "enclose all of macro parameter");
4246 paramsize
[nparam
] += white
+ 1;
4248 } /* parameter loop */
4250 while (m
&& (m
->nparam
!= nparam
||
4251 mstrcmp(m
->name
, mname
,
4255 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4256 "macro `%s' exists, "
4257 "but not taking %d parameters",
4258 mstart
->text
, nparam
);
4261 if (m
&& m
->in_progress
)
4263 if (!m
) { /* in progess or didn't find '(' or wrong nparam */
4265 * Design question: should we handle !tline, which
4266 * indicates missing ')' here, or expand those
4267 * macros anyway, which requires the (t) test a few
4271 nasm_free(paramsize
);
4275 * Expand the macro: we are placed on the last token of the
4276 * call, so that we can easily split the call from the
4277 * following tokens. We also start by pushing an SMAC_END
4278 * token for the cycle removal.
4285 tt
= new_Token(tline
, TOK_SMAC_END
, NULL
, 0);
4287 m
->in_progress
= true;
4289 list_for_each(t
, m
->expansion
) {
4290 if (t
->type
>= TOK_SMAC_PARAM
) {
4291 Token
*pcopy
= tline
, **ptail
= &pcopy
;
4295 ttt
= params
[t
->type
- TOK_SMAC_PARAM
];
4296 i
= paramsize
[t
->type
- TOK_SMAC_PARAM
];
4298 pt
= *ptail
= new_Token(tline
, ttt
->type
,
4304 } else if (t
->type
== TOK_PREPROC_Q
) {
4305 tt
= new_Token(tline
, TOK_ID
, mname
, 0);
4307 } else if (t
->type
== TOK_PREPROC_QQ
) {
4308 tt
= new_Token(tline
, TOK_ID
, m
->name
, 0);
4311 tt
= new_Token(tline
, t
->type
, t
->text
, 0);
4317 * Having done that, get rid of the macro call, and clean
4318 * up the parameters.
4321 nasm_free(paramsize
);
4324 continue; /* main token loop */
4329 if (tline
->type
== TOK_SMAC_END
) {
4330 tline
->a
.mac
->in_progress
= false;
4331 tline
= delete_Token(tline
);
4334 tline
= tline
->next
;
4342 * Now scan the entire line and look for successive TOK_IDs that resulted
4343 * after expansion (they can't be produced by tokenize()). The successive
4344 * TOK_IDs should be concatenated.
4345 * Also we look for %+ tokens and concatenate the tokens before and after
4346 * them (without white spaces in between).
4349 const struct tokseq_match t
[] = {
4351 PP_CONCAT_MASK(TOK_ID
) |
4352 PP_CONCAT_MASK(TOK_PREPROC_ID
), /* head */
4353 PP_CONCAT_MASK(TOK_ID
) |
4354 PP_CONCAT_MASK(TOK_PREPROC_ID
) |
4355 PP_CONCAT_MASK(TOK_NUMBER
) /* tail */
4358 if (paste_tokens(&thead
, t
, ARRAY_SIZE(t
), true)) {
4360 * If we concatenated something, *and* we had previously expanded
4361 * an actual macro, scan the lines again for macros...
4372 *org_tline
= *thead
;
4373 /* since we just gave text to org_line, don't free it */
4375 delete_Token(thead
);
4377 /* the expression expanded to empty line;
4378 we can't return NULL for some reasons
4379 we just set the line to a single WHITESPACE token. */
4380 memset(org_tline
, 0, sizeof(*org_tline
));
4381 org_tline
->text
= NULL
;
4382 org_tline
->type
= TOK_WHITESPACE
;
4391 * Similar to expand_smacro but used exclusively with macro identifiers
4392 * right before they are fetched in. The reason is that there can be
4393 * identifiers consisting of several subparts. We consider that if there
4394 * are more than one element forming the name, user wants a expansion,
4395 * otherwise it will be left as-is. Example:
4399 * the identifier %$abc will be left as-is so that the handler for %define
4400 * will suck it and define the corresponding value. Other case:
4402 * %define _%$abc cde
4404 * In this case user wants name to be expanded *before* %define starts
4405 * working, so we'll expand %$abc into something (if it has a value;
4406 * otherwise it will be left as-is) then concatenate all successive
4409 static Token
*expand_id(Token
* tline
)
4411 Token
*cur
, *oldnext
= NULL
;
4413 if (!tline
|| !tline
->next
)
4418 (cur
->next
->type
== TOK_ID
||
4419 cur
->next
->type
== TOK_PREPROC_ID
4420 || cur
->next
->type
== TOK_NUMBER
))
4423 /* If identifier consists of just one token, don't expand */
4428 oldnext
= cur
->next
; /* Detach the tail past identifier */
4429 cur
->next
= NULL
; /* so that expand_smacro stops here */
4432 tline
= expand_smacro(tline
);
4435 /* expand_smacro possibly changhed tline; re-scan for EOL */
4437 while (cur
&& cur
->next
)
4440 cur
->next
= oldnext
;
4447 * Determine whether the given line constitutes a multi-line macro
4448 * call, and return the MMacro structure called if so. Doesn't have
4449 * to check for an initial label - that's taken care of in
4450 * expand_mmacro - but must check numbers of parameters. Guaranteed
4451 * to be called with tline->type == TOK_ID, so the putative macro
4452 * name is easy to find.
4454 static MMacro
*is_mmacro(Token
* tline
, Token
*** params_array
)
4460 head
= (MMacro
*) hash_findix(&mmacros
, tline
->text
);
4463 * Efficiency: first we see if any macro exists with the given
4464 * name. If not, we can return NULL immediately. _Then_ we
4465 * count the parameters, and then we look further along the
4466 * list if necessary to find the proper MMacro.
4468 list_for_each(m
, head
)
4469 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4475 * OK, we have a potential macro. Count and demarcate the
4478 count_mmac_params(tline
->next
, &nparam
, ¶ms
);
4481 * So we know how many parameters we've got. Find the MMacro
4482 * structure that handles this number.
4485 if (m
->nparam_min
<= nparam
4486 && (m
->plus
|| nparam
<= m
->nparam_max
)) {
4488 * This one is right. Just check if cycle removal
4489 * prohibits us using it before we actually celebrate...
4491 if (m
->in_progress
> m
->max_depth
) {
4492 if (m
->max_depth
> 0) {
4493 nasm_error(ERR_WARNING
,
4494 "reached maximum recursion depth of %i",
4501 * It's right, and we can use it. Add its default
4502 * parameters to the end of our list if necessary.
4504 if (m
->defaults
&& nparam
< m
->nparam_min
+ m
->ndefs
) {
4506 nasm_realloc(params
,
4507 ((m
->nparam_min
+ m
->ndefs
+
4508 1) * sizeof(*params
)));
4509 while (nparam
< m
->nparam_min
+ m
->ndefs
) {
4510 params
[nparam
] = m
->defaults
[nparam
- m
->nparam_min
];
4515 * If we've gone over the maximum parameter count (and
4516 * we're in Plus mode), ignore parameters beyond
4519 if (m
->plus
&& nparam
> m
->nparam_max
)
4520 nparam
= m
->nparam_max
;
4522 * Then terminate the parameter list, and leave.
4524 if (!params
) { /* need this special case */
4525 params
= nasm_malloc(sizeof(*params
));
4528 params
[nparam
] = NULL
;
4529 *params_array
= params
;
4533 * This one wasn't right: look for the next one with the
4536 list_for_each(m
, m
->next
)
4537 if (!mstrcmp(m
->name
, tline
->text
, m
->casesense
))
4542 * After all that, we didn't find one with the right number of
4543 * parameters. Issue a warning, and fail to expand the macro.
4545 nasm_error(ERR_WARNING
|ERR_PASS1
|ERR_WARN_MNP
,
4546 "macro `%s' exists, but not taking %d parameters",
4547 tline
->text
, nparam
);
4554 * Save MMacro invocation specific fields in
4555 * preparation for a recursive macro expansion
4557 static void push_mmacro(MMacro
*m
)
4559 MMacroInvocation
*i
;
4561 i
= nasm_malloc(sizeof(MMacroInvocation
));
4563 i
->params
= m
->params
;
4564 i
->iline
= m
->iline
;
4565 i
->nparam
= m
->nparam
;
4566 i
->rotate
= m
->rotate
;
4567 i
->paramlen
= m
->paramlen
;
4568 i
->unique
= m
->unique
;
4569 i
->condcnt
= m
->condcnt
;
4575 * Restore MMacro invocation specific fields that were
4576 * saved during a previous recursive macro expansion
4578 static void pop_mmacro(MMacro
*m
)
4580 MMacroInvocation
*i
;
4585 m
->params
= i
->params
;
4586 m
->iline
= i
->iline
;
4587 m
->nparam
= i
->nparam
;
4588 m
->rotate
= i
->rotate
;
4589 m
->paramlen
= i
->paramlen
;
4590 m
->unique
= i
->unique
;
4591 m
->condcnt
= i
->condcnt
;
4598 * Expand the multi-line macro call made by the given line, if
4599 * there is one to be expanded. If there is, push the expansion on
4600 * istk->expansion and return 1. Otherwise return 0.
4602 static int expand_mmacro(Token
* tline
)
4604 Token
*startline
= tline
;
4605 Token
*label
= NULL
;
4606 int dont_prepend
= 0;
4607 Token
**params
, *t
, *tt
;
4610 int i
, nparam
, *paramlen
;
4615 /* if (!tok_type_(t, TOK_ID)) Lino 02/25/02 */
4616 if (!tok_type_(t
, TOK_ID
) && !tok_type_(t
, TOK_PREPROC_ID
))
4618 m
= is_mmacro(t
, ¶ms
);
4624 * We have an id which isn't a macro call. We'll assume
4625 * it might be a label; we'll also check to see if a
4626 * colon follows it. Then, if there's another id after
4627 * that lot, we'll check it again for macro-hood.
4631 if (tok_type_(t
, TOK_WHITESPACE
))
4632 last
= t
, t
= t
->next
;
4633 if (tok_is_(t
, ":")) {
4635 last
= t
, t
= t
->next
;
4636 if (tok_type_(t
, TOK_WHITESPACE
))
4637 last
= t
, t
= t
->next
;
4639 if (!tok_type_(t
, TOK_ID
) || !(m
= is_mmacro(t
, ¶ms
)))
4647 * Fix up the parameters: this involves stripping leading and
4648 * trailing whitespace, then stripping braces if they are
4651 for (nparam
= 0; params
[nparam
]; nparam
++) ;
4652 paramlen
= nparam
? nasm_malloc(nparam
* sizeof(*paramlen
)) : NULL
;
4654 for (i
= 0; params
[i
]; i
++) {
4656 int comma
= (!m
->plus
|| i
< nparam
- 1);
4660 if (tok_is_(t
, "{"))
4661 t
= t
->next
, brace
++, comma
= false;
4665 if (comma
&& t
->type
== TOK_OTHER
&& !strcmp(t
->text
, ","))
4666 break; /* ... because we have hit a comma */
4667 if (comma
&& t
->type
== TOK_WHITESPACE
4668 && tok_is_(t
->next
, ","))
4669 break; /* ... or a space then a comma */
4670 if (brace
&& t
->type
== TOK_OTHER
) {
4671 if (t
->text
[0] == '{')
4672 brace
++; /* ... or a nested opening brace */
4673 else if (t
->text
[0] == '}')
4675 break; /* ... or a brace */
4681 nasm_error(ERR_NONFATAL
, "macro params should be enclosed in braces");
4685 * OK, we have a MMacro structure together with a set of
4686 * parameters. We must now go through the expansion and push
4687 * copies of each Line on to istk->expansion. Substitution of
4688 * parameter tokens and macro-local tokens doesn't get done
4689 * until the single-line macro substitution process; this is
4690 * because delaying them allows us to change the semantics
4691 * later through %rotate.
4693 * First, push an end marker on to istk->expansion, mark this
4694 * macro as in progress, and set up its invocation-specific
4697 ll
= nasm_malloc(sizeof(Line
));
4698 ll
->next
= istk
->expansion
;
4701 istk
->expansion
= ll
;
4704 * Save the previous MMacro expansion in the case of
4707 if (m
->max_depth
&& m
->in_progress
)
4715 m
->paramlen
= paramlen
;
4716 m
->unique
= unique
++;
4720 m
->next_active
= istk
->mstk
;
4723 list_for_each(l
, m
->expansion
) {
4726 ll
= nasm_malloc(sizeof(Line
));
4727 ll
->finishes
= NULL
;
4728 ll
->next
= istk
->expansion
;
4729 istk
->expansion
= ll
;
4732 list_for_each(t
, l
->first
) {
4736 tt
= *tail
= new_Token(NULL
, TOK_ID
, mname
, 0);
4738 case TOK_PREPROC_QQ
:
4739 tt
= *tail
= new_Token(NULL
, TOK_ID
, m
->name
, 0);
4741 case TOK_PREPROC_ID
:
4742 if (t
->text
[1] == '0' && t
->text
[2] == '0') {
4750 tt
= *tail
= new_Token(NULL
, x
->type
, x
->text
, 0);
4759 * If we had a label, push it on as the first line of
4760 * the macro expansion.
4763 if (dont_prepend
< 0)
4764 free_tlist(startline
);
4766 ll
= nasm_malloc(sizeof(Line
));
4767 ll
->finishes
= NULL
;
4768 ll
->next
= istk
->expansion
;
4769 istk
->expansion
= ll
;
4770 ll
->first
= startline
;
4771 if (!dont_prepend
) {
4773 label
= label
->next
;
4774 label
->next
= tt
= new_Token(NULL
, TOK_OTHER
, ":", 0);
4779 lfmt
->uplevel(m
->nolist
? LIST_MACRO_NOLIST
: LIST_MACRO
);
4785 * This function adds macro names to error messages, and suppresses
4786 * them if necessary.
4788 static void pp_verror(int severity
, const char *fmt
, va_list arg
)
4791 MMacro
*mmac
= NULL
;
4795 * If we're in a dead branch of IF or something like it, ignore the error.
4796 * However, because %else etc are evaluated in the state context
4797 * of the previous branch, errors might get lost:
4798 * %if 0 ... %else trailing garbage ... %endif
4799 * So %else etc should set the ERR_PP_PRECOND flag.
4801 if ((severity
& ERR_MASK
) < ERR_FATAL
&&
4802 istk
&& istk
->conds
&&
4803 ((severity
& ERR_PP_PRECOND
) ?
4804 istk
->conds
->state
== COND_NEVER
:
4805 !emitting(istk
->conds
->state
)))
4808 /* get %macro name */
4809 if (!(severity
& ERR_NOFILE
) && istk
&& istk
->mstk
) {
4811 /* but %rep blocks should be skipped */
4812 while (mmac
&& !mmac
->name
)
4813 mmac
= mmac
->next_active
, delta
++;
4817 vsnprintf(buff
, sizeof(buff
), fmt
, arg
);
4819 nasm_set_verror(real_verror
);
4820 nasm_error(severity
, "(%s:%d) %s",
4821 mmac
->name
, mmac
->lineno
- delta
, buff
);
4822 nasm_set_verror(pp_verror
);
4824 real_verror(severity
, fmt
, arg
);
4829 pp_reset(char *file
, int apass
, StrList
**deplist
)
4834 istk
= nasm_malloc(sizeof(Include
));
4837 istk
->expansion
= NULL
;
4839 istk
->fp
= fopen(file
, "r");
4841 src_set_fname(nasm_strdup(file
));
4845 nasm_fatal(ERR_NOFILE
, "unable to open input file `%s'", file
);
4847 nested_mac_count
= 0;
4848 nested_rep_count
= 0;
4851 if (tasm_compatible_mode
) {
4852 stdmacpos
= nasm_stdmac
;
4854 stdmacpos
= nasm_stdmac_after_tasm
;
4856 any_extrastdmac
= extrastdmac
&& *extrastdmac
;
4860 * 0 for dependencies, 1 for preparatory passes, 2 for final pass.
4861 * The caller, however, will also pass in 3 for preprocess-only so
4862 * we can set __PASS__ accordingly.
4864 pass
= apass
> 2 ? 2 : apass
;
4866 dephead
= deptail
= deplist
;
4868 StrList
*sl
= nasm_malloc(strlen(file
)+1+sizeof sl
->next
);
4870 strcpy(sl
->str
, file
);
4872 deptail
= &sl
->next
;
4876 * Define the __PASS__ macro. This is defined here unlike
4877 * all the other builtins, because it is special -- it varies between
4880 t
= nasm_malloc(sizeof(*t
));
4882 make_tok_num(t
, apass
);
4884 define_smacro(NULL
, "__PASS__", true, 0, t
);
4887 static char *pp_getline(void)
4892 real_verror
= nasm_set_verror(pp_verror
);
4896 * Fetch a tokenized line, either from the macro-expansion
4897 * buffer or from the input file.
4900 while (istk
->expansion
&& istk
->expansion
->finishes
) {
4901 Line
*l
= istk
->expansion
;
4902 if (!l
->finishes
->name
&& l
->finishes
->in_progress
> 1) {
4906 * This is a macro-end marker for a macro with no
4907 * name, which means it's not really a macro at all
4908 * but a %rep block, and the `in_progress' field is
4909 * more than 1, meaning that we still need to
4910 * repeat. (1 means the natural last repetition; 0
4911 * means termination by %exitrep.) We have
4912 * therefore expanded up to the %endrep, and must
4913 * push the whole block on to the expansion buffer
4914 * again. We don't bother to remove the macro-end
4915 * marker: we'd only have to generate another one
4918 l
->finishes
->in_progress
--;
4919 list_for_each(l
, l
->finishes
->expansion
) {
4920 Token
*t
, *tt
, **tail
;
4922 ll
= nasm_malloc(sizeof(Line
));
4923 ll
->next
= istk
->expansion
;
4924 ll
->finishes
= NULL
;
4928 list_for_each(t
, l
->first
) {
4929 if (t
->text
|| t
->type
== TOK_WHITESPACE
) {
4930 tt
= *tail
= new_Token(NULL
, t
->type
, t
->text
, 0);
4935 istk
->expansion
= ll
;
4939 * Check whether a `%rep' was started and not ended
4940 * within this macro expansion. This can happen and
4941 * should be detected. It's a fatal error because
4942 * I'm too confused to work out how to recover
4947 nasm_panic(0, "defining with name in expansion");
4948 else if (istk
->mstk
->name
)
4949 nasm_fatal(0, "`%%rep' without `%%endrep' within"
4950 " expansion of macro `%s'",
4955 * FIXME: investigate the relationship at this point between
4956 * istk->mstk and l->finishes
4959 MMacro
*m
= istk
->mstk
;
4960 istk
->mstk
= m
->next_active
;
4963 * This was a real macro call, not a %rep, and
4964 * therefore the parameter information needs to
4969 l
->finishes
->in_progress
--;
4971 nasm_free(m
->params
);
4972 free_tlist(m
->iline
);
4973 nasm_free(m
->paramlen
);
4974 l
->finishes
->in_progress
= 0;
4979 istk
->expansion
= l
->next
;
4981 lfmt
->downlevel(LIST_MACRO
);
4984 while (1) { /* until we get a line we can use */
4986 if (istk
->expansion
) { /* from a macro expansion */
4988 Line
*l
= istk
->expansion
;
4990 istk
->mstk
->lineno
++;
4992 istk
->expansion
= l
->next
;
4994 p
= detoken(tline
, false);
4995 lfmt
->line(LIST_MACRO
, p
);
5000 if (line
) { /* from the current input file */
5001 line
= prepreproc(line
);
5002 tline
= tokenize(line
);
5007 * The current file has ended; work down the istk
5013 /* nasm_error can't be conditionally suppressed */
5015 "expected `%%endif' before end of file");
5017 /* only set line and file name if there's a next node */
5019 src_set_linnum(i
->lineno
);
5020 src_set_fname(nasm_strdup(i
->fname
));
5023 lfmt
->downlevel(LIST_INCLUDE
);
5029 if (istk
->expansion
&& istk
->expansion
->finishes
)
5035 * We must expand MMacro parameters and MMacro-local labels
5036 * _before_ we plunge into directive processing, to cope
5037 * with things like `%define something %1' such as STRUC
5038 * uses. Unless we're _defining_ a MMacro, in which case
5039 * those tokens should be left alone to go into the
5040 * definition; and unless we're in a non-emitting
5041 * condition, in which case we don't want to meddle with
5044 if (!defining
&& !(istk
->conds
&& !emitting(istk
->conds
->state
))
5045 && !(istk
->mstk
&& !istk
->mstk
->in_progress
)) {
5046 tline
= expand_mmac_params(tline
);
5050 * Check the line to see if it's a preprocessor directive.
5052 if (do_directive(tline
) == DIRECTIVE_FOUND
) {
5054 } else if (defining
) {
5056 * We're defining a multi-line macro. We emit nothing
5058 * shove the tokenized line on to the macro definition.
5060 Line
*l
= nasm_malloc(sizeof(Line
));
5061 l
->next
= defining
->expansion
;
5064 defining
->expansion
= l
;
5066 } else if (istk
->conds
&& !emitting(istk
->conds
->state
)) {
5068 * We're in a non-emitting branch of a condition block.
5069 * Emit nothing at all, not even a blank line: when we
5070 * emerge from the condition we'll give a line-number
5071 * directive so we keep our place correctly.
5075 } else if (istk
->mstk
&& !istk
->mstk
->in_progress
) {
5077 * We're in a %rep block which has been terminated, so
5078 * we're walking through to the %endrep without
5079 * emitting anything. Emit nothing at all, not even a
5080 * blank line: when we emerge from the %rep block we'll
5081 * give a line-number directive so we keep our place
5087 tline
= expand_smacro(tline
);
5088 if (!expand_mmacro(tline
)) {
5090 * De-tokenize the line again, and emit it.
5092 line
= detoken(tline
, true);
5096 continue; /* expand_mmacro calls free_tlist */
5102 nasm_set_verror(real_verror
);
5106 static void pp_cleanup(int pass
)
5108 real_verror
= nasm_set_verror(pp_verror
);
5111 if (defining
->name
) {
5112 nasm_error(ERR_NONFATAL
,
5113 "end of file while still defining macro `%s'",
5116 nasm_error(ERR_NONFATAL
, "end of file while still in %%rep");
5119 free_mmacro(defining
);
5123 nasm_set_verror(real_verror
);
5132 nasm_free(i
->fname
);
5137 nasm_free(src_set_fname(NULL
));
5144 while ((i
= ipath
)) {
5153 static void pp_include_path(char *path
)
5157 i
= nasm_malloc(sizeof(IncPath
));
5158 i
->path
= path
? nasm_strdup(path
) : NULL
;
5171 static void pp_pre_include(char *fname
)
5173 Token
*inc
, *space
, *name
;
5176 name
= new_Token(NULL
, TOK_INTERNAL_STRING
, fname
, 0);
5177 space
= new_Token(name
, TOK_WHITESPACE
, NULL
, 0);
5178 inc
= new_Token(space
, TOK_PREPROC_ID
, "%include", 0);
5180 l
= nasm_malloc(sizeof(Line
));
5187 static void pp_pre_define(char *definition
)
5193 real_verror
= nasm_set_verror(pp_verror
);
5195 equals
= strchr(definition
, '=');
5196 space
= new_Token(NULL
, TOK_WHITESPACE
, NULL
, 0);
5197 def
= new_Token(space
, TOK_PREPROC_ID
, "%define", 0);
5200 space
->next
= tokenize(definition
);
5204 if (space
->next
->type
!= TOK_PREPROC_ID
&&
5205 space
->next
->type
!= TOK_ID
)
5206 nasm_error(ERR_WARNING
, "pre-defining non ID `%s\'\n", definition
);
5208 l
= nasm_malloc(sizeof(Line
));
5214 nasm_set_verror(real_verror
);
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 static void pp_list_one_macro(MMacro
*m
, int severity
)
5251 /* We need to print the next_active list in reverse order */
5252 pp_list_one_macro(m
->next_active
, severity
);
5254 if (m
->name
&& !m
->nolist
) {
5255 src_set_linnum(m
->xline
+ m
->lineno
);
5256 src_set_fname(m
->fname
);
5257 nasm_error(severity
, "... from macro `%s' defined here", m
->name
);
5261 static void pp_error_list_macros(int severity
)
5264 const char *saved_fname
= NULL
;
5266 severity
|= ERR_PP_LISTMACRO
| ERR_NO_SEVERITY
;
5267 saved_line
= src_get_linnum();
5268 saved_fname
= src_get_fname();
5270 pp_list_one_macro(istk
->mstk
, severity
);
5272 src_set_fname((char *)saved_fname
);
5273 src_set_linnum(saved_line
);
5276 const struct preproc_ops nasmpp
= {
5285 pp_error_list_macros
,