
#include "yodl.h"

void
gram_DEFINEMACRO ()
{
  char
   *macname, *nargstring, *redef;
  int
    nargs;

  macname = gram_parlist (builtin_get (idx_DEFINEMACRO), 0);
  gram_onename (builtin_get (idx_DEFINEMACRO), macname);

  while (lextok == tok_space ||	/* skip whitespace */
	 lextok == tok_newline
    )
    lexer ();

  nargstring = gram_parlist (builtin_get (idx_DEFINEMACRO), 0);
  nargs = gram_onenumber (builtin_get (idx_DEFINEMACRO), nargstring);
  if (nargs < 0 || nargs > 9 + 26 + 26)
    error_gram (builtin_get (idx_DEFINEMACRO),
		"0 to 61 arguments supported, not %d", nargs);

  while (lextok == tok_space ||	/* skip whitespace */
	 lextok == tok_newline
    )
    lexer ();

  redef = gram_parlist (builtin_get (idx_DEFINEMACRO), 0);

  if (strtab_find (userdef, nuserdef, macname) != -1)
    error_gram (builtin_get (idx_DEFINEMACRO), "macro %s is already defined",
		macname);

  message (3, "%s %s: %s\n", builtin_get (idx_DEFINEMACRO), macname,
	   str_short (redef));

  userdef = strtab_add (userdef, &nuserdef, macname);

  definition = (char **) xrealloc (definition, nuserdef * sizeof (char *));
  definition[nuserdef - 1] = xstrdup (redef);

  narg = (int *) xrealloc (narg, (nuserdef * sizeof (int)));
  narg[nuserdef - 1] = nargs;

  free (macname);
  free (nargstring);
  free (redef);
}
