
#include "yodl.h"

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

  macname = gram_parlist (builtin[idx_DEFINEMACRO], 0);
  gram_onename (builtin[idx_DEFINEMACRO], macname);

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

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

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

  redef = gram_parlist (builtin[idx_DEFINEMACRO], 0);

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

  message (3, "%s %s: %s\n", builtin[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);
}
