
#include "yodl.h"

int
gram_try_expand ()
{
  int
    i, slot;
  char
   *macro, *list, argstring[80];
  static char
    argchar[] = "123456789"
  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  "abcdefghijklmnopqrstuvwxyz";

  if ((slot = strtab_find (userdef, nuserdef, lexbuf)) == -1)
    {
      if (strtab_find (nousermacro, nnousermacro, lexbuf) == -1)
	gram_warn ("macro expansion",
		   "cannot expand possible user-macro %s", lexbuf);
      return (0);
    }

  macro = xstrdup (definition[slot]);

  message (3, "%s %s\n", lexbuf, str_short (macro));

  lexer ();

  if (!narg[slot])		/* no args expected */
    {				/* eat empty parameter list */
      list = gram_parlist (userdef[slot], 0);
      if (list && *list)
	gram_warn ("macro parameter list retrieval",
		   "%s() should have zero arguments, "
		   "but non-empty parlist found", userdef[slot]);
      free (list);
    }
  /* for >= 1 arguments: */
  for (i = 0; i < narg[slot]; i++)	/* handle all arguments */
    {
      list = gram_parlist (userdef[slot], 0);
      sprintf (argstring, "ARG%c", argchar[i]);
      macro = str_replace (macro, argstring, list);
      free (list);

      if (i < narg[slot] - 1)
	while (lextok == tok_space ||	/* skip spaces, newlines */
	       lextok == tok_newline	/* between parlists */
	  )
	  lexer ();
    }

  macro = gram_do_expand (macro);
  lexer_pushstr (lexbuf);	/* push back beyond parlist */
  lexer_pushstr (macro);	/* push expansion */
  lexer ();			/* prepare next symbol */

  free (macro);

  return (1);
}
