/* * macro.c - macro implementation * * Copyright (c) 2000-2024 Shiro Kawai * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the authors nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define LIBGAUCHE_BODY #include "gauche.h" #include "gauche/priv/configP.h" #include "gauche/code.h" #include "gauche/vminsn.h" #include "gauche/priv/macroP.h" #include "gauche/priv/identifierP.h" #include "gauche/priv/builtin-syms.h" /* avoid C++ reserved name conflict. (I hate languages that take away names from programmers!) */ #define template templat /* define if you want to debug syntax-rule expander */ /*#define DEBUG_SYNRULE*/ /*=================================================================== * Syntax object */ static void syntax_print(ScmObj obj, ScmPort *port, ScmWriteContext *mode SCM_UNUSED) { ScmSymbol *name = SCM_SYNTAX(obj)->name; ScmModule *mod = SCM_SYNTAX(obj)->mod; if (mod == NULL) { Scm_Printf(port, "#", (name ? SCM_OBJ(name) : SCM_FALSE)); } else { Scm_Printf(port, "#", mod->name, (name ? SCM_OBJ(name) : SCM_FALSE)); } } SCM_DEFINE_BUILTIN_CLASS_SIMPLE(Scm_SyntaxClass, syntax_print); ScmObj Scm_MakeSyntax(ScmSymbol *name, ScmModule *mod, ScmObj handler) { ScmSyntax *s = SCM_NEW(ScmSyntax); SCM_SET_CLASS(s, SCM_CLASS_SYNTAX); s->name = name; s->mod = mod; s->handler = handler; return SCM_OBJ(s); } /*=================================================================== * Macro object */ ScmObj Scm_MakeMacro(ScmObj name, ScmObj transformer, ScmObj info, u_long flags) { ScmMacro *s = SCM_NEW(ScmMacro); SCM_SET_CLASS(s, SCM_CLASS_MACRO); s->name = name; s->transformer = transformer; s->info_alist = info; s->flags = flags; return SCM_OBJ(s); } ScmObj Scm_MacroTransformer(ScmMacro *mac) { return mac->transformer; } ScmObj Scm_MacroName(ScmMacro *mac) { return (mac->name? SCM_OBJ(mac->name) : SCM_FALSE); } /* Called from syntax-parameterize. This API is internal and subject to change. */ void Scm__SwapMacroTransformer(ScmMacro *mac, ScmObj *pxformer, u_long *pflags) { if (!(mac->flags & SCM_MACRO_PARAMETERIZABLE)) { Scm_Error("Macro %S is not parameterizable.", SCM_OBJ(mac)); } ScmObj oxformer = mac->transformer; u_long oflags = mac->flags; mac->transformer = *pxformer; mac->flags = *pflags | SCM_MACRO_PARAMETERIZABLE; *pxformer = oxformer; *pflags = oflags & (~SCM_MACRO_PARAMETERIZABLE); } /*=================================================================== * SyntaxPattern object * Repesents a repeatable subpattern * (e.g. x ...), as well as the placeholder of the repeated match * in a template. */ typedef struct ScmSyntaxPatternRec { SCM_HEADER; ScmObj pattern; /* subpattern */ ScmObj vars; /* pattern variables in this subpattern */ short level; /* level of this subpattern */ short numFollowingItems; /* only used in pattern (not template). this specifies the # of items that follows the repetition, excluding the last CDR. E.g. From (x ... y z), `x ...' part becomes SyntaxPattern with numFollowingItems=2. From (x ... . y), `x ...' part becomes SyntaxPattern with numFollowingItems=0. */ } ScmSyntaxPattern; SCM_CLASS_DECL(Scm_SyntaxPatternClass); #define SCM_CLASS_SYNTAX_PATTERN (&Scm_SyntaxPatternClass) #define SCM_SYNTAX_PATTERN(obj) ((ScmSyntaxPattern*)(obj)) #define SCM_SYNTAX_PATTERN_P(obj) SCM_XTYPEP(obj, SCM_CLASS_SYNTAX_PATTERN) static void pattern_print(ScmObj obj, ScmPort *port, ScmWriteContext *ctx SCM_UNUSED) { Scm_Printf(port, "#", SCM_SYNTAX_PATTERN(obj)->level, SCM_SYNTAX_PATTERN(obj)->vars, SCM_SYNTAX_PATTERN(obj)->pattern, SCM_SYNTAX_PATTERN(obj)->numFollowingItems? " ..." : ""); } SCM_DEFINE_BUILTIN_CLASS_SIMPLE(Scm_SyntaxPatternClass, pattern_print); ScmSyntaxPattern *make_syntax_pattern(int level, int numFollowing) { ScmSyntaxPattern *p = SCM_NEW(ScmSyntaxPattern); SCM_SET_CLASS(p, SCM_CLASS_SYNTAX_PATTERN); p->pattern = SCM_NIL; p->vars = SCM_NIL; p->level = level; p->numFollowingItems = numFollowing; return p; } /*=================================================================== * SyntaxRules object * Internal object to construct pattern matcher */ static void synrule_print(ScmObj obj, ScmPort *port, ScmWriteContext *mode SCM_UNUSED) { ScmSyntaxRules *r = SCM_SYNTAX_RULES(obj); Scm_Printf(port, "#numRules); for (int i = 0; i < r->numRules; i++) { Scm_Printf(port, "%2d: (numPvars=%d, maxLevel=%d)\n", i, r->rules[i].numPvars, r->rules[i].maxLevel); Scm_Printf(port, " pattern = %S\n", r->rules[i].pattern); Scm_Printf(port, " template = %S\n", r->rules[i].template); } Scm_Printf(port, ">"); } SCM_DEFINE_BUILTIN_CLASS_SIMPLE(Scm_SyntaxRulesClass, synrule_print); ScmSyntaxRules *make_syntax_rules(int nr) { ScmSyntaxRules *r = SCM_NEW2(ScmSyntaxRules *, sizeof(ScmSyntaxRules)+(nr-1)*sizeof(ScmSyntaxRuleBranch)); SCM_SET_CLASS(r, SCM_CLASS_SYNTAX_RULES); r->numRules = nr; return r; } /*=================================================================== * Traditional Macro */ static ScmMacro *resolve_macro_autoload(ScmAutoload *adata) { ScmObj mac = Scm_ResolveAutoload(adata, 0); if (SCM_UNBOUNDP(mac)) { Scm_Error("tried to autoload macro %S, but it caused circular autoload.", adata->name); } if (!SCM_MACROP(mac)) { Scm_Error("tried to autoload macro %S, but it yields non-macro object: %S", adata->name, mac); } return SCM_MACRO(mac); } static ScmObj macro_autoload(ScmObj *argv, int argc, void *data) { SCM_ASSERT(argc == 2); ScmObj form = argv[0]; ScmObj env = argv[1]; /* Important to save form and env before calling resolve_macro_autoload, for it may overwrite stack region pointed by argv. */ SCM_ASSERT(SCM_AUTOLOADP(data)); ScmMacro *mac = resolve_macro_autoload(SCM_AUTOLOAD(data)); return Scm_CallMacroExpander(mac, form, env); } #define AUTOLOAD_MACRO_SUFFIX " (autoload)" ScmObj Scm_MakeMacroAutoload(ScmSymbol *name, ScmAutoload *adata) { ScmObj transformer = Scm_MakeSubr(macro_autoload, adata, 2, 0, SCM_FALSE); ScmObj name1 = Scm_StringAppendC(SCM_SYMBOL_NAME(name), AUTOLOAD_MACRO_SUFFIX, sizeof(AUTOLOAD_MACRO_SUFFIX)-1, sizeof(AUTOLOAD_MACRO_SUFFIX)-1); return Scm_MakeMacro(Scm_MakeSymbol(SCM_STRING(name1), FALSE), transformer, SCM_NIL, 0); } /*=================================================================== * R5RS Macro */ /* Keeping hygienic reference * * - symbols which a template inserts into the expanded form are * converted to identifiers at the macro definition time, encapsulating * the defining environment of the macro. So it doesn't interfere * with the macro call environment. * * - literal symbols provided to the syntax-rules are also converted * to identifiers encapsulating the defining environment, and the * environment information is used when comparing with the symbols * in the macro call. * * - symbols in the macro call is treated as they are. Since the result * of macro expansion is immediately compiled in the macro call * environment, those symbols can refer proper bindings. */ /*------------------------------------------------------------------- * pattern language compiler * - recognize repeatable subpatterns and replace it to SyntaxPattern node. * - convert free symbols in the template into identifiers * - convert pattern variables into LREF object. */ /* TODO: avoid unnecessary consing as much as possible */ /* context of pattern traversal */ typedef struct { ScmObj name; /* name of this macro (for error msg)*/ ScmObj form; /* form being compiled (for error msg) */ ScmObj literals; /* list of literals */ ScmObj pvars; /* list of (pvar . pvref) */ ScmObj renames; /* list of (var . identifier) Keep mapping of input symbol/identifier to fresh identifier */ ScmObj ellipsis; /* symbol/identifier/keyword for ellipsis SCM_TRUE means default (...) SCM_FALSE means disabled */ int pvcnt; /* counter of pattern variables */ int maxlev; /* maximum level */ ScmModule *mod; /* module where this macro is defined */ ScmObj env; /* compiler env of this macro definition */ } PatternContext; #define PVREF_P(pvref) SCM_PVREF_P(pvref) #define PVREF_LEVEL(pvref) (int)SCM_PVREF_LEVEL(pvref) #define PVREF_COUNT(pvref) (int)SCM_PVREF_COUNT(pvref) #define PVREF_LEVEL_MAX 0xff #define PVREF_COUNT_MAX 0xff /* add pattern variable pvar. called when compiling a pattern */ static inline ScmObj add_pvar(PatternContext *ctx, ScmSyntaxPattern *pat, ScmObj pvar) { if (pat->level > PVREF_LEVEL_MAX) { Scm_Error("Pattern levels too deeply nested in the macro definition of %S", ctx->name); } if (ctx->pvcnt > PVREF_COUNT_MAX) { Scm_Error("Too many pattern variables in the macro definition of %S", ctx->name); } ScmObj pvref = SCM_MAKE_PVREF(pat->level, ctx->pvcnt); if (!SCM_FALSEP(Scm_Assq(pvar, ctx->pvars))) { Scm_Error("Pattern variable %S appears more than once in the macro definition of %S: %S", pvar, ctx->name, ctx->form); } ctx->pvcnt++; ctx->pvars = Scm_Acons(pvar, pvref, ctx->pvars); pat->vars = Scm_Cons(pvref, pat->vars); return pvref; } /* Like SCM_APPEND1 and SCM_APPEND, but try to preserve source info of the input. SOURCE is the macro source in its definition, ORIGIN is the macro expansion input in its entirety. ORIGIN is #f while compiling a macro; only given when expanding it. */ static ScmObj get_source_info_attrs(ScmObj source, ScmObj origin) { ScmObj attrs = SCM_NIL; if (SCM_PAIRP(source)) { ScmObj info = Scm_PairAttrGet(SCM_PAIR(source), SCM_SYM_SOURCE_INFO, SCM_FALSE); if (SCM_PAIRP(info)) attrs = Scm_Acons(SCM_SYM_SOURCE_INFO, info, attrs); } if (SCM_PAIRP(origin)) { attrs = Scm_Acons(SCM_SYM_ORIGINAL, origin, attrs); } return attrs; } static void template_append1(ScmObj *head, ScmObj *tail, ScmObj elt, ScmObj source, ScmObj origin) { if (SCM_NULLP(*head)) { ScmObj attrs = get_source_info_attrs(source, origin); if (SCM_PAIRP(attrs)) { ScmObj p = Scm_MakeExtendedPair(elt, SCM_NIL, attrs); *head = *tail = p; return; } *head = *tail = Scm_Cons(elt, SCM_NIL); return; } ScmObj p = Scm_Cons(elt, SCM_NIL); SCM_SET_CDR(*tail, p); *tail = p; } static void template_append(ScmObj *head, ScmObj *tail, ScmObj rest, ScmObj source, ScmObj origin) { if (SCM_NULLP(*head)) { if (SCM_PAIRP(rest)) { ScmObj attrs = get_source_info_attrs(source, origin); if (SCM_PAIRP(attrs)) { ScmObj p = Scm_MakeExtendedPair(SCM_CAR(rest), SCM_CDR(rest), attrs); *head = p; *tail = Scm_LastPair(p); return; } } *head = rest; *tail = SCM_PAIRP(rest)? Scm_LastPair(rest) : rest; return; } SCM_SET_CDR(*tail, rest); /* rest can be () */ if (SCM_PAIRP(rest)) *tail = Scm_LastPair(rest); } /* returns pvref corresponds to the given pvar in template compilation. if pvar is not a valid pvar, returns pvar itself. */ static inline ScmObj pvar_to_pvref(PatternContext *ctx, ScmSyntaxPattern *pat, ScmObj pvar) { ScmObj q = Scm_Assq(pvar, ctx->pvars); if (!SCM_PAIRP(q)) return pvar; ScmObj pvref = SCM_CDR(q); if (PVREF_LEVEL(pvref) > pat->level) { Scm_Error("%S: Pattern variable %S is used in wrong level: %S", ctx->name, pvar, ctx->form); } return pvref; } static int isEllipsis(PatternContext *ctx, ScmObj obj) { if (SCM_FALSEP(ctx->ellipsis)) return FALSE; /* inside (... TEMPLATE) */ if (SCM_TRUEP(ctx->ellipsis)) { /* default ellipsis (...) */ return Scm__ERCompare(SCM_SYM_ELLIPSIS, obj, ctx->mod, ctx->env); } else { /* specified ellipsis */ return SCM_EQ(ctx->ellipsis, obj); } } #define ELLIPSIS_FOLLOWING(Pat, Ctx) \ (SCM_PAIRP(SCM_CDR(Pat)) && isEllipsis(Ctx, SCM_CADR(Pat))) #define BAD_ELLIPSIS(Ctx) \ Scm_Error("Bad ellipsis usage in macro definition of %S: %S", \ Ctx->name, Ctx->form) static ScmObj check_literals(ScmObj literals) { ScmObj lp, h = SCM_NIL, t = SCM_NIL; SCM_FOR_EACH(lp, literals) { ScmObj lit = SCM_CAR(lp); if (SCM_SYMBOLP(lit) || SCM_IDENTIFIERP(lit)) SCM_APPEND1(h, t, lit); else if (SCM_KEYWORDP(lit)) /* This branch is to allow r7rs-compliant code to go through with legacy mode. If keyword-symbol integration is turned on, we never reach here. */; else Scm_Error("literal list contains non-symbol: %S", literals); } if (!SCM_NULLP(lp)) Scm_Error("bad literal list in syntax-rules: %S", literals); return h; } /* Renaming: Map input variable (symbol or identifier) to fresh identifier. The same (eq?) variable must map to the same identifier. */ static ScmObj rename_variable(ScmObj var, ScmObj *id_alist, /* ((var . id) ...) */ ScmModule *mod, ScmObj env) { ScmObj id, p = Scm_Assq(var, *id_alist); if (SCM_PAIRP(p)) return SCM_CDR(p); if (SCM_SYMBOLP(var)) { id = Scm_MakeIdentifier(var, mod, env); } else { SCM_ASSERT(SCM_IDENTIFIERP(var)); id = Scm_WrapIdentifier(SCM_IDENTIFIER(var)); } *id_alist = Scm_Acons(var, id, *id_alist); return id; } /* Compile a pattern or a template. In the pattern, we replace variables to identifiers. We also recognize pattern variables, and replace them for PVARs in the pattern, and for PVREFs in the template. When encounters a repeatable subpattern, replace it with SyntaxPattern node. */ static ScmObj compile_rule1(ScmObj form, ScmSyntaxPattern *spat, PatternContext *ctx, int patternp) { if (SCM_PAIRP(form)) { ScmObj h = SCM_NIL, t = SCM_NIL; int ellipsis_seen = FALSE; if (SCM_PAIRP(SCM_CDR(form)) && isEllipsis(ctx, SCM_CAR(form))) { /* (...