xref: /netbsd-src/external/gpl3/binutils/dist/gas/macro.c (revision a5847cc334d9a7029f6352b847e9e8d71a0f9e0c)
1 /* macro.c - macro support for gas
2    Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
3    2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 
5    Written by Steve and Judy Chamberlain of Cygnus Support,
6       sac@cygnus.com
7 
8    This file is part of GAS, the GNU Assembler.
9 
10    GAS is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3, or (at your option)
13    any later version.
14 
15    GAS is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19 
20    You should have received a copy of the GNU General Public License
21    along with GAS; see the file COPYING.  If not, write to the Free
22    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
23    02110-1301, USA.  */
24 
25 #include "as.h"
26 #include "safe-ctype.h"
27 #include "sb.h"
28 #include "macro.h"
29 
30 /* The routines in this file handle macro definition and expansion.
31    They are called by gas.  */
32 
33 #define ISWHITE(x) ((x) == ' ' || (x) == '\t')
34 
35 #define ISSEP(x) \
36  ((x) == ' ' || (x) == '\t' || (x) == ',' || (x) == '"' || (x) == ';' \
37   || (x) == ')' || (x) == '(' \
38   || ((macro_alternate || macro_mri) && ((x) == '<' || (x) == '>')))
39 
40 #define ISBASE(x) \
41   ((x) == 'b' || (x) == 'B' \
42    || (x) == 'q' || (x) == 'Q' \
43    || (x) == 'h' || (x) == 'H' \
44    || (x) == 'd' || (x) == 'D')
45 
46 /* The macro hash table.  */
47 
48 struct hash_control *macro_hash;
49 
50 /* Whether any macros have been defined.  */
51 
52 int macro_defined;
53 
54 /* Whether we are in alternate syntax mode.  */
55 
56 static int macro_alternate;
57 
58 /* Whether we are in MRI mode.  */
59 
60 static int macro_mri;
61 
62 /* Whether we should strip '@' characters.  */
63 
64 static int macro_strip_at;
65 
66 /* Function to use to parse an expression.  */
67 
68 static int (*macro_expr) (const char *, int, sb *, int *);
69 
70 /* Number of macro expansions that have been done.  */
71 
72 static int macro_number;
73 
74 /* Initialize macro processing.  */
75 
76 void
77 macro_init (int alternate, int mri, int strip_at,
78 	    int (*exp) (const char *, int, sb *, int *))
79 {
80   macro_hash = hash_new ();
81   macro_defined = 0;
82   macro_alternate = alternate;
83   macro_mri = mri;
84   macro_strip_at = strip_at;
85   macro_expr = exp;
86 }
87 
88 /* Switch in and out of alternate mode on the fly.  */
89 
90 void
91 macro_set_alternate (int alternate)
92 {
93   macro_alternate = alternate;
94 }
95 
96 /* Switch in and out of MRI mode on the fly.  */
97 
98 void
99 macro_mri_mode (int mri)
100 {
101   macro_mri = mri;
102 }
103 
104 /* Read input lines till we get to a TO string.
105    Increase nesting depth if we get a FROM string.
106    Put the results into sb at PTR.
107    FROM may be NULL (or will be ignored) if TO is "ENDR".
108    Add a new input line to an sb using GET_LINE.
109    Return 1 on success, 0 on unexpected EOF.  */
110 
111 int
112 buffer_and_nest (const char *from, const char *to, sb *ptr,
113 		 int (*get_line) (sb *))
114 {
115   int from_len;
116   int to_len = strlen (to);
117   int depth = 1;
118   int line_start = ptr->len;
119 
120   int more = get_line (ptr);
121 
122   if (to_len == 4 && strcasecmp(to, "ENDR") == 0)
123     {
124       from = NULL;
125       from_len = 0;
126     }
127   else
128     from_len = strlen (from);
129 
130   while (more)
131     {
132       /* Try to find the first pseudo op on the line.  */
133       int i = line_start;
134       bfd_boolean had_colon = FALSE;
135 
136       /* With normal syntax we can suck what we want till we get
137 	 to the dot.  With the alternate, labels have to start in
138 	 the first column, since we can't tell what's a label and
139 	 what's a pseudoop.  */
140 
141       if (! LABELS_WITHOUT_COLONS)
142 	{
143 	  /* Skip leading whitespace.  */
144 	  while (i < ptr->len && ISWHITE (ptr->ptr[i]))
145 	    i++;
146 	}
147 
148       for (;;)
149 	{
150 	  /* Skip over a label, if any.  */
151 	  if (i >= ptr->len || ! is_name_beginner (ptr->ptr[i]))
152 	    break;
153 	  i++;
154 	  while (i < ptr->len && is_part_of_name (ptr->ptr[i]))
155 	    i++;
156 	  if (i < ptr->len && is_name_ender (ptr->ptr[i]))
157 	    i++;
158 	  /* Skip whitespace.  */
159 	  while (i < ptr->len && ISWHITE (ptr->ptr[i]))
160 	    i++;
161 	  /* Check for the colon.  */
162 	  if (i >= ptr->len || ptr->ptr[i] != ':')
163 	    {
164 	      /* LABELS_WITHOUT_COLONS doesn't mean we cannot have a
165 		 colon after a label.  If we do have a colon on the
166 		 first label then handle more than one label on the
167 		 line, assuming that each label has a colon.  */
168 	      if (LABELS_WITHOUT_COLONS && !had_colon)
169 		break;
170 	      i = line_start;
171 	      break;
172 	    }
173 	  i++;
174 	  line_start = i;
175 	  had_colon = TRUE;
176 	}
177 
178       /* Skip trailing whitespace.  */
179       while (i < ptr->len && ISWHITE (ptr->ptr[i]))
180 	i++;
181 
182       if (i < ptr->len && (ptr->ptr[i] == '.'
183 			   || NO_PSEUDO_DOT
184 			   || macro_mri))
185 	{
186 	  if (! flag_m68k_mri && ptr->ptr[i] == '.')
187 	    i++;
188 	  if (from == NULL
189 	     && strncasecmp (ptr->ptr + i, "IRPC", from_len = 4) != 0
190 	     && strncasecmp (ptr->ptr + i, "IRP", from_len = 3) != 0
191 	     && strncasecmp (ptr->ptr + i, "IREPC", from_len = 5) != 0
192 	     && strncasecmp (ptr->ptr + i, "IREP", from_len = 4) != 0
193 	     && strncasecmp (ptr->ptr + i, "REPT", from_len = 4) != 0
194 	     && strncasecmp (ptr->ptr + i, "REP", from_len = 3) != 0)
195 	    from_len = 0;
196 	  if ((from != NULL
197 	       ? strncasecmp (ptr->ptr + i, from, from_len) == 0
198 	       : from_len > 0)
199 	      && (ptr->len == (i + from_len)
200 		  || ! (is_part_of_name (ptr->ptr[i + from_len])
201 			|| is_name_ender (ptr->ptr[i + from_len]))))
202 	    depth++;
203 	  if (strncasecmp (ptr->ptr + i, to, to_len) == 0
204 	      && (ptr->len == (i + to_len)
205 		  || ! (is_part_of_name (ptr->ptr[i + to_len])
206 			|| is_name_ender (ptr->ptr[i + to_len]))))
207 	    {
208 	      depth--;
209 	      if (depth == 0)
210 		{
211 		  /* Reset the string to not include the ending rune.  */
212 		  ptr->len = line_start;
213 		  break;
214 		}
215 	    }
216 	}
217 
218       /* Add the original end-of-line char to the end and keep running.  */
219       sb_add_char (ptr, more);
220       line_start = ptr->len;
221       more = get_line (ptr);
222     }
223 
224   /* Return 1 on success, 0 on unexpected EOF.  */
225   return depth == 0;
226 }
227 
228 /* Pick up a token.  */
229 
230 static int
231 get_token (int idx, sb *in, sb *name)
232 {
233   if (idx < in->len
234       && is_name_beginner (in->ptr[idx]))
235     {
236       sb_add_char (name, in->ptr[idx++]);
237       while (idx < in->len
238 	     && is_part_of_name (in->ptr[idx]))
239 	{
240 	  sb_add_char (name, in->ptr[idx++]);
241 	}
242       if (idx < in->len
243 	     && is_name_ender (in->ptr[idx]))
244 	{
245 	  sb_add_char (name, in->ptr[idx++]);
246 	}
247     }
248   /* Ignore trailing &.  */
249   if (macro_alternate && idx < in->len && in->ptr[idx] == '&')
250     idx++;
251   return idx;
252 }
253 
254 /* Pick up a string.  */
255 
256 static int
257 getstring (int idx, sb *in, sb *acc)
258 {
259   while (idx < in->len
260 	 && (in->ptr[idx] == '"'
261 	     || (in->ptr[idx] == '<' && (macro_alternate || macro_mri))
262 	     || (in->ptr[idx] == '\'' && macro_alternate)))
263     {
264       if (in->ptr[idx] == '<')
265 	{
266 	  int nest = 0;
267 	  idx++;
268 	  while ((in->ptr[idx] != '>' || nest)
269 		 && idx < in->len)
270 	    {
271 	      if (in->ptr[idx] == '!')
272 		{
273 		  idx++;
274 		  sb_add_char (acc, in->ptr[idx++]);
275 		}
276 	      else
277 		{
278 		  if (in->ptr[idx] == '>')
279 		    nest--;
280 		  if (in->ptr[idx] == '<')
281 		    nest++;
282 		  sb_add_char (acc, in->ptr[idx++]);
283 		}
284 	    }
285 	  idx++;
286 	}
287       else if (in->ptr[idx] == '"' || in->ptr[idx] == '\'')
288 	{
289 	  char tchar = in->ptr[idx];
290 	  int escaped = 0;
291 
292 	  idx++;
293 
294 	  while (idx < in->len)
295 	    {
296 	      if (in->ptr[idx - 1] == '\\')
297 		escaped ^= 1;
298 	      else
299 		escaped = 0;
300 
301 	      if (macro_alternate && in->ptr[idx] == '!')
302 		{
303 		  idx ++;
304 
305 		  sb_add_char (acc, in->ptr[idx]);
306 
307 		  idx ++;
308 		}
309 	      else if (escaped && in->ptr[idx] == tchar)
310 		{
311 		  sb_add_char (acc, tchar);
312 		  idx ++;
313 		}
314 	      else
315 		{
316 		  if (in->ptr[idx] == tchar)
317 		    {
318 		      idx ++;
319 
320 		      if (idx >= in->len || in->ptr[idx] != tchar)
321 			break;
322 		    }
323 
324 		  sb_add_char (acc, in->ptr[idx]);
325 		  idx ++;
326 		}
327 	    }
328 	}
329     }
330 
331   return idx;
332 }
333 
334 /* Fetch string from the input stream,
335    rules:
336     'Bxyx<whitespace>  	-> return 'Bxyza
337     %<expr>		-> return string of decimal value of <expr>
338     "string"		-> return string
339     (string)		-> return (string-including-whitespaces)
340     xyx<whitespace>     -> return xyz.  */
341 
342 static int
343 get_any_string (int idx, sb *in, sb *out)
344 {
345   sb_reset (out);
346   idx = sb_skip_white (idx, in);
347 
348   if (idx < in->len)
349     {
350       if (in->len > idx + 2 && in->ptr[idx + 1] == '\'' && ISBASE (in->ptr[idx]))
351 	{
352 	  while (!ISSEP (in->ptr[idx]))
353 	    sb_add_char (out, in->ptr[idx++]);
354 	}
355       else if (in->ptr[idx] == '%' && macro_alternate)
356 	{
357 	  int val;
358 	  char buf[20];
359 
360 	  /* Turns the next expression into a string.  */
361 	  /* xgettext: no-c-format */
362 	  idx = (*macro_expr) (_("% operator needs absolute expression"),
363 			       idx + 1,
364 			       in,
365 			       &val);
366 	  sprintf (buf, "%d", val);
367 	  sb_add_string (out, buf);
368 	}
369       else if (in->ptr[idx] == '"'
370 	       || (in->ptr[idx] == '<' && (macro_alternate || macro_mri))
371 	       || (macro_alternate && in->ptr[idx] == '\''))
372 	{
373 	  if (macro_alternate && ! macro_strip_at && in->ptr[idx] != '<')
374 	    {
375 	      /* Keep the quotes.  */
376 	      sb_add_char (out, '"');
377 	      idx = getstring (idx, in, out);
378 	      sb_add_char (out, '"');
379 	    }
380 	  else
381 	    {
382 	      idx = getstring (idx, in, out);
383 	    }
384 	}
385       else
386 	{
387 	  char *br_buf = (char *) xmalloc(1);
388 	  char *in_br = br_buf;
389 
390 	  *in_br = '\0';
391 	  while (idx < in->len
392 		 && (*in_br
393 		     || (in->ptr[idx] != ' '
394 			 && in->ptr[idx] != '\t'))
395 		 && in->ptr[idx] != ','
396 		 && (in->ptr[idx] != '<'
397 		     || (! macro_alternate && ! macro_mri)))
398 	    {
399 	      char tchar = in->ptr[idx];
400 
401 	      switch (tchar)
402 		{
403 		case '"':
404 		case '\'':
405 		  sb_add_char (out, in->ptr[idx++]);
406 		  while (idx < in->len
407 			 && in->ptr[idx] != tchar)
408 		    sb_add_char (out, in->ptr[idx++]);
409 		  if (idx == in->len)
410 		    return idx;
411 		  break;
412 		case '(':
413 		case '[':
414 		  if (in_br > br_buf)
415 		    --in_br;
416 		  else
417 		    {
418 		      br_buf = (char *) xmalloc(strlen(in_br) + 2);
419 		      strcpy(br_buf + 1, in_br);
420 		      free(in_br);
421 		      in_br = br_buf;
422 		    }
423 		  *in_br = tchar;
424 		  break;
425 		case ')':
426 		  if (*in_br == '(')
427 		    ++in_br;
428 		  break;
429 		case ']':
430 		  if (*in_br == '[')
431 		    ++in_br;
432 		  break;
433 		}
434 	      sb_add_char (out, tchar);
435 	      ++idx;
436 	    }
437 	  free(br_buf);
438 	}
439     }
440 
441   return idx;
442 }
443 
444 /* Allocate a new formal.  */
445 
446 static formal_entry *
447 new_formal (void)
448 {
449   formal_entry *formal;
450 
451   formal = (formal_entry *) xmalloc (sizeof (formal_entry));
452 
453   sb_new (&formal->name);
454   sb_new (&formal->def);
455   sb_new (&formal->actual);
456   formal->next = NULL;
457   formal->type = FORMAL_OPTIONAL;
458   return formal;
459 }
460 
461 /* Free a formal.  */
462 
463 static void
464 del_formal (formal_entry *formal)
465 {
466   sb_kill (&formal->actual);
467   sb_kill (&formal->def);
468   sb_kill (&formal->name);
469   free (formal);
470 }
471 
472 /* Pick up the formal parameters of a macro definition.  */
473 
474 static int
475 do_formals (macro_entry *macro, int idx, sb *in)
476 {
477   formal_entry **p = &macro->formals;
478   const char *name;
479 
480   idx = sb_skip_white (idx, in);
481   while (idx < in->len)
482     {
483       formal_entry *formal = new_formal ();
484       int cidx;
485 
486       idx = get_token (idx, in, &formal->name);
487       if (formal->name.len == 0)
488 	{
489 	  if (macro->formal_count)
490 	    --idx;
491 	  break;
492 	}
493       idx = sb_skip_white (idx, in);
494       /* This is a formal.  */
495       name = sb_terminate (&formal->name);
496       if (! macro_mri
497 	  && idx < in->len
498 	  && in->ptr[idx] == ':'
499 	  && (! is_name_beginner (':')
500 	      || idx + 1 >= in->len
501 	      || ! is_part_of_name (in->ptr[idx + 1])))
502 	{
503 	  /* Got a qualifier.  */
504 	  sb qual;
505 
506 	  sb_new (&qual);
507 	  idx = get_token (sb_skip_white (idx + 1, in), in, &qual);
508 	  sb_terminate (&qual);
509 	  if (qual.len == 0)
510 	    as_bad_where (macro->file,
511 			  macro->line,
512 			  _("Missing parameter qualifier for `%s' in macro `%s'"),
513 			  name,
514 			  macro->name);
515 	  else if (strcmp (qual.ptr, "req") == 0)
516 	    formal->type = FORMAL_REQUIRED;
517 	  else if (strcmp (qual.ptr, "vararg") == 0)
518 	    formal->type = FORMAL_VARARG;
519 	  else
520 	    as_bad_where (macro->file,
521 			  macro->line,
522 			  _("`%s' is not a valid parameter qualifier for `%s' in macro `%s'"),
523 			  qual.ptr,
524 			  name,
525 			  macro->name);
526 	  sb_kill (&qual);
527 	  idx = sb_skip_white (idx, in);
528 	}
529       if (idx < in->len && in->ptr[idx] == '=')
530 	{
531 	  /* Got a default.  */
532 	  idx = get_any_string (idx + 1, in, &formal->def);
533 	  idx = sb_skip_white (idx, in);
534 	  if (formal->type == FORMAL_REQUIRED)
535 	    {
536 	      sb_reset (&formal->def);
537 	      as_warn_where (macro->file,
538 			    macro->line,
539 			    _("Pointless default value for required parameter `%s' in macro `%s'"),
540 			    name,
541 			    macro->name);
542 	    }
543 	}
544 
545       /* Add to macro's hash table.  */
546       if (! hash_find (macro->formal_hash, name))
547 	hash_jam (macro->formal_hash, name, formal);
548       else
549 	as_bad_where (macro->file,
550 		      macro->line,
551 		      _("A parameter named `%s' already exists for macro `%s'"),
552 		      name,
553 		      macro->name);
554 
555       formal->index = macro->formal_count++;
556       *p = formal;
557       p = &formal->next;
558       if (formal->type == FORMAL_VARARG)
559 	break;
560       cidx = idx;
561       idx = sb_skip_comma (idx, in);
562       if (idx != cidx && idx >= in->len)
563 	{
564 	  idx = cidx;
565 	  break;
566 	}
567     }
568 
569   if (macro_mri)
570     {
571       formal_entry *formal = new_formal ();
572 
573       /* Add a special NARG formal, which macro_expand will set to the
574          number of arguments.  */
575       /* The same MRI assemblers which treat '@' characters also use
576          the name $NARG.  At least until we find an exception.  */
577       if (macro_strip_at)
578 	name = "$NARG";
579       else
580 	name = "NARG";
581 
582       sb_add_string (&formal->name, name);
583 
584       /* Add to macro's hash table.  */
585       if (hash_find (macro->formal_hash, name))
586 	as_bad_where (macro->file,
587 		      macro->line,
588 		      _("Reserved word `%s' used as parameter in macro `%s'"),
589 		      name,
590 		      macro->name);
591       hash_jam (macro->formal_hash, name, formal);
592 
593       formal->index = NARG_INDEX;
594       *p = formal;
595     }
596 
597   return idx;
598 }
599 
600 /* Free the memory allocated to a macro.  */
601 
602 static void
603 free_macro (macro_entry *macro)
604 {
605   formal_entry *formal;
606 
607   for (formal = macro->formals; formal; )
608     {
609       formal_entry *f;
610 
611       f = formal;
612       formal = formal->next;
613       del_formal (f);
614     }
615   hash_die (macro->formal_hash);
616   sb_kill (&macro->sub);
617   free (macro);
618 }
619 
620 /* Define a new macro.  Returns NULL on success, otherwise returns an
621    error message.  If NAMEP is not NULL, *NAMEP is set to the name of
622    the macro which was defined.  */
623 
624 const char *
625 define_macro (int idx, sb *in, sb *label,
626 	      int (*get_line) (sb *),
627 	      char *file, unsigned int line,
628 	      const char **namep)
629 {
630   macro_entry *macro;
631   sb name;
632   const char *error = NULL;
633 
634   macro = (macro_entry *) xmalloc (sizeof (macro_entry));
635   sb_new (&macro->sub);
636   sb_new (&name);
637   macro->file = file;
638   macro->line = line;
639 
640   macro->formal_count = 0;
641   macro->formals = 0;
642   macro->formal_hash = hash_new ();
643 
644   idx = sb_skip_white (idx, in);
645   if (! buffer_and_nest ("MACRO", "ENDM", &macro->sub, get_line))
646     error = _("unexpected end of file in macro `%s' definition");
647   if (label != NULL && label->len != 0)
648     {
649       sb_add_sb (&name, label);
650       macro->name = sb_terminate (&name);
651       if (idx < in->len && in->ptr[idx] == '(')
652 	{
653 	  /* It's the label: MACRO (formals,...)  sort  */
654 	  idx = do_formals (macro, idx + 1, in);
655 	  if (idx < in->len && in->ptr[idx] == ')')
656 	    idx = sb_skip_white (idx + 1, in);
657 	  else if (!error)
658 	    error = _("missing `)' after formals in macro definition `%s'");
659 	}
660       else
661 	{
662 	  /* It's the label: MACRO formals,...  sort  */
663 	  idx = do_formals (macro, idx, in);
664 	}
665     }
666   else
667     {
668       int cidx;
669 
670       idx = get_token (idx, in, &name);
671       macro->name = sb_terminate (&name);
672       if (name.len == 0)
673 	error = _("Missing macro name");
674       cidx = sb_skip_white (idx, in);
675       idx = sb_skip_comma (cidx, in);
676       if (idx == cidx || idx < in->len)
677 	idx = do_formals (macro, idx, in);
678       else
679 	idx = cidx;
680     }
681   if (!error && idx < in->len)
682     error = _("Bad parameter list for macro `%s'");
683 
684   /* And stick it in the macro hash table.  */
685   for (idx = 0; idx < name.len; idx++)
686     name.ptr[idx] = TOLOWER (name.ptr[idx]);
687   if (hash_find (macro_hash, macro->name))
688     error = _("Macro `%s' was already defined");
689   if (!error)
690     error = hash_jam (macro_hash, macro->name, (void *) macro);
691 
692   if (namep != NULL)
693     *namep = macro->name;
694 
695   if (!error)
696     macro_defined = 1;
697   else
698     free_macro (macro);
699 
700   return error;
701 }
702 
703 /* Scan a token, and then skip KIND.  */
704 
705 static int
706 get_apost_token (int idx, sb *in, sb *name, int kind)
707 {
708   idx = get_token (idx, in, name);
709   if (idx < in->len
710       && in->ptr[idx] == kind
711       && (! macro_mri || macro_strip_at)
712       && (! macro_strip_at || kind == '@'))
713     idx++;
714   return idx;
715 }
716 
717 /* Substitute the actual value for a formal parameter.  */
718 
719 static int
720 sub_actual (int start, sb *in, sb *t, struct hash_control *formal_hash,
721 	    int kind, sb *out, int copyifnotthere)
722 {
723   int src;
724   formal_entry *ptr;
725 
726   src = get_apost_token (start, in, t, kind);
727   /* See if it's in the macro's hash table, unless this is
728      macro_strip_at and kind is '@' and the token did not end in '@'.  */
729   if (macro_strip_at
730       && kind == '@'
731       && (src == start || in->ptr[src - 1] != '@'))
732     ptr = NULL;
733   else
734     ptr = (formal_entry *) hash_find (formal_hash, sb_terminate (t));
735   if (ptr)
736     {
737       if (ptr->actual.len)
738 	{
739 	  sb_add_sb (out, &ptr->actual);
740 	}
741       else
742 	{
743 	  sb_add_sb (out, &ptr->def);
744 	}
745     }
746   else if (kind == '&')
747     {
748       /* Doing this permits people to use & in macro bodies.  */
749       sb_add_char (out, '&');
750       sb_add_sb (out, t);
751       if (src != start && in->ptr[src - 1] == '&')
752 	sb_add_char (out, '&');
753     }
754   else if (copyifnotthere)
755     {
756       sb_add_sb (out, t);
757     }
758   else
759     {
760       sb_add_char (out, '\\');
761       sb_add_sb (out, t);
762     }
763   return src;
764 }
765 
766 /* Expand the body of a macro.  */
767 
768 static const char *
769 macro_expand_body (sb *in, sb *out, formal_entry *formals,
770 		   struct hash_control *formal_hash, const macro_entry *macro)
771 {
772   sb t;
773   int src = 0, inquote = 0, macro_line = 0;
774   formal_entry *loclist = NULL;
775   const char *err = NULL;
776 
777   sb_new (&t);
778 
779   while (src < in->len && !err)
780     {
781       if (in->ptr[src] == '&')
782 	{
783 	  sb_reset (&t);
784 	  if (macro_mri)
785 	    {
786 	      if (src + 1 < in->len && in->ptr[src + 1] == '&')
787 		src = sub_actual (src + 2, in, &t, formal_hash, '\'', out, 1);
788 	      else
789 		sb_add_char (out, in->ptr[src++]);
790 	    }
791 	  else
792 	    {
793 	      /* Permit macro parameter substition delineated with
794 		 an '&' prefix and optional '&' suffix.  */
795 	      src = sub_actual (src + 1, in, &t, formal_hash, '&', out, 0);
796 	    }
797 	}
798       else if (in->ptr[src] == '\\')
799 	{
800 	  src++;
801 	  if (src < in->len && in->ptr[src] == '(')
802 	    {
803 	      /* Sub in till the next ')' literally.  */
804 	      src++;
805 	      while (src < in->len && in->ptr[src] != ')')
806 		{
807 		  sb_add_char (out, in->ptr[src++]);
808 		}
809 	      if (src < in->len)
810 		src++;
811 	      else if (!macro)
812 		err = _("missing `)'");
813 	      else
814 		as_bad_where (macro->file, macro->line + macro_line, _("missing `)'"));
815 	    }
816 	  else if (src < in->len && in->ptr[src] == '@')
817 	    {
818 	      /* Sub in the macro invocation number.  */
819 
820 	      char buffer[10];
821 	      src++;
822 	      sprintf (buffer, "%d", macro_number);
823 	      sb_add_string (out, buffer);
824 	    }
825 	  else if (src < in->len && in->ptr[src] == '&')
826 	    {
827 	      /* This is a preprocessor variable name, we don't do them
828 		 here.  */
829 	      sb_add_char (out, '\\');
830 	      sb_add_char (out, '&');
831 	      src++;
832 	    }
833 	  else if (macro_mri && src < in->len && ISALNUM (in->ptr[src]))
834 	    {
835 	      int ind;
836 	      formal_entry *f;
837 
838 	      if (ISDIGIT (in->ptr[src]))
839 		ind = in->ptr[src] - '0';
840 	      else if (ISUPPER (in->ptr[src]))
841 		ind = in->ptr[src] - 'A' + 10;
842 	      else
843 		ind = in->ptr[src] - 'a' + 10;
844 	      ++src;
845 	      for (f = formals; f != NULL; f = f->next)
846 		{
847 		  if (f->index == ind - 1)
848 		    {
849 		      if (f->actual.len != 0)
850 			sb_add_sb (out, &f->actual);
851 		      else
852 			sb_add_sb (out, &f->def);
853 		      break;
854 		    }
855 		}
856 	    }
857 	  else
858 	    {
859 	      sb_reset (&t);
860 	      src = sub_actual (src, in, &t, formal_hash, '\'', out, 0);
861 	    }
862 	}
863       else if ((macro_alternate || macro_mri)
864 	       && is_name_beginner (in->ptr[src])
865 	       && (! inquote
866 		   || ! macro_strip_at
867 		   || (src > 0 && in->ptr[src - 1] == '@')))
868 	{
869 	  if (! macro
870 	      || src + 5 >= in->len
871 	      || strncasecmp (in->ptr + src, "LOCAL", 5) != 0
872 	      || ! ISWHITE (in->ptr[src + 5])
873 	      /* PR 11507: Skip keyword LOCAL if it is found inside a quoted string.  */
874 	      || inquote)
875 	    {
876 	      sb_reset (&t);
877 	      src = sub_actual (src, in, &t, formal_hash,
878 				(macro_strip_at && inquote) ? '@' : '\'',
879 				out, 1);
880 	    }
881 	  else
882 	    {
883 	      src = sb_skip_white (src + 5, in);
884 	      while (in->ptr[src] != '\n')
885 		{
886 		  const char *name;
887 		  formal_entry *f = new_formal ();
888 
889 		  src = get_token (src, in, &f->name);
890 		  name = sb_terminate (&f->name);
891 		  if (! hash_find (formal_hash, name))
892 		    {
893 		      static int loccnt;
894 		      char buf[20];
895 
896 		      f->index = LOCAL_INDEX;
897 		      f->next = loclist;
898 		      loclist = f;
899 
900 		      sprintf (buf, IS_ELF ? ".LL%04x" : "LL%04x", ++loccnt);
901 		      sb_add_string (&f->actual, buf);
902 
903 		      err = hash_jam (formal_hash, name, f);
904 		      if (err != NULL)
905 			break;
906 		    }
907 		  else
908 		    {
909 		      as_bad_where (macro->file,
910 				    macro->line + macro_line,
911 				    _("`%s' was already used as parameter (or another local) name"),
912 				    name);
913 		      del_formal (f);
914 		    }
915 
916 		  src = sb_skip_comma (src, in);
917 		}
918 	    }
919 	}
920       else if (in->ptr[src] == '"'
921 	       || (macro_mri && in->ptr[src] == '\''))
922 	{
923 	  inquote = !inquote;
924 	  sb_add_char (out, in->ptr[src++]);
925 	}
926       else if (in->ptr[src] == '@' && macro_strip_at)
927 	{
928 	  ++src;
929 	  if (src < in->len
930 	      && in->ptr[src] == '@')
931 	    {
932 	      sb_add_char (out, '@');
933 	      ++src;
934 	    }
935 	}
936       else if (macro_mri
937 	       && in->ptr[src] == '='
938 	       && src + 1 < in->len
939 	       && in->ptr[src + 1] == '=')
940 	{
941 	  formal_entry *ptr;
942 
943 	  sb_reset (&t);
944 	  src = get_token (src + 2, in, &t);
945 	  ptr = (formal_entry *) hash_find (formal_hash, sb_terminate (&t));
946 	  if (ptr == NULL)
947 	    {
948 	      /* FIXME: We should really return a warning string here,
949                  but we can't, because the == might be in the MRI
950                  comment field, and, since the nature of the MRI
951                  comment field depends upon the exact instruction
952                  being used, we don't have enough information here to
953                  figure out whether it is or not.  Instead, we leave
954                  the == in place, which should cause a syntax error if
955                  it is not in a comment.  */
956 	      sb_add_char (out, '=');
957 	      sb_add_char (out, '=');
958 	      sb_add_sb (out, &t);
959 	    }
960 	  else
961 	    {
962 	      if (ptr->actual.len)
963 		{
964 		  sb_add_string (out, "-1");
965 		}
966 	      else
967 		{
968 		  sb_add_char (out, '0');
969 		}
970 	    }
971 	}
972       else
973 	{
974 	  if (in->ptr[src] == '\n')
975 	    ++macro_line;
976 	  sb_add_char (out, in->ptr[src++]);
977 	}
978     }
979 
980   sb_kill (&t);
981 
982   while (loclist != NULL)
983     {
984       formal_entry *f;
985       const char *name;
986 
987       f = loclist->next;
988       name = sb_terminate (&loclist->name);
989       hash_delete (formal_hash, name, f == NULL);
990       del_formal (loclist);
991       loclist = f;
992     }
993 
994   return err;
995 }
996 
997 /* Assign values to the formal parameters of a macro, and expand the
998    body.  */
999 
1000 static const char *
1001 macro_expand (int idx, sb *in, macro_entry *m, sb *out)
1002 {
1003   sb t;
1004   formal_entry *ptr;
1005   formal_entry *f;
1006   int is_keyword = 0;
1007   int narg = 0;
1008   const char *err = NULL;
1009 
1010   sb_new (&t);
1011 
1012   /* Reset any old value the actuals may have.  */
1013   for (f = m->formals; f; f = f->next)
1014     sb_reset (&f->actual);
1015   f = m->formals;
1016   while (f != NULL && f->index < 0)
1017     f = f->next;
1018 
1019   if (macro_mri)
1020     {
1021       /* The macro may be called with an optional qualifier, which may
1022          be referred to in the macro body as \0.  */
1023       if (idx < in->len && in->ptr[idx] == '.')
1024 	{
1025 	  /* The Microtec assembler ignores this if followed by a white space.
1026 	     (Macro invocation with empty extension) */
1027 	  idx++;
1028 	  if (    idx < in->len
1029 		  && in->ptr[idx] != ' '
1030 		  && in->ptr[idx] != '\t')
1031 	    {
1032 	      formal_entry *n = new_formal ();
1033 
1034 	      n->index = QUAL_INDEX;
1035 
1036 	      n->next = m->formals;
1037 	      m->formals = n;
1038 
1039 	      idx = get_any_string (idx, in, &n->actual);
1040 	    }
1041 	}
1042     }
1043 
1044   /* Peel off the actuals and store them away in the hash tables' actuals.  */
1045   idx = sb_skip_white (idx, in);
1046   while (idx < in->len)
1047     {
1048       int scan;
1049 
1050       /* Look and see if it's a positional or keyword arg.  */
1051       scan = idx;
1052       while (scan < in->len
1053 	     && !ISSEP (in->ptr[scan])
1054 	     && !(macro_mri && in->ptr[scan] == '\'')
1055 	     && (!macro_alternate && in->ptr[scan] != '='))
1056 	scan++;
1057       if (scan < in->len && !macro_alternate && in->ptr[scan] == '=')
1058 	{
1059 	  is_keyword = 1;
1060 
1061 	  /* It's OK to go from positional to keyword.  */
1062 
1063 	  /* This is a keyword arg, fetch the formal name and
1064 	     then the actual stuff.  */
1065 	  sb_reset (&t);
1066 	  idx = get_token (idx, in, &t);
1067 	  if (in->ptr[idx] != '=')
1068 	    {
1069 	      err = _("confusion in formal parameters");
1070 	      break;
1071 	    }
1072 
1073 	  /* Lookup the formal in the macro's list.  */
1074 	  ptr = (formal_entry *) hash_find (m->formal_hash, sb_terminate (&t));
1075 	  if (!ptr)
1076 	    {
1077 	      as_bad (_("Parameter named `%s' does not exist for macro `%s'"),
1078 		      t.ptr,
1079 		      m->name);
1080 	      sb_reset (&t);
1081 	      idx = get_any_string (idx + 1, in, &t);
1082 	    }
1083 	  else
1084 	    {
1085 	      /* Insert this value into the right place.  */
1086 	      if (ptr->actual.len)
1087 		{
1088 		  as_warn (_("Value for parameter `%s' of macro `%s' was already specified"),
1089 			   ptr->name.ptr,
1090 			   m->name);
1091 		  sb_reset (&ptr->actual);
1092 		}
1093 	      idx = get_any_string (idx + 1, in, &ptr->actual);
1094 	      if (ptr->actual.len > 0)
1095 		++narg;
1096 	    }
1097 	}
1098       else
1099 	{
1100 	  if (is_keyword)
1101 	    {
1102 	      err = _("can't mix positional and keyword arguments");
1103 	      break;
1104 	    }
1105 
1106 	  if (!f)
1107 	    {
1108 	      formal_entry **pf;
1109 	      int c;
1110 
1111 	      if (!macro_mri)
1112 		{
1113 		  err = _("too many positional arguments");
1114 		  break;
1115 		}
1116 
1117 	      f = new_formal ();
1118 
1119 	      c = -1;
1120 	      for (pf = &m->formals; *pf != NULL; pf = &(*pf)->next)
1121 		if ((*pf)->index >= c)
1122 		  c = (*pf)->index + 1;
1123 	      if (c == -1)
1124 		c = 0;
1125 	      *pf = f;
1126 	      f->index = c;
1127 	    }
1128 
1129 	  if (f->type != FORMAL_VARARG)
1130 	    idx = get_any_string (idx, in, &f->actual);
1131 	  else
1132 	    {
1133 	      sb_add_buffer (&f->actual, in->ptr + idx, in->len - idx);
1134 	      idx = in->len;
1135 	    }
1136 	  if (f->actual.len > 0)
1137 	    ++narg;
1138 	  do
1139 	    {
1140 	      f = f->next;
1141 	    }
1142 	  while (f != NULL && f->index < 0);
1143 	}
1144 
1145       if (! macro_mri)
1146 	idx = sb_skip_comma (idx, in);
1147       else
1148 	{
1149 	  if (in->ptr[idx] == ',')
1150 	    ++idx;
1151 	  if (ISWHITE (in->ptr[idx]))
1152 	    break;
1153 	}
1154     }
1155 
1156   if (! err)
1157     {
1158       for (ptr = m->formals; ptr; ptr = ptr->next)
1159 	{
1160 	  if (ptr->type == FORMAL_REQUIRED && ptr->actual.len == 0)
1161 	    as_bad (_("Missing value for required parameter `%s' of macro `%s'"),
1162 		    ptr->name.ptr,
1163 		    m->name);
1164 	}
1165 
1166       if (macro_mri)
1167 	{
1168 	  char buffer[20];
1169 
1170 	  sb_reset (&t);
1171 	  sb_add_string (&t, macro_strip_at ? "$NARG" : "NARG");
1172 	  ptr = (formal_entry *) hash_find (m->formal_hash, sb_terminate (&t));
1173 	  sprintf (buffer, "%d", narg);
1174 	  sb_add_string (&ptr->actual, buffer);
1175 	}
1176 
1177       err = macro_expand_body (&m->sub, out, m->formals, m->formal_hash, m);
1178     }
1179 
1180   /* Discard any unnamed formal arguments.  */
1181   if (macro_mri)
1182     {
1183       formal_entry **pf;
1184 
1185       pf = &m->formals;
1186       while (*pf != NULL)
1187 	{
1188 	  if ((*pf)->name.len != 0)
1189 	    pf = &(*pf)->next;
1190 	  else
1191 	    {
1192 	      f = (*pf)->next;
1193 	      del_formal (*pf);
1194 	      *pf = f;
1195 	    }
1196 	}
1197     }
1198 
1199   sb_kill (&t);
1200   if (!err)
1201     macro_number++;
1202 
1203   return err;
1204 }
1205 
1206 /* Check for a macro.  If one is found, put the expansion into
1207    *EXPAND.  Return 1 if a macro is found, 0 otherwise.  */
1208 
1209 int
1210 check_macro (const char *line, sb *expand,
1211 	     const char **error, macro_entry **info)
1212 {
1213   const char *s;
1214   char *copy, *cls;
1215   macro_entry *macro;
1216   sb line_sb;
1217 
1218   if (! is_name_beginner (*line)
1219       && (! macro_mri || *line != '.'))
1220     return 0;
1221 
1222   s = line + 1;
1223   while (is_part_of_name (*s))
1224     ++s;
1225   if (is_name_ender (*s))
1226     ++s;
1227 
1228   copy = (char *) alloca (s - line + 1);
1229   memcpy (copy, line, s - line);
1230   copy[s - line] = '\0';
1231   for (cls = copy; *cls != '\0'; cls ++)
1232     *cls = TOLOWER (*cls);
1233 
1234   macro = (macro_entry *) hash_find (macro_hash, copy);
1235 
1236   if (macro == NULL)
1237     return 0;
1238 
1239   /* Wrap the line up in an sb.  */
1240   sb_new (&line_sb);
1241   while (*s != '\0' && *s != '\n' && *s != '\r')
1242     sb_add_char (&line_sb, *s++);
1243 
1244   sb_new (expand);
1245   *error = macro_expand (0, &line_sb, macro, expand);
1246 
1247   sb_kill (&line_sb);
1248 
1249   /* Export the macro information if requested.  */
1250   if (info)
1251     *info = macro;
1252 
1253   return 1;
1254 }
1255 
1256 /* Delete a macro.  */
1257 
1258 void
1259 delete_macro (const char *name)
1260 {
1261   char *copy;
1262   size_t i, len;
1263   macro_entry *macro;
1264 
1265   len = strlen (name);
1266   copy = (char *) alloca (len + 1);
1267   for (i = 0; i < len; ++i)
1268     copy[i] = TOLOWER (name[i]);
1269   copy[i] = '\0';
1270 
1271   /* We can only ask hash_delete to free memory if we are deleting
1272      macros in reverse order to their definition.
1273      So just clear out the entry.  */
1274   if ((macro = (macro_entry *) hash_find (macro_hash, copy)) != NULL)
1275     {
1276       hash_jam (macro_hash, copy, NULL);
1277       free_macro (macro);
1278     }
1279   else
1280     as_warn (_("Attempt to purge non-existant macro `%s'"), copy);
1281 }
1282 
1283 /* Handle the MRI IRP and IRPC pseudo-ops.  These are handled as a
1284    combined macro definition and execution.  This returns NULL on
1285    success, or an error message otherwise.  */
1286 
1287 const char *
1288 expand_irp (int irpc, int idx, sb *in, sb *out, int (*get_line) (sb *))
1289 {
1290   sb sub;
1291   formal_entry f;
1292   struct hash_control *h;
1293   const char *err;
1294 
1295   idx = sb_skip_white (idx, in);
1296 
1297   sb_new (&sub);
1298   if (! buffer_and_nest (NULL, "ENDR", &sub, get_line))
1299     return _("unexpected end of file in irp or irpc");
1300 
1301   sb_new (&f.name);
1302   sb_new (&f.def);
1303   sb_new (&f.actual);
1304 
1305   idx = get_token (idx, in, &f.name);
1306   if (f.name.len == 0)
1307     return _("missing model parameter");
1308 
1309   h = hash_new ();
1310   err = hash_jam (h, sb_terminate (&f.name), &f);
1311   if (err != NULL)
1312     return err;
1313 
1314   f.index = 1;
1315   f.next = NULL;
1316   f.type = FORMAL_OPTIONAL;
1317 
1318   sb_reset (out);
1319 
1320   idx = sb_skip_comma (idx, in);
1321   if (idx >= in->len)
1322     {
1323       /* Expand once with a null string.  */
1324       err = macro_expand_body (&sub, out, &f, h, 0);
1325     }
1326   else
1327     {
1328       bfd_boolean in_quotes = FALSE;
1329 
1330       if (irpc && in->ptr[idx] == '"')
1331 	{
1332 	  in_quotes = TRUE;
1333 	  ++idx;
1334 	}
1335 
1336       while (idx < in->len)
1337 	{
1338 	  if (!irpc)
1339 	    idx = get_any_string (idx, in, &f.actual);
1340 	  else
1341 	    {
1342 	      if (in->ptr[idx] == '"')
1343 		{
1344 		  int nxt;
1345 
1346 		  if (irpc)
1347 		    in_quotes = ! in_quotes;
1348 
1349 		  nxt = sb_skip_white (idx + 1, in);
1350 		  if (nxt >= in->len)
1351 		    {
1352 		      idx = nxt;
1353 		      break;
1354 		    }
1355 		}
1356 	      sb_reset (&f.actual);
1357 	      sb_add_char (&f.actual, in->ptr[idx]);
1358 	      ++idx;
1359 	    }
1360 
1361 	  err = macro_expand_body (&sub, out, &f, h, 0);
1362 	  if (err != NULL)
1363 	    break;
1364 	  if (!irpc)
1365 	    idx = sb_skip_comma (idx, in);
1366 	  else if (! in_quotes)
1367 	    idx = sb_skip_white (idx, in);
1368 	}
1369     }
1370 
1371   hash_die (h);
1372   sb_kill (&f.actual);
1373   sb_kill (&f.def);
1374   sb_kill (&f.name);
1375   sb_kill (&sub);
1376 
1377   return err;
1378 }
1379