2 // RMAC - Reboot's Macro Assembler for all Atari computers
3 // MACRO.C - Macro Definition and Invocation
4 // Copyright (C) 199x Landon Dyer, 2011-2017 Reboot and Friends
5 // RMAC derived from MADMAC v1.07 Written by Landon Dyer, 1986
6 // Source utilised with the kind permission of Landon Dyer
20 LONG curuniq; // Current macro's unique number
21 int macnum; // Unique number for macro definition
22 TOKEN * argPtrs[128]; // 128 arguments ought to be enough for anyone
25 static LONG macuniq; // Unique-per-macro number
26 static SYM * curmac; // Macro currently being defined
27 static VALUE argno; // Formal argument count
29 static LONG * firstrpt; // First .rept line
30 static LONG * nextrpt; // Last .rept line
31 static int rptlevel; // .rept nesting level
33 // Function prototypes
34 static int KWMatch(char *, char *);
35 static int LNCatch(int (*)(), char *);
39 // Initialize macro processor
51 // -- pop any intervening include files and repeat blocks;
52 // -- restore argument stack;
57 WARNING(!!! Bad macro exiting !!!)
60 This is a problem. Currently, the argument logic just keeps the current
61 arguments and doesn't save anything if a new macro is called in the middle
62 of another (nested macros). Need to fix that somehow.
64 // Pop intervening include files and .rept blocks
65 while (cur_inobj != NULL && cur_inobj->in_type != SRC_IMACRO)
68 if (cur_inobj == NULL)
69 fatal("too many ENDMs");
73 // o old unique number
74 // ...and then pop the macro.
76 IMACRO * imacro = cur_inobj->inobj.imacro;
77 curuniq = imacro->im_olduniq;
79 // /*TOKEN ** p = */argp--;
80 // argp = (TOKEN **)*argp;
81 DEBUG { printf("ExitMacro: argp: %d -> ", argp); }
82 argp -= imacro->im_nargs;
83 DEBUG { printf("%d (nargs = %d)\n", argp, imacro->im_nargs); }
90 // Add a formal argument to a macro definition
92 int defmac2(char * argname)
96 if (lookup(argname, MACARG, (int)curmac->sattr) != NULL)
97 return error("multiple formal argument definition");
99 arg = NewSymbol(argname, MACARG, (int)curmac->sattr);
100 arg->svalue = argno++;
107 // Add a line to a macro definition; also print lines to listing file (if
108 // enabled). The last line of the macro (containing .endm) is not included in
109 // the macro. A label on that line will be lost.
110 // notEndFlag is -1 for all lines but the last one (.endm), when it is 0.
112 int defmac1(char * ln, int notEndFlag)
116 listeol(); // Flush previous source line
117 lstout('.'); // Mark macro definition with period
120 // This is just wrong, wrong, wrong. It makes up a weird kind of string with
121 // a pointer on front, and then uses a ** to manage them: This is a recipe
123 // How to manage it then?
124 // Could use a linked list, like Landon uses everywhere else.
127 Allocate a space big enough for the string + NULL + pointer.
128 Set the pointer to NULL.
129 Copy the string to the space after the pointer.
130 If this is the 1st time through, set the SYM * "svalue" to the pointer.
131 If this is the 2nd time through, derefence the ** to point to the memory you
132 just allocated. Then, set the ** to the location of the memory you allocated
133 for the next pass through.
135 This is a really low level way to do a linked list, and by bypassing all the
136 safety features of the language. Seems like we can do better here.
141 len = strlen(ln) + 1 + sizeof(LONG);
144 strcpy(p.cp + sizeof(LONG), ln);
146 // Link line of text onto end of list
148 curmac->svalue = p.cp;
152 curmln = (char **)p.cp;
153 return 1; // Keep looking
155 if (curmac->lineList == NULL)
157 curmac->lineList = malloc(sizeof(struct LineList));
158 curmac->lineList->next = NULL;
159 curmac->lineList->line = strdup(ln);
160 curmac->last = curmac->lineList;
164 curmac->last->next = malloc(sizeof(struct LineList));
165 curmac->last->next->next = NULL;
166 curmac->last->next->line = strdup(ln);
167 curmac->last = curmac->last->next;
170 return 1; // Keep looking
174 return 0; // Stop looking at the end
181 // macro foo arg1,arg2,...
188 // `defmac1' adds lines of text to the macro definition
189 // `defmac2' processes the formal arguments (and sticks them into the symbol
192 int DefineMacro(void)
194 // Setup entry in symbol table, make sure the macro isn't a duplicate
195 // entry, and that it doesn't override any processor mnemonic or assembler
197 if (*tok++ != SYMBOL)
198 return error("missing symbol");
200 char * name = string[*tok++];
202 if (lookup(name, MACRO, 0) != NULL)
203 return error("duplicate macro definition");
205 curmac = NewSymbol(name, MACRO, 0);
207 curmac->sattr = (WORD)(macnum++);
209 // Parse and define formal arguments in symbol table
217 // Suck in the macro definition; we're looking for an ENDM symbol on a line
218 // by itself to terminate the definition.
220 curmac->lineList = NULL;
221 LNCatch(defmac1, "endm ");
228 // Add lines to a .rept definition
230 int defr1(char * ln, int kwno)
234 listeol(); // Flush previous source line
235 lstout('#'); // Mark this a 'rept' block
249 //MORE stupidity here...
250 WARNING("!!! Casting (char *) as LONG !!!")
251 // Allocate length of line + 1('\0') + LONG
252 LONG len = strlen(ln) + 1 + sizeof(LONG);
253 LONG * p = (LONG *)malloc(len);
256 strcpy((char *)(p + 1), ln);
260 firstrpt = p; // First line of rept statement
274 // Define a .rept block, this gets hairy because they can be nested
280 // Evaluate repeat expression
281 if (abs_expr(&eval) != OK)
284 // Suck in lines for .rept block
288 LNCatch(defr1, "endr rept ");
290 // Alloc and init input object
293 INOBJ * inobj = a_inobj(SRC_IREPT); // Create a new REPT input object
294 IREPT * irept = inobj->inobj.irept;
295 irept->ir_firstln = firstrpt;
296 irept->ir_nextln = NULL;
297 irept->ir_count = eval;
305 // Hand off lines of text to the function 'lnfunc' until a line containing one
306 // of the directives in 'dirlist' is encountered. Return the number of the
307 // keywords encountered (0..n)
309 // 'dirlist' contains null-seperated terminated keywords. A final null
310 // terminates the list. Directives are compared to the keywords without regard
313 // If 'lnfunc' is NULL, then lines are simply skipped.
314 // If 'lnfunc' returns an error, processing is stopped.
316 // 'lnfunc' is called with an argument of -1 for every line but the last one,
317 // when it is called with an argument of the keyword number that caused the
320 static int LNCatch(int (* lnfunc)(), char * dirlist)
326 lnsave++; // Tell tokenizer to keep lines
330 if (TokenizeLine() == TKEOF)
332 error("encountered end-of-file looking for '%s'", dirlist);
333 fatal("cannot continue");
336 // Test for end condition. Two cases to handle:
338 // symbol: <directive>
344 if ((tok[2] == ':' || tok[2] == DCOLON))
346 if (tok[3] == SYMBOL) // label: symbol
351 p = string[tok[1]]; // Symbol
357 if (*p == '.') // ignore leading '.'s
360 k = KWMatch(p, dirlist);
363 // Hand-off line to function
364 // if it returns 0, and we found a keyword, stop looking.
365 // if it returns 1, hand off the line and keep looking.
367 k = (*lnfunc)(lnbuf, k);
374 lnsave--; // Tell tokenizer to stop keeping lines
381 // See if the string `kw' matches one of the keywords in `kwlist'. If so,
382 // return the number of the keyword matched. Return -1 if there was no match.
383 // Strings are compared without regard for case.
385 static int KWMatch(char * kw, char * kwlist)
387 for(int k=0; *kwlist; k++)
394 if (c2 >= 'A' && c2 <= 'Z')
397 if (c1 == ' ' && c2 == EOS)
404 // Skip to beginning of next keyword in `kwlist'
405 while (*kwlist && (*kwlist != ' '))
418 // o parse, count and copy arguments
419 // o push macro's string-stream
421 int InvokeMacro(SYM * mac, WORD siz)
426 // TOKEN ** argptr = NULL;
427 //Doesn't need to be global! (or does it???--it does)
429 DEBUG printf("InvokeMacro: argp: %d -> ", argp);
431 INOBJ * inobj = a_inobj(SRC_IMACRO); // Alloc and init IMACRO
432 IMACRO * imacro = inobj->inobj.imacro;
433 imacro->im_siz = siz;
435 TOKEN * beg_tok = tok; // 'tok' comes from token.c
441 for(dry_run=1; ; dry_run--)
443 for(tok=beg_tok; *tok!=EOL;)
457 // Keep going while tok isn't pointing at a comma or EOL
458 while (*tok != ',' && *tok != EOL)
460 // Skip over backslash character, unless it's followed by an EOL
461 if (*tok == '\\' && tok[1] != EOL)
468 //Shamus: Possible bug. ACONST has 2 tokens after it, not just 1
472 arg_siz += sizeof(TOKEN);
479 // FALLTHROUGH (picks up the arg after a CONST, SYMBOL or ACONST)
483 arg_siz += sizeof(TOKEN);
495 // We hit the comma or EOL, so count/stuff it
497 arg_siz += sizeof(TOKEN);
501 // If we hit the comma instead of an EOL, skip over it
505 // Do our QnD token grabbing (this will be redone once we get all
506 // the data structures fixed as this is a really dirty hack)
509 dest = imacro->argument[argumentNum].token;
514 // Remap strings to point the IMACRO internal token storage
515 if (*startOfArg == SYMBOL || *startOfArg == STRING)
517 *dest++ = *startOfArg++;
518 imacro->argument[argumentNum].string[stringNum] = strdup(string[*startOfArg++]);
519 *dest++ = stringNum++;
522 *dest++ = *startOfArg++;
524 while (*startOfArg != EOL);
526 *dest = *startOfArg; // Copy EOL...
531 // Allocate space for argument ptrs and so on and then go back and
532 // construct the arg frame
536 p = (TOKEN *)malloc(arg_siz);
537 // p = (TOKEN *)malloc(arg_siz + sizeof(TOKEN));
541 This construct is meant to deal with nested macros, so the simple minded way
542 we deal with them now won't work. :-/ Have to think about how to fix.
543 What we could do is simply move the argp with each call, and move it back by
544 the number of arguments in the macro that's ending. That would solve the
546 [Which we do now. But that uncovered another problem: the token strings are all
547 stale by the time a nested macro gets to the end. But they're supposed to be
548 symbols, which means if we put symbol references into the argument token
549 streams, we can alleviate this problem.]
552 argptr = (TOKEN **)malloc((nargs + 1) * sizeof(LONG));
553 *argptr++ = (TOKEN *)argp;
556 // We don't need to do anything here since we already advance argp
557 // when parsing the arguments.
565 DEBUG { printf("%d\n", argp); }
569 // o -> macro symbol;
570 // o -> macro definition string list;
571 // o save 'curuniq', to be restored when the macro pops;
572 // o bump `macuniq' counter and set 'curuniq' to it;
573 imacro->im_nargs = nargs;
574 imacro->im_macro = mac;
575 imacro->im_nextln = mac->lineList;
576 imacro->im_olduniq = curuniq;
578 imacro->argBase = argp - nargs; // Shamus: keep track of argument base
582 printf("nargs=%d\n", nargs);
584 for(nargs=0; nargs<imacro->im_nargs; nargs++)
586 printf("arg%d=", nargs);
587 dumptok(argPtrs[(argp - imacro->im_nargs) + nargs]);