1 /*****************************************************************************/
5 /* Macros for the ca65 macroassembler */
9 /* (C) 1998-2004 Ullrich von Bassewitz */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
15 /* This software is provided 'as-is', without any expressed or implied */
16 /* warranty. In no event will the authors be held liable for any damages */
17 /* arising from the use of this software. */
19 /* Permission is granted to anyone to use this software for any purpose, */
20 /* including commercial applications, and to alter it and redistribute it */
21 /* freely, subject to the following restrictions: */
23 /* 1. The origin of this software must not be misrepresented; you must not */
24 /* claim that you wrote the original software. If you use this software */
25 /* in a product, an acknowledgment in the product documentation would be */
26 /* appreciated but is not required. */
27 /* 2. Altered source versions must be plainly marked as such, and must not */
28 /* be misrepresented as being the original software. */
29 /* 3. This notice may not be removed or altered from any source */
32 /*****************************************************************************/
58 /*****************************************************************************/
60 /*****************************************************************************/
64 static unsigned HT_GenHash (const void* Key);
65 /* Generate the hash over a key. */
67 static const void* HT_GetKey (void* Entry);
68 /* Given a pointer to the user entry data, return a pointer to the key */
70 static HashNode* HT_GetHashNode (void* Entry);
71 /* Given a pointer to the user entry data, return a pointer to the hash node */
73 static int HT_Compare (const void* Key1, const void* Key2);
74 /* Compare two keys. The function must return a value less than zero if
75 * Key1 is smaller than Key2, zero if both are equal, and a value greater
76 * than zero if Key1 is greater then Key2.
81 /*****************************************************************************/
83 /*****************************************************************************/
87 /* Struct that describes an identifer (macro param, local list) */
88 typedef struct IdDesc IdDesc;
90 IdDesc* Next; /* Linked list */
91 char Id [1]; /* Identifier, dynamically allocated */
96 /* Struct that describes a macro definition */
97 typedef struct Macro Macro;
99 HashNode Node; /* Hash list node */
100 Macro* List; /* List of all macros */
101 unsigned LocalCount; /* Count of local symbols */
102 IdDesc* Locals; /* List of local symbols */
103 unsigned ParamCount; /* Parameter count of macro */
104 IdDesc* Params; /* Identifiers of macro parameters */
105 unsigned TokCount; /* Number of tokens for this macro */
106 TokNode* TokRoot; /* Root of token list */
107 TokNode* TokLast; /* Pointer to last token in list */
108 unsigned char Style; /* Macro style */
109 char Name [1]; /* Macro name, dynamically allocated */
112 /* Hash table functions */
113 static const HashFunctions HashFunc = {
120 /* Macro hash table */
121 static HashTable MacroTab = STATIC_HASHTABLE_INITIALIZER (117, &HashFunc);
123 /* Global macro data */
124 static Macro* MacroRoot = 0; /* List of all macros */
126 /* Structs that holds data for a macro expansion */
127 typedef struct MacExp MacExp;
129 MacExp* Next; /* Pointer to next expansion */
130 Macro* M; /* Which macro do we expand? */
131 unsigned IfSP; /* .IF stack pointer at start of expansion */
132 TokNode* Exp; /* Pointer to current token */
133 TokNode* Final; /* Pointer to final token */
134 unsigned LocalStart; /* Start of counter for local symbol names */
135 unsigned ParamCount; /* Number of actual parameters */
136 TokNode** Params; /* List of actual parameters */
137 TokNode* ParamExp; /* Node for expanding parameters */
140 /* Number of active macro expansions */
141 static unsigned MacExpansions = 0;
143 /* Flag if a macro expansion should get aborted */
144 static int DoMacAbort = 0;
146 /* Counter to create local names for symbols */
147 static unsigned LocalName = 0;
151 /*****************************************************************************/
152 /* Hash table functions */
153 /*****************************************************************************/
157 static unsigned HT_GenHash (const void* Key)
158 /* Generate the hash over a key. */
160 return HashStr (Key);
165 static const void* HT_GetKey (void* Entry)
166 /* Given a pointer to the user entry data, return a pointer to the index */
168 return ((Macro*) Entry)->Name;
173 static HashNode* HT_GetHashNode (void* Entry)
174 /* Given a pointer to the user entry data, return a pointer to the hash node */
176 return &((Macro*) Entry)->Node;
181 static int HT_Compare (const void* Key1, const void* Key2)
182 /* Compare two keys. The function must return a value less than zero if
183 * Key1 is smaller than Key2, zero if both are equal, and a value greater
184 * than zero if Key1 is greater then Key2.
187 return strcmp (Key1, Key2);
192 /*****************************************************************************/
194 /*****************************************************************************/
198 static IdDesc* NewIdDesc (const char* Id)
199 /* Create a new IdDesc, initialize and return it */
201 /* Allocate memory */
202 unsigned Len = strlen (Id);
203 IdDesc* I = xmalloc (sizeof (IdDesc) + Len);
205 /* Initialize the struct */
207 memcpy (I->Id, Id, Len);
210 /* Return the new struct */
216 static Macro* NewMacro (const char* Name, unsigned char Style)
217 /* Generate a new macro entry, initialize and return it */
219 /* Allocate memory */
220 unsigned Len = strlen (Name);
221 Macro* M = xmalloc (sizeof (Macro) + Len);
223 /* Initialize the macro struct */
224 InitHashNode (&M->Node, M);
233 memcpy (M->Name, Name, Len+1);
235 /* Insert the macro into the global macro list */
239 /* Insert the macro into the hash table */
240 HT_Insert (&MacroTab, &M->Node);
242 /* Return the new macro struct */
248 static MacExp* NewMacExp (Macro* M)
249 /* Create a new expansion structure for the given macro */
253 /* Allocate memory */
254 MacExp* E = xmalloc (sizeof (MacExp));
256 /* Initialize the data */
258 E->IfSP = GetIfStack ();
261 E->LocalStart = LocalName;
262 LocalName += M->LocalCount;
264 E->Params = xmalloc (M->ParamCount * sizeof (TokNode*));
266 for (I = 0; I < M->ParamCount; ++I) {
270 /* One macro expansion more */
273 /* Return the new macro expansion */
279 static void FreeMacExp (MacExp* E)
280 /* Remove and free the current macro expansion */
284 /* One macro expansion less */
287 /* Free the parameter list */
288 for (I = 0; I < E->ParamCount; ++I) {
289 xfree (E->Params [I]);
293 /* Free the final token if we have one */
295 FreeTokNode (E->Final);
298 /* Free the structure itself */
304 static void MacSkipDef (unsigned Style)
305 /* Skip a macro definition */
307 if (Style == MAC_STYLE_CLASSIC) {
308 /* Skip tokens until we reach the final .endmacro */
309 while (Tok != TOK_ENDMACRO && Tok != TOK_EOF) {
312 if (Tok != TOK_EOF) {
315 Error ("`.ENDMACRO' expected");
318 /* Skip until end of line */
325 void MacDef (unsigned Style)
326 /* Parse a macro definition */
332 /* We expect a macro name here */
333 if (Tok != TOK_IDENT) {
334 Error ("Identifier expected");
337 } else if (!UbiquitousIdents && FindInstruction (SVal) >= 0) {
338 /* The identifier is a name of a 6502 instruction, which is not
339 * allowed if not explicitly enabled.
341 Error ("Cannot use an instruction as macro name");
346 /* Did we already define that macro? */
347 if (HT_Find (&MacroTab, SVal) != 0) {
348 /* Macro is already defined */
349 Error ("A macro named `%s' is already defined", SVal);
350 /* Skip tokens until we reach the final .endmacro */
355 /* Define the macro */
356 M = NewMacro (SVal, Style);
358 /* Switch to raw token mode and skip the macro name */
359 EnterRawTokenMode ();
362 /* If we have a DEFINE style macro, we may have parameters in braces,
363 * otherwise we may have parameters without braces.
365 if (Style == MAC_STYLE_CLASSIC) {
368 if (Tok == TOK_LPAREN) {
376 /* Parse the parameter list */
379 while (Tok == TOK_IDENT) {
381 /* Create a struct holding the identifier */
382 IdDesc* I = NewIdDesc (SVal);
384 /* Insert the struct into the list, checking for duplicate idents */
385 if (M->ParamCount == 0) {
388 IdDesc* List = M->Params;
390 if (strcmp (List->Id, SVal) == 0) {
391 Error ("Duplicate symbol `%s'", SVal);
393 if (List->Next == 0) {
406 /* Maybe there are more params... */
407 if (Tok == TOK_COMMA) {
415 /* For class macros, we expect a separator token, for define style macros,
416 * we expect the closing paren.
418 if (Style == MAC_STYLE_CLASSIC) {
420 } else if (HaveParams) {
424 /* Preparse the macro body. We will read the tokens until we reach end of
425 * file, or a .endmacro (or end of line for DEFINE style macros) and store
426 * them into an token list internal to the macro. For classic macros, there
427 * the .LOCAL command is detected and removed at this time.
431 /* Check for end of macro */
432 if (Style == MAC_STYLE_CLASSIC) {
433 /* In classic macros, only .endmacro is allowed */
434 if (Tok == TOK_ENDMACRO) {
438 /* May not have end of file in a macro definition */
439 if (Tok == TOK_EOF) {
440 Error ("`.ENDMACRO' expected");
444 /* Accept a newline or end of file for new style macros */
445 if (TokIsSep (Tok)) {
450 /* Check for a .LOCAL declaration */
451 if (Tok == TOK_LOCAL && Style == MAC_STYLE_CLASSIC) {
457 /* Skip .local or comma */
460 /* Need an identifer */
461 if (Tok != TOK_IDENT) {
462 Error ("Identifier expected");
467 /* Put the identifier into the locals list and skip it */
468 I = NewIdDesc (SVal);
474 /* Check for end of list */
475 if (Tok != TOK_COMMA) {
481 /* We need end of line after the locals */
486 /* Create a token node for the current token */
489 /* If the token is an ident, check if it is a local parameter */
490 if (Tok == TOK_IDENT) {
492 IdDesc* I = M->Params;
494 if (strcmp (I->Id, SVal) == 0) {
495 /* Local param name, replace it */
496 T->Tok = TOK_MACPARAM;
505 /* Insert the new token in the list */
506 if (M->TokCount == 0) {
508 M->TokRoot = M->TokLast = T;
510 /* We have already tokens */
511 M->TokLast->Next = T;
516 /* Read the next token */
520 /* Skip the .endmacro for a classic macro */
521 if (Style == MAC_STYLE_CLASSIC) {
526 /* Switch out of raw token mode */
527 LeaveRawTokenMode ();
532 static int MacExpand (void* Data)
533 /* If we're currently expanding a macro, set the the scanner token and
534 * attribute to the next value and return true. If we are not expanding
535 * a macro, return false.
538 /* Cast the Data pointer to the actual data structure */
539 MacExp* Mac = (MacExp*) Data;
541 /* Check if we should abort this macro */
547 /* Abort any open .IF statements in this macro expansion */
548 CleanupIfStack (Mac->IfSP);
550 /* Terminate macro expansion */
554 /* We're expanding a macro. Check if we are expanding one of the
559 /* Ok, use token from parameter list */
560 TokSet (Mac->ParamExp);
562 /* Set pointer to next token */
563 Mac->ParamExp = Mac->ParamExp->Next;
570 /* We're not expanding macro parameters. Check if we have tokens left from
575 /* Use next macro token */
578 /* Set pointer to next token */
579 Mac->Exp = Mac->Exp->Next;
581 /* Is it a request for actual parameter count? */
582 if (Tok == TOK_PARAMCOUNT) {
584 IVal = Mac->ParamCount;
588 /* Is it the name of a macro parameter? */
589 if (Tok == TOK_MACPARAM) {
591 /* Start to expand the parameter token list */
592 Mac->ParamExp = Mac->Params [IVal];
594 /* Recursive call to expand the parameter */
595 return MacExpand (Mac);
598 /* If it's an identifier, it may in fact be a local symbol */
599 if (Tok == TOK_IDENT && Mac->M->LocalCount) {
600 /* Search for the local symbol in the list */
602 IdDesc* I = Mac->M->Locals;
604 if (strcmp (SVal, I->Id) == 0) {
605 /* This is in fact a local symbol, change the name. Be sure
606 * to generate a local label name if the original name was
607 * a local label, and also generate a name that cannot be
608 * generated by a user.
610 unsigned PrefixLen = (I->Id[0] == LocalStart);
611 sprintf (SVal, "%.*sLOCAL-MACRO-SYMBOL-%04X", PrefixLen,
612 I->Id, Mac->LocalStart + Index);
624 /* The token was successfully set */
629 /* No more macro tokens. Do we have a final token? */
632 /* Set the final token and remove it */
634 FreeTokNode (Mac->Final);
637 /* The token was successfully set */
643 /* End of macro expansion */
646 /* Pop the input function */
649 /* No token available */
655 static void StartExpClassic (Macro* M)
656 /* Start expanding the classic macro M */
662 /* Skip the macro name */
665 /* Create a structure holding expansion data */
668 /* Read the actual parameters */
669 while (!TokIsSep (Tok)) {
673 /* Check for maximum parameter count */
674 if (E->ParamCount >= M->ParamCount) {
675 ErrorSkip ("Too many macro parameters");
679 /* The macro may optionally be enclosed in curly braces */
680 Term = GetTokListTerm (TOK_COMMA);
682 /* Read tokens for one parameter, accept empty params */
684 while (Tok != Term && Tok != TOK_SEP) {
688 /* Check for end of file */
689 if (Tok == TOK_EOF) {
690 Error ("Unexpected end of file");
695 /* Get the next token in a node */
698 /* Insert it into the list */
700 E->Params [E->ParamCount] = T;
710 /* One parameter more */
713 /* If the macro argument was enclosed in curly braces, end-of-line
714 * is an error. Skip the closing curly brace.
716 if (Term == TOK_RCURLY) {
717 if (Tok == TOK_SEP) {
718 Error ("End of line encountered within macro argument");
724 /* Check for a comma */
725 if (Tok == TOK_COMMA) {
732 /* We must be at end of line now, otherwise something is wrong */
735 /* Insert a new token input function */
736 PushInput (MacExpand, E, ".MACRO");
741 static void StartExpDefine (Macro* M)
742 /* Start expanding a DEFINE style macro */
744 /* Create a structure holding expansion data */
745 MacExp* E = NewMacExp (M);
747 /* A define style macro must be called with as many actual parameters
748 * as there are formal ones. Get the parameter count.
750 unsigned Count = M->ParamCount;
752 /* Skip the current token */
755 /* Read the actual parameters */
760 /* The macro may optionally be enclosed in curly braces */
761 enum Token Term = GetTokListTerm (TOK_COMMA);
763 /* Check if there is really a parameter */
764 if (TokIsSep (Tok) || Tok == Term) {
765 ErrorSkip ("Macro parameter #%u is empty", E->ParamCount+1);
770 /* Read tokens for one parameter */
776 /* Get the next token in a node */
779 /* Insert it into the list */
781 E->Params [E->ParamCount] = T;
790 } while (Tok != Term && !TokIsSep (Tok));
792 /* One parameter more */
795 /* If the macro argument was enclosed in curly braces, end-of-line
796 * is an error. Skip the closing curly brace.
798 if (Term == TOK_RCURLY) {
799 if (TokIsSep (Tok)) {
800 Error ("End of line encountered within macro argument");
806 /* Check for a comma */
808 if (Tok == TOK_COMMA) {
811 Error ("`,' expected");
816 /* Macro expansion will overwrite the current token. This is a problem
817 * for define style macros since these are called from the scanner level.
818 * To avoid it, remember the current token and re-insert it, once macro
821 E->Final = NewTokNode ();
823 /* Insert a new token input function */
824 PushInput (MacExpand, E, ".DEFINE");
829 void MacExpandStart (void)
830 /* Start expanding the macro in SVal */
832 /* Search for the macro */
833 Macro* M = HT_FindEntry (&MacroTab, SVal);
836 /* Call the apropriate subroutine */
838 case MAC_STYLE_CLASSIC: StartExpClassic (M); break;
839 case MAC_STYLE_DEFINE: StartExpDefine (M); break;
840 default: Internal ("Invalid macro style: %d", M->Style);
847 /* Abort the current macro expansion */
849 /* Must have an expansion */
850 CHECK (MacExpansions > 0);
852 /* Set a flag so macro expansion will terminate on the next call */
858 int IsMacro (const char* Name)
859 /* Return true if the given name is the name of a macro */
861 return (HT_Find (&MacroTab, Name) != 0);
866 int IsDefine (const char* Name)
867 /* Return true if the given name is the name of a define style macro */
869 Macro* M = HT_FindEntry (&MacroTab, Name);
870 return (M != 0 && M->Style == MAC_STYLE_DEFINE);
875 int InMacExpansion (void)
876 /* Return true if we're currently expanding a macro */
878 return (MacExpansions > 0);