Commit 47191ea9
47191ea99a5bMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified
Description
Merge pull request #1509 from ryanseys/rs-alias-under-modifier
Support alias under a statement modifier
Details
- Commit
- 47191ea99a5b
- Parent
- e47ca2a8ba3e
- Merge parent
- c96235979651
src/analyze_scope.cmodifiedView file
@@ -994,6 +994,20 @@
994994
}995995
}996996
997+
/* Classify a modifier/if predicate as a compile-time constant: 1 = always998+
truthy, 0 = always falsy, -1 = a runtime value. Only literal true / non-nil999+
literals and false / nil fold; anything else (a call, constant, variable) is1000+
runtime. */1001+
static int alias_pred_const(const NodeTable *nt, int pred) {1002+
const char *t = pred >= 0 ? nt_type(nt, pred) : NULL;1003+
if (!t) return -1;1004+
if (!strcmp(t, "FalseNode") || !strcmp(t, "NilNode")) return 0;1005+
if (!strcmp(t, "TrueNode") || !strcmp(t, "IntegerNode") || !strcmp(t, "FloatNode") ||1006+
!strcmp(t, "StringNode") || !strcmp(t, "SymbolNode"))1007+
return 1;1008+
return -1;1009+
}1010+
9971011
/* Collect `alias new old` (AliasMethodNode) and `alias_method :new, :old`9981012
(CallNode) statements in class bodies into the class alias table. */9991013
void register_aliases_body(Compiler *c, ClassInfo *cls, int body) {@@ -1021,6 +1035,21 @@
10211035
nt_type(nt, argv[1]) && !strcmp(nt_type(nt, argv[1]), "SymbolNode"))10221036
comp_add_alias(cls, nt_str(nt, argv[0], "value"), nt_str(nt, argv[1], "value"));10231037
}1038+
else if (!strcmp(sty, "IfNode") || !strcmp(sty, "UnlessNode")) {1039+
/* A statement modifier (`alias a b if cond`) wraps the alias in an IfNode.1040+
An alias resolves at compile time, so only register the branch the1041+
condition statically selects. A non-constant guard registers nothing:1042+
the alias cannot be created conditionally with static method tables, so1043+
the name is left unresolved and codegen rejects it loudly if reached. */1044+
int is_unless = !strcmp(sty, "UnlessNode");1045+
int pc = alias_pred_const(nt, nt_ref(nt, s, "predicate"));1046+
int then_runs = is_unless ? (pc == 0) : (pc == 1);1047+
int else_runs = is_unless ? (pc == 1) : (pc == 0);1048+
if (then_runs) register_aliases_body(c, cls, nt_ref(nt, s, "statements"));1049+
int els = nt_ref(nt, s, is_unless ? "else_clause" : "subsequent");1050+
if (else_runs && els >= 0 && nt_type(nt, els) && !strcmp(nt_type(nt, els), "ElseNode"))1051+
register_aliases_body(c, cls, nt_ref(nt, els, "statements"));1052+
}10241053
}10251054
}10261055
src/codegen_stmt.cmodifiedView file
Loading diff…
test/alias_under_modifier.rbaddedView file
Loading diff…
test/alias_under_modifier.rb.expectedaddedView file
Loading diff…