+ m = mx_parse(path, 1, b, b + sb.st_size);
+ rc = mx_expand(m, output, u);
+ if(rc && rc != -1)
+ /* Mention inclusion in backtrace */
+ error(0, " ...in inclusion of file '%s'", path);
+ return rc;
+}
+
+/** @brief Rewrite a parse tree substituting in macro arguments
+ * @param m Parse tree to rewrite (from macro definition)
+ * @param h Hash mapping argument names to argument values
+ * @return Rewritten parse tree
+ */
+static const struct mx_node *mx__rewrite(const struct mx_node *m,
+ hash *h) {
+ const struct mx_node *head = 0, **tailp = &head, *arg, *mm;
+ struct mx_node *nm;
+ int n;
+
+ for(; m; m = m->next) {
+ switch(m->type) {
+ case MX_TEXT:
+ nm = xmalloc(sizeof *nm);
+ *nm = *m; /* Dumb copy of text node fields */
+ nm->next = 0; /* Maintain list structure */
+ *tailp = nm;
+ tailp = (const struct mx_node **)&nm->next;
+ break;
+ case MX_EXPANSION:
+ if(m->nargs == 0
+ && (arg = hash_find(h, m->name))) {
+ /* This expansion has no arguments and its name matches one of the
+ * macro arguments. (Even if it's a valid expansion name we override
+ * it.) We insert its value at this point. We do NOT recursively
+ * rewrite the argument's value - it is outside the lexical scope of
+ * the argument name.
+ *
+ * We need to recreate the list structure but a shallow copy will
+ * suffice here.
+ */
+ for(mm = arg; mm; mm = mm->next) {
+ nm = xmalloc(sizeof *nm);
+ *nm = *mm;
+ nm->next = 0;
+ *tailp = nm;
+ tailp = (const struct mx_node **)&nm->next;
+ }
+ } else {
+ /* This is some other expansion. We recursively rewrite its argument
+ * values according to h. */
+ nm = xmalloc(sizeof *nm);
+ *nm = *mm;
+ for(n = 0; n < nm->nargs; ++n)
+ nm->args[n] = mx__rewrite(m->args[n], h);
+ nm->next = 0;
+ *tailp = nm;
+ tailp = (const struct mx_node **)&nm->next;
+ }
+ break;
+ default:
+ assert(!"invalid m->type");
+ }
+ }
+ *tailp = 0; /* Mark end of list */
+ return head;
+}
+
+/** @brief Expand a macro
+ * @param e Macro definition
+ * @param m Macro expansion
+ * @param output Where to send output
+ * @param u User data
+ * @return 0 on success, non-0 on error
+ */
+static int mx__expand_macro(const struct expansion *e,
+ const struct mx_node *m,
+ struct sink *output,
+ void *u) {
+ hash *h = hash_new(sizeof (struct mx_node *));
+ int n;
+
+ /* We store the macro arguments in a hash. Currently there is no check for
+ * duplicate argument names (and this would be the wrong place for it
+ * anyway); if you do that you just lose in some undefined way. */
+ for(n = 0; n < m->nargs; ++n)
+ hash_add(h, e->args[n], m->args[n], HASH_INSERT);
+ /* Generate a rewritten parse tree */
+ m = mx__rewrite(e->definition, h);
+ /* Expand the result */
+ return mx_expand(m, output, u);
+ /* mx_expand() will update the backtrace */