1 /*****************************************************************************/
5 /* Macros for the ca65 macroassembler */
9 /* (C) 1998-2011, Ullrich von Bassewitz */
10 /* Roemerstrasse 52 */
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 /*****************************************************************************/
59 /*****************************************************************************/
61 /*****************************************************************************/
65 static unsigned HT_GenHash (const void* Key);
66 /* Generate the hash over a key. */
68 static const void* HT_GetKey (void* Entry);
69 /* Given a pointer to the user entry data, return a pointer to the key */
71 static HashNode* HT_GetHashNode (void* Entry);
72 /* Given a pointer to the user entry data, return a pointer to the hash node */
74 static int HT_Compare (const void* Key1, const void* Key2);
75 /* Compare two keys. The function must return a value less than zero if
76 * Key1 is smaller than Key2, zero if both are equal, and a value greater
77 * than zero if Key1 is greater then Key2.
82 /*****************************************************************************/
84 /*****************************************************************************/
88 /* Struct that describes an identifer (macro param, local list) */
89 typedef struct IdDesc IdDesc;
91 IdDesc* Next; /* Linked list */
92 StrBuf Id; /* Identifier, dynamically allocated */
97 /* Struct that describes a macro definition */
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 StrBuf Name; /* Macro name, dynamically allocated */
109 unsigned Expansions; /* Number of active macro expansions */
110 unsigned char Style; /* Macro style */
111 unsigned char Incomplete; /* Macro is currently built */
114 /* Hash table functions */
115 static const HashFunctions HashFunc = {
122 /* Macro hash table */
123 static HashTable MacroTab = STATIC_HASHTABLE_INITIALIZER (117, &HashFunc);
125 /* Structs that holds data for a macro expansion */
126 typedef struct MacExp MacExp;
128 MacExp* Next; /* Pointer to next expansion */
129 Macro* M; /* Which macro do we expand? */
130 unsigned IfSP; /* .IF stack pointer at start of expansion */
131 TokNode* Exp; /* Pointer to current token */
132 TokNode* Final; /* Pointer to final token */
133 unsigned LocalStart; /* Start of counter for local symbol names */
134 unsigned ParamCount; /* Number of actual parameters */
135 TokNode** Params; /* List of actual parameters */
136 TokNode* ParamExp; /* Node for expanding parameters */
137 int LISlot; /* Slot for additional line infos */
140 /* Maximum number of nested macro expansions */
141 #define MAX_MACEXPANSIONS 256U
143 /* Number of active macro expansions */
144 static unsigned MacExpansions = 0;
146 /* Flag if a macro expansion should get aborted */
147 static int DoMacAbort = 0;
149 /* Counter to create local names for symbols */
150 static unsigned LocalName = 0;
152 /* Define style macros disabled if != 0 */
153 static unsigned DisableDefines = 0;
157 /*****************************************************************************/
158 /* Hash table functions */
159 /*****************************************************************************/
163 static unsigned HT_GenHash (const void* Key)
164 /* Generate the hash over a key. */
166 return HashBuf (Key);
171 static const void* HT_GetKey (void* Entry)
172 /* Given a pointer to the user entry data, return a pointer to the index */
174 return &((Macro*) Entry)->Name;
179 static HashNode* HT_GetHashNode (void* Entry)
180 /* Given a pointer to the user entry data, return a pointer to the hash node */
182 return &((Macro*) Entry)->Node;
187 static int HT_Compare (const void* Key1, const void* Key2)
188 /* Compare two keys. The function must return a value less than zero if
189 * Key1 is smaller than Key2, zero if both are equal, and a value greater
190 * than zero if Key1 is greater then Key2.
193 return SB_Compare (Key1, Key2);
198 /*****************************************************************************/
200 /*****************************************************************************/
204 static IdDesc* NewIdDesc (const StrBuf* Id)
205 /* Create a new IdDesc, initialize and return it */
207 /* Allocate memory */
208 IdDesc* ID = xmalloc (sizeof (IdDesc));
210 /* Initialize the struct */
213 SB_Copy (&ID->Id, Id);
215 /* Return the new struct */
221 static void FreeIdDesc (IdDesc* ID)
227 /* Free the structure itself */
233 static void FreeIdDescList (IdDesc* ID)
234 /* Free a complete list of IdDesc structures */
245 static Macro* NewMacro (const StrBuf* Name, unsigned char Style)
246 /* Generate a new macro entry, initialize and return it */
248 /* Allocate memory */
249 Macro* M = xmalloc (sizeof (Macro));
251 /* Initialize the macro struct */
252 InitHashNode (&M->Node, M);
261 SB_Copy (&M->Name, Name);
266 /* Insert the macro into the hash table */
267 HT_Insert (&MacroTab, &M->Node);
269 /* Return the new macro struct */
275 static void FreeMacro (Macro* M)
276 /* Free a macro entry which has already been removed from the macro table. */
281 FreeIdDescList (M->Locals);
283 /* Free identifiers of parameters */
284 FreeIdDescList (M->Params);
286 /* Free the token list for the macro */
287 while ((T = M->TokRoot) != 0) {
288 M->TokRoot = T->Next;
292 /* Free the macro name */
295 /* Free the macro structure itself */
301 static MacExp* NewMacExp (Macro* M)
302 /* Create a new expansion structure for the given macro */
306 /* Allocate memory */
307 MacExp* E = xmalloc (sizeof (MacExp));
309 /* Initialize the data */
311 E->IfSP = GetIfStack ();
314 E->LocalStart = LocalName;
315 LocalName += M->LocalCount;
317 E->Params = xmalloc (M->ParamCount * sizeof (TokNode*));
318 for (I = 0; I < M->ParamCount; ++I) {
322 E->LISlot = AllocLineInfoSlot (LI_TYPE_MACRO, MacExpansions);
324 /* Mark the macro as expanding */
327 /* One macro expansion more */
330 /* Return the new macro expansion */
336 static void FreeMacExp (MacExp* E)
337 /* Remove and free the current macro expansion */
341 /* One macro expansion less */
344 /* No longer expanding this macro */
347 /* Free the parameter lists */
348 for (I = 0; I < E->ParamCount; ++I) {
349 /* Free one parameter list */
350 TokNode* N = E->Params[I];
352 TokNode* P = N->Next;
359 /* Free the additional line info slot */
360 FreeLineInfoSlot (E->LISlot);
362 /* Free the final token if we have one */
364 FreeTokNode (E->Final);
367 /* Free the structure itself */
373 static void MacSkipDef (unsigned Style)
374 /* Skip a macro definition */
376 if (Style == MAC_STYLE_CLASSIC) {
377 /* Skip tokens until we reach the final .endmacro */
378 while (CurTok.Tok != TOK_ENDMACRO && CurTok.Tok != TOK_EOF) {
381 if (CurTok.Tok != TOK_EOF) {
384 Error ("`.ENDMACRO' expected");
387 /* Skip until end of line */
394 void MacDef (unsigned Style)
395 /* Parse a macro definition */
401 /* We expect a macro name here */
402 if (CurTok.Tok != TOK_IDENT) {
403 Error ("Identifier expected");
406 } else if (!UbiquitousIdents && FindInstruction (&CurTok.SVal) >= 0) {
407 /* The identifier is a name of a 6502 instruction, which is not
408 * allowed if not explicitly enabled.
410 Error ("Cannot use an instruction as macro name");
415 /* Did we already define that macro? */
416 if (HT_Find (&MacroTab, &CurTok.SVal) != 0) {
417 /* Macro is already defined */
418 Error ("A macro named `%m%p' is already defined", &CurTok.SVal);
419 /* Skip tokens until we reach the final .endmacro */
424 /* Define the macro */
425 M = NewMacro (&CurTok.SVal, Style);
427 /* Switch to raw token mode and skip the macro name */
428 EnterRawTokenMode ();
431 /* If we have a DEFINE style macro, we may have parameters in braces,
432 * otherwise we may have parameters without braces.
434 if (Style == MAC_STYLE_CLASSIC) {
437 if (CurTok.Tok == TOK_LPAREN) {
445 /* Parse the parameter list */
448 while (CurTok.Tok == TOK_IDENT) {
450 /* Create a struct holding the identifier */
451 IdDesc* I = NewIdDesc (&CurTok.SVal);
453 /* Insert the struct into the list, checking for duplicate idents */
454 if (M->ParamCount == 0) {
457 IdDesc* List = M->Params;
459 if (SB_Compare (&List->Id, &CurTok.SVal) == 0) {
460 Error ("Duplicate symbol `%m%p'", &CurTok.SVal);
462 if (List->Next == 0) {
475 /* Maybe there are more params... */
476 if (CurTok.Tok == TOK_COMMA) {
484 /* For class macros, we expect a separator token, for define style macros,
485 * we expect the closing paren.
487 if (Style == MAC_STYLE_CLASSIC) {
489 } else if (HaveParams) {
493 /* Preparse the macro body. We will read the tokens until we reach end of
494 * file, or a .endmacro (or end of line for DEFINE style macros) and store
495 * them into an token list internal to the macro. For classic macros, there
496 * the .LOCAL command is detected and removed at this time.
500 /* Check for end of macro */
501 if (Style == MAC_STYLE_CLASSIC) {
502 /* In classic macros, only .endmacro is allowed */
503 if (CurTok.Tok == TOK_ENDMACRO) {
507 /* May not have end of file in a macro definition */
508 if (CurTok.Tok == TOK_EOF) {
509 Error ("`.ENDMACRO' expected");
513 /* Accept a newline or end of file for new style macros */
514 if (TokIsSep (CurTok.Tok)) {
519 /* Check for a .LOCAL declaration */
520 if (CurTok.Tok == TOK_LOCAL && Style == MAC_STYLE_CLASSIC) {
526 /* Skip .local or comma */
529 /* Need an identifer */
530 if (CurTok.Tok != TOK_IDENT && CurTok.Tok != TOK_LOCAL_IDENT) {
531 Error ("Identifier expected");
536 /* Put the identifier into the locals list and skip it */
537 I = NewIdDesc (&CurTok.SVal);
543 /* Check for end of list */
544 if (CurTok.Tok != TOK_COMMA) {
550 /* We need end of line after the locals */
555 /* Create a token node for the current token */
558 /* If the token is an ident, check if it is a local parameter */
559 if (CurTok.Tok == TOK_IDENT) {
561 IdDesc* I = M->Params;
563 if (SB_Compare (&I->Id, &CurTok.SVal) == 0) {
564 /* Local param name, replace it */
565 N->T.Tok = TOK_MACPARAM;
574 /* Insert the new token in the list */
575 if (M->TokCount == 0) {
577 M->TokRoot = M->TokLast = N;
579 /* We have already tokens */
580 M->TokLast->Next = N;
585 /* Read the next token */
589 /* Skip the .endmacro for a classic macro */
590 if (Style == MAC_STYLE_CLASSIC) {
594 /* Reset the Incomplete flag now that parsing is done */
598 /* Switch out of raw token mode */
599 LeaveRawTokenMode ();
604 void MacUndef (const StrBuf* Name, unsigned char Style)
605 /* Undefine the macro with the given name and style. A style mismatch is
606 * treated as if the macro didn't exist.
609 /* Search for the macro */
610 Macro* M = HT_FindEntry (&MacroTab, Name);
612 /* Don't let the user kid with us */
613 if (M == 0 || M->Style != Style) {
614 Error ("No such macro: %m%p", Name);
617 if (M->Expansions > 0) {
618 Error ("Cannot delete a macro that is currently expanded");
622 /* Remove the macro from the macro table */
623 HT_RemoveEntry (&MacroTab, M);
625 /* Free the macro structure */
631 static int MacExpand (void* Data)
632 /* If we're currently expanding a macro, set the the scanner token and
633 * attribute to the next value and return true. If we are not expanding
634 * a macro, return false.
637 /* Cast the Data pointer to the actual data structure */
638 MacExp* Mac = (MacExp*) Data;
640 /* Check if we should abort this macro */
646 /* Abort any open .IF statements in this macro expansion */
647 CleanupIfStack (Mac->IfSP);
649 /* Terminate macro expansion */
653 /* We're expanding a macro. Check if we are expanding one of the
659 /* Ok, use token from parameter list, but don't use its line info */
660 TokSet (Mac->ParamExp, LI_SLOT_INV);
662 /* Set pointer to next token */
663 Mac->ParamExp = Mac->ParamExp->Next;
669 /* We're not expanding macro parameters. Check if we have tokens left from
674 /* Use next macro token */
675 TokSet (Mac->Exp, Mac->LISlot);
677 /* Set pointer to next token */
678 Mac->Exp = Mac->Exp->Next;
680 /* Is it a request for actual parameter count? */
681 if (CurTok.Tok == TOK_PARAMCOUNT) {
682 CurTok.Tok = TOK_INTCON;
683 CurTok.IVal = Mac->ParamCount;
687 /* Is it the name of a macro parameter? */
688 if (CurTok.Tok == TOK_MACPARAM) {
690 /* Start to expand the parameter token list */
691 Mac->ParamExp = Mac->Params[CurTok.IVal];
693 /* Go back and expand the parameter */
697 /* If it's an identifier, it may in fact be a local symbol */
698 if ((CurTok.Tok == TOK_IDENT || CurTok.Tok == TOK_LOCAL_IDENT) &&
699 Mac->M->LocalCount) {
700 /* Search for the local symbol in the list */
702 IdDesc* I = Mac->M->Locals;
704 if (SB_Compare (&CurTok.SVal, &I->Id) == 0) {
705 /* This is in fact a local symbol, change the name. Be sure
706 * to generate a local label name if the original name was
707 * a local label, and also generate a name that cannot be
708 * generated by a user.
710 if (SB_At (&I->Id, 0) == LocalStart) {
711 /* Must generate a local symbol */
712 SB_Printf (&CurTok.SVal, "%cLOCAL-MACRO_SYMBOL-%04X",
713 LocalStart, Mac->LocalStart + Index);
716 SB_Printf (&CurTok.SVal, "LOCAL-MACRO_SYMBOL-%04X",
717 Mac->LocalStart + Index);
730 /* The token was successfully set */
734 /* No more macro tokens. Do we have a final token? */
737 /* Set the final token and remove it */
738 TokSet (Mac->Final, LI_SLOT_INV);
739 FreeTokNode (Mac->Final);
742 /* Problem: When a .define style macro is expanded within the call
743 * of a classic one, the latter may be terminated and removed while
744 * the expansion of the .define style macro is still active. Because
745 * line info slots are "stacked", this runs into a CHECK FAILED. For
746 * now, we will fix that by removing the .define style macro expansion
747 * immediately, once the final token is placed. The better solution
748 * would probably be to not require AllocLineInfoSlot/FreeLineInfoSlot
749 * to be called in FIFO order, but this is a bigger change.
751 /* End of macro expansion and pop the input function */
755 /* The token was successfully set */
760 /* End of macro expansion */
763 /* Pop the input function */
766 /* No token available */
772 static void StartExpClassic (MacExp* E)
773 /* Start expanding a classic macro */
777 /* Skip the macro name */
780 /* Read the actual parameters */
781 while (!TokIsSep (CurTok.Tok)) {
785 /* Check for maximum parameter count */
786 if (E->ParamCount >= E->M->ParamCount) {
787 ErrorSkip ("Too many macro parameters");
791 /* The macro may optionally be enclosed in curly braces */
792 Term = GetTokListTerm (TOK_COMMA);
794 /* Read tokens for one parameter, accept empty params */
796 while (CurTok.Tok != Term && CurTok.Tok != TOK_SEP) {
800 /* Check for end of file */
801 if (CurTok.Tok == TOK_EOF) {
802 Error ("Unexpected end of file");
807 /* Get the next token in a node */
810 /* Insert it into the list */
812 E->Params [E->ParamCount] = T;
822 /* One parameter more */
825 /* If the macro argument was enclosed in curly braces, end-of-line
826 * is an error. Skip the closing curly brace.
828 if (Term == TOK_RCURLY) {
829 if (CurTok.Tok == TOK_SEP) {
830 Error ("End of line encountered within macro argument");
836 /* Check for a comma */
837 if (CurTok.Tok == TOK_COMMA) {
844 /* We must be at end of line now, otherwise something is wrong */
847 /* Insert a new token input function */
848 PushInput (MacExpand, E, ".MACRO");
853 static void StartExpDefine (MacExp* E)
854 /* Start expanding a DEFINE style macro */
856 /* A define style macro must be called with as many actual parameters
857 * as there are formal ones. Get the parameter count.
859 unsigned Count = E->M->ParamCount;
861 /* Skip the current token */
864 /* Read the actual parameters */
869 /* The macro may optionally be enclosed in curly braces */
870 token_t Term = GetTokListTerm (TOK_COMMA);
872 /* Check if there is really a parameter */
873 if (TokIsSep (CurTok.Tok) || CurTok.Tok == Term) {
874 ErrorSkip ("Macro parameter #%u is empty", E->ParamCount+1);
879 /* Read tokens for one parameter */
885 /* Get the next token in a node */
888 /* Insert it into the list */
890 E->Params [E->ParamCount] = T;
899 } while (CurTok.Tok != Term && !TokIsSep (CurTok.Tok));
901 /* One parameter more */
904 /* If the macro argument was enclosed in curly braces, end-of-line
905 * is an error. Skip the closing curly brace.
907 if (Term == TOK_RCURLY) {
908 if (TokIsSep (CurTok.Tok)) {
909 Error ("End of line encountered within macro argument");
915 /* Check for a comma */
917 if (CurTok.Tok == TOK_COMMA) {
920 Error ("`,' expected");
925 /* Macro expansion will overwrite the current token. This is a problem
926 * for define style macros since these are called from the scanner level.
927 * To avoid it, remember the current token and re-insert it, once macro
930 E->Final = NewTokNode ();
932 /* Insert a new token input function */
933 PushInput (MacExpand, E, ".DEFINE");
938 void MacExpandStart (Macro* M)
939 /* Start expanding a macro */
943 /* Check the argument */
944 PRECONDITION (M && (M->Style != MAC_STYLE_DEFINE || DisableDefines == 0));
946 /* We cannot expand an incomplete macro */
948 Error ("Cannot expand an incomplete macro");
952 /* Don't allow too many nested macro expansions - otherwise it is possible
953 * to force an endless loop and assembler crash.
955 if (MacExpansions >= MAX_MACEXPANSIONS) {
956 Error ("Too many nested macro expansions");
960 /* Create a structure holding expansion data */
963 /* Call the apropriate subroutine */
965 case MAC_STYLE_CLASSIC: StartExpClassic (E); break;
966 case MAC_STYLE_DEFINE: StartExpDefine (E); break;
967 default: Internal ("Invalid macro style: %d", M->Style);
974 /* Abort the current macro expansion */
976 /* Must have an expansion */
977 CHECK (MacExpansions > 0);
979 /* Set a flag so macro expansion will terminate on the next call */
985 Macro* FindMacro (const StrBuf* Name)
986 /* Try to find the macro with the given name and return it. If no macro with
987 * this name was found, return NULL.
990 Macro* M = HT_FindEntry (&MacroTab, Name);
991 return (M != 0 && M->Style == MAC_STYLE_CLASSIC)? M : 0;
996 Macro* FindDefine (const StrBuf* Name)
997 /* Try to find the define style macro with the given name and return it. If no
998 * such macro was found, return NULL.
1003 /* Never if disabled */
1004 if (DisableDefines) {
1008 /* Check if we have such a macro */
1009 M = HT_FindEntry (&MacroTab, Name);
1010 return (M != 0 && M->Style == MAC_STYLE_DEFINE)? M : 0;
1015 int InMacExpansion (void)
1016 /* Return true if we're currently expanding a macro */
1018 return (MacExpansions > 0);
1023 void DisableDefineStyleMacros (void)
1024 /* Disable define style macros until EnableDefineStyleMacros is called */
1031 void EnableDefineStyleMacros (void)
1032 /* Re-enable define style macros previously disabled with
1033 * DisableDefineStyleMacros.
1036 PRECONDITION (DisableDefines > 0);