Commit d8316313

d83163135c73Merged

Ori Pekelman <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified

Description

fix(codegen): ENV.fetch(key, default)

Pre-fix ENV.fetch(k, dflt) emitted "cannot resolve call to 'fetch' on int" and segfaulted at runtime. ENV[k] was wired but the fetch arm never landed.

Adds the type-inference and codegen arms for the two-arg form:

ENV.fetch(key, default) -> ({ const char *_t = getenv(key); _t ? sp_str_dup_external(_t) : (default); })

Single-arg ENV.fetch("X") falls through to the same path as ENV["X"] -- spinel doesn't model KeyError, so the strict CRuby behaviour isn't reproduced; callers wanting that should pass an explicit default. Block form (ENV.fetch("X") { ... }) is not handled.

Regression test: test/env_fetch.rb covers literal, computed, and concatenation defaults.

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
d83163135c73
Parent
ae1a0f329f3d

spinel_codegen.rbmodifiedView file

@@ -4802,6 +4802,9 @@
48024802 if mname == "[]"
48034803 return "string"
48044804 end
4805+ if mname == "fetch"
4806+ return "string"
4807+ end
48054808 end
48064809 if rcname == "Dir"
48074810 if mname == "home"
@@ -27916,6 +27919,29 @@
2791627919 if mname == "[]"
2791727920 return "sp_str_dup_external(getenv(" + compile_arg0(nid) + "))"
2791827921 end
27922+ if mname == "fetch"
27923+ # Two-arg form: ENV.fetch(key, default). If the env var is
27924+ # set, return its value; otherwise return the supplied
27925+ # default. The single-arg form (`ENV.fetch("X")`) raises
27926+ # KeyError in CRuby; spinel doesn't model that, so it
27927+ # behaves like ENV[] -- callers wanting strict behaviour
27928+ # should pass an explicit default.
27929+ args_id = @nd_arguments[nid]
27930+ if args_id >= 0
27931+ argz = get_args(args_id)
27932+ if argz.length >= 2
27933+ key = compile_expr(argz[0])
27934+ dfl = compile_expr_as_string(argz[1])
27935+ tmp = new_temp
27936+ return "({ const char *" + tmp + " = getenv(" + key + "); " +
27937+ tmp + " ? sp_str_dup_external(" + tmp + ") : (" + dfl + "); })"
27938+ end
27939+ if argz.length == 1
27940+ return "sp_str_dup_external(getenv(" + compile_arg0(nid) + "))"
27941+ end
27942+ end
27943+ return "(&(\"\\xff\")[1])"
27944+ end
2791927945 end
2792027946 # Dir
2792127947 if rcname == "Dir"