9e8180f90197 — Leonard Ritter 6 days ago
* more porting work
* dag_scheduler prototype, vertex wiggle ranges, harp diagrams
M include/scopes/scopes.h +1 -0
@@ 360,6 360,7 @@ SCOPES_LIBEXPORT void sc_exit(int c);
 
 SCOPES_LIBEXPORT sc_value_raises_t sc_map_get(sc_value_t key);
 SCOPES_LIBEXPORT void sc_map_set(sc_value_t key, sc_value_t value);
+SCOPES_LIBEXPORT void sc_map_del(sc_value_t key);
 
 // C bridge
 

          
M lib/scopes/compiler/retcon/Value.sx +10 -3
@@ 512,7 512,7 @@ abstract type Value
         type RTLoadLibraryFailedError
             msg = "runtime: error loading library {name}: {reason}"
             name : String
-            reason : String
+            reason : builtin_string
         type RTGetAddressFailedError
             msg = "runtime: could not find symbol '{name}' in C namespace"
             name : Symbol

          
@@ 702,7 702,14 @@ abstract type Value
         end : usize # points at the first invalid index of list in data
     typedef List : ? ListSlice
     typedef Lists : Array List
-    abstract type ScopeTrie
+
+    type ScopeCell
+        key : Const
+        value : Value
+        doc : ? String
+        next : Scope
+
+    #abstract type ScopeTrie
         enum ScopeKind
         type ScopeL
             by : Anchor

          
@@ 711,7 718,7 @@ abstract type Value
             doc : ? String
         type ScopeB # HAMT
             slots : array Scope 16
-    typedef Scope : ? ScopeTrie
+    typedef Scope : ? ScopeCell
     type Closure
         func : Template
         frame : Function

          
M lib/scopes/compiler/retcon/gensyms.sc +1 -0
@@ 583,6 583,7 @@ inline SCOPES_STYLE_SYMBOLS(T)
     T 'Style_Symbol "style-symbol"
     T 'Style_String "style-string"
     T 'Style_Number "style-number"
+    T 'Style_Constant "style-constant"
     T 'Style_Keyword "style-keyword"
     T 'Style_Function "style-function"
     T 'Style_SfxFunction "style-sfxfunction"

          
M src/boot.cpp +1 -1
@@ 268,7 268,7 @@ void init(void *c_main, int argc, char *
     }
 
     init_types();
-    init_globals(argc, argv);
+    complete_globals(argc, argv);
 }
 
 SCOPES_RESULT(int) try_main() {

          
M src/convert_result.inc +76 -19
@@ 11,37 11,94 @@ 
 
 namespace scopes {
 
-#define CRESULT { return {_result.ok(), (_result.ok()?nullptr:_result.unsafe_error()), _result.unsafe_extract()}; }
-#define VOID_CRESULT { return {_result.ok(), (_result.ok()?nullptr:_result.unsafe_error())}; }
+#define CNULLERROR (std::bit_cast<Error>(size_t(0)))
+
+template<typename T>
+struct CResultConverter {};
+
+template<typename T>
+struct CResultConverter< Result<T> > {
+    bool ok;
+    Maybe<Error> err;
+    Maybe<T> value;
+
+    template<typename Q>
+    operator Q() const {
+        return { ok, std::bit_cast<Error>(err), std::bit_cast<T>(value) };
+    }
+
+    CResultConverter(auto &&result) {
+        if (result.ok()) {
+            ok = true;
+            value = result.unsafe_extract();
+        } else {
+            ok = false;
+            err = result.unsafe_error();
+        }
+    }
+};
+
+template<typename T>
+struct CResultConverter< Result< Maybe<T> > > {
+    bool ok;
+    Maybe<Error> err;
+    Maybe<T> value;
+
+    template<typename Q>
+    operator Q() const {
+        return { ok, std::bit_cast<Error>(err), std::bit_cast<T>(value) };
+    }
+
+    CResultConverter(auto &&result) {
+        if (result.ok()) {
+            ok = true;
+            value = result.unsafe_extract();
+        } else {
+            ok = false;
+            err = result.unsafe_error();
+        }
+    }
+};
+
+template<typename T>
+inline auto c_result_converter(const T &result) {
+    CResultConverter<T> ret(result);
+    return ret;
+}
+
+#define VALUE_CRESULT { return c_result_converter(_result); }
+#define CRESULT { return {_result.ok(), (_result.ok()?CNULLERROR:_result.unsafe_error()), _result.unsafe_extract()}; }
+
+#define VOID_CRESULT { return {_result.ok(), (_result.ok()?CNULLERROR:_result.unsafe_error())}; }
 
 static sc_void_raises_t convert_result(const Result<void> &_result) VOID_CRESULT;
 
-static sc_valueref_list_scope_raises_t convert_result(const Result<sc_valueref_list_scope_tuple_t> &_result) CRESULT;
+static sc_value_list_scope_raises_t convert_result(const Result<sc_value_list_scope_tuple_t> &_result) CRESULT;
 static sc_bool_i32_i32_raises_t convert_result(const Result<sc_bool_i32_i32_tuple_t> &_result) CRESULT;
 
-static sc_valueref_raises_t convert_result(const Result<PureRef> &_result) CRESULT;
-static sc_valueref_raises_t convert_result(const Result<ValueRef> &_result) CRESULT;
-static sc_valueref_raises_t convert_result(const Result<TypedValueRef> &_result) CRESULT;
-static sc_valueref_raises_t convert_result(const Result<FunctionRef> &_result) CRESULT;
-static sc_valueref_raises_t convert_result(const Result<TemplateRef> &_result) CRESULT;
-static sc_valueref_raises_t convert_result(const Result<ConstPointerRef> &_result) CRESULT;
-static sc_valueref_raises_t convert_result(const Result<ConstRef> &_result) CRESULT;
-static sc_valueref_raises_t convert_result(const Result<ConstAggregateRef> &_result) CRESULT;
 
-static sc_type_raises_t convert_result(const Result<const Type *> &_result) CRESULT;
-static sc_string_raises_t convert_result(const Result<const String *> &_result) CRESULT;
+static sc_value_raises_t convert_result(const Result<Pure> &_result) VALUE_CRESULT;
+static sc_value_raises_t convert_result(const Result<Value> &_result) VALUE_CRESULT;
+static sc_value_raises_t convert_result(const Result<TypedValue> &_result) VALUE_CRESULT;
+static sc_value_raises_t convert_result(const Result<Function> &_result) VALUE_CRESULT;
+static sc_value_raises_t convert_result(const Result<Template> &_result) VALUE_CRESULT;
+static sc_value_raises_t convert_result(const Result<ConstPointer> &_result) VALUE_CRESULT;
+static sc_value_raises_t convert_result(const Result<Const> &_result) VALUE_CRESULT;
+static sc_value_raises_t convert_result(const Result<ConstAggregate> &_result) VALUE_CRESULT;
 
-static sc_scope_raises_t convert_result(const Result<const Scope *> &_result) CRESULT;
+static sc_type_raises_t convert_result(const Result<Type> &_result) VALUE_CRESULT;
+static sc_string_raises_t convert_result(const Result<String> &_result) VALUE_CRESULT;
+
+static sc_scope_raises_t convert_result(const Result<Scope> &_result) VALUE_CRESULT;
+
+static sc_symbol_raises_t convert_result(const Result<Symbol> &_result) VALUE_CRESULT;
 
 static sc_bool_raises_t convert_result(const Result<bool> &_result) CRESULT;
 static sc_int_raises_t convert_result(const Result<int> &_result) CRESULT;
 static sc_uint_raises_t convert_result(const Result<uint32_t> &_result) CRESULT;
 static sc_size_raises_t convert_result(const Result<size_t> &_result) CRESULT;
 
-static sc_symbol_raises_t convert_result(const Result<Symbol> &_result) {
-    return {_result.ok(),
-        (_result.ok()?nullptr:_result.unsafe_error()),
-        _result.unsafe_extract().value()}; }
+static sc_value_raises_t convert_maybe_result(const Result< Maybe<Value> > &_result) VALUE_CRESULT;
 
 #undef CRESULT
 #undef VOID_CRESULT

          
@@ 50,7 107,7 @@ static sc_symbol_raises_t convert_result
     return convert_result(Result<_result_type>((EXPR)));
 
 #define SCOPES_C_ERROR(CLASS, ...) \
-    return convert_result(Result<_result_type>::raise(Error ## CLASS::from(__VA_ARGS__)));
+    return convert_result(Result<_result_type>::raise(CLASS ## Error::from({ .by = builtin_anchor(), __VA_ARGS__})));
 
 #define SCOPES_C_RETURN_ERROR(ERR) return convert_result(Result<_result_type>::raise(ERR));
 // if ok fails, return

          
M src/expander.cpp +1 -1
@@ 1374,7 1374,7 @@ SCOPES_RESULT(sc_value_list_scope_tuple_
     return result;
 }
 
-SCOPES_RESULT(Template) expand_inline(Template astscope, List expr, Scope scope) {
+SCOPES_RESULT(Template) expand_inline(Maybe<Template> astscope, List expr, Scope scope) {
     SCOPES_RESULT_TYPE(Template);
     Timer sum_expand_time(TIMER_Expand);
     //const Anchor *anchor = expr->anchor();

          
M src/expander.hpp +1 -1
@@ 16,7 16,7 @@ namespace scopes {
 SCOPES_RESULT(sc_value_list_scope_tuple_t) expand(Value expr, List next, Scope scope = Scope());
 SCOPES_RESULT(Template) expand_module(List expr, Scope scope = Scope());
 SCOPES_RESULT(Template) expand_module_stage(List expr, Scope scope = Scope());
-SCOPES_RESULT(Template) expand_inline(Template astscope, List expr, Scope scope = Scope());
+SCOPES_RESULT(Template) expand_inline(Maybe<Template> astscope, List expr, Scope scope = Scope());
 
 } // namespace scopes
 

          
M src/gen_llvm.cpp +0 -4
@@ 3396,10 3396,6 @@ static std::string LLVMConvertMessageStr
     }
 }
 
-static std::string LLVMGetErrorMessageString(LLVMErrorRef err) {
-    return LLVMConvertMessageString(LLVMGetErrorMessage(err));
-}
-
 SCOPES_RESULT(void) compile_object(String triple,
     CompilerFileKind kind, String path, Scope scope, uint64_t flags) {
     SCOPES_RESULT_TYPE(void);

          
M src/gencc.inc +4 -0
@@ 258,6 258,10 @@ struct Maybe {
         return &(*std::bit_cast<ValueType>(_value));
     }
 
+    inline size_t id() const {
+        return _value.id();
+    }
+
     inline bool operator ==(const ValueType &other) const {
         return _value == other;
     }

          
M src/globals.cpp +584 -595
@@ 31,7 31,8 @@ 
 #include "boot.hpp"
 #include "execution.hpp"
 #include "cache.hpp"
-#include "symbol_enum.inc"
+#include "symbol.hpp"
+#include "print.hpp"
 #include "bag.hpp"
 
 #include "scopes/scopes.h"

          
@@ 55,7 56,6 @@ 
 
 #include "llvm-c/Support.h"
 
-#include "dyn_cast.inc"
 #include "verify_tools.inc"
 
 #include "convert_result.inc"

          
@@ 66,55 66,49 @@ namespace scopes {
 
 //------------------------------------------------------------------------------
 
+Scope init_globals();
+
+static Scope globals;
+static Scope original_globals = init_globals();
+
+static TypedValue reimport_symbol(std::string_view sym) {
+    auto globs = sc_get_original_globals();
+    auto _tmp = sc_scope_at(globs, symbol(sym));
+    assert(_tmp.ok);
+    return cast<TypedValue>(_tmp._0);
+}
+
 #define T(NAME, STR) \
-    TypedValueRef NAME;
+    TypedValue NAME = reimport_symbol(STR);
 SCOPES_REIMPORT_SYMBOLS()
 #undef T
 
-static void import_symbols() {
-    auto globs = sc_get_original_globals();
-#define T(NAME, STR) \
-    {   auto _tmp = sc_scope_at(globs, ConstInt::symbol_from(STR))._0; \
-        assert(_tmp && STR); \
-        NAME = _tmp.cast<TypedValue>(); }
-SCOPES_REIMPORT_SYMBOLS()
-#undef T
-}
-
 //------------------------------------------------------------------------------
 
-static void init_values_array(scopes::Values &dest, int numvalues, const sc_valueref_t *values) {
+static void init_values_array(scopes::Values &dest, int numvalues, const sc_value_t *values) {
     dest.reserve(numvalues);
     for (int i = 0; i < numvalues; ++i) {
-        assert(values[i]);
-        //assert(values[i] > (Value *)0x1000);
         dest.push_back(values[i]);
     }
 }
 
 template<typename T>
-static void init_values_arrayT(std::vector< T * > &dest, int numvalues, const sc_valueref_t *values) {
+static void init_values_arrayT(std::vector<T> &dest, int numvalues, const sc_value_t *values) {
     dest.reserve(numvalues);
     for (int i = 0; i < numvalues; ++i) {
-        assert(values[i]);
-        dest.push_back(values[i].cast<T>().unref());
+        dest.push_back(cast<T>(values[i]));
     }
 }
 
 //------------------------------------------------------------------------------
 
-static const Scope *globals = nullptr;
-static const Scope *original_globals = Scope::from(nullptr, nullptr);
-
-//------------------------------------------------------------------------------
-
 } // namespace scopes
 
 extern "C" {
 
-sc_valueref_raises_t sc_load_from_executable(const char *path) {
-    using namespace scopes;
-    return convert_result(load_custom_core(path));
+sc_value_raises_t sc_load_from_executable(const char *path) {
+    using namespace scopes;
+    return convert_maybe_result(load_custom_core(path));
 }
 
 void sc_init(void *c_main, int argc, char *argv[]) {

          
@@ 168,7 162,7 @@ sc_capture_variable_func_t sc_get_captur
     return get_capture_variable_handler();
 }
 
-uint64_t sc_get_address(sc_valueref_t value) {
+uint64_t sc_get_address(sc_value_t value) {
     using namespace scopes;
     return resolve_global_symbol(value);
 }

          
@@ 178,67 172,67 @@ void sc_set_compile_handler(sc_compile_f
     foreign_compile_hook = func;
 }
 
-sc_valueref_list_scope_raises_t sc_expand(sc_valueref_t expr, const sc_list_t *next, const sc_scope_t *scope) {
+sc_value_list_scope_raises_t sc_expand(sc_value_t expr, sc_list_t next, sc_scope_t scope) {
     using namespace scopes;
     return convert_result(expand(expr, next, scope));
 }
 
-sc_valueref_raises_t sc_eval(const sc_list_t *expr, const sc_scope_t *scope) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(TypedValueRef);
+sc_value_raises_t sc_eval(sc_list_t expr, sc_scope_t scope) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(TypedValue);
     auto module_result = SCOPES_C_GET_RESULT(expand_module(expr, scope));
-    return convert_result(prove(FunctionRef(), module_result, {}));
-}
-
-sc_valueref_raises_t sc_eval_stage(const sc_list_t *expr, const sc_scope_t *scope) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(TypedValueRef);
+    return convert_result(prove({}, module_result, {}));
+}
+
+sc_value_raises_t sc_eval_stage(sc_list_t expr, sc_scope_t scope) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(TypedValue);
     auto module_result = SCOPES_C_GET_RESULT(expand_module_stage(expr, scope));
-    return convert_result(prove(FunctionRef(), module_result, {}));
-}
-
-sc_valueref_raises_t sc_prove(sc_valueref_t expr) {
+    return convert_result(prove({}, module_result, {}));
+}
+
+sc_value_raises_t sc_prove(sc_value_t expr) {
     using namespace scopes;
     //SCOPES_RESULT_TYPE(TypedValue *);
     return convert_result(prove(expr));
 }
 
-sc_valueref_raises_t sc_resolve(sc_valueref_t expr) {
+sc_value_raises_t sc_resolve(sc_value_t expr) {
     using namespace scopes;
     //SCOPES_RESULT_TYPE(TypedValue *);
     return convert_result(resolve(expr));
 }
 
-void sc_bind(sc_valueref_t expr, sc_valueref_t result) {
-    using namespace scopes;
-    bind(expr, result.cast<TypedValue>());
-}
-
-sc_valueref_raises_t sc_eval_inline(const sc_list_t *expr, const sc_scope_t *scope) {
+void sc_bind(sc_value_t expr, sc_value_t result) {
+    using namespace scopes;
+    bind(expr, cast<TypedValue>(result));
+}
+
+sc_value_raises_t sc_eval_inline(sc_list_t expr, sc_scope_t scope) {
     using namespace scopes;
     //const Anchor *anchor = expr->anchor();
     //auto list = SCOPES_GET_RESULT(extract_list_constant(expr));
-    return convert_result(expand_inline(TemplateRef(), expr, scope));
-}
-
-sc_valueref_raises_t sc_typify_template(sc_valueref_t f, int numtypes, const sc_type_t **typeargs) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(ValueRef);
+    return convert_result(expand_inline({}, expr, scope));
+}
+
+sc_value_raises_t sc_typify_template(sc_value_t f, int numtypes, const sc_type_t *typeargs) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(Value);
     auto tf = SCOPES_C_GET_RESULT(extract_template_constant(f));
-    if (tf->is_inline()) {
+    if (is_inline(tf)) {
         SCOPES_C_ERROR(CannotTypeInline);
     }
     Types types;
     for (int i = 0; i < numtypes; ++i) {
         types.push_back(typeargs[i]);
     }
-    return convert_result(prove(FunctionRef(), tf, types));
-}
-
-sc_valueref_raises_t sc_typify(const sc_closure_t *srcl, int numtypes, const sc_type_t **typeargs) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(ValueRef);
-    if (srcl->func->is_inline()) {
+    return convert_result(prove({}, tf, types));
+}
+
+sc_value_raises_t sc_typify(sc_closure_t srcl, int numtypes, const sc_type_t *typeargs) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(Value);
+    if (is_inline(srcl->func)) {
         SCOPES_C_ERROR(CannotTypeInline);
     }
     Types types;

          
@@ 254,20 248,20 @@ sc_valueref_raises_t sc_typify(const sc_
     return convert_result(prove(srcl->frame, srcl->func, types));
 }
 
-sc_valueref_raises_t sc_compile(sc_valueref_t srcl, uint64_t flags) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(ConstPointerRef);
+sc_value_raises_t sc_compile(sc_value_t srcl, uint64_t flags) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(ConstPointer);
     auto result = SCOPES_C_GET_RESULT(extract_function_constant(srcl));
     return convert_result(compile(result, flags));
 }
 
-const sc_string_t *sc_default_target_triple() {
-    using namespace scopes;
-    return get_default_target_triple();
-}
-
-sc_void_raises_t sc_compile_object(const sc_string_t *target_triple,
-    int file_kind, const sc_string_t *path, const sc_scope_t *table, uint64_t flags) {
+sc_string_t sc_default_target_triple() {
+    using namespace scopes;
+    return string_from_stdstring(get_default_target_triple());
+}
+
+sc_void_raises_t sc_compile_object(sc_string_t target_triple,
+    int file_kind, sc_string_t path, sc_scope_t table, uint64_t flags) {
     using namespace scopes;
     return convert_result(compile_object(target_triple, (CompilerFileKind)file_kind, path, table, flags));
 }

          
@@ 280,26 274,29 @@ void sc_enter_solver_cli () {
 // stdin/out
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_string_t *sc_default_styler(sc_symbol_t _style, const sc_string_t *str) {
-    using namespace scopes;
-    StyledString ss;
-    auto style = Symbol::wrap(_style);
-    if (!style.is_known()) {
-        ss.out << str->data;
-    } else {
-        ss.out << Style(style.known_value()) << str->data << Style_None;
+sc_string_t sc_default_styler(sc_symbol_t _style, sc_string_t str) {
+    using namespace scopes;
+    StyledStringPrinter sp;
+    Style style = Style::None;
+    switch(symbol_hash(_style)) {
+#define T(NAME) case KnownSymbol::Style_ ## NAME: style = Style::NAME; break;
+SC_PRINT_STYLES(T)
+#undef T
+    default: break;
     }
-    return ss.str();
-}
-
-sc_bool_string_tuple_t sc_prompt(const sc_string_t *s, const sc_string_t *pre) {
-    using namespace scopes;
-    if (pre->count) {
-        linenoisePreloadBuffer(pre->data);
+    sp(Pstyle(style, str));
+    sp.flush_style();
+    return string_from_stdstring(sp.tostring());
+}
+
+sc_bool_string_tuple_t sc_prompt(sc_string_t s, sc_string_t pre) {
+    using namespace scopes;
+    if (pre->data.size()) {
+        linenoisePreloadBuffer(pre->data.data());
     }
-    char *r = linenoise(s->data);
+    char *r = linenoise(s->data.data());
     if (!r) {
-        return { false, Symbol(SYM_Unnamed).name() };
+        return { false, string_from_cstr("") };
     }
     linenoiseHistoryAdd(r);
 #ifdef SCOPES_WIN32

          
@@ 308,17 305,17 @@ sc_bool_string_tuple_t sc_prompt(const s
     ss << std::endl;
 #endif
 #endif
-    return { true, String::from_cstr(r) };
-}
-
-void sc_prompt_save_history(const sc_string_t *path) {
-    using namespace scopes;
-    linenoiseHistorySave(path->data);
-}
-
-void sc_prompt_load_history(const sc_string_t *path) {
-    using namespace scopes;
-    linenoiseHistoryLoad(path->data);
+    return { true, string_from_cstr(r) };
+}
+
+void sc_prompt_save_history(sc_string_t path) {
+    using namespace scopes;
+    linenoiseHistorySave(path->data.data());
+}
+
+void sc_prompt_load_history(sc_string_t path) {
+    using namespace scopes;
+    linenoiseHistoryLoad(path->data.data());
 }
 
 namespace scopes {

          
@@ 341,66 338,62 @@ void sc_prompt_add_completion(void *ctx,
     linenoiseAddCompletion((linenoiseCompletions *)ctx, text);
 }
 
-void sc_prompt_add_completion_from_scope(void *ctx, const char *searchtext, int offset, const sc_scope_t* scope) {
-    using namespace scopes;
-    const String* name = String::from_cstr(searchtext + offset);
+void sc_prompt_add_completion_from_scope(void *ctx, const char *searchtext, int offset, sc_scope_t scope) {
+    using namespace scopes;
+    String name = string_from_cstr(searchtext + offset);
     Symbol sym(name);
     scope = scope ? scope : globals;
 
-    for (const auto& m : scope->find_elongations(sym)) {
+    for (const auto& m : find_elongations(scope, sym)) {
         auto result =
-            std::string(searchtext, offset) + std::string(m.name()->data);
+            std::string(searchtext, offset) + m->data;
         linenoiseAddCompletion((linenoiseCompletions *)ctx, result.c_str());
     }
 }
 
-const sc_string_t *sc_format_message(const sc_anchor_t *anchor, const sc_string_t *message) {
-    using namespace scopes;
-    StyledString ss;
-    if (anchor) {
-        ss.out << anchor << " ";
-    }
-    ss.out << message->data << std::endl;
-    if (anchor) {
-        anchor->stream_source_line(ss.out);
-    }
-    return ss.str();
+sc_string_t sc_format_message(sc_anchor_t anchor, sc_string_t message) {
+    using namespace scopes;
+    StringPrinter sp;
+    sp(anchor);
+    sp(message);
+    stream_source_line(anchor_location(anchor), sp);
+    return string_from_stdstring(sp.tostring());
 }
 
 // file i/o
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_string_t *sc_realpath(const sc_string_t *path) {
+sc_string_t sc_realpath(sc_string_t path) {
     using namespace scopes;
     char buf[PATH_MAX];
-    auto result = realpath(path->data, buf);
+    auto result = realpath(path->data.data(), buf);
     if (!result) {
-        return Symbol(SYM_Unnamed).name();
+        return string_from_cstr("");
     } else {
-        return String::from_cstr(result);
+        return string_from_cstr(result);
     }
 }
 
-const sc_string_t *sc_dirname(const sc_string_t *path) {
-    using namespace scopes;
-    auto pathcopy = strdup(path->data);
-    auto result = String::from_cstr(dirname(pathcopy));
+sc_string_t sc_dirname(sc_string_t path) {
+    using namespace scopes;
+    auto pathcopy = strdup(path->data.data());
+    auto result = string_from_cstr(dirname(pathcopy));
     free(pathcopy);
     return result;
 }
 
-const sc_string_t *sc_basename(const sc_string_t *path) {
-    using namespace scopes;
-    auto pathcopy = strdup(path->data);
-    auto result = String::from_cstr(basename(pathcopy));
+sc_string_t sc_basename(sc_string_t path) {
+    using namespace scopes;
+    auto pathcopy = strdup(path->data.data());
+    auto result = string_from_cstr(basename(pathcopy));
     free(pathcopy);
     return result;
 }
 
-bool sc_is_file(const sc_string_t *path) {
+bool sc_is_file(sc_string_t path) {
     using namespace scopes;
     struct stat s;
-    if( stat(path->data,&s) == 0 ) {
+    if( stat(path->data.data(),&s) == 0 ) {
         if( s.st_mode & S_IFDIR ) {
         } else if ( s.st_mode & S_IFREG ) {
             return true;

          
@@ 409,10 402,10 @@ bool sc_is_file(const sc_string_t *path)
     return false;
 }
 
-bool sc_is_directory(const sc_string_t *path) {
+bool sc_is_directory(sc_string_t path) {
     using namespace scopes;
     struct stat s;
-    if( stat(path->data,&s) == 0 ) {
+    if( stat(path->data.data(),&s) == 0 ) {
         if( s.st_mode & S_IFDIR ) {
             return true;
         }

          
@@ 423,17 416,17 @@ bool sc_is_directory(const sc_string_t *
 // globals
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_scope_t *sc_get_globals() {
+sc_scope_t sc_get_globals() {
     using namespace scopes;
     return globals;
 }
 
-const sc_scope_t *sc_get_original_globals() {
+sc_scope_t sc_get_original_globals() {
     using namespace scopes;
     return original_globals;
 }
 
-void sc_set_globals(const sc_scope_t *s) {
+void sc_set_globals(sc_scope_t s) {
     using namespace scopes;
     globals = s;
 }

          
@@ 441,18 434,18 @@ void sc_set_globals(const sc_scope_t *s)
 // Error Handling
 ////////////////////////////////////////////////////////////////////////////////
 
-sc_error_t *sc_error_new(const sc_string_t *msg) {
-    using namespace scopes;
-    return ErrorUser::from(msg);
-}
-const sc_string_t *sc_format_error(const sc_error_t *err) {
-    using namespace scopes;
-    StyledString ss;
-    stream_error_message(ss.out, err);
-    return ss.str();
-}
-
-void sc_dump_error(const sc_error_t *err) {
+sc_error_t sc_error_new(sc_string_t msg) {
+    using namespace scopes;
+    return UserError::from({ .by = unknown_anchor(), .reason = msg->data });
+}
+sc_string_t sc_format_error(sc_error_t err) {
+    using namespace scopes;
+    StringPrinter sp;
+    stream_error_message(sp, err);
+    return string_from_stdstring(sp.tostring());
+}
+
+void sc_dump_error(sc_error_t err) {
     using namespace scopes;
     print_error(err);
 }

          
@@ 478,23 471,23 @@ void sc_exit(int c) {
 namespace scopes {
 
 struct MemoKeyEqual {
-    bool operator()( Value *lhs, Value *rhs ) const {
+    bool operator()( Value lhs, Value rhs ) const {
         if (lhs == rhs) return true;
-        if (lhs->kind() != rhs->kind())
+        if (lhs.kind() != rhs.kind())
             return false;
         if (isa<ArgumentList>(lhs)) {
             auto a = cast<ArgumentList>(lhs);
             auto b = cast<ArgumentList>(rhs);
-            if (a->get_type() != b->get_type())
+            if (a->type != b->type)
                 return false;
             for (int i = 0; i < a->values.size(); ++i) {
                 auto u = a->values[i];
                 auto v = b->values[i];
                 if (u == v) continue;
-                if (u->kind() != v->kind())
+                if (u.kind() != v.kind())
                     return false;
-                if (u.isa<Pure>()) {
-                    if (!u.cast<Pure>()->key_equal(v.cast<Pure>().unref()))
+                if (isa<Pure>(u)) {
+                    if (!key_equal(cast<Pure>(u),cast<Pure>(v)))
                         return false;
                 } else {
                     if (u != v)

          
@@ 505,16 498,16 @@ struct MemoKeyEqual {
         } else if (isa<ArgumentListTemplate>(lhs)) {
             auto a = cast<ArgumentListTemplate>(lhs);
             auto b = cast<ArgumentListTemplate>(rhs);
-            auto &&a_values = a->values();
-            auto &&b_values = b->values();
+            auto &&a_values = a->values;
+            auto &&b_values = b->values;
             for (int i = 0; i < a_values.size(); ++i) {
                 auto u = a_values[i];
                 auto v = b_values[i];
                 if (u == v) continue;
-                if (u->kind() != v->kind())
+                if (u.kind() != v.kind())
                     return false;
-                if (u.isa<Pure>()) {
-                    if (!u.cast<Pure>()->key_equal(v.cast<Pure>().unref()))
+                if (isa<Pure>(u)) {
+                    if (!key_equal(cast<Pure>(u),cast<Pure>(v)))
                         return false;
                 } else {
                     if (u != v)

          
@@ 524,13 517,13 @@ struct MemoKeyEqual {
             return true;
         } else if (isa<Pure>(lhs)) {
             if (isa<ConstPointer>(lhs)
-                && cast<ConstPointer>(lhs)->get_type() == TYPE_List
-                && cast<ConstPointer>(rhs)->get_type() == TYPE_List) {
+                && cast<ConstPointer>(lhs)->type == TYPE_List
+                && cast<ConstPointer>(rhs)->type == TYPE_List) {
                 return sc_list_compare(
-                    (const List *)cast<ConstPointer>(lhs)->value,
-                    (const List *)cast<ConstPointer>(rhs)->value);
+                    cast<List>(cast<ConstPointer>(lhs)->value),
+                    cast<List>(cast<ConstPointer>(rhs)->value));
             }
-            return cast<Pure>(lhs)->key_equal(cast<Pure>(rhs));
+            return key_equal(cast<Pure>(lhs), cast<Pure>(rhs));
         } else {
             return false;
         }

          
@@ 538,49 531,49 @@ struct MemoKeyEqual {
 };
 
 struct MemoHash {
-    std::size_t operator()(Value *l) const {
+    std::size_t operator()(Value l) const {
         if (isa<ArgumentList>(l)) {
             auto alist = cast<ArgumentList>(l);
-            uint64_t h = std::hash<const Type *>{}(alist->get_type());
+            uint64_t h = std::hash<Type>{}(alist->type);
             for (int i = 0; i < alist->values.size(); ++i) {
                 auto x = alist->values[i];
-                if (x.isa<Pure>()) {
-                    h = hash2(h, x.cast<Pure>()->hash());
+                if (isa<Pure>(x)) {
+                    h = hash2(h, cast<Pure>(x).hash());
                 } else {
-                    h = hash2(h, std::hash<const TypedValue *>{}(x.unref()));
+                    h = hash2(h, std::hash<TypedValue>{}(x));
                 }
             }
             return h;
         } else if (isa<ArgumentListTemplate>(l)) {
             auto alist = cast<ArgumentListTemplate>(l);
             uint64_t h = 0;
-            auto &&values = alist->values();
+            auto &&values = alist->values;
             for (int i = 0; i < values.size(); ++i) {
                 auto x = values[i];
-                if (x.isa<Pure>()) {
-                    h = hash2(h, x.cast<Pure>()->hash());
+                if (isa<Pure>(x)) {
+                    h = hash2(h, cast<Pure>(x).hash());
                 } else {
-                    h = hash2(h, std::hash<const Value *>{}(x.unref()));
+                    h = hash2(h, std::hash<Value>{}(x));
                 }
             }
             return h;
         } else if (isa<Pure>(l)) {
-            return cast<Pure>(l)->hash();
+            return cast<Pure>(l).hash();
         } else {
-            return std::hash<const Value *>{}(l);
+            return std::hash<Value>{}(l);
         }
     }
 };
 
-typedef std::unordered_map<Value *, ValueRef, MemoHash, MemoKeyEqual> MemoMap;
+typedef std::unordered_map<Value, Value, MemoHash, MemoKeyEqual> MemoMap;
 static MemoMap memo_map;
 
 }
 
-sc_valueref_raises_t sc_map_get(sc_valueref_t key) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(ValueRef);
-    auto it = memo_map.find(key.unref());
+sc_value_raises_t sc_map_get(sc_value_t key) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(Value);
+    auto it = memo_map.find(key);
     if (it != memo_map.end()) {
         return convert_result(it->second);
     } else {

          
@@ 588,48 581,49 @@ sc_valueref_raises_t sc_map_get(sc_value
     }
 }
 
-void sc_map_set(sc_valueref_t key, sc_valueref_t value) {
-    using namespace scopes;
-    if (!value) {
-        auto it = memo_map.find(key.unref());
-        if (it != memo_map.end()) {
-            memo_map.erase(it);
-        }
-    } else {
-        auto ret = memo_map.insert({key.unref(), value});
-        if (!ret.second) {
-            ret.first->second = value;
-        }
+void sc_map_set(sc_value_t key, sc_value_t value) {
+    using namespace scopes;
+    auto ret = memo_map.insert({key, value});
+    if (!ret.second) {
+        ret.first->second = value;
+    }
+}
+
+void sc_map_del(sc_value_t key) {
+    using namespace scopes;
+    auto it = memo_map.find(key);
+    if (it != memo_map.end()) {
+        memo_map.erase(it);
     }
 }
 
 // C Bridge
 ////////////////////////////////////////////////////////////////////////////////
 
-sc_void_raises_t sc_load_library(const sc_string_t *name) {
+sc_void_raises_t sc_load_library(sc_string_t name) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(void);
 //#ifdef SCOPES_WIN32
     // try to load library through regular interface first
     // so we get better error reporting
     dlerror();
-    void *handle = dlopen(name->data, RTLD_LAZY);
+    void *handle = dlopen(name->data.data(), RTLD_LAZY);
     if (!handle) {
         char *err = dlerror();
-        SCOPES_C_ERROR(RTLoadLibraryFailed, name, strdup(err));
+        SCOPES_C_ERROR(RTLoadLibraryFailed, name, err);
     }
 //#endif
-    if (LLVMLoadLibraryPermanently(name->data)) {
+    if (LLVMLoadLibraryPermanently(name->data.data())) {
         SCOPES_C_ERROR(RTLoadLibraryFailed, name, "reason unknown");
     }
-    return convert_result({});
-}
-
-sc_void_raises_t sc_load_object(const sc_string_t *path) {
+    return convert_result(Result<void>{});
+}
+
+sc_void_raises_t sc_load_object(sc_string_t path) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(void);
-    SCOPES_C_CHECK_RESULT(add_object(path->data));
-    return convert_result({});
+    SCOPES_C_CHECK_RESULT(add_object(path->data.data()));
+    return convert_result(Result<void>{});
 }
 
 void* sc_dlfcn_dlopen(char* path, int32_t mode) {

          
@@ 643,29 637,23 @@ char* sc_dlfcn_dlerror() {
 // Scope
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_scope_t *sc_scope_bind(const sc_scope_t *scope, sc_valueref_t key, sc_valueref_t value) {
-    using namespace scopes;
-    // ignore null values; this can happen when such a value is explicitly
-    // created on the console
-    if (!value) return scope;
-    return Scope::bind_from(key.cast<Const>(), value, nullptr, scope);
-}
-
-const sc_scope_t *sc_scope_bind_with_docstring(const sc_scope_t *scope, sc_valueref_t key, sc_valueref_t value, const sc_string_t *doc) {
-    using namespace scopes;
-    // ignore null values; this can happen when such a value is explicitly
-    // created on the console
-    if (!value) return scope;
-    return Scope::bind_from(key.cast<Const>(), value, doc, scope);
-}
-
-sc_valueref_raises_t sc_scope_at(const sc_scope_t *scope, sc_valueref_t key) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(ValueRef);
-    ValueRef result;
-    const String *doc;
-    bool ok = scope->lookup(SCOPES_C_GET_RESULT(extract_constant(key)), result, doc);
-    if (!ok) {
+sc_scope_t sc_scope_bind(sc_scope_t scope, sc_value_t key, sc_value_t value) {
+    using namespace scopes;
+    bind(scope, cast<Const>(key), value, {});
+    return scope;
+}
+
+sc_scope_t sc_scope_bind_with_docstring(sc_scope_t scope, sc_value_t key, sc_value_t value, sc_string_t doc) {
+    using namespace scopes;
+    bind(scope, cast<Const>(key), value, doc);
+    return scope;
+}
+
+sc_value_raises_t sc_scope_at(sc_scope_t scope, sc_value_t key) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(Value);
+    auto result = lookup(scope, SCOPES_C_GET_RESULT(extract_constant(key)));
+    if (!result) {
         if (try_get_const_type(key) == TYPE_Symbol) {
             auto sym = extract_symbol_constant(key).assert_ok();
             SCOPES_C_ERROR(RTMissingScopeAttribute, sym, scope);

          
@@ 673,15 661,14 @@ sc_valueref_raises_t sc_scope_at(const s
             SCOPES_C_ERROR(RTMissingScopeAnyAttribute, key);
         }
     }
-    return convert_result(result);
-}
-
-sc_valueref_raises_t sc_scope_local_at(const sc_scope_t *scope, sc_valueref_t key) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(ValueRef);
-    ValueRef result;
-    bool ok = scope->lookup_local(SCOPES_C_GET_RESULT(extract_constant(key)), result);
-    if (!ok) {
+    return convert_result(*result);
+}
+
+sc_value_raises_t sc_scope_local_at(sc_scope_t scope, sc_value_t key) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(Value);
+    auto result = lookup_local(scope, SCOPES_C_GET_RESULT(extract_constant(key)));
+    if (!result) {
         if (try_get_const_type(key) == TYPE_Symbol) {
             auto sym = extract_symbol_constant(key).assert_ok();
             SCOPES_C_ERROR(RTMissingLocalScopeAttribute, sym);

          
@@ 689,67 676,68 @@ sc_valueref_raises_t sc_scope_local_at(c
             SCOPES_C_ERROR(RTMissingLocalScopeAnyAttribute, key);
         }
     }
-    return convert_result(result);
-}
-
-const sc_string_t *sc_scope_module_docstring(const sc_scope_t *scope) {
-    using namespace scopes;
-    const String *doc = scope->header_doc();
-    if (doc) return doc;
-    return Symbol(SYM_Unnamed).name();
-}
-
-const sc_string_t *sc_scope_docstring(const sc_scope_t *scope, sc_valueref_t key) {
-    using namespace scopes;
-    ValueRef result;
-    const String *doc;
-    if (scope->lookup(key.cast<Const>(), result, doc) && doc) {
-        return doc;
+    return convert_result(*result);
+}
+
+sc_string_t sc_scope_module_docstring(sc_scope_t scope) {
+    using namespace scopes;
+    auto doc = header_doc(scope);
+    if (doc) return *doc;
+    return string_from_cstr("");
+}
+
+sc_string_t sc_scope_docstring(sc_scope_t scope, sc_value_t key) {
+    using namespace scopes;
+    Maybe<String> doc;
+    auto result = lookup(scope, cast<Const>(key), doc);
+    if (result && doc) {
+        return *doc;
     }
-    return Symbol(SYM_Unnamed).name();
-}
-
-const sc_scope_t *sc_scope_new() {
-    using namespace scopes;
-    return Scope::from(nullptr, nullptr);
-}
-
-const sc_scope_t *sc_scope_new_with_docstring(const sc_string_t *doc) {
-    using namespace scopes;
-    return Scope::from(doc, nullptr);
-}
-
-const sc_scope_t *sc_scope_reparent(const sc_scope_t *scope, const sc_scope_t *parent) {
-    using namespace scopes;
-    return Scope::reparent_from(scope, parent);
-}
-
-const sc_scope_t *sc_scope_unparent(const sc_scope_t *scope) {
-    using namespace scopes;
-    return Scope::reparent_from(scope, nullptr);
-}
-
-const sc_scope_t *sc_scope_new_subscope(const sc_scope_t *scope) {
-    using namespace scopes;
-    return Scope::from(nullptr, scope);
-}
-
-const sc_scope_t *sc_scope_new_subscope_with_docstring(const sc_scope_t *scope, const sc_string_t *doc) {
-    using namespace scopes;
-    return Scope::from(doc, scope);
-}
-
-const sc_scope_t *sc_scope_get_parent(const sc_scope_t *scope) {
-    using namespace scopes;
-    return scope->parent();
-}
-
-const sc_scope_t *sc_scope_unbind(const sc_scope_t *scope, sc_valueref_t key) {
-    using namespace scopes;
-    return Scope::unbind_from(key.cast<Const>(), scope);
-}
-
-sc_valueref_valueref_i32_tuple_t sc_scope_next(const sc_scope_t *scope, int index) {
+    return string_from_cstr("");
+}
+
+sc_scope_t sc_scope_new() {
+    using namespace scopes;
+    return Scope();
+}
+
+sc_scope_t sc_scope_new_with_docstring(sc_string_t doc) {
+    using namespace scopes;
+    return scope_from({}, doc);
+}
+
+sc_scope_t sc_scope_reparent(sc_scope_t scope, sc_scope_t parent) {
+    using namespace scopes;
+    return reparent(scope, parent);
+}
+
+sc_scope_t sc_scope_unparent(sc_scope_t scope) {
+    using namespace scopes;
+    return reparent(scope, {});
+}
+
+sc_scope_t sc_scope_new_subscope(sc_scope_t scope) {
+    using namespace scopes;
+    return scope_from(scope);
+}
+
+sc_scope_t sc_scope_new_subscope_with_docstring(sc_scope_t scope, sc_string_t doc) {
+    using namespace scopes;
+    return scope_from(scope, doc);
+}
+
+sc_scope_t sc_scope_get_parent(sc_scope_t scope) {
+    using namespace scopes;
+    return scope_parent(scope);
+}
+
+sc_scope_t sc_scope_unbind(sc_scope_t scope, sc_value_t key) {
+    using namespace scopes;
+    unbind(scope, cast<Const>(key));
+    return scope;
+}
+
+sc_valueref_valueref_i32_tuple_t sc_scope_next(sc_scope_t scope, int index) {
     using namespace scopes;
     auto &&map = scope->table();
     int count = map.entries.size();

          
@@ 765,7 753,7 @@ sc_valueref_valueref_i32_tuple_t sc_scop
     return { g_none, g_none, -1 };
 }
 
-sc_scope_valueref_valueref_i32_tuple_t sc_scope_any_next(const sc_scope_t *scope, int index) {
+sc_scope_valueref_valueref_i32_tuple_t sc_scope_any_next(sc_scope_t scope, int index) {
     using namespace scopes;
     while (scope) {
         auto &&map = scope->table();

          
@@ 785,7 773,7 @@ sc_scope_valueref_valueref_i32_tuple_t s
     return { nullptr, g_none, g_none, -1 };
 }
 
-sc_valueref_i32_tuple_t sc_scope_next_deleted(const sc_scope_t *scope, int index) {
+sc_valueref_i32_tuple_t sc_scope_next_deleted(sc_scope_t scope, int index) {
     using namespace scopes;
     auto &&map = scope->table();
     int count = map.entries.size();

          
@@ 803,7 791,7 @@ sc_valueref_i32_tuple_t sc_scope_next_de
 // Symbol
 ////////////////////////////////////////////////////////////////////////////////
 
-sc_symbol_t sc_symbol_new(const sc_string_t *str) {
+sc_symbol_t sc_symbol_new(sc_string_t str) {
     using namespace scopes;
     return Symbol(str).value();
 }

          
@@ 813,13 801,13 @@ bool sc_symbol_is_variadic(sc_symbol_t s
     return ends_with_parenthesis(Symbol::wrap(sym));
 }
 
-const sc_string_t *sc_symbol_to_string(sc_symbol_t sym) {
+sc_string_t sc_symbol_to_string(sc_symbol_t sym) {
     using namespace scopes;
     return Symbol::wrap(sym).name();
 }
 
 size_t counter = 1;
-sc_symbol_t sc_symbol_new_unique(const sc_string_t *str) {
+sc_symbol_t sc_symbol_new_unique(sc_string_t str) {
     using namespace scopes;
     std::stringstream ss;
     ss << "#" << counter++ << "#" << str->data;

          
@@ 840,17 828,17 @@ sc_symbol_t sc_symbol_style(sc_symbol_t 
 // String
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_string_t *sc_string_new(const char *ptr, size_t count) {
+sc_string_t sc_string_new(const char *ptr, size_t count) {
     using namespace scopes;
     return String::from(ptr, count);
 }
 
-const sc_string_t *sc_string_new_from_cstr(const char *ptr) {
+sc_string_t sc_string_new_from_cstr(const char *ptr) {
     using namespace scopes;
     return String::from(ptr, strlen(ptr));
 }
 
-const sc_string_t *sc_string_join(const sc_string_t *a, const sc_string_t *b) {
+sc_string_t sc_string_join(sc_string_t a, sc_string_t b) {
     using namespace scopes;
     return String::join(a,b);
 }

          
@@ 858,7 846,7 @@ const sc_string_t *sc_string_join(const 
 namespace scopes {
     static std::unordered_map<const String *, pcre2_code_8 *> pattern_cache;
 }
-sc_bool_i32_i32_raises_t sc_string_match(const sc_string_t *pattern, const sc_string_t *text) {
+sc_bool_i32_i32_raises_t sc_string_match(sc_string_t pattern, sc_string_t text) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(sc_bool_i32_i32_tuple_t);
     auto it = pattern_cache.find(pattern);

          
@@ 902,12 890,12 @@ sc_bool_i32_i32_raises_t sc_string_match
     SCOPES_C_RETURN(result);
 }
 
-size_t sc_string_count(const sc_string_t *str) {
+size_t sc_string_count(sc_string_t str) {
     using namespace scopes;
     return str->count;
 }
 
-int sc_string_compare(const sc_string_t *a, const sc_string_t *b) {
+int sc_string_compare(sc_string_t a, sc_string_t b) {
     using namespace scopes;
     auto c = memcmp(a->data, b->data, std::min(a->count, b->count));
     if (c) return c;

          
@@ 916,12 904,12 @@ int sc_string_compare(const sc_string_t 
     return 0;
 }
 
-sc_rawstring_size_t_tuple_t sc_string_buffer(const sc_string_t *str) {
+sc_rawstring_size_t_tuple_t sc_string_buffer(sc_string_t str) {
     using namespace scopes;
     return {str->data, str->count};
 }
 
-const sc_string_t *sc_string_rslice(const sc_string_t *str, size_t offset) {
+sc_string_t sc_string_rslice(sc_string_t str, size_t offset) {
     using namespace scopes;
     if (!offset) return str;
     if (offset >= str->count)

          
@@ 929,14 917,14 @@ const sc_string_t *sc_string_rslice(cons
     return String::from(str->data + offset, str->count - offset);
 }
 
-const sc_string_t *sc_string_lslice(const sc_string_t *str, size_t offset) {
+sc_string_t sc_string_lslice(sc_string_t str, size_t offset) {
     using namespace scopes;
     if (!offset) return Symbol(SYM_Unnamed).name();
     if (offset >= str->count) return str;
     return String::from(str->data, offset);
 }
 
-const sc_string_t *sc_string_unescape(const sc_string_t *str) {
+sc_string_t sc_string_unescape(sc_string_t str) {
     using namespace scopes;
     char *s = strdup(str->data);
     int sz = unescape_string(s);

          
@@ 948,31 936,31 @@ const sc_string_t *sc_string_unescape(co
 // List
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_list_t *sc_list_cons(sc_valueref_t at, const sc_list_t *next) {
+sc_list_t sc_list_cons(sc_value_t at, sc_list_t next) {
     using namespace scopes;
     return List::from(at, next);
 }
 
-const sc_list_t *sc_list_join(const sc_list_t *a, const sc_list_t *b) {
+sc_list_t sc_list_join(sc_list_t a, sc_list_t b) {
     using namespace scopes;
     return List::join(a, b);
 }
 
-const sc_list_t *sc_list_dump(const sc_list_t *l) {
+sc_list_t sc_list_dump(sc_list_t l) {
     using namespace scopes;
     StyledStream ss(SCOPES_CERR);
     stream_list(ss, l);
     return l;
 }
 
-const sc_string_t *sc_list_repr(const sc_list_t *l) {
+sc_string_t sc_list_repr(sc_list_t l) {
     using namespace scopes;
     StyledString ss;
     stream_list(ss.out, l, StreamListFormat::singleline());
     return ss.str();
 }
 
-const sc_string_t *sc_list_serialize(const sc_list_t *l) {
+sc_string_t sc_list_serialize(sc_list_t l) {
     using namespace scopes;
     StyledString ss = StyledString::plain();
     while (l) {

          
@@ 982,7 970,7 @@ const sc_string_t *sc_list_serialize(con
     return ss.str();
 }
 
-sc_valueref_list_tuple_t sc_list_decons(const sc_list_t *l) {
+sc_valueref_list_tuple_t sc_list_decons(sc_list_t l) {
     using namespace scopes;
     if (l)
         return { l->at, l->next };

          
@@ 990,27 978,27 @@ sc_valueref_list_tuple_t sc_list_decons(
         return { g_none, nullptr };
 }
 
-int sc_list_count(const sc_list_t *l) {
+int sc_list_count(sc_list_t l) {
     using namespace scopes;
     return List::count(l);
 }
 
-sc_valueref_t sc_list_at(const sc_list_t *l) {
-    using namespace scopes;
-    return l?l->at:ValueRef(g_none);
-}
-
-const sc_list_t *sc_list_next(const sc_list_t *l) {
+sc_value_t sc_list_at(sc_list_t l) {
+    using namespace scopes;
+    return l?l->at:Value(g_none);
+}
+
+sc_list_t sc_list_next(sc_list_t l) {
     using namespace scopes;
     return l?l->next:EOL;
 }
 
-const sc_list_t *sc_list_reverse(const sc_list_t *l) {
+sc_list_t sc_list_reverse(sc_list_t l) {
     using namespace scopes;
     return reverse_list(l);
 }
 
-bool sc_list_compare(const sc_list_t *a, const sc_list_t *b) {
+bool sc_list_compare(sc_list_t a, sc_list_t b) {
     using namespace scopes;
     if (a == b)
         return true;

          
@@ 1030,7 1018,7 @@ bool sc_list_compare(const sc_list_t *a,
 // Trace
 ////////////////////////////////////////////////////////////////////////////////
 
-int sc_traceback_push(const sc_anchor_t *anchor, int kind, const sc_trace_t *context) {
+int sc_traceback_push(sc_anchor_t anchor, int kind, const sc_trace_t *context) {
     using namespace scopes;
     return traceback_push(anchor, (TraceKind)kind, context);
 }

          
@@ 1060,7 1048,7 @@ const sc_trace_t *sc_extend_trace(const 
     return extend_trace(trace);
 }
 
-const sc_anchor_t *sc_trace_anchor(const sc_trace_t *trace) {
+sc_anchor_t sc_trace_anchor(const sc_trace_t *trace) {
     assert(trace);
     return trace->anchor();
 }

          
@@ 1094,33 1082,33 @@ int sc_trace_kind(const sc_trace_t *trac
 // Anchors
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_anchor_t *sc_anchor_new(sc_symbol_t path, int lineno, int column, int offset) {
+sc_anchor_t sc_anchor_new(sc_symbol_t path, int lineno, int column, int offset) {
     using namespace scopes;
     Location loc = { lineno, column, offset };
     return Anchor::from(Symbol::wrap(path), loc, loc);
 }
 
-sc_symbol_t sc_anchor_path(const sc_anchor_t *anchor) {
+sc_symbol_t sc_anchor_path(sc_anchor_t anchor) {
     using namespace scopes;
     return anchor->path.value();
 }
 
-int sc_anchor_lineno(const sc_anchor_t *anchor) {
+int sc_anchor_lineno(sc_anchor_t anchor) {
     using namespace scopes;
     return anchor->first.lineno;
 }
 
-int sc_anchor_column(const sc_anchor_t *anchor) {
+int sc_anchor_column(sc_anchor_t anchor) {
     using namespace scopes;
     return anchor->first.column;
 }
 
-int sc_anchor_get_offset(const sc_anchor_t *anchor) {
+int sc_anchor_get_offset(sc_anchor_t anchor) {
     using namespace scopes;
     return anchor->first.offset;
 }
 
-const sc_anchor_t *sc_anchor_offset(const sc_anchor_t *anchor, int offset) {
+sc_anchor_t sc_anchor_offset(sc_anchor_t anchor, int offset) {
     using namespace scopes;
 
     Location first = {

          
@@ 1136,7 1124,7 @@ const sc_anchor_t *sc_anchor_offset(cons
         anchor->buffer);
 }
 
-const sc_anchor_t *sc_anchor_range_new(sc_symbol_t path,
+sc_anchor_t sc_anchor_range_new(sc_symbol_t path,
     int first_lineno, int first_column, int first_offset,
     int last_lineno, int last_column, int last_offset) {
     using namespace scopes;

          
@@ 1144,15 1132,15 @@ const sc_anchor_t *sc_anchor_range_new(s
         {first_lineno, first_column, first_offset},
         {last_lineno, last_column, last_offset});
 }
-int sc_anchor_last_lineno(const sc_anchor_t *anchor) {
+int sc_anchor_last_lineno(sc_anchor_t anchor) {
     using namespace scopes;
     return anchor->last.lineno;
 }
-int sc_anchor_last_column(const sc_anchor_t *anchor) {
+int sc_anchor_last_column(sc_anchor_t anchor) {
     using namespace scopes;
     return anchor->last.column;
 }
-int sc_anchor_last_offset(const sc_anchor_t *anchor) {
+int sc_anchor_last_offset(sc_anchor_t anchor) {
     using namespace scopes;
     return anchor->last.offset;
 }

          
@@ 1160,7 1148,7 @@ int sc_anchor_last_offset(const sc_ancho
 // Closure
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_string_t *sc_closure_get_docstring(const sc_closure_t *func) {
+sc_string_t sc_closure_get_docstring(sc_closure_t func) {
     using namespace scopes;
     assert(func);
     if (!func->func->docstring)

          
@@ 1168,26 1156,26 @@ const sc_string_t *sc_closure_get_docstr
     return func->func->docstring;
 }
 
-sc_valueref_t sc_closure_get_template(const sc_closure_t *func) {
+sc_value_t sc_closure_get_template(sc_closure_t func) {
     using namespace scopes;
     assert(func);
     return func->func;
 }
 
-sc_valueref_t sc_closure_get_context(const sc_closure_t *func) {
+sc_value_t sc_closure_get_context(sc_closure_t func) {
     using namespace scopes;
     assert(func);
     return func->frame;
 }
 
-void sc_closure_transplant(const sc_closure_t *_dest, const sc_closure_t *src) {
+void sc_closure_transplant(sc_closure_t _dest, sc_closure_t src) {
     using namespace scopes;
     auto dest = const_cast<sc_closure_t *>(_dest);
     dest->func = src->func;
     dest->frame = src->frame;
 }
 
-const sc_closure_t *sc_closure_new(sc_valueref_t func, sc_valueref_t env) {
+sc_closure_t sc_closure_new(sc_value_t func, sc_value_t env) {
     using namespace scopes;
     return Closure::from(func.cast<Template>(), env.cast<Function>());
 }

          
@@ 1195,42 1183,42 @@ const sc_closure_t *sc_closure_new(sc_va
 // Value
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_string_t *sc_value_repr (sc_valueref_t value) {
+sc_string_t sc_value_repr (sc_value_t value) {
     using namespace scopes;
     StyledString ss;
     stream_value(ss.out, value, StreamValueFormat::singleline());
     return ss.str();
 }
 
-const sc_string_t *sc_value_content_repr (sc_valueref_t value) {
+sc_string_t sc_value_content_repr (sc_value_t value) {
     using namespace scopes;
     StyledString ss;
     stream_value(ss.out, value, StreamValueFormat::content());
     return ss.str();
 }
 
-const sc_string_t *sc_value_ast_repr (sc_valueref_t value) {
+sc_string_t sc_value_ast_repr (sc_value_t value) {
     using namespace scopes;
     StyledString ss;
     stream_value(ss.out, value);
     return ss.str();
 }
 
-const sc_string_t *sc_value_tostring (sc_valueref_t value) {
+sc_string_t sc_value_tostring (sc_value_t value) {
     using namespace scopes;
     StyledString ss = StyledString::plain();
     stream_value(ss.out, value, StreamValueFormat::content());
     return ss.str();
 }
 
-const sc_type_t *sc_value_type (sc_valueref_t value) {
+sc_type_t sc_value_type (sc_value_t value) {
     using namespace scopes;
     if (!value.isa<TypedValue>())
         return TYPE_Unknown;
     return strip_qualifiers(value.cast<TypedValue>()->get_type());
 }
 
-const sc_string_t *sc_value_pack(sc_valueref_t value) {
+sc_string_t sc_value_pack(sc_value_t value) {
     using namespace scopes;
     Writer writer;
     writer(value);

          
@@ 1239,9 1227,9 @@ const sc_string_t *sc_value_pack(sc_valu
         (const char *)result.data(), result.size() * sizeof(size_t));
 }
 
-sc_valueref_raises_t sc_value_unpack(const sc_string_t *str) {
-    using namespace scopes;
-    //SCOPES_RESULT_TYPE(ValueRef);
+sc_value_raises_t sc_value_unpack(sc_string_t str) {
+    using namespace scopes;
+    //SCOPES_RESULT_TYPE(Value);
     assert(false); // todo
     /*
     SCOPES_C_CHECK_RESULT(map_keyed_arguments(

          
@@ 1250,34 1238,34 @@ sc_valueref_raises_t sc_value_unpack(con
     return convert_result(ArgumentListTemplate::from({}));
 }
 
-const sc_type_t *sc_value_qualified_type (sc_valueref_t value) {
+sc_type_t sc_value_qualified_type (sc_value_t value) {
     using namespace scopes;
     if (!value.isa<TypedValue>())
         return TYPE_Unknown;
     return value.cast<TypedValue>()->get_type();
 }
 
-const sc_anchor_t *sc_value_anchor (sc_valueref_t value) {
+sc_anchor_t sc_value_anchor (sc_value_t value) {
     using namespace scopes;
     return value.anchor();
 }
 
-const sc_trace_t *sc_value_trace (sc_valueref_t value) {
+const sc_trace_t *sc_value_trace (sc_value_t value) {
     using namespace scopes;
     return value.trace();
 }
 
-sc_valueref_t sc_value_set_trace (const sc_trace_t *trace, sc_valueref_t value) {
+sc_value_t sc_value_set_trace (const sc_trace_t *trace, sc_value_t value) {
     using namespace scopes;
     return ref(trace, value);
 }
 
-bool sc_value_is_constant(sc_valueref_t value) {
+bool sc_value_is_constant(sc_value_t value) {
     using namespace scopes;
     return value.isa<Const>();
 }
 
-bool sc_value_is_pure (sc_valueref_t value) {
+bool sc_value_is_pure (sc_value_t value) {
     using namespace scopes;
     if (value.isa<ArgumentList>()) {
         auto al = value.cast<ArgumentList>();

          
@@ 1292,37 1280,37 @@ bool sc_value_is_pure (sc_valueref_t val
     }
 }
 
-bool sc_value_compare (sc_valueref_t a, sc_valueref_t b) {
+bool sc_value_compare (sc_value_t a, sc_value_t b) {
     using namespace scopes;
     if (a == b) return true;
     if (!a || !b) return false;
     return MemoKeyEqual{}(a.unref(),b.unref());
 }
 
-int sc_value_kind (sc_valueref_t value) {
+int sc_value_kind (sc_value_t value) {
     using namespace scopes;
     return value->kind();
 }
 
-int sc_value_block_depth (sc_valueref_t value) {
+int sc_value_block_depth (sc_value_t value) {
     using namespace scopes;
     return value->get_depth();
 }
 
-sc_valueref_t sc_identity(sc_valueref_t value) {
+sc_value_t sc_identity(sc_value_t value) {
     return value;
 }
 
-sc_valueref_t sc_value_wrap(const sc_type_t *type, sc_valueref_t value) {
+sc_value_t sc_value_wrap(sc_type_t type, sc_value_t value) {
     using namespace scopes;
     auto result = wrap_value(type, value);
     assert(result);
     return result;
 }
 
-sc_valueref_t sc_value_unwrap(const sc_type_t *type, sc_valueref_t value) {
-    using namespace scopes;
-    ValueRef result;
+sc_value_t sc_value_unwrap(sc_type_t type, sc_value_t value) {
+    using namespace scopes;
+    Value result;
     if (!is_opaque(type)) {
         result = unwrap_value(type, value);
     }

          
@@ 1332,39 1320,39 @@ sc_valueref_t sc_value_unwrap(const sc_t
     return result;
 }
 
-const sc_string_t *sc_value_kind_string(int kind) {
+sc_string_t sc_value_kind_string(int kind) {
     using namespace scopes;
     return String::from_cstr(get_value_kind_name((ValueKind)kind));
 }
 
-sc_valueref_t sc_keyed_new(sc_symbol_t key, sc_valueref_t value) {
+sc_value_t sc_keyed_new(sc_symbol_t key, sc_value_t value) {
     using namespace scopes;
     return KeyedTemplate::from(Symbol::wrap(key), value);
 }
 
-sc_symbol_t sc_keyed_key(sc_valueref_t value) {
+sc_symbol_t sc_keyed_key(sc_value_t value) {
     using namespace scopes;
     return value.cast<KeyedTemplate>()->key.value();
 }
 
-sc_valueref_t sc_keyed_value(sc_valueref_t value) {
+sc_value_t sc_keyed_value(sc_value_t value) {
     using namespace scopes;
     return value.cast<KeyedTemplate>()->value;
 }
 
-sc_valueref_t sc_empty_argument_list() {
+sc_value_t sc_empty_argument_list() {
     using namespace scopes;
     return ArgumentList::from({});
 }
 
-sc_valueref_t sc_argument_list_new(int count, const sc_valueref_t *values) {
+sc_value_t sc_argument_list_new(int count, const sc_value_t *values) {
     using namespace scopes;
     Values valueslist;
     init_values_array(valueslist, count, values);
     return ArgumentListTemplate::from(valueslist);
 }
 
-int sc_argcount(sc_valueref_t value) {
+int sc_argcount(sc_value_t value) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_ArgumentList: {

          
@@ 1377,7 1365,7 @@ int sc_argcount(sc_valueref_t value) {
     }
 }
 
-sc_valueref_t sc_getarg(sc_valueref_t value, int index) {
+sc_value_t sc_getarg(sc_value_t value, int index) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_ArgumentList: {

          
@@ 1400,7 1388,7 @@ sc_valueref_t sc_getarg(sc_valueref_t va
     return ConstAggregate::none_from();
 }
 
-sc_valueref_t sc_getarglist(sc_valueref_t value, int index) {
+sc_value_t sc_getarglist(sc_value_t value, int index) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_ArgumentList: {

          
@@ 1430,11 1418,11 @@ sc_valueref_t sc_getarglist(sc_valueref_
     }
 }
 
-sc_valueref_raises_t sc_map_argument_keys(
-    sc_valueref_t error_context, const sc_list_t *_symbols,
-    sc_valueref_t arguments, sc_valueref_t _defaults) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(ValueRef);
+sc_value_raises_t sc_map_argument_keys(
+    sc_value_t error_context, sc_list_t _symbols,
+    sc_value_t arguments, sc_value_t _defaults) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(Value);
     Values outargs;
     Values values;
     Values defaults;

          
@@ 1469,37 1457,37 @@ sc_valueref_raises_t sc_map_argument_key
 }
 
 
-sc_valueref_t sc_extract_argument_new(sc_valueref_t value, int index) {
+sc_value_t sc_extract_argument_new(sc_value_t value, int index) {
     using namespace scopes;
     return ExtractArgumentTemplate::from(value, index);
 }
 
-sc_valueref_t sc_extract_argument_list_new(sc_valueref_t value, int index) {
+sc_value_t sc_extract_argument_list_new(sc_value_t value, int index) {
     using namespace scopes;
     return ExtractArgumentTemplate::from(value, index, true);
 }
 
-int sc_extract_argument_index(sc_valueref_t value) {
+int sc_extract_argument_index(sc_value_t value) {
     using namespace scopes;
     return value.cast<ExtractArgumentTemplate>()->index;
 }
 
-sc_valueref_t sc_extract_argument_value(sc_valueref_t value) {
+sc_value_t sc_extract_argument_value(sc_value_t value) {
     using namespace scopes;
     return value.cast<ExtractArgumentTemplate>()->value;
 }
 
-bool sc_extract_argument_is_variadic(sc_valueref_t value) {
+bool sc_extract_argument_is_variadic(sc_value_t value) {
     using namespace scopes;
     return value.cast<ExtractArgumentTemplate>()->vararg;
 }
 
-sc_valueref_t sc_template_new(sc_symbol_t name) {
+sc_value_t sc_template_new(sc_symbol_t name) {
     using namespace scopes;
     return Template::from(Symbol::wrap(name));
 }
 
-sc_valueref_t sc_lazy_expression_new(sc_valueref_t value) {
+sc_value_t sc_lazy_expression_new(sc_value_t value) {
     using namespace scopes;
     auto val = Template::from(SYM_HiddenInline);
     val->set_inline();

          
@@ 1508,104 1496,104 @@ sc_valueref_t sc_lazy_expression_new(sc_
     return val;
 }
 
-void sc_template_set_name(sc_valueref_t fn, sc_symbol_t name) {
+void sc_template_set_name(sc_value_t fn, sc_symbol_t name) {
     using namespace scopes;
     fn.cast<Template>()->name = Symbol::wrap(name);
 }
-sc_symbol_t sc_template_get_name(sc_valueref_t fn) {
+sc_symbol_t sc_template_get_name(sc_value_t fn) {
     using namespace scopes;
     return fn.cast<Template>()->name.value();
 }
-void sc_template_append_parameter(sc_valueref_t fn, sc_valueref_t symbol) {
+void sc_template_append_parameter(sc_value_t fn, sc_value_t symbol) {
     using namespace scopes;
     fn.cast<Template>()->append_param(symbol.cast<ParameterTemplate>());
 }
-void sc_template_set_body(sc_valueref_t fn, sc_valueref_t value) {
+void sc_template_set_body(sc_value_t fn, sc_value_t value) {
     using namespace scopes;
     fn.cast<Template>()->value = value;
 }
 
-sc_valueref_t sc_template_get_body(sc_valueref_t fn) {
+sc_value_t sc_template_get_body(sc_value_t fn) {
     using namespace scopes;
     return fn.cast<Template>()->value;
 }
 
-void sc_template_set_docstring(sc_valueref_t fn, sc_string_t *doc) {
+void sc_template_set_docstring(sc_value_t fn, sc_string_t *doc) {
     using namespace scopes;
     fn.cast<Template>()->docstring = doc;
 }
 
-void sc_template_set_inline(sc_valueref_t fn) {
+void sc_template_set_inline(sc_value_t fn) {
     using namespace scopes;
     fn.cast<Template>()->set_inline();
 }
 
-void sc_template_set_anchor(sc_valueref_t fn, sc_anchor_t *anchor) {
+void sc_template_set_anchor(sc_value_t fn, sc_anchor_t *anchor) {
     using namespace scopes;
     //fn.set_trace(Trace::from(anchor, fn.trace()));
 }
 
-bool sc_template_is_inline(sc_valueref_t fn) {
+bool sc_template_is_inline(sc_value_t fn) {
     using namespace scopes;
     return fn.cast<Template>()->is_inline();
 }
 
-bool sc_template_is_hidden(sc_valueref_t fn) {
+bool sc_template_is_hidden(sc_value_t fn) {
     using namespace scopes;
     return fn.cast<Template>()->is_hidden();
 }
 
-bool sc_template_is_typeof(sc_valueref_t fn) {
+bool sc_template_is_typeof(sc_value_t fn) {
     using namespace scopes;
     return fn.cast<Template>()->is_typeof();
 }
 
-bool sc_template_is_forward_decl(sc_valueref_t fn) {
+bool sc_template_is_forward_decl(sc_value_t fn) {
     using namespace scopes;
     return fn.cast<Template>()->is_forward_decl();
 }
 
-int sc_template_parameter_count(sc_valueref_t fn) {
+int sc_template_parameter_count(sc_value_t fn) {
     using namespace scopes;
     return fn.cast<Template>()->params.size();
 }
 
-sc_valueref_t sc_template_parameter(sc_valueref_t fn, int index) {
+sc_value_t sc_template_parameter(sc_value_t fn, int index) {
     using namespace scopes;
     return fn.cast<Template>()->params[index];
 }
 
-sc_valueref_t sc_expression_new() {
+sc_value_t sc_expression_new() {
     using namespace scopes;
     return Expression::unscoped_from();
 }
 
-void sc_expression_set_scoped(sc_valueref_t expr) {
+void sc_expression_set_scoped(sc_value_t expr) {
     using namespace scopes;
     expr.cast<Expression>()->scoped = true;
 }
 
-void sc_expression_append(sc_valueref_t expr, sc_valueref_t value) {
+void sc_expression_append(sc_value_t expr, sc_value_t value) {
     using namespace scopes;
     expr.cast<Expression>()->append(value);
 }
 
-int sc_expression_count(sc_valueref_t expr) {
+int sc_expression_count(sc_value_t expr) {
     using namespace scopes;
     return expr.cast<Expression>()->body.size();
 }
 
-sc_valueref_t sc_expression_get(sc_valueref_t expr, int index) {
+sc_value_t sc_expression_get(sc_value_t expr, int index) {
     using namespace scopes;
     return expr.cast<Expression>()->body[index];
 }
 
-sc_valueref_t sc_expression_value(sc_valueref_t expr) {
+sc_value_t sc_expression_value(sc_value_t expr) {
     using namespace scopes;
     return expr.cast<Expression>()->value;
 }
 
-sc_valueref_t sc_expression_complete(sc_valueref_t val) {
+sc_value_t sc_expression_complete(sc_value_t val) {
     using namespace scopes;
     auto expr = val.cast<Expression>();
     if (expr->value) {

          
@@ 1616,13 1604,13 @@ sc_valueref_t sc_expression_complete(sc_
     return ArgumentListTemplate::from();
 }
 
-sc_valueref_t sc_global_new(sc_symbol_t name, const sc_type_t *type,
+sc_value_t sc_global_new(sc_symbol_t name, sc_type_t type,
     uint32_t flags, sc_symbol_t storage_class) {
     using namespace scopes;
     return Global::from(type, Symbol::wrap(name), flags, Symbol::wrap(storage_class));
 }
 
-sc_void_raises_t sc_global_set_location(sc_valueref_t value, int location) {
+sc_void_raises_t sc_global_set_location(sc_value_t value, int location) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(void);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));

          
@@ 1630,7 1618,7 @@ sc_void_raises_t sc_global_set_location(
     return convert_result({});
 }
 
-sc_void_raises_t sc_global_set_binding(sc_valueref_t value, int binding) {
+sc_void_raises_t sc_global_set_binding(sc_value_t value, int binding) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(void);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));

          
@@ 1638,7 1626,7 @@ sc_void_raises_t sc_global_set_binding(s
     return convert_result({});
 }
 
-sc_void_raises_t sc_global_set_descriptor_set(sc_valueref_t value, int set) {
+sc_void_raises_t sc_global_set_descriptor_set(sc_value_t value, int set) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(void);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));

          
@@ 1646,8 1634,8 @@ sc_void_raises_t sc_global_set_descripto
     return convert_result({});
 }
 
-sc_void_raises_t sc_global_set_initializer(sc_valueref_t value,
-    sc_valueref_t init) {
+sc_void_raises_t sc_global_set_initializer(sc_value_t value,
+    sc_value_t init) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(void);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));

          
@@ 1659,8 1647,8 @@ sc_void_raises_t sc_global_set_initializ
     return convert_result({});
 }
 
-sc_void_raises_t sc_global_set_constructor(sc_valueref_t value,
-    sc_valueref_t func) {
+sc_void_raises_t sc_global_set_constructor(sc_value_t value,
+    sc_value_t func) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(void);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));

          
@@ 1668,42 1656,42 @@ sc_void_raises_t sc_global_set_construct
     return convert_result({});
 }
 
-sc_int_raises_t sc_global_location(sc_valueref_t value) {
+sc_int_raises_t sc_global_location(sc_value_t value) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(int);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));
     SCOPES_C_RETURN(glob->location);
 }
 
-sc_int_raises_t sc_global_binding(sc_valueref_t value) {
+sc_int_raises_t sc_global_binding(sc_value_t value) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(int);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));
     SCOPES_C_RETURN(glob->binding);
 }
 
-sc_int_raises_t sc_global_descriptor_set(sc_valueref_t value) {
+sc_int_raises_t sc_global_descriptor_set(sc_value_t value) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(int);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));
     SCOPES_C_RETURN(glob->descriptor_set);
 }
 
-sc_symbol_raises_t sc_global_storage_class(sc_valueref_t value) {
+sc_symbol_raises_t sc_global_storage_class(sc_value_t value) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(Symbol);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));
     SCOPES_C_RETURN(glob->storage_class);
 }
 
-sc_symbol_raises_t sc_global_name(sc_valueref_t value) {
+sc_symbol_raises_t sc_global_name(sc_value_t value) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(Symbol);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));
     SCOPES_C_RETURN(glob->name);
 }
 
-sc_void_raises_t sc_global_set_module(sc_valueref_t value, sc_symbol_t name) {
+sc_void_raises_t sc_global_set_module(sc_value_t value, sc_symbol_t name) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(void);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));

          
@@ 1711,42 1699,42 @@ sc_void_raises_t sc_global_set_module(sc
     return convert_result({});
 }
 
-sc_symbol_raises_t sc_global_module(sc_valueref_t value) {
+sc_symbol_raises_t sc_global_module(sc_value_t value) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(Symbol);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));
     SCOPES_C_RETURN(glob->module);
 }
 
-sc_void_raises_t sc_global_needs_capability(sc_valueref_t value, sc_symbol_t name) {
+sc_void_raises_t sc_global_needs_capability(sc_value_t value, sc_symbol_t name) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(void);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));
     glob->capabilities.push_back(Symbol::wrap(name));
     return convert_result({});
 }
-sc_int_raises_t sc_global_capability_count(sc_valueref_t value) {
+sc_int_raises_t sc_global_capability_count(sc_value_t value) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(int);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));
     SCOPES_C_RETURN(glob->capabilities.size());
 }
 
-sc_symbol_raises_t sc_global_capability(sc_valueref_t value, int index) {
+sc_symbol_raises_t sc_global_capability(sc_value_t value, int index) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(Symbol);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));
     SCOPES_C_RETURN(glob->capabilities[index]);
 }
 
-sc_uint_raises_t sc_global_flags(sc_valueref_t value) {
+sc_uint_raises_t sc_global_flags(sc_value_t value) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(uint32_t);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));
     SCOPES_C_RETURN((uint32_t)glob->flags);
 }
 
-sc_valueref_raises_t sc_global_initializer(sc_valueref_t value) {
+sc_value_raises_t sc_global_initializer(sc_value_t value) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(PureRef);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));

          
@@ 1756,7 1744,7 @@ sc_valueref_raises_t sc_global_initializ
     return convert_result(glob->initializer);
 }
 
-sc_valueref_raises_t sc_global_constructor(sc_valueref_t value) {
+sc_value_raises_t sc_global_constructor(sc_value_t value) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(FunctionRef);
     auto glob = SCOPES_C_GET_RESULT(extract_global_constant(value));

          
@@ 1766,62 1754,62 @@ sc_valueref_raises_t sc_global_construct
     return convert_result(glob->constructor);
 }
 
-sc_valueref_t sc_pure_cast_new(const sc_type_t *type, sc_valueref_t value) {
+sc_value_t sc_pure_cast_new(sc_type_t type, sc_value_t value) {
     using namespace scopes;
     return PureCast::from(type, value.cast<Pure>());
 }
 
-sc_valueref_t sc_cond_new(sc_valueref_t cond, sc_valueref_t then_value, sc_valueref_t else_value) {
+sc_value_t sc_cond_new(sc_value_t cond, sc_value_t then_value, sc_value_t else_value) {
     using namespace scopes;
     return CondTemplate::from(cond, then_value, else_value);
 }
 
-sc_valueref_t sc_case_new(sc_valueref_t literal, sc_valueref_t body) {
+sc_value_t sc_case_new(sc_value_t literal, sc_value_t body) {
     using namespace scopes;
     return CaseTemplate::case_from(literal, body);
 }
 
-sc_valueref_t sc_pass_case_new(sc_valueref_t literal, sc_valueref_t body) {
+sc_value_t sc_pass_case_new(sc_value_t literal, sc_value_t body) {
     using namespace scopes;
     return CaseTemplate::pass_from(literal, body);
 }
 
-sc_valueref_t sc_do_case_new(sc_valueref_t body) {
+sc_value_t sc_do_case_new(sc_value_t body) {
     using namespace scopes;
     return CaseTemplate::do_from(body);
 }
 
-sc_valueref_t sc_default_case_new(sc_valueref_t body) {
+sc_value_t sc_default_case_new(sc_value_t body) {
     using namespace scopes;
     return CaseTemplate::default_from(body);
 }
 
-sc_valueref_t sc_switch_new(sc_valueref_t expr) {
+sc_value_t sc_switch_new(sc_value_t expr) {
     using namespace scopes;
     return SwitchTemplate::from(expr);
 }
-void sc_switch_append(sc_valueref_t value, sc_valueref_t _case) {
+void sc_switch_append(sc_value_t value, sc_value_t _case) {
     using namespace scopes;
     value.cast<SwitchTemplate>()->append(_case);
 }
-void sc_switch_append_case(sc_valueref_t value, sc_valueref_t literal, sc_valueref_t body) {
+void sc_switch_append_case(sc_value_t value, sc_value_t literal, sc_value_t body) {
     using namespace scopes;
     value.cast<SwitchTemplate>()->append_case(literal, body);
 }
-void sc_switch_append_pass(sc_valueref_t value, sc_valueref_t literal, sc_valueref_t body) {
+void sc_switch_append_pass(sc_value_t value, sc_value_t literal, sc_value_t body) {
     using namespace scopes;
     value.cast<SwitchTemplate>()->append_pass(literal, body);
 }
-void sc_switch_append_do(sc_valueref_t value, sc_valueref_t body) {
+void sc_switch_append_do(sc_value_t value, sc_value_t body) {
     using namespace scopes;
     value.cast<SwitchTemplate>()->append_do(body);
 }
-void sc_switch_append_default(sc_valueref_t value, sc_valueref_t body) {
+void sc_switch_append_default(sc_value_t value, sc_value_t body) {
     using namespace scopes;
     value.cast<SwitchTemplate>()->append_default(body);
 }
 
-sc_valueref_t sc_parameter_new(sc_symbol_t _name) {
+sc_value_t sc_parameter_new(sc_symbol_t _name) {
     using namespace scopes;
     auto name = Symbol::wrap(_name);
     if (ends_with_parenthesis(name)) {

          
@@ 1831,12 1819,12 @@ sc_valueref_t sc_parameter_new(sc_symbol
     }
 }
 
-bool sc_parameter_is_variadic(sc_valueref_t param) {
+bool sc_parameter_is_variadic(sc_value_t param) {
     using namespace scopes;
     return param.cast<ParameterTemplate>()->is_variadic();
 }
 
-sc_symbol_t sc_parameter_name(sc_valueref_t value) {
+sc_symbol_t sc_parameter_name(sc_value_t value) {
     using namespace scopes;
     if (value.isa<ParameterTemplate>()) {
         return value.cast<ParameterTemplate>()->name.value();

          
@@ 1846,61 1834,61 @@ sc_symbol_t sc_parameter_name(sc_valuere
     return SYM_Unnamed;
 }
 
-sc_valueref_t sc_call_new(sc_valueref_t callee) {
+sc_value_t sc_call_new(sc_value_t callee) {
     using namespace scopes;
     return CallTemplate::from(callee);
 }
 
-void sc_call_append_argument(sc_valueref_t call, sc_valueref_t value) {
+void sc_call_append_argument(sc_value_t call, sc_value_t value) {
     using namespace scopes;
     call.cast<CallTemplate>()->args.push_back(value);
 }
 
-bool sc_call_is_rawcall(sc_valueref_t value) {
+bool sc_call_is_rawcall(sc_value_t value) {
     using namespace scopes;
     return value.cast<CallTemplate>()->is_rawcall();
 }
 
-void sc_call_set_rawcall(sc_valueref_t value, bool enable) {
+void sc_call_set_rawcall(sc_value_t value, bool enable) {
     using namespace scopes;
     value.cast<CallTemplate>()->set_rawcall();
 }
 
-sc_valueref_t sc_call_callee(sc_valueref_t value) {
+sc_value_t sc_call_callee(sc_value_t value) {
     using namespace scopes;
     return value.cast<CallTemplate>()->callee;
 }
 
-int sc_call_argument_count(sc_valueref_t value) {
+int sc_call_argument_count(sc_value_t value) {
     using namespace scopes;
     return value.cast<CallTemplate>()->args.size();
 }
 
-sc_valueref_t sc_call_argument(sc_valueref_t value, int index) {
+sc_value_t sc_call_argument(sc_value_t value, int index) {
     using namespace scopes;
     return value.cast<CallTemplate>()->args[index];
 }
 
-sc_valueref_t sc_loop_new(sc_valueref_t init) {
+sc_value_t sc_loop_new(sc_value_t init) {
     using namespace scopes;
     return Loop::from(init);
 }
 
-sc_valueref_t sc_loop_arguments(sc_valueref_t loop) {
+sc_value_t sc_loop_arguments(sc_value_t loop) {
     using namespace scopes;
     return loop.cast<Loop>()->args;
 }
 
-void sc_loop_set_body(sc_valueref_t loop, sc_valueref_t body) {
+void sc_loop_set_body(sc_value_t loop, sc_value_t body) {
     using namespace scopes;
     loop.cast<Loop>()->value = body;
 }
 
-sc_valueref_t sc_const_int_new(const sc_type_t *type, uint64_t value) {
+sc_value_t sc_const_int_new(sc_type_t type, uint64_t value) {
     using namespace scopes;
     return ConstInt::from(type, value);
 }
-sc_valueref_t sc_const_int_words_new(const sc_type_t *type, int numwords, uint64_t *words) {
+sc_value_t sc_const_int_words_new(sc_type_t type, int numwords, uint64_t *words) {
     using namespace scopes;
     std::vector<uint64_t> values;
     values.resize(numwords);

          
@@ 1909,11 1897,11 @@ sc_valueref_t sc_const_int_words_new(con
     }
     return ConstInt::from(type, values);
 }
-sc_valueref_t sc_const_real_new(const sc_type_t *type, double value) {
+sc_value_t sc_const_real_new(sc_type_t type, double value) {
     using namespace scopes;
     return ConstReal::from(type, value);
 }
-sc_valueref_raises_t sc_const_aggregate_new(const sc_type_t *type, int numconsts, sc_valueref_t *consts) {
+sc_value_raises_t sc_const_aggregate_new(sc_type_t type, int numconsts, sc_value_t *consts) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(ConstAggregateRef);
     ConstantPtrs vals;

          
@@ 1929,45 1917,45 @@ sc_valueref_raises_t sc_const_aggregate_
     }
     return convert_result(ConstAggregate::from(type, vals));
 }
-sc_valueref_t sc_const_pointer_new(const sc_type_t *type, const void *pointer) {
+sc_value_t sc_const_pointer_new(sc_type_t type, const void *pointer) {
     using namespace scopes;
     return ConstPointer::from(type, pointer);
 }
-sc_valueref_raises_t sc_const_null_new(const sc_type_t *type) {
+sc_value_raises_t sc_const_null_new(sc_type_t type) {
     using namespace scopes;
     return convert_result(nullof(type));
 }
-sc_valueref_raises_t sc_const_pointer_to_global(const sc_valueref_t value) {
+sc_value_raises_t sc_const_pointer_to_global(const sc_value_t value) {
     using namespace scopes;
     return convert_result(value.cast<ConstPointer>()->to_global());
 }
 
-uint64_t sc_const_int_extract(const sc_valueref_t value) {
+uint64_t sc_const_int_extract(const sc_value_t value) {
     using namespace scopes;
     return value.cast<ConstInt>()->msw();
 }
-uint64_t sc_const_int_extract_word(const sc_valueref_t value, int index) {
+uint64_t sc_const_int_extract_word(const sc_value_t value, int index) {
     using namespace scopes;
     auto ci = value.cast<ConstInt>();
     assert (index < ci->words.size());
     return ci->words[index];
 }
-uint64_t *sc_const_int_word_ptr(const sc_valueref_t value) {
+uint64_t *sc_const_int_word_ptr(const sc_value_t value) {
     using namespace scopes;
     auto ci = value.cast<ConstInt>();
     return ci->words.data();
 }
-int sc_const_int_word_count(const sc_valueref_t value) {
+int sc_const_int_word_count(const sc_value_t value) {
     using namespace scopes;
     auto ci = value.cast<ConstInt>();
     return (int)ci->words.size();
 }
 
-double sc_const_real_extract(const sc_valueref_t value) {
+double sc_const_real_extract(const sc_value_t value) {
     using namespace scopes;
     return value.cast<ConstReal>()->value;
 }
-sc_valueref_t sc_const_extract_at(const sc_valueref_t value, int index) {
+sc_value_t sc_const_extract_at(const sc_value_t value, int index) {
     using namespace scopes;
     if (value.isa<ConstString>()) {
         auto val = value.cast<ConstString>();

          
@@ 1979,7 1967,7 @@ sc_valueref_t sc_const_extract_at(const 
         return get_field(val, index);
     }
 }
-const void *sc_const_pointer_extract(const sc_valueref_t value) {
+const void *sc_const_pointer_extract(const sc_value_t value) {
     using namespace scopes;
     if (value.isa<ConstNull>()) {
         return nullptr;

          
@@ 1988,12 1976,12 @@ const void *sc_const_pointer_extract(con
     }
 }
 
-sc_valueref_t sc_const_string_new(const sc_string_t *str) {
+sc_value_t sc_const_string_new(sc_string_t str) {
     using namespace scopes;
     return ConstString::from(str);
 }
 
-const sc_string_t *sc_const_string_extract(sc_valueref_t value) {
+sc_string_t sc_const_string_extract(sc_value_t value) {
     using namespace scopes;
     if (value.isa<ConstString>()) {
         return value.cast<ConstString>()->value;

          
@@ 2002,34 1990,34 @@ const sc_string_t *sc_const_string_extra
     }
 }
 
-sc_valueref_t sc_quote_new(sc_valueref_t value) {
+sc_value_t sc_quote_new(sc_value_t value) {
     using namespace scopes;
     return Quote::from(value);
 }
 
-sc_valueref_t sc_unquote_new(sc_valueref_t value) {
+sc_value_t sc_unquote_new(sc_value_t value) {
     using namespace scopes;
     return Unquote::from(value);
 }
 
-sc_valueref_t sc_label_new(int kind, sc_symbol_t name) {
+sc_value_t sc_label_new(int kind, sc_symbol_t name) {
     using namespace scopes;
     return LabelTemplate::from((LabelKind)kind, Symbol::wrap(name));
 }
-void sc_label_set_body(sc_valueref_t label, sc_valueref_t body) {
+void sc_label_set_body(sc_value_t label, sc_value_t body) {
     using namespace scopes;
     label.cast<LabelTemplate>()->value = body;
 }
-sc_valueref_t sc_label_get_body(sc_valueref_t label) {
+sc_value_t sc_label_get_body(sc_value_t label) {
     using namespace scopes;
     return label.cast<LabelTemplate>()->value;
 }
-sc_valueref_t sc_merge_new(sc_valueref_t label, sc_valueref_t value) {
+sc_value_t sc_merge_new(sc_value_t label, sc_value_t value) {
     using namespace scopes;
     return MergeTemplate::from(label.cast<LabelTemplate>(), value);
 }
 
-sc_valueref_t sc_compile_stage_new(const sc_list_t *next, const sc_scope_t *env) {
+sc_value_t sc_compile_stage_new(sc_list_t next, sc_scope_t env) {
     using namespace scopes;
     return CompileStage::from(next, env);
 }

          
@@ 2037,9 2025,9 @@ sc_valueref_t sc_compile_stage_new(const
 // Parser
 ////////////////////////////////////////////////////////////////////////////////
 
-sc_valueref_raises_t sc_parse_from_path(const sc_string_t *path) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(ValueRef);
+sc_value_raises_t sc_parse_from_path(sc_string_t path) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(Value);
     auto sf = SourceFile::from_file(path);
     if (!sf) {
         SCOPES_C_ERROR(RTUnableToOpenFile, path);

          
@@ 2048,7 2036,7 @@ sc_valueref_raises_t sc_parse_from_path(
     return convert_result(parser.parse());
 }
 
-sc_valueref_raises_t sc_parse_from_string(const sc_string_t *str) {
+sc_value_raises_t sc_parse_from_string(sc_string_t str) {
     using namespace scopes;
     auto sf = SourceFile::from_string(Symbol("<string>"), str);
     assert(sf);

          
@@ 2059,12 2047,12 @@ sc_valueref_raises_t sc_parse_from_strin
 // Types
 ////////////////////////////////////////////////////////////////////////////////
 
-sc_valueref_raises_t sc_type_at(const sc_type_t *T, sc_symbol_t _key) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(ValueRef);
+sc_value_raises_t sc_type_at(sc_type_t T, sc_symbol_t _key) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(Value);
     auto key = Symbol::wrap(_key);
     T = strip_qualifiers(T);
-    ValueRef result;
+    Value result;
     bool ok = T->lookup(key, result);
     if (!ok) {
         SCOPES_C_ERROR(RTMissingTypeAttribute, key, T);

          
@@ 2072,12 2060,12 @@ sc_valueref_raises_t sc_type_at(const sc
     return convert_result(result);
 }
 
-sc_valueref_raises_t sc_type_local_at(const sc_type_t *T, sc_symbol_t _key) {
-    using namespace scopes;
-    SCOPES_RESULT_TYPE(ValueRef);
+sc_value_raises_t sc_type_local_at(sc_type_t T, sc_symbol_t _key) {
+    using namespace scopes;
+    SCOPES_RESULT_TYPE(Value);
     auto key = Symbol::wrap(_key);
     T = strip_qualifiers(T);
-    ValueRef result;
+    Value result;
     bool ok = T->lookup_local(key, result);
     if (!ok) {
         SCOPES_C_ERROR(RTMissingLocalTypeAttribute, key);

          
@@ 2085,7 2073,7 @@ sc_valueref_raises_t sc_type_local_at(co
     return convert_result(result);
 }
 
-const sc_string_t *sc_type_get_docstring(const sc_type_t *T, sc_symbol_t _key) {
+sc_string_t sc_type_get_docstring(sc_type_t T, sc_symbol_t _key) {
     using namespace scopes;
     auto key = Symbol::wrap(_key);
     TypeEntry entry;

          
@@ 2095,7 2083,7 @@ const sc_string_t *sc_type_get_docstring
     return Symbol(SYM_Unnamed).name();
 }
 
-void sc_type_set_docstring(const sc_type_t *T, sc_symbol_t _key, const sc_string_t *str) {
+void sc_type_set_docstring(sc_type_t T, sc_symbol_t _key, sc_string_t str) {
     using namespace scopes;
     auto key = Symbol::wrap(_key);
     TypeEntry entry;

          
@@ 2106,19 2094,19 @@ void sc_type_set_docstring(const sc_type
     T->bind_with_doc(key, entry);
 }
 
-sc_size_raises_t sc_type_sizeof(const sc_type_t *T) {
+sc_size_raises_t sc_type_sizeof(sc_type_t T) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(size_t);
     SCOPES_C_RETURN(size_of(T));
 }
 
-sc_size_raises_t sc_type_alignof(const sc_type_t *T) {
+sc_size_raises_t sc_type_alignof(sc_type_t T) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(size_t);
     SCOPES_C_RETURN(align_of(T));
 }
 
-sc_size_raises_t sc_type_offsetof(const sc_type_t *T, size_t index) {
+sc_size_raises_t sc_type_offsetof(sc_type_t T, size_t index) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(size_t);
     T = SCOPES_C_GET_RESULT(storage_type(T));

          
@@ 2137,7 2125,7 @@ sc_size_raises_t sc_type_offsetof(const 
     SCOPES_C_RETURN(sz);
 }
 
-sc_int_raises_t sc_type_countof(const sc_type_t *T) {
+sc_int_raises_t sc_type_countof(sc_type_t T) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(int);
     T = SCOPES_C_GET_RESULT(storage_type(T));

          
@@ 2157,7 2145,7 @@ sc_int_raises_t sc_type_countof(const sc
     SCOPES_C_ERROR(RTUncountableStorageType, T);
 }
 
-sc_bool_raises_t sc_type_is_unsized(const sc_type_t *T) {
+sc_bool_raises_t sc_type_is_unsized(sc_type_t T) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(bool);
     T = SCOPES_C_GET_RESULT(storage_type(T));

          
@@ 2169,7 2157,7 @@ sc_bool_raises_t sc_type_is_unsized(cons
     SCOPES_C_RETURN(false);
 }
 
-sc_type_raises_t sc_type_element_at(const sc_type_t *T, int i) {
+sc_type_raises_t sc_type_element_at(sc_type_t T, int i) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(const Type *);
     T = SCOPES_C_GET_RESULT(storage_type(T));

          
@@ 2191,7 2179,7 @@ sc_type_raises_t sc_type_element_at(cons
     SCOPES_C_RETURN(result);
 }
 
-sc_int_raises_t sc_type_field_index(const sc_type_t *T, sc_symbol_t _name) {
+sc_int_raises_t sc_type_field_index(sc_type_t T, sc_symbol_t _name) {
     using namespace scopes;
     auto name = Symbol::wrap(_name);
     SCOPES_RESULT_TYPE(int);

          
@@ 2209,7 2197,7 @@ sc_int_raises_t sc_type_field_index(cons
     SCOPES_C_ERROR(RTNoNamedElementsInStorageType, T);
 }
 
-sc_symbol_raises_t sc_type_field_name(const sc_type_t *T, int index) {
+sc_symbol_raises_t sc_type_field_name(sc_type_t T, int index) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(Symbol);
     T = SCOPES_C_GET_RESULT(storage_type(T));

          
@@ 2221,13 2209,13 @@ sc_symbol_raises_t sc_type_field_name(co
     SCOPES_C_ERROR(RTNoNamedElementsInStorageType, T);
 }
 
-int32_t sc_type_kind(const sc_type_t *T) {
+int32_t sc_type_kind(sc_type_t T) {
     using namespace scopes;
     T = strip_qualifiers(T);
     return T->kind();
 }
 
-void sc_type_debug_abi(const sc_type_t *T) {
+void sc_type_debug_abi(sc_type_t T) {
     using namespace scopes;
     ABIClass classes[MAX_ABI_CLASSES];
     size_t sz = abi_classify(T, classes);

          
@@ 2239,22 2227,22 @@ void sc_type_debug_abi(const sc_type_t *
     ss << std::endl;
 }
 
-sc_type_raises_t sc_type_storage(const sc_type_t *T) {
+sc_type_raises_t sc_type_storage(sc_type_t T) {
     using namespace scopes;
     return convert_result(storage_type(T));
 }
 
-bool sc_type_is_plain(const sc_type_t *T) {
+bool sc_type_is_plain(sc_type_t T) {
     using namespace scopes;
     return is_plain(T);
 }
 
-bool sc_type_is_opaque(const sc_type_t *T) {
+bool sc_type_is_opaque(sc_type_t T) {
     using namespace scopes;
     return is_opaque(T);
 }
 
-bool sc_type_is_superof(const sc_type_t *super, const sc_type_t *T) {
+bool sc_type_is_superof(sc_type_t super, sc_type_t T) {
     using namespace scopes;
     for (int i = 0; i < SCOPES_MAX_RECURSIONS; ++i) {
         T = sc_typename_type_get_super(T);

          
@@ 2264,24 2252,24 @@ bool sc_type_is_superof(const sc_type_t 
     return false;
 }
 
-bool sc_type_compatible(const sc_type_t *have, const sc_type_t *need) {
+bool sc_type_compatible(sc_type_t have, sc_type_t need) {
     using namespace scopes;
     return types_compatible(need, have);
 }
 
-bool sc_type_is_default_suffix(const sc_type_t *T) {
+bool sc_type_is_default_suffix(sc_type_t T) {
     using namespace scopes;
     return is_default_suffix(T);
 }
 
-const sc_string_t *sc_type_string(const sc_type_t *T) {
+sc_string_t sc_type_string(sc_type_t T) {
     using namespace scopes;
     StyledString ss = StyledString::plain();
     stream_type_name(ss.out, T);
     return ss.str();
 }
 
-sc_symbol_valueref_tuple_t sc_type_next(const sc_type_t *type, sc_symbol_t key) {
+sc_symbol_valueref_tuple_t sc_type_next(sc_type_t type, sc_symbol_t key) {
     using namespace scopes;
     type = strip_qualifiers(type);
     auto &&map = type->get_symbols();

          
@@ 2306,16 2294,16 @@ sc_symbol_valueref_tuple_t sc_type_next(
     if (index != count) {
         return { map.entries[index].first.value(), map.entries[index].second.expr };
     }
-    return { SYM_Unnamed, ValueRef() };
-}
-
-void sc_type_set_symbol(const sc_type_t *T, sc_symbol_t sym, sc_valueref_t value) {
+    return { SYM_Unnamed, Value() };
+}
+
+void sc_type_set_symbol(sc_type_t T, sc_symbol_t sym, sc_value_t value) {
     using namespace scopes;
     T = strip_qualifiers(T);
     const_cast<Type *>(T)->bind(Symbol::wrap(sym), value);
 }
 
-void sc_type_del_symbol(const sc_type_t *T, sc_symbol_t sym) {
+void sc_type_del_symbol(sc_type_t T, sc_symbol_t sym) {
     using namespace scopes;
     T = strip_qualifiers(T);
     const_cast<Type *>(T)->unbind(Symbol::wrap(sym));

          
@@ 2324,33 2312,33 @@ void sc_type_del_symbol(const sc_type_t 
 // Qualifier
 ////////////////////////////////////////////////////////////////////////////////
 
-sc_symbol_type_tuple_t sc_type_key(const sc_type_t *T) {
+sc_symbol_type_tuple_t sc_type_key(sc_type_t T) {
     using namespace scopes;
     auto tk = type_key(T);
     return {tk._0.value(), tk._1};
 }
 
-const sc_type_t *sc_key_type(sc_symbol_t name, const sc_type_t *T) {
+sc_type_t sc_key_type(sc_symbol_t name, sc_type_t T) {
     using namespace scopes;
     return key_type(Symbol::wrap(name), T);
 }
 
-bool sc_type_is_refer(const sc_type_t *T) {
+bool sc_type_is_refer(sc_type_t T) {
     using namespace scopes;
     return has_qualifier<ReferQualifier>(T);
 }
 
-bool sc_type_is_view(const sc_type_t *T) {
+bool sc_type_is_view(sc_type_t T) {
     using namespace scopes;
     return has_qualifier<ViewQualifier>(T);
 }
 
-bool sc_type_is_unique(const sc_type_t *T) {
+bool sc_type_is_unique(sc_type_t T) {
     using namespace scopes;
     return has_qualifier<UniqueQualifier>(T);
 }
 
-int sc_view_id_count(const sc_type_t *T) {
+int sc_view_id_count(sc_type_t T) {
     using namespace scopes;
     auto uq = try_qualifier<UniqueQualifier>(T);
     if (uq) {

          
@@ 2363,7 2351,7 @@ int sc_view_id_count(const sc_type_t *T)
     return 0;
 }
 
-int sc_view_id_at(const sc_type_t *T, int index) {
+int sc_view_id_at(sc_type_t T, int index) {
     using namespace scopes;
     auto uq = try_qualifier<UniqueQualifier>(T);
     if (uq) {

          
@@ 2379,12 2367,12 @@ int sc_view_id_at(const sc_type_t *T, in
 // Pointer Type
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_type_t *sc_pointer_type(const sc_type_t *T, uint64_t flags, sc_symbol_t storage_class) {
+sc_type_t sc_pointer_type(sc_type_t T, uint64_t flags, sc_symbol_t storage_class) {
     using namespace scopes;
     return pointer_type(T, flags, Symbol::wrap(storage_class));
 }
 
-uint64_t sc_pointer_type_get_flags(const sc_type_t *T) {
+uint64_t sc_pointer_type_get_flags(sc_type_t T) {
     using namespace scopes;
     if (is_kind<TK_Pointer>(T)) {
         return cast<PointerType>(T)->flags;

          
@@ 2392,7 2380,7 @@ uint64_t sc_pointer_type_get_flags(const
     return 0;
 }
 
-const sc_type_t *sc_pointer_type_set_flags(const sc_type_t *T, uint64_t flags) {
+sc_type_t sc_pointer_type_set_flags(sc_type_t T, uint64_t flags) {
     using namespace scopes;
     if (is_kind<TK_Pointer>(T)) {
         auto pt = cast<PointerType>(T);

          
@@ 2401,7 2389,7 @@ const sc_type_t *sc_pointer_type_set_fla
     return T;
 }
 
-sc_symbol_t sc_pointer_type_get_storage_class(const sc_type_t *T) {
+sc_symbol_t sc_pointer_type_get_storage_class(sc_type_t T) {
     using namespace scopes;
     if (is_kind<TK_Pointer>(T)) {
         return cast<PointerType>(T)->storage_class.value();

          
@@ 2409,7 2397,7 @@ sc_symbol_t sc_pointer_type_get_storage_
     return SYM_Unnamed;
 }
 
-const sc_type_t *sc_pointer_type_set_storage_class(const sc_type_t *T, sc_symbol_t storage_class) {
+sc_type_t sc_pointer_type_set_storage_class(sc_type_t T, sc_symbol_t storage_class) {
     using namespace scopes;
     if (is_kind<TK_Pointer>(T)) {
         auto pt = cast<PointerType>(T);

          
@@ 2418,7 2406,7 @@ const sc_type_t *sc_pointer_type_set_sto
     return T;
 }
 
-const sc_type_t *sc_pointer_type_set_element_type(const sc_type_t *T, const sc_type_t *ET) {
+sc_type_t sc_pointer_type_set_element_type(sc_type_t T, sc_type_t ET) {
     using namespace scopes;
     if (is_kind<TK_Pointer>(T)) {
         auto pt = cast<PointerType>(T);

          
@@ 2430,7 2418,7 @@ const sc_type_t *sc_pointer_type_set_ele
 // numerical types
 ////////////////////////////////////////////////////////////////////////////////
 
-int32_t sc_type_bitcountof(const sc_type_t *T) {
+int32_t sc_type_bitcountof(sc_type_t T) {
     using namespace scopes;
     auto rT = storage_type(T);
     if (!rT.ok()) return 0;

          
@@ 2448,12 2436,12 @@ int32_t sc_type_bitcountof(const sc_type
 // Integer Type
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_type_t *sc_integer_type(int width, bool issigned) {
+sc_type_t sc_integer_type(int width, bool issigned) {
     using namespace scopes;
     return integer_type(width, issigned);
 }
 
-bool sc_integer_type_is_signed(const sc_type_t *T) {
+bool sc_integer_type_is_signed(sc_type_t T) {
     using namespace scopes;
     auto rT = storage_type(T);
     if (!rT.ok()) return false;

          
@@ 2467,7 2455,7 @@ bool sc_integer_type_is_signed(const sc_
 // Typename Type
 ////////////////////////////////////////////////////////////////////////////////
 
-sc_type_raises_t sc_typename_type(const sc_string_t *str, const sc_type_t *supertype) {
+sc_type_raises_t sc_typename_type(sc_string_t str, sc_type_t supertype) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(const Type *);
     SCOPES_C_CHECK_RESULT(verify_kind<TK_Typename>(supertype));

          
@@ 2480,40 2468,40 @@ sc_type_raises_t sc_typename_type(const 
     SCOPES_C_RETURN(T);
 }
 
-const sc_string_t *sc_typename_type_get_name(const sc_type_t *T) {
+sc_string_t sc_typename_type_get_name(sc_type_t T) {
     using namespace scopes;
     if (!isa<TypenameType>(T))
         return sc_value_tostring(ConstPointer::type_from(T));
     return cast<TypenameType>(T)->name();
 }
 
-const sc_string_t *sc_typename_type_get_original_name(const sc_type_t *T) {
+sc_string_t sc_typename_type_get_original_name(sc_type_t T) {
     using namespace scopes;
     if (!isa<TypenameType>(T))
         return sc_value_tostring(ConstPointer::type_from(T));
     return cast<TypenameType>(T)->original_name();
 }
 
-const sc_type_t *sc_typename_type_get_super(const sc_type_t *T) {
+sc_type_t sc_typename_type_get_super(sc_type_t T) {
     using namespace scopes;
     return superof(T);
 }
 
-sc_void_raises_t sc_typename_type_set_storage(const sc_type_t *T, const sc_type_t *T2, uint32_t flags) {
+sc_void_raises_t sc_typename_type_set_storage(sc_type_t T, sc_type_t T2, uint32_t flags) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(void);
     SCOPES_C_CHECK_RESULT(verify_kind<TK_Typename>(T));
     return convert_result(cast<TypenameType>(T)->complete(T2, flags));
 }
 
-sc_void_raises_t sc_typename_type_set_opaque(const sc_type_t *T) {
+sc_void_raises_t sc_typename_type_set_opaque(sc_type_t T) {
     using namespace scopes;
     SCOPES_RESULT_TYPE(void);
     SCOPES_C_CHECK_RESULT(verify_kind<TK_Typename>(T));
     return convert_result(cast<TypenameType>(T)->complete());
 }
 
-bool sc_typename_type_is_complete(const sc_type_t *T) {
+bool sc_typename_type_is_complete(sc_type_t T) {
     using namespace scopes;
     if (!isa<TypenameType>(T))
         return true;

          
@@ 2523,12 2511,12 @@ bool sc_typename_type_is_complete(const 
 // Array Type
 ////////////////////////////////////////////////////////////////////////////////
 
-sc_type_raises_t sc_array_type(const sc_type_t *element_type, size_t count) {
+sc_type_raises_t sc_array_type(sc_type_t element_type, size_t count) {
     using namespace scopes;
     return convert_result(array_type(element_type, count));
 }
 
-const sc_type_t *sc_array_type_set_zterm(const sc_type_t *T, bool zterm) {
+sc_type_t sc_array_type_set_zterm(sc_type_t T, bool zterm) {
     using namespace scopes;
     if (is_kind<TK_Array>(T)) {
         auto at = cast<ArrayType>(T);

          
@@ 2537,7 2525,7 @@ const sc_type_t *sc_array_type_set_zterm
     return T;
 }
 
-const sc_type_t *sc_array_type_set_count(const sc_type_t *T, size_t count) {
+sc_type_t sc_array_type_set_count(sc_type_t T, size_t count) {
     using namespace scopes;
     if (is_kind<TK_Array>(T)) {
         auto at = cast<ArrayType>(T);

          
@@ 2546,7 2534,7 @@ const sc_type_t *sc_array_type_set_count
     return T;
 }
 
-bool sc_array_type_is_zterm(const sc_type_t *T) {
+bool sc_array_type_is_zterm(sc_type_t T) {
     using namespace scopes;
     if (is_kind<TK_Array>(T)) {
         return cast<ArrayType>(T)->is_zterm();

          
@@ 2557,7 2545,7 @@ bool sc_array_type_is_zterm(const sc_typ
 // Vector Type
 ////////////////////////////////////////////////////////////////////////////////
 
-sc_type_raises_t sc_vector_type(const sc_type_t *element_type, size_t count) {
+sc_type_raises_t sc_vector_type(sc_type_t element_type, size_t count) {
     using namespace scopes;
     return convert_result(vector_type(element_type, count));
 }

          
@@ 2565,7 2553,7 @@ sc_type_raises_t sc_vector_type(const sc
 // Matrix Type
 ////////////////////////////////////////////////////////////////////////////////
 
-sc_type_raises_t sc_matrix_type(const sc_type_t *element_type, size_t count) {
+sc_type_raises_t sc_matrix_type(sc_type_t element_type, size_t count) {
     using namespace scopes;
     return convert_result(matrix_type(element_type, count));
 }

          
@@ 2573,7 2561,7 @@ sc_type_raises_t sc_matrix_type(const sc
 // Tuple Type
 ////////////////////////////////////////////////////////////////////////////////
 
-sc_type_raises_t sc_tuple_type(int numtypes, const sc_type_t **typeargs) {
+sc_type_raises_t sc_tuple_type(int numtypes, sc_type_t *typeargs) {
     using namespace scopes;
     Types types;
     types.reserve(numtypes);

          
@@ 2583,7 2571,7 @@ sc_type_raises_t sc_tuple_type(int numty
     return convert_result(tuple_type(types));
 }
 
-sc_type_raises_t sc_packed_tuple_type(int numtypes, const sc_type_t **typeargs) {
+sc_type_raises_t sc_packed_tuple_type(int numtypes, sc_type_t *typeargs) {
     using namespace scopes;
     Types types;
     types.reserve(numtypes);

          
@@ 2593,12 2581,12 @@ sc_type_raises_t sc_packed_tuple_type(in
     return convert_result(tuple_type(types, true));
 }
 
-bool sc_tuple_type_is_packed(const sc_type_t *T) {
+bool sc_tuple_type_is_packed(sc_type_t T) {
     using namespace scopes;
     return cast<TupleType>(T)->packed;
 }
 
-sc_type_raises_t sc_union_storage_type(int numtypes, const sc_type_t **typeargs) {
+sc_type_raises_t sc_union_storage_type(int numtypes, sc_type_t *typeargs) {
     using namespace scopes;
     Types types;
     types.reserve(numtypes);

          
@@ 2611,7 2599,7 @@ sc_type_raises_t sc_union_storage_type(i
 // Arguments Type
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_type_t *sc_arguments_type(int numtypes, const sc_type_t **typeargs) {
+sc_type_t sc_arguments_type(int numtypes, sc_type_t *typeargs) {
     using namespace scopes;
     Types types;
     types.reserve(numtypes);

          
@@ 2621,7 2609,7 @@ const sc_type_t *sc_arguments_type(int n
     return arguments_type(types);
 }
 
-const sc_type_t *sc_arguments_type_join(const sc_type_t *T1, const sc_type_t *T2) {
+sc_type_t sc_arguments_type_join(sc_type_t T1, sc_type_t T2) {
     using namespace scopes;
     Types types;
     if (isa<ArgumentsType>(T1)) {

          
@@ 2646,12 2634,12 @@ int sc_arguments_type_argcount(sc_type_t
     return get_argument_count(T);
 }
 
-const sc_type_t *sc_arguments_type_getarg(sc_type_t *T, int index) {
+sc_type_t sc_arguments_type_getarg(sc_type_t *T, int index) {
     using namespace scopes;
     return get_argument(T, index);
 }
 
-const sc_type_t *sc_arguments_type_to_tuple_type(const sc_type_t *T) {
+sc_type_t sc_arguments_type_to_tuple_type(sc_type_t T) {
     using namespace scopes;
     return cast<ArgumentsType>(T)->to_tuple_type();
 }

          
@@ 2659,7 2647,7 @@ const sc_type_t *sc_arguments_type_to_tu
 // Unique Type
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_type_t *sc_view_type(const sc_type_t *type, int id) {
+sc_type_t sc_view_type(sc_type_t type, int id) {
     using namespace scopes;
     if (id < 0)
         return view_type(type, {});

          
@@ 2667,22 2655,22 @@ const sc_type_t *sc_view_type(const sc_t
         return view_type(type, { id });
 }
 
-const sc_type_t *sc_unique_type(const sc_type_t *type, int id) {
+sc_type_t sc_unique_type(sc_type_t type, int id) {
     using namespace scopes;
     return unique_type(type, id);
 }
 
-const sc_type_t *sc_mutate_type(const sc_type_t *type) {
+sc_type_t sc_mutate_type(sc_type_t type) {
     using namespace scopes;
     return mutate_type(type);
 }
 
-const sc_type_t *sc_refer_type(const sc_type_t *type, uint64_t flags, sc_symbol_t storage_class) {
+sc_type_t sc_refer_type(sc_type_t type, uint64_t flags, sc_symbol_t storage_class) {
     using namespace scopes;
     return refer_type(type, flags, Symbol::wrap(storage_class));
 }
 
-uint64_t sc_refer_flags(const sc_type_t *type) {
+uint64_t sc_refer_flags(sc_type_t type) {
     using namespace scopes;
     auto rq = try_qualifier<ReferQualifier>(type);
     if (rq) {

          
@@ 2691,7 2679,7 @@ uint64_t sc_refer_flags(const sc_type_t 
     return 0;
 }
 
-sc_symbol_t sc_refer_storage_class(const sc_type_t *type) {
+sc_symbol_t sc_refer_storage_class(sc_type_t type) {
     using namespace scopes;
     auto rq = try_qualifier<ReferQualifier>(type);
     if (rq) {

          
@@ 2700,12 2688,12 @@ sc_symbol_t sc_refer_storage_class(const
     return SYM_Unnamed;
 }
 
-const sc_type_t *sc_strip_qualifiers(const sc_type_t *type) {
+sc_type_t sc_strip_qualifiers(sc_type_t type) {
     using namespace scopes;
     return strip_qualifiers(type);
 }
 
-const sc_type_t *sc_canonical_type(const sc_type_t *type) {
+sc_type_t sc_canonical_type(sc_type_t type) {
     using namespace scopes;
     return strip_lifetime(type);
 }

          
@@ 2713,7 2701,7 @@ const sc_type_t *sc_canonical_type(const
 // Function Type
 ////////////////////////////////////////////////////////////////////////////////
 
-bool sc_function_type_is_variadic(const sc_type_t *T) {
+bool sc_function_type_is_variadic(sc_type_t T) {
     using namespace scopes;
     T = strip_qualifiers(T);
     if (is_kind<TK_Function>(T)) {

          
@@ 2723,8 2711,8 @@ bool sc_function_type_is_variadic(const 
     return false;
 }
 
-const sc_type_t *sc_function_type(const sc_type_t *return_type,
-    int numtypes, const sc_type_t **typeargs) {
+sc_type_t sc_function_type(sc_type_t return_type,
+    int numtypes, sc_type_t *typeargs) {
     using namespace scopes;
     Types types;
     types.reserve(numtypes);

          
@@ 2739,15 2727,15 @@ const sc_type_t *sc_function_type(const 
     return function_type(return_type, types, flags);
 }
 
-const sc_type_t *sc_function_type_raising(const sc_type_t *T,
-    const sc_type_t *except_type) {
+sc_type_t sc_function_type_raising(sc_type_t T,
+    sc_type_t except_type) {
     using namespace scopes;
     auto ft = cast<FunctionType>(strip_qualifiers(T));
     return raising_function_type(except_type, ft->return_type,
         ft->argument_types, ft->flags);
 }
 
-sc_type_type_tuple_t sc_function_type_return_type(const sc_type_t *T) {
+sc_type_type_tuple_t sc_function_type_return_type(sc_type_t T) {
     using namespace scopes;
     auto val = dyn_cast<FunctionType>(strip_qualifiers(T));
     if (val) {

          
@@ 2760,8 2748,8 @@ sc_type_type_tuple_t sc_function_type_re
 // Image Type
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_type_t *sc_image_type(
-    const sc_type_t *_type,
+sc_type_t sc_image_type(
+    sc_type_t _type,
     sc_symbol_t _dim,
     int _depth,
     int _arrayed,

          
@@ 2774,37 2762,37 @@ const sc_type_t *sc_image_type(
         _multisampled, _sampled, Symbol::wrap(_format), Symbol::wrap(_access));
 }
 
-sc_symbol_t sc_image_type_dim(const sc_type_t *T) {
+sc_symbol_t sc_image_type_dim(sc_type_t T) {
     using namespace scopes;
     return cast<ImageType>(T)->dim.value();
 }
 
-int sc_image_type_depth(const sc_type_t *T) {
+int sc_image_type_depth(sc_type_t T) {
     using namespace scopes;
     return cast<ImageType>(T)->depth;
 }
 
-int sc_image_type_arrayed(const sc_type_t *T) {
+int sc_image_type_arrayed(sc_type_t T) {
     using namespace scopes;
     return cast<ImageType>(T)->arrayed;
 }
 
-int sc_image_type_multisampled(const sc_type_t *T) {
+int sc_image_type_multisampled(sc_type_t T) {
     using namespace scopes;
     return cast<ImageType>(T)->multisampled;
 }
 
-int sc_image_type_sampled(const sc_type_t *T) {
+int sc_image_type_sampled(sc_type_t T) {
     using namespace scopes;
     return cast<ImageType>(T)->sampled;
 }
 
-sc_symbol_t sc_image_type_format(const sc_type_t *T) {
+sc_symbol_t sc_image_type_format(sc_type_t T) {
     using namespace scopes;
     return cast<ImageType>(T)->format.value();
 }
 
-sc_symbol_t sc_image_type_access(const sc_type_t *T) {
+sc_symbol_t sc_image_type_access(sc_type_t T) {
     using namespace scopes;
     return cast<ImageType>(T)->access.value();
 }

          
@@ 2812,7 2800,7 @@ sc_symbol_t sc_image_type_access(const s
 // Sampled Image Type
 ////////////////////////////////////////////////////////////////////////////////
 
-const sc_type_t *sc_sampled_image_type(const sc_type_t *_type) {
+sc_type_t sc_sampled_image_type(sc_type_t _type) {
     using namespace scopes;
     return sampled_image_type(cast<ImageType>(_type));
 }

          
@@ 2820,7 2808,7 @@ const sc_type_t *sc_sampled_image_type(c
 // Inspect API
 ////////////////////////////////////////////////////////////////////////////////
 
-int sc_typed_value_body_count(sc_valueref_t value) {
+int sc_typed_value_body_count(sc_value_t value) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_Function:

          
@@ 2836,7 2824,7 @@ int sc_typed_value_body_count(sc_valuere
     }
 }
 
-sc_valueref_t sc_typed_value_body(sc_valueref_t value, int index) {
+sc_value_t sc_typed_value_body(sc_value_t value, int index) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_Function: return value.cast<Function>()->body;

          
@@ 2861,7 2849,7 @@ sc_valueref_t sc_typed_value_body(sc_val
     return BlockRef();
 }
 
-sc_symbol_t sc_typed_value_name(sc_valueref_t value) {
+sc_symbol_t sc_typed_value_name(sc_value_t value) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_Function: { return value.cast<Function>()->name.value(); } break;

          
@@ 2875,7 2863,7 @@ sc_symbol_t sc_typed_value_name(sc_value
     }
 }
 
-int sc_typed_value_attribute_group_count(sc_valueref_t value) {
+int sc_typed_value_attribute_group_count(sc_value_t value) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_Function:

          
@@ 2919,7 2907,7 @@ int sc_typed_value_attribute_group_count
     }
 }
 
-int sc_typed_value_attribute_count(sc_valueref_t value, int group) {
+int sc_typed_value_attribute_count(sc_value_t value, int group) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_Function: return value.cast<Function>()->params.size();

          
@@ 3006,7 2994,7 @@ int sc_typed_value_attribute_count(sc_va
     return 0;
 }
 
-sc_valueref_t sc_typed_value_attribute_at(sc_valueref_t value, int group, int index) {
+sc_value_t sc_typed_value_attribute_at(sc_value_t value, int group, int index) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_Function: return value.cast<Function>()->params[index];

          
@@ 3175,7 3163,7 @@ sc_valueref_t sc_typed_value_attribute_a
     return ConstAggregate::none_from();
 }
 
-int sc_typed_value_op_kind(sc_valueref_t value) {
+int sc_typed_value_op_kind(sc_value_t value) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_Cast: return value.cast<Cast>()->op;

          
@@ 3191,7 3179,7 @@ int sc_typed_value_op_kind(sc_valueref_t
     return -1;
 }
 
-int sc_typed_value_index_count(sc_valueref_t value) {
+int sc_typed_value_index_count(sc_value_t value) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_ExtractArgument: return 1;

          
@@ 3205,7 3193,7 @@ int sc_typed_value_index_count(sc_valuer
     return 0;
 }
 
-int sc_typed_value_index(sc_valueref_t value, int index) {
+int sc_typed_value_index(sc_value_t value, int index) {
     using namespace scopes;
     switch(value->kind()) {
     case VK_ExtractArgument: return value.cast<ExtractArgument>()->index;

          
@@ 3222,26 3210,26 @@ int sc_typed_value_index(sc_valueref_t v
 // Block
 ////////////////////////////////////////////////////////////////////////////////
 
-int sc_block_instruction_count(sc_valueref_t block) {
+int sc_block_instruction_count(sc_value_t block) {
     using namespace scopes;
     assert(block);
     return block.cast<Block>()->body.size();
 }
 
-sc_valueref_t sc_block_get_instruction(sc_valueref_t block, int index) {
+sc_value_t sc_block_get_instruction(sc_value_t block, int index) {
     using namespace scopes;
     assert(block);
     return block.cast<Block>()->body[index];
 }
 
-sc_valueref_t sc_block_terminator(sc_valueref_t block) {
+sc_value_t sc_block_terminator(sc_value_t block) {
     using namespace scopes;
     assert(block);
     assert(block.cast<Block>()->terminator);
     return block.cast<Block>()->terminator;
 }
 
-bool sc_block_is_terminated(sc_valueref_t block) {
+bool sc_block_is_terminated(sc_value_t block) {
     using namespace scopes;
     return (bool)block.cast<Block>()->terminator;
 }

          
@@ 3260,7 3248,7 @@ static void bind_extern(Symbol globalsym
         nullptr, globals);
 }
 
-static void bind_new_value(Symbol sym, const ValueRef &value) {
+static void bind_new_value(Symbol sym, const Value &value) {
     globals = Scope::bind_from(ConstInt::symbol_from(sym),
         value, nullptr, globals);
 }

          
@@ 3273,11 3261,17 @@ static void bind_extern(Symbol sym, cons
     bind_extern(sym, sym, T);
 }
 
-void init_globals(int argc, char *argv[]) {
-    globals = original_globals;
+void complete_globals(int argc, char *argv[]) {
     scopes_argc = argc;
     scopes_argv = argv;
 
+    linenoiseSetCompletionCallback(prompt_completion_cb);
+
+}
+
+Scope init_globals() {
+    globals = Scope();
+
 #define DEFINE_EXTERN_C_FUNCTION(FUNC, RETTYPE, ...) \
     (void)FUNC; /* ensure that the symbol is there */ \
     bind_extern(Symbol(#FUNC), function_type(RETTYPE, { __VA_ARGS__ }));

          
@@ 3456,12 3450,7 @@ SCOPES_BARRIER_KIND()
     // make fast
     globals->table();
 
-    original_globals = globals;
-
-    linenoiseSetCompletionCallback(prompt_completion_cb);
-
-    // reimport wrapped symbols
-    import_symbols();
+    return globals;
 }
 
 } // namespace scopes

          
M src/globals.hpp +1 -1
@@ 105,7 105,7 @@ namespace scopes {
 SCOPES_REIMPORT_SYMBOLS()
 #undef T
 
-void init_globals(int argc, char *argv[]);
+void complete_globals(int argc, char *argv[]);
 
 } // namespace scopes
 

          
M src/known_symbols.hh +1 -0
@@ 491,6 491,7 @@ 
     T(Style_Symbol, "style-symbol", 0x9748a4cacefb796aull) \
     T(Style_String, "style-string", 0xc9a41afa10270df6ull) \
     T(Style_Number, "style-number", 0x246de8538171c71cull) \
+    T(Style_Constant, "style-constant", 0xf842f2b25a3da71bull) \
     T(Style_Keyword, "style-keyword", 0xea7f9eedd654a4beull) \
     T(Style_Function, "style-function", 0x9bf11a5a304c7086ull) \
     T(Style_SfxFunction, "style-sfxfunction", 0xe7fdd95410be778eull) \

          
M src/scope.hpp +2 -0
@@ 80,6 80,8 @@ public:
 #endif
 
 Scope scope_parent(Scope scope);
+Maybe<String> header_doc(Scope scope);
+Symbols find_elongations(Scope scope, Symbol name);
 
 Scope reparent(Scope content, Scope parent);
 void bind(Scope &scope, Const name, Value value, Maybe<String> doc = {});

          
M src/trace.hpp +3 -2
@@ 14,8 14,7 @@ 
 
 namespace scopes {
 
-struct Anchor;
-template<typename T> struct TValueRef;
+#if 0
 
 /*
 

          
@@ 203,6 202,8 @@ protected:
 
 //------------------------------------------------------------------------------
 
+#endif
+
 } // namespace scopes
 
 #endif // SCOPES_TRACE_HPP
  No newline at end of file

          
M src/value.hpp +6 -0
@@ 309,6 309,12 @@ struct Pure : TypedValue {
     Pure(ValueKind _kind, const Type *type);
 };
 
+#endif
+
+bool key_equal(Pure a, Pure b);
+
+#if 0
+
 //------------------------------------------------------------------------------
 
 struct Template : UntypedValue {

          
M src/value_defs.hh +6 -15
@@ 13,14 13,12 @@ SCOPES_DEFINE_TYPE_BITSET(FunctionFlags)
 SCOPES_DEFINE_TYPE_BITSET(CallTemplateFlags)
 #define TYPE_BITSET_BlockFlags(T) T(TagTraceback, 0) T(IgnorePrematureNoreturn, 1)
 SCOPES_DEFINE_TYPE_BITSET(BlockFlags)
-#define TYPE_ENUM_ValueKind(T, U) T(ParserBadTasteError) T(ParserUnterminatedSequenceError) T(ParserUnexpectedLineBreakError) T(ParserInvalidIntegerSuffixError) T(ParserInvalidRealSuffixError) T(ParserUnclosedOpenBracketError) T(ParserStrayClosingBracketError) T(ParserUnterminatedQuoteError) T(ParserUnexpectedTokenError) T(ParserStrayEscapeTokenError) T(ParserIndentationMismatchError) T(ParserBadIndentationLevelError) T(ParserStrayStatementTokenError) T(SyntaxCallExpressionEmptyError) T(SyntaxTooManyArgumentsError) T(SyntaxNotEnoughArgumentsError) T(SyntaxUnnamedForwardDeclarationError) T(SyntaxVariadicSymbolNotLastError) T(SyntaxAssignmentTokenExpectedError) T(SyntaxKeyedArgumentMismatchError) T(SyntaxUnexpectedExtraTokenError) T(SyntaxUndeclaredIdentifierError) T(SyntaxExceptBlockExpectedError) T(SyntaxMissingDefaultCaseError) T(SyntaxCaseBlockExpectedError) T(SyntaxLabelExpectedError) T(SyntaxSymbolExpanderTypeMismatchError) T(SyntaxListExpanderTypeMismatchError) T(SyntaxExcessBindingArgumentError) T(TypeKindMismatchError) T(ValueKindMismatchError) T(CannotCreateConstantOfError) T(ConstantExpectedError) T(ConstantValueKindMismatchError) T(TypedConstantValueKindMismatchError) T(TooManyArgumentsError) T(NotEnoughArgumentsError) T(CannotTypeInlineError) T(ValueMustBeReferenceError) T(NonReadableReferenceError) T(NonWritableReferenceError) T(NonReadablePointerError) T(NonWritablePointerError) T(MergeConflictError) T(InaccessibleValueError) T(DropReturnsArgumentsError) T(RecursiveDropError) T(SwitchPassMovedValueError) T(CaseValueExpectedError) T(BadIndirectCaseArgumentListError) T(DuplicateCaseLiteralError) T(LoopMovedValueError) T(ViewExitingScopeError) T(MovingGlobalUniqueError) T(DuplicateParameterKeyError) T(UnknownParameterKeyError) T(BreakOutsideLoopError) T(RepeatOutsideLoopError) T(LabelExpectedError) T(RecursiveFunctionChangedTypeError) T(UnknownTupleFieldError) T(PlainToUniqueCastError) T(ManagedPointerCannotLoadError) T(UniqueValueExpectedError) T(CannotDupeManagedPointerError) T(SimilarViewValueExpectedForStoreError) T(IncompatibleStorageTypeForUniqueError) T(SpiceMacroReturnedNullError) T(UnsupportedDimensionalityError) T(UnsupportedExecutionModeError) T(CastCategoryError) T(CastSizeError) T(CastIncompatibleAggregateTypeError) T(InvalidOperandsError) T(InvalidArgumentTypeForBuiltinError) T(UnsupportedBuiltinError) T(InvalidCalleeError) T(TooManyFunctionArgumentsError) T(NotEnoughFunctionArgumentsError) T(DuplicateSwitchDefaultCaseError) T(MissingDefaultCaseError) T(UnclosedPassError) T(DoWithoutPassError) T(VariadicParameterNotLastError) T(RecursionOverflowError) T(ResultMustBePureError) T(GlobalInitializerMustBePureError) T(NoGlobalInitializerError) T(NoGlobalConstructorError) T(ParameterTypeMismatchError) T(FunctionPointerExpectedError) T(ScalarOrVectorExpectedError) T(FixedVectorSizeMismatchError) T(VectorSizeMismatchError) T(TypeMismatchError) T(InvalidMatrixSizeError) T(ConditionNotBoolError) T(UnexpectedValueKindError) T(UnresolvedValueError) T(PtrToGlobalHandlerMissingError) T(CannotSerializeTypeError) T(PrematureReturnFromExpressionError) T(OpaqueTypeError) T(UntrackedTypeError) T(MovableTypeMismatchError) T(DupeUniqueStorageError) T(GenericIndexOutOfRangeError) T(ShuffleVectorIndexOutOfRangeError) T(ExtractStringConstantIndexOutOfRangeError) T(ArgumentsTypeIndexOutOfRangeError) T(FunctionTypeIndexOutOfRangeError) T(ArrayOrVectorTypeIndexOutOfRangeError) T(TupleTypeIndexOutOfRangeError) T(TypenameCompleteError) T(TypenameIncompleteError) T(TypenameIncompatibleStorageError) T(StorageTypeExpectedError) T(PlainStorageTypeExpectedError) T(VariableOutOfScopeError) T(UnboundValueError) T(CannotProveForwardDeclarationError) T(QuoteUnsupportedValueKindError) T(QuoteUnboundValueError) T(CGenTypeUnsupportedInTargetError) T(CGenFailedToTranslateTypeError) T(CGenUnboundValueError) T(CGenInvalidRedeclarationError) T(CGenUnsupportedBuiltinError) T(CGenUnsupportedArrayAllocError) T(CGenUnsupportedMallocError) T(CGenUnsupportedUnOpError) T(CGenUnsupportedBinOpError) T(CGenUnsupportedTriOpError) T(CGenUnsupportedImageOpError) T(CGenUnsupportedCastOpError) T(CGenUnsupportedAtomicOpError) T(CGenUnsupportedTargetError) T(CGenInvalidCalleeError) T(CGenFailedToTranslateValueError) T(CGenUnsupportedInstructionError) T(CGenFailedToResolveExternError) T(CGenRecursiveConstructorError) T(CGenBackendFailedError) T(CGenBackendFailedErrnoError) T(CGenCannotSerializeConstPointerError) T(CGenBackendValidationFailedError) T(CGenBackendOptimizationFailedError) T(CGenUnsupportedCapabilityError) T(CGenUnsupportedDimensionalityError) T(CGenUnsupportedImageFormatError) T(CGenUnsupportedExecutionModeError) T(CGenUnrecognizedSymbolicMaskError) T(CGenUnsupportedPointerStorageClassError) T(CGenUnsupportedArgumentPointerStorageClassError) T(CGenUnsupportedBufferAlignmentError) T(CGenUnsupportedReturnArgumentError) T(CGenUnsupportedIntrinsicError) T(CGenEntryFunctionSignatureMismatchError) T(CGenUnsupportedVectorSizeError) T(CGenUnsupportedMatrixSizeError) T(RTLoadLibraryFailedError) T(RTGetAddressFailedError) T(RTMissingKeyError) T(RTMissingScopeAnyAttributeError) T(RTMissingLocalScopeAnyAttributeError) T(RTMissingScopeAttributeError) T(RTMissingLocalScopeAttributeError) T(RTMissingTypeAttributeError) T(RTMissingLocalTypeAttributeError) T(RTMissingTupleAttributeError) T(RTRegExError) T(RTUnableToOpenFileError) T(RTUncountableStorageTypeError) T(RTNoElementsInStorageTypeError) T(RTNoNamedElementsInStorageTypeError) T(RTTypeBitcountMismatchError) T(RTUndefinedAttributeError) T(MainInaccessibleBinaryError) T(InvalidFooterError) T(CoreModuleFunctionTypeMismatchError) T(CoreMissingError) T(UserError) T(ExecutionEngineFailedError) T(OptimizationPassFailedError) T(StackOverflowError) T(SourceText) T(SourceLocation) T(UnknownOriginTrace) T(DummyTrace) T(TraceTrace) T(CallTrace) T(ParserTrace) T(ExpanderTrace) T(InvokeHookTrace) T(ProveExpressionTrace) T(ProveTemplateTrace) T(ProveArgumentTrace) T(ProveParamMapTrace) T(ProveArgumentLifetimeTrace) T(ProveDropTrace) T(TranslateTrace) T(QuoteTrace) T(UnwrapTrace) T(BuiltinTrace) T(BindSymbolTrace) T(FollowSymbolTrace) T(BindExprTrace) T(FollowExprTrace) T(ConvertForeignTypeTrace) T(ConvertForeignValueTrace) T(UserTrace) T(String) T(Symbol) T(Builtin) T(ListBuffer) T(ListSlice) T(ScopeL) T(ScopeB) T(Closure) T(QualifyType) T(ArgumentsType) T(TypenameType) T(IntegerType) T(RealType) T(PointerType) T(ArrayType) T(VectorType) T(MatrixType) T(TupleType) T(FunctionType) T(SamplerType) T(ImageType) T(SampledImageType) T(ReferQualifier) T(UniqueQualifier) T(ViewQualifier) T(MutateQualifier) T(KeyQualifier) T(Template) T(UserLabelTemplate) T(InlineLabelTemplate) T(TryLabelTemplate) T(ExceptLabelTemplate) T(ExceptAllLabelTemplate) T(ThenLabelTemplate) T(BreakLabelTemplate) T(BranchMergeLabelTemplate) T(TypeOfLabelTemplate) T(Loop) T(LoopArguments) T(KeyedTemplate) T(Expression) T(Quote) T(Unquote) T(CompileStage) T(CondTemplate) T(SwitchTemplate) T(Case) T(Pass) T(DoCase) T(DefaultCase) T(MergeTemplate) T(CallTemplate) T(ArgumentListTemplate) T(ExtractArgumentTemplate) T(ParameterTemplate) T(Keyed) T(Parameter) T(Exception) T(ArgumentList) T(Block) T(ExtractArgument) T(LoopLabelArguments) T(Function) T(Global) T(PureCast) T(Undef) T(ConstNull) T(ConstInt) T(ConstReal) T(ConstString) T(ConstAggregate) T(ConstPointer) T(ConstValue) T(UserLabel) T(InlineLabel) T(TryLabel) T(ExceptLabel) T(ExceptAllLabel) T(ThenLabel) T(BreakLabel) T(BranchMergeLabel) T(TypeOfLabel) T(LoopLabel) T(CondBr) T(Switch) T(Call) T(Select) T(ExtractValue) T(InsertValue) T(GetElementPtr) T(ExtractElement) T(InsertElement) T(ShuffleVector) T(Alloca) T(Malloc) T(Free) T(Load) T(Store) T(AtomicXchg) T(AtomicAdd) T(AtomicSub) T(AtomicBAnd) T(AtomicBNAnd) T(AtomicBOr) T(AtomicBXor) T(AtomicSMin) T(AtomicSMax) T(AtomicUMin) T(AtomicUMax) T(AtomicFAdd) T(AtomicFSub) T(CmpXchg) T(BarrierControl) T(BarrierMemory) T(BarrierMemoryGroup) T(BarrierMemoryImage) T(BarrierMemoryBuffer) T(BarrierMemoryShared) T(ICmpEQ) T(ICmpNE) T(ICmpUGT) T(ICmpUGE) T(ICmpULT) T(ICmpULE) T(ICmpSGT) T(ICmpSGE) T(ICmpSLT) T(ICmpSLE) T(FCmpOEQ) T(FCmpONE) T(FCmpORD) T(FCmpOGT) T(FCmpOGE) T(FCmpOLT) T(FCmpOLE) T(FCmpUEQ) T(FCmpUNE) T(FCmpUNO) T(FCmpUGT) T(FCmpUGE) T(FCmpULT) T(FCmpULE) T(UnOpBitReverse) T(UnOpBitCount) T(UnOpFindMSB) T(UnOpFindLSB) T(UnOpFNeg) T(UnOpSin) T(UnOpCos) T(UnOpTan) T(UnOpAsin) T(UnOpAcos) T(UnOpAtan) T(UnOpSinh) T(UnOpCosh) T(UnOpTanh) T(UnOpASinh) T(UnOpACosh) T(UnOpATanh) T(UnOpTrunc) T(UnOpFloor) T(UnOpFAbs) T(UnOpLog) T(UnOpLog2) T(UnOpExp) T(UnOpExp2) T(UnOpSqrt) T(BinOpAdd) T(BinOpAddNUW) T(BinOpAddNSW) T(BinOpSub) T(BinOpSubNUW) T(BinOpSubNSW) T(BinOpMul) T(BinOpMulNUW) T(BinOpMulNSW) T(BinOpUDiv) T(BinOpSDiv) T(BinOpURem) T(BinOpSRem) T(BinOpShl) T(BinOpLShr) T(BinOpAShr) T(BinOpBAnd) T(BinOpBOr) T(BinOpBXor) T(BinOpFAdd) T(BinOpFSub) T(BinOpFMul) T(BinOpFDiv) T(BinOpFRem) T(BinOpAtan2) T(BinOpPow) T(Annotate) T(ExecutionMode) T(CastBitcast) T(CastIntToPtr) T(CastPtrToInt) T(CastSExt) T(CastITrunc) T(CastZExt) T(CastFPTrunc) T(CastFPExt) T(CastFPToUI) T(CastFPToSI) T(CastUIToFP) T(CastSIToFP) T(CastPtrToRef) T(CastRefToPtr) T(CastCellToData) T(CastDataToCell) T(Merge) T(Repeat) T(Return) T(Raise) T(Unreachable) T(Discard)
+#define TYPE_ENUM_ValueKind(T, U) T(ParserBadTasteError) T(ParserUnterminatedSequenceError) T(ParserUnexpectedLineBreakError) T(ParserInvalidIntegerSuffixError) T(ParserInvalidRealSuffixError) T(ParserUnclosedOpenBracketError) T(ParserStrayClosingBracketError) T(ParserUnterminatedQuoteError) T(ParserUnexpectedTokenError) T(ParserStrayEscapeTokenError) T(ParserIndentationMismatchError) T(ParserBadIndentationLevelError) T(ParserStrayStatementTokenError) T(SyntaxCallExpressionEmptyError) T(SyntaxTooManyArgumentsError) T(SyntaxNotEnoughArgumentsError) T(SyntaxUnnamedForwardDeclarationError) T(SyntaxVariadicSymbolNotLastError) T(SyntaxAssignmentTokenExpectedError) T(SyntaxKeyedArgumentMismatchError) T(SyntaxUnexpectedExtraTokenError) T(SyntaxUndeclaredIdentifierError) T(SyntaxExceptBlockExpectedError) T(SyntaxMissingDefaultCaseError) T(SyntaxCaseBlockExpectedError) T(SyntaxLabelExpectedError) T(SyntaxSymbolExpanderTypeMismatchError) T(SyntaxListExpanderTypeMismatchError) T(SyntaxExcessBindingArgumentError) T(TypeKindMismatchError) T(ValueKindMismatchError) T(CannotCreateConstantOfError) T(ConstantExpectedError) T(ConstantValueKindMismatchError) T(TypedConstantValueKindMismatchError) T(TooManyArgumentsError) T(NotEnoughArgumentsError) T(CannotTypeInlineError) T(ValueMustBeReferenceError) T(NonReadableReferenceError) T(NonWritableReferenceError) T(NonReadablePointerError) T(NonWritablePointerError) T(MergeConflictError) T(InaccessibleValueError) T(DropReturnsArgumentsError) T(RecursiveDropError) T(SwitchPassMovedValueError) T(CaseValueExpectedError) T(BadIndirectCaseArgumentListError) T(DuplicateCaseLiteralError) T(LoopMovedValueError) T(ViewExitingScopeError) T(MovingGlobalUniqueError) T(DuplicateParameterKeyError) T(UnknownParameterKeyError) T(BreakOutsideLoopError) T(RepeatOutsideLoopError) T(LabelExpectedError) T(RecursiveFunctionChangedTypeError) T(UnknownTupleFieldError) T(PlainToUniqueCastError) T(ManagedPointerCannotLoadError) T(UniqueValueExpectedError) T(CannotDupeManagedPointerError) T(SimilarViewValueExpectedForStoreError) T(IncompatibleStorageTypeForUniqueError) T(SpiceMacroReturnedNullError) T(UnsupportedDimensionalityError) T(UnsupportedExecutionModeError) T(CastCategoryError) T(CastSizeError) T(CastIncompatibleAggregateTypeError) T(InvalidOperandsError) T(InvalidArgumentTypeForBuiltinError) T(UnsupportedBuiltinError) T(InvalidCalleeError) T(TooManyFunctionArgumentsError) T(NotEnoughFunctionArgumentsError) T(DuplicateSwitchDefaultCaseError) T(MissingDefaultCaseError) T(UnclosedPassError) T(DoWithoutPassError) T(VariadicParameterNotLastError) T(RecursionOverflowError) T(ResultMustBePureError) T(GlobalInitializerMustBePureError) T(NoGlobalInitializerError) T(NoGlobalConstructorError) T(ParameterTypeMismatchError) T(FunctionPointerExpectedError) T(ScalarOrVectorExpectedError) T(FixedVectorSizeMismatchError) T(VectorSizeMismatchError) T(TypeMismatchError) T(InvalidMatrixSizeError) T(ConditionNotBoolError) T(UnexpectedValueKindError) T(UnresolvedValueError) T(PtrToGlobalHandlerMissingError) T(CannotSerializeTypeError) T(PrematureReturnFromExpressionError) T(OpaqueTypeError) T(UntrackedTypeError) T(MovableTypeMismatchError) T(DupeUniqueStorageError) T(GenericIndexOutOfRangeError) T(ShuffleVectorIndexOutOfRangeError) T(ExtractStringConstantIndexOutOfRangeError) T(ArgumentsTypeIndexOutOfRangeError) T(FunctionTypeIndexOutOfRangeError) T(ArrayOrVectorTypeIndexOutOfRangeError) T(TupleTypeIndexOutOfRangeError) T(TypenameCompleteError) T(TypenameIncompleteError) T(TypenameIncompatibleStorageError) T(StorageTypeExpectedError) T(PlainStorageTypeExpectedError) T(VariableOutOfScopeError) T(UnboundValueError) T(CannotProveForwardDeclarationError) T(QuoteUnsupportedValueKindError) T(QuoteUnboundValueError) T(CGenTypeUnsupportedInTargetError) T(CGenFailedToTranslateTypeError) T(CGenUnboundValueError) T(CGenInvalidRedeclarationError) T(CGenUnsupportedBuiltinError) T(CGenUnsupportedArrayAllocError) T(CGenUnsupportedMallocError) T(CGenUnsupportedUnOpError) T(CGenUnsupportedBinOpError) T(CGenUnsupportedTriOpError) T(CGenUnsupportedImageOpError) T(CGenUnsupportedCastOpError) T(CGenUnsupportedAtomicOpError) T(CGenUnsupportedTargetError) T(CGenInvalidCalleeError) T(CGenFailedToTranslateValueError) T(CGenUnsupportedInstructionError) T(CGenFailedToResolveExternError) T(CGenRecursiveConstructorError) T(CGenBackendFailedError) T(CGenBackendFailedErrnoError) T(CGenCannotSerializeConstPointerError) T(CGenBackendValidationFailedError) T(CGenBackendOptimizationFailedError) T(CGenUnsupportedCapabilityError) T(CGenUnsupportedDimensionalityError) T(CGenUnsupportedImageFormatError) T(CGenUnsupportedExecutionModeError) T(CGenUnrecognizedSymbolicMaskError) T(CGenUnsupportedPointerStorageClassError) T(CGenUnsupportedArgumentPointerStorageClassError) T(CGenUnsupportedBufferAlignmentError) T(CGenUnsupportedReturnArgumentError) T(CGenUnsupportedIntrinsicError) T(CGenEntryFunctionSignatureMismatchError) T(CGenUnsupportedVectorSizeError) T(CGenUnsupportedMatrixSizeError) T(RTLoadLibraryFailedError) T(RTGetAddressFailedError) T(RTMissingKeyError) T(RTMissingScopeAnyAttributeError) T(RTMissingLocalScopeAnyAttributeError) T(RTMissingScopeAttributeError) T(RTMissingLocalScopeAttributeError) T(RTMissingTypeAttributeError) T(RTMissingLocalTypeAttributeError) T(RTMissingTupleAttributeError) T(RTRegExError) T(RTUnableToOpenFileError) T(RTUncountableStorageTypeError) T(RTNoElementsInStorageTypeError) T(RTNoNamedElementsInStorageTypeError) T(RTTypeBitcountMismatchError) T(RTUndefinedAttributeError) T(MainInaccessibleBinaryError) T(InvalidFooterError) T(CoreModuleFunctionTypeMismatchError) T(CoreMissingError) T(UserError) T(ExecutionEngineFailedError) T(OptimizationPassFailedError) T(StackOverflowError) T(SourceText) T(SourceLocation) T(UnknownOriginTrace) T(DummyTrace) T(TraceTrace) T(CallTrace) T(ParserTrace) T(ExpanderTrace) T(InvokeHookTrace) T(ProveExpressionTrace) T(ProveTemplateTrace) T(ProveArgumentTrace) T(ProveParamMapTrace) T(ProveArgumentLifetimeTrace) T(ProveDropTrace) T(TranslateTrace) T(QuoteTrace) T(UnwrapTrace) T(BuiltinTrace) T(BindSymbolTrace) T(FollowSymbolTrace) T(BindExprTrace) T(FollowExprTrace) T(ConvertForeignTypeTrace) T(ConvertForeignValueTrace) T(UserTrace) T(String) T(Symbol) T(Builtin) T(ListBuffer) T(ListSlice) T(ScopeCell) T(Closure) T(QualifyType) T(ArgumentsType) T(TypenameType) T(IntegerType) T(RealType) T(PointerType) T(ArrayType) T(VectorType) T(MatrixType) T(TupleType) T(FunctionType) T(SamplerType) T(ImageType) T(SampledImageType) T(ReferQualifier) T(UniqueQualifier) T(ViewQualifier) T(MutateQualifier) T(KeyQualifier) T(Template) T(UserLabelTemplate) T(InlineLabelTemplate) T(TryLabelTemplate) T(ExceptLabelTemplate) T(ExceptAllLabelTemplate) T(ThenLabelTemplate) T(BreakLabelTemplate) T(BranchMergeLabelTemplate) T(TypeOfLabelTemplate) T(Loop) T(LoopArguments) T(KeyedTemplate) T(Expression) T(Quote) T(Unquote) T(CompileStage) T(CondTemplate) T(SwitchTemplate) T(Case) T(Pass) T(DoCase) T(DefaultCase) T(MergeTemplate) T(CallTemplate) T(ArgumentListTemplate) T(ExtractArgumentTemplate) T(ParameterTemplate) T(Keyed) T(Parameter) T(Exception) T(ArgumentList) T(Block) T(ExtractArgument) T(LoopLabelArguments) T(Function) T(Global) T(PureCast) T(Undef) T(ConstNull) T(ConstInt) T(ConstReal) T(ConstString) T(ConstAggregate) T(ConstPointer) T(ConstValue) T(UserLabel) T(InlineLabel) T(TryLabel) T(ExceptLabel) T(ExceptAllLabel) T(ThenLabel) T(BreakLabel) T(BranchMergeLabel) T(TypeOfLabel) T(LoopLabel) T(CondBr) T(Switch) T(Call) T(Select) T(ExtractValue) T(InsertValue) T(GetElementPtr) T(ExtractElement) T(InsertElement) T(ShuffleVector) T(Alloca) T(Malloc) T(Free) T(Load) T(Store) T(AtomicXchg) T(AtomicAdd) T(AtomicSub) T(AtomicBAnd) T(AtomicBNAnd) T(AtomicBOr) T(AtomicBXor) T(AtomicSMin) T(AtomicSMax) T(AtomicUMin) T(AtomicUMax) T(AtomicFAdd) T(AtomicFSub) T(CmpXchg) T(BarrierControl) T(BarrierMemory) T(BarrierMemoryGroup) T(BarrierMemoryImage) T(BarrierMemoryBuffer) T(BarrierMemoryShared) T(ICmpEQ) T(ICmpNE) T(ICmpUGT) T(ICmpUGE) T(ICmpULT) T(ICmpULE) T(ICmpSGT) T(ICmpSGE) T(ICmpSLT) T(ICmpSLE) T(FCmpOEQ) T(FCmpONE) T(FCmpORD) T(FCmpOGT) T(FCmpOGE) T(FCmpOLT) T(FCmpOLE) T(FCmpUEQ) T(FCmpUNE) T(FCmpUNO) T(FCmpUGT) T(FCmpUGE) T(FCmpULT) T(FCmpULE) T(UnOpBitReverse) T(UnOpBitCount) T(UnOpFindMSB) T(UnOpFindLSB) T(UnOpFNeg) T(UnOpSin) T(UnOpCos) T(UnOpTan) T(UnOpAsin) T(UnOpAcos) T(UnOpAtan) T(UnOpSinh) T(UnOpCosh) T(UnOpTanh) T(UnOpASinh) T(UnOpACosh) T(UnOpATanh) T(UnOpTrunc) T(UnOpFloor) T(UnOpFAbs) T(UnOpLog) T(UnOpLog2) T(UnOpExp) T(UnOpExp2) T(UnOpSqrt) T(BinOpAdd) T(BinOpAddNUW) T(BinOpAddNSW) T(BinOpSub) T(BinOpSubNUW) T(BinOpSubNSW) T(BinOpMul) T(BinOpMulNUW) T(BinOpMulNSW) T(BinOpUDiv) T(BinOpSDiv) T(BinOpURem) T(BinOpSRem) T(BinOpShl) T(BinOpLShr) T(BinOpAShr) T(BinOpBAnd) T(BinOpBOr) T(BinOpBXor) T(BinOpFAdd) T(BinOpFSub) T(BinOpFMul) T(BinOpFDiv) T(BinOpFRem) T(BinOpAtan2) T(BinOpPow) T(Annotate) T(ExecutionMode) T(CastBitcast) T(CastIntToPtr) T(CastPtrToInt) T(CastSExt) T(CastITrunc) T(CastZExt) T(CastFPTrunc) T(CastFPExt) T(CastFPToUI) T(CastFPToSI) T(CastUIToFP) T(CastSIToFP) T(CastPtrToRef) T(CastRefToPtr) T(CastCellToData) T(CastDataToCell) T(Merge) T(Repeat) T(Return) T(Raise) T(Unreachable) T(Discard)
 SCOPES_DEFINE_TYPE_ENUM(ValueKind)
 #define TYPE_ENUM_ErrorKind(T, U) U(ParserBadTasteError, ValueKind) U(ParserUnterminatedSequenceError, ValueKind) U(ParserUnexpectedLineBreakError, ValueKind) U(ParserInvalidIntegerSuffixError, ValueKind) U(ParserInvalidRealSuffixError, ValueKind) U(ParserUnclosedOpenBracketError, ValueKind) U(ParserStrayClosingBracketError, ValueKind) U(ParserUnterminatedQuoteError, ValueKind) U(ParserUnexpectedTokenError, ValueKind) U(ParserStrayEscapeTokenError, ValueKind) U(ParserIndentationMismatchError, ValueKind) U(ParserBadIndentationLevelError, ValueKind) U(ParserStrayStatementTokenError, ValueKind) U(SyntaxCallExpressionEmptyError, ValueKind) U(SyntaxTooManyArgumentsError, ValueKind) U(SyntaxNotEnoughArgumentsError, ValueKind) U(SyntaxUnnamedForwardDeclarationError, ValueKind) U(SyntaxVariadicSymbolNotLastError, ValueKind) U(SyntaxAssignmentTokenExpectedError, ValueKind) U(SyntaxKeyedArgumentMismatchError, ValueKind) U(SyntaxUnexpectedExtraTokenError, ValueKind) U(SyntaxUndeclaredIdentifierError, ValueKind) U(SyntaxExceptBlockExpectedError, ValueKind) U(SyntaxMissingDefaultCaseError, ValueKind) U(SyntaxCaseBlockExpectedError, ValueKind) U(SyntaxLabelExpectedError, ValueKind) U(SyntaxSymbolExpanderTypeMismatchError, ValueKind) U(SyntaxListExpanderTypeMismatchError, ValueKind) U(SyntaxExcessBindingArgumentError, ValueKind) U(TypeKindMismatchError, ValueKind) U(ValueKindMismatchError, ValueKind) U(CannotCreateConstantOfError, ValueKind) U(ConstantExpectedError, ValueKind) U(ConstantValueKindMismatchError, ValueKind) U(TypedConstantValueKindMismatchError, ValueKind) U(TooManyArgumentsError, ValueKind) U(NotEnoughArgumentsError, ValueKind) U(CannotTypeInlineError, ValueKind) U(ValueMustBeReferenceError, ValueKind) U(NonReadableReferenceError, ValueKind) U(NonWritableReferenceError, ValueKind) U(NonReadablePointerError, ValueKind) U(NonWritablePointerError, ValueKind) U(MergeConflictError, ValueKind) U(InaccessibleValueError, ValueKind) U(DropReturnsArgumentsError, ValueKind) U(RecursiveDropError, ValueKind) U(SwitchPassMovedValueError, ValueKind) U(CaseValueExpectedError, ValueKind) U(BadIndirectCaseArgumentListError, ValueKind) U(DuplicateCaseLiteralError, ValueKind) U(LoopMovedValueError, ValueKind) U(ViewExitingScopeError, ValueKind) U(MovingGlobalUniqueError, ValueKind) U(DuplicateParameterKeyError, ValueKind) U(UnknownParameterKeyError, ValueKind) U(BreakOutsideLoopError, ValueKind) U(RepeatOutsideLoopError, ValueKind) U(LabelExpectedError, ValueKind) U(RecursiveFunctionChangedTypeError, ValueKind) U(UnknownTupleFieldError, ValueKind) U(PlainToUniqueCastError, ValueKind) U(ManagedPointerCannotLoadError, ValueKind) U(UniqueValueExpectedError, ValueKind) U(CannotDupeManagedPointerError, ValueKind) U(SimilarViewValueExpectedForStoreError, ValueKind) U(IncompatibleStorageTypeForUniqueError, ValueKind) U(SpiceMacroReturnedNullError, ValueKind) U(UnsupportedDimensionalityError, ValueKind) U(UnsupportedExecutionModeError, ValueKind) U(CastCategoryError, ValueKind) U(CastSizeError, ValueKind) U(CastIncompatibleAggregateTypeError, ValueKind) U(InvalidOperandsError, ValueKind) U(InvalidArgumentTypeForBuiltinError, ValueKind) U(UnsupportedBuiltinError, ValueKind) U(InvalidCalleeError, ValueKind) U(TooManyFunctionArgumentsError, ValueKind) U(NotEnoughFunctionArgumentsError, ValueKind) U(DuplicateSwitchDefaultCaseError, ValueKind) U(MissingDefaultCaseError, ValueKind) U(UnclosedPassError, ValueKind) U(DoWithoutPassError, ValueKind) U(VariadicParameterNotLastError, ValueKind) U(RecursionOverflowError, ValueKind) U(ResultMustBePureError, ValueKind) U(GlobalInitializerMustBePureError, ValueKind) U(NoGlobalInitializerError, ValueKind) U(NoGlobalConstructorError, ValueKind) U(ParameterTypeMismatchError, ValueKind) U(FunctionPointerExpectedError, ValueKind) U(ScalarOrVectorExpectedError, ValueKind) U(FixedVectorSizeMismatchError, ValueKind) U(VectorSizeMismatchError, ValueKind) U(TypeMismatchError, ValueKind) U(InvalidMatrixSizeError, ValueKind) U(ConditionNotBoolError, ValueKind) U(UnexpectedValueKindError, ValueKind) U(UnresolvedValueError, ValueKind) U(PtrToGlobalHandlerMissingError, ValueKind) U(CannotSerializeTypeError, ValueKind) U(PrematureReturnFromExpressionError, ValueKind) U(OpaqueTypeError, ValueKind) U(UntrackedTypeError, ValueKind) U(MovableTypeMismatchError, ValueKind) U(DupeUniqueStorageError, ValueKind) U(GenericIndexOutOfRangeError, ValueKind) U(ShuffleVectorIndexOutOfRangeError, ValueKind) U(ExtractStringConstantIndexOutOfRangeError, ValueKind) U(ArgumentsTypeIndexOutOfRangeError, ValueKind) U(FunctionTypeIndexOutOfRangeError, ValueKind) U(ArrayOrVectorTypeIndexOutOfRangeError, ValueKind) U(TupleTypeIndexOutOfRangeError, ValueKind) U(TypenameCompleteError, ValueKind) U(TypenameIncompleteError, ValueKind) U(TypenameIncompatibleStorageError, ValueKind) U(StorageTypeExpectedError, ValueKind) U(PlainStorageTypeExpectedError, ValueKind) U(VariableOutOfScopeError, ValueKind) U(UnboundValueError, ValueKind) U(CannotProveForwardDeclarationError, ValueKind) U(QuoteUnsupportedValueKindError, ValueKind) U(QuoteUnboundValueError, ValueKind) U(CGenTypeUnsupportedInTargetError, ValueKind) U(CGenFailedToTranslateTypeError, ValueKind) U(CGenUnboundValueError, ValueKind) U(CGenInvalidRedeclarationError, ValueKind) U(CGenUnsupportedBuiltinError, ValueKind) U(CGenUnsupportedArrayAllocError, ValueKind) U(CGenUnsupportedMallocError, ValueKind) U(CGenUnsupportedUnOpError, ValueKind) U(CGenUnsupportedBinOpError, ValueKind) U(CGenUnsupportedTriOpError, ValueKind) U(CGenUnsupportedImageOpError, ValueKind) U(CGenUnsupportedCastOpError, ValueKind) U(CGenUnsupportedAtomicOpError, ValueKind) U(CGenUnsupportedTargetError, ValueKind) U(CGenInvalidCalleeError, ValueKind) U(CGenFailedToTranslateValueError, ValueKind) U(CGenUnsupportedInstructionError, ValueKind) U(CGenFailedToResolveExternError, ValueKind) U(CGenRecursiveConstructorError, ValueKind) U(CGenBackendFailedError, ValueKind) U(CGenBackendFailedErrnoError, ValueKind) U(CGenCannotSerializeConstPointerError, ValueKind) U(CGenBackendValidationFailedError, ValueKind) U(CGenBackendOptimizationFailedError, ValueKind) U(CGenUnsupportedCapabilityError, ValueKind) U(CGenUnsupportedDimensionalityError, ValueKind) U(CGenUnsupportedImageFormatError, ValueKind) U(CGenUnsupportedExecutionModeError, ValueKind) U(CGenUnrecognizedSymbolicMaskError, ValueKind) U(CGenUnsupportedPointerStorageClassError, ValueKind) U(CGenUnsupportedArgumentPointerStorageClassError, ValueKind) U(CGenUnsupportedBufferAlignmentError, ValueKind) U(CGenUnsupportedReturnArgumentError, ValueKind) U(CGenUnsupportedIntrinsicError, ValueKind) U(CGenEntryFunctionSignatureMismatchError, ValueKind) U(CGenUnsupportedVectorSizeError, ValueKind) U(CGenUnsupportedMatrixSizeError, ValueKind) U(RTLoadLibraryFailedError, ValueKind) U(RTGetAddressFailedError, ValueKind) U(RTMissingKeyError, ValueKind) U(RTMissingScopeAnyAttributeError, ValueKind) U(RTMissingLocalScopeAnyAttributeError, ValueKind) U(RTMissingScopeAttributeError, ValueKind) U(RTMissingLocalScopeAttributeError, ValueKind) U(RTMissingTypeAttributeError, ValueKind) U(RTMissingLocalTypeAttributeError, ValueKind) U(RTMissingTupleAttributeError, ValueKind) U(RTRegExError, ValueKind) U(RTUnableToOpenFileError, ValueKind) U(RTUncountableStorageTypeError, ValueKind) U(RTNoElementsInStorageTypeError, ValueKind) U(RTNoNamedElementsInStorageTypeError, ValueKind) U(RTTypeBitcountMismatchError, ValueKind) U(RTUndefinedAttributeError, ValueKind) U(MainInaccessibleBinaryError, ValueKind) U(InvalidFooterError, ValueKind) U(CoreModuleFunctionTypeMismatchError, ValueKind) U(CoreMissingError, ValueKind) U(UserError, ValueKind) U(ExecutionEngineFailedError, ValueKind) U(OptimizationPassFailedError, ValueKind) U(StackOverflowError, ValueKind)
 SCOPES_DEFINE_TYPE_ENUM(ErrorKind)
 #define TYPE_ENUM_TraceKind(T, U) U(UnknownOriginTrace, ValueKind) U(DummyTrace, ValueKind) U(TraceTrace, ValueKind) U(CallTrace, ValueKind) U(ParserTrace, ValueKind) U(ExpanderTrace, ValueKind) U(InvokeHookTrace, ValueKind) U(ProveExpressionTrace, ValueKind) U(ProveTemplateTrace, ValueKind) U(ProveArgumentTrace, ValueKind) U(ProveParamMapTrace, ValueKind) U(ProveArgumentLifetimeTrace, ValueKind) U(ProveDropTrace, ValueKind) U(TranslateTrace, ValueKind) U(QuoteTrace, ValueKind) U(UnwrapTrace, ValueKind) U(BuiltinTrace, ValueKind) U(BindSymbolTrace, ValueKind) U(FollowSymbolTrace, ValueKind) U(BindExprTrace, ValueKind) U(FollowExprTrace, ValueKind) U(ConvertForeignTypeTrace, ValueKind) U(ConvertForeignValueTrace, ValueKind) U(UserTrace, ValueKind)
 SCOPES_DEFINE_TYPE_ENUM(TraceKind)
-#define TYPE_ENUM_ScopeKind(T, U) U(ScopeL, ValueKind) U(ScopeB, ValueKind)
-SCOPES_DEFINE_TYPE_ENUM(ScopeKind)
 #define TYPE_ENUM_TypeKind(T, U) U(QualifyType, ValueKind) U(ArgumentsType, ValueKind) U(TypenameType, ValueKind) U(IntegerType, ValueKind) U(RealType, ValueKind) U(PointerType, ValueKind) U(ArrayType, ValueKind) U(VectorType, ValueKind) U(MatrixType, ValueKind) U(TupleType, ValueKind) U(FunctionType, ValueKind) U(SamplerType, ValueKind) U(ImageType, ValueKind) U(SampledImageType, ValueKind)
 SCOPES_DEFINE_TYPE_ENUM(TypeKind)
 #define TYPE_ENUM_QualifierKind(T, U) U(ReferQualifier, ValueKind) U(UniqueQualifier, ValueKind) U(ViewQualifier, ValueKind) U(MutateQualifier, ValueKind) U(KeyQualifier, ValueKind)

          
@@ 370,7 368,7 @@ SCOPES_DEFINE_TYPE(Concrete, CGenEntryFu
 SCOPES_DEFINE_TYPE(Concrete, CGenUnsupportedVectorSizeError, Error, ErrorKind)
 #define TYPE_FIELDS_CGenUnsupportedMatrixSizeError(T) T(by, Anchor) T(type, Type) T(size, SCOPES_i32)
 SCOPES_DEFINE_TYPE(Concrete, CGenUnsupportedMatrixSizeError, Error, ErrorKind)
-#define TYPE_FIELDS_RTLoadLibraryFailedError(T) T(by, Anchor) T(name, String) T(reason, String)
+#define TYPE_FIELDS_RTLoadLibraryFailedError(T) T(by, Anchor) T(name, String) T(reason, SCOPES_builtin_string)
 SCOPES_DEFINE_TYPE(Concrete, RTLoadLibraryFailedError, Error, ErrorKind)
 #define TYPE_FIELDS_RTGetAddressFailedError(T) T(by, Anchor) T(name, Symbol)
 SCOPES_DEFINE_TYPE(Concrete, RTGetAddressFailedError, Error, ErrorKind)

          
@@ 488,13 486,8 @@ SCOPES_DEFINE_TYPE(Alias, Builtin, Strin
 SCOPES_DEFINE_TYPE(Concrete, ListBuffer, Value, ValueKind)
 #define TYPE_FIELDS_ListSlice(T) T(data, ListBuffer) T(begin, SCOPES_usize) T(end, SCOPES_usize)
 SCOPES_DEFINE_TYPE(Concrete, ListSlice, Value, ValueKind)
-#define TYPE_FIELDS_ScopeTrie(T)
-#define TYPE_SUBTYPES_ScopeTrie(T) T(Concrete, ScopeL) T(Concrete, ScopeB)
-SCOPES_DEFINE_TYPE(Abstract, ScopeTrie, Value, ScopeKind)
-#define TYPE_FIELDS_ScopeL(T) T(by, Anchor) T(key, Const) T(value, Value) T(doc, SCOPES_OPTIONAL_ID_TYPE(String))
-SCOPES_DEFINE_TYPE(Concrete, ScopeL, ScopeTrie, ScopeKind)
-#define TYPE_FIELDS_ScopeB(T) T(slots, SCOPES_SARRAY_TYPE(Scope, 16))
-SCOPES_DEFINE_TYPE(Concrete, ScopeB, ScopeTrie, ScopeKind)
+#define TYPE_FIELDS_ScopeCell(T) T(key, Const) T(value, Value) T(doc, SCOPES_OPTIONAL_ID_TYPE(String)) T(next, Scope)
+SCOPES_DEFINE_TYPE(Concrete, ScopeCell, Value, ValueKind)
 #define TYPE_FIELDS_Closure(T) T(func, Template) T(frame, Function)
 SCOPES_DEFINE_TYPE(Concrete, Closure, Value, ValueKind)
 #define TYPE_FIELDS_Type(T)

          
@@ 983,6 976,7 @@ SCOPES_DEFINE_TYPE(Concrete, Unreachable
 SCOPES_DEFINE_TYPE(Concrete, Discard, Terminator, ValueKind)
 #define STRUCT_FIELDS_ListCell(T) T(by, Anchor) T(at, Value)
 SCOPES_DEFINE_STRUCT(ListCell)
+SCOPES_TYPEDEF(Scope, SCOPES_OPTIONAL_ID_TYPE(ScopeCell))
 SCOPES_TYPEDEF(IDSet, SCOPES_SET_TYPE(SCOPES_i32))
 SCOPES_TYPEDEF(IDs, SCOPES_DARRAY_TYPE(SCOPES_i32))
 SCOPES_TYPEDEF(Types, SCOPES_DARRAY_TYPE(Type))

          
@@ 1003,7 997,6 @@ SCOPES_TYPEDEF(Strings, SCOPES_DARRAY_TY
 SCOPES_TYPEDEF(Symbols, SCOPES_DARRAY_TYPE(Symbol))
 SCOPES_TYPEDEF(List, SCOPES_OPTIONAL_ID_TYPE(ListSlice))
 SCOPES_TYPEDEF(Lists, SCOPES_DARRAY_TYPE(List))
-SCOPES_TYPEDEF(Scope, SCOPES_OPTIONAL_ID_TYPE(ScopeTrie))
 SCOPES_TYPEDEF(Qualifiers, SCOPES_DARRAY_TYPE(Qualifier))
 SCOPES_TYPEDEF(ID2SetMap, SCOPES_MAP_TYPE(SCOPES_i32, IDSet))
 SCOPES_TYPEDEF(ValueIndexSet, SCOPES_SET_TYPE(ValueIndex))

          
@@ 1247,9 1240,7 @@ SCOPES_IMPL_FIELDS(Concrete, ArgumentsTy
 SCOPES_IMPL_FIELDS(Concrete, QualifyType, Type)
 SCOPES_IMPL_FIELDS(Abstract, Type, Value)
 SCOPES_IMPL_FIELDS(Concrete, Closure, Value)
-SCOPES_IMPL_FIELDS(Concrete, ScopeB, ScopeTrie)
-SCOPES_IMPL_FIELDS(Concrete, ScopeL, ScopeTrie)
-SCOPES_IMPL_FIELDS(Abstract, ScopeTrie, Value)
+SCOPES_IMPL_FIELDS(Concrete, ScopeCell, Value)
 SCOPES_IMPL_FIELDS(Concrete, ListSlice, Value)
 SCOPES_IMPL_FIELDS(Concrete, ListBuffer, Value)
 SCOPES_IMPL_FIELDS(Concrete, String, Value)

          
M testing/various/dag_scheduler.sc +353 -19
@@ 12,20 12,24 @@ dlog := report
 inline dlog (...) ...
 @endif
 
-seed := hash 1
+#seed := hash 1
+#NUM_VERTS := 16
 
-NUM_VERTS := 16
+seed := hash 3
+NUM_VERTS := 16 + 2
+
+CH := 0.5
 
 Edge := tuple i32 i32
 EdgeLen := tuple i32 i32 i32
 
-local edges : Set Edge
-local sources : Map i32 (Set i32)
-local sinks : Map i32 (Set i32)
+global edges : Set Edge
+global sources : Map i32 (Set i32)
+global sinks : Map i32 (Set i32)
 for v in (range 1 (NUM_VERTS - 1))
     'set sources v ((Set i32))
     'set sinks v ((Set i32))
-inline edge (v0 v1)
+fn edge (v0 v1)
     edge := Edge v0 v1
     'insert edges edge
     'insert (try! 'get& sources v1) v0

          
@@ 33,13 37,15 @@ inline edge (v0 v1)
     ;
 
 # generate a complete directed graph, randomly skip some edges
-local k = 0
-for v0 in (range 1 (NUM_VERTS - 1))
-    for v1 in (range (v0 + 1) (NUM_VERTS - 1))
-        H := (storagecast (hash seed k)) / -1:u64
-        k += 1
-        if (H < 0.2)
-            edge v0 v1
+do
+    local k = 0
+    for v0 in (range 1 (NUM_VERTS - 1))
+        for v1 in (range (v0 + 1) (NUM_VERTS - 1))
+            H := (storagecast (hash seed k)) / -1:u64
+            d := 1.0 / (v1 - v0) as f32 # the higher the distance, the unlikelier the connection
+            k += 1
+            if (H < d * CH)
+                edge v0 v1
 
 do
     # add canonical start and finish

          
@@ 59,7 65,86 @@ do
     for v0 v1 in (unpack* newedges)
         edge v0 v1
 
+# discover all paths and their cost O(x²)
+global paths : Set EdgeLen
+global maxpath : Map Edge i32
+global minpath : Map Edge i32
+do
+    for v0 v1 in (unpack* edges)
+        edge := EdgeLen v0 v1 1
+        'insert paths edge
+        'set maxpath (Edge v0 v1) 1
+        'set minpath (Edge v0 v1) 1
+    local i = 0:usize
+    while (i < (countof paths))
+        v0 v1 d01 := unpack (copy (try! paths @ i))
+        for j in (range (countof paths))
+            if (i == j)
+                continue;
+            v2 v3 d23 := unpack (copy (try! paths @ j))
+            if (v1 != v2)
+                continue;
+            d := d01 + d23
+            edge := EdgeLen v0 v3 d
+            if (edge in paths)
+                continue;
+            'insert paths edge
+            edge := Edge v0 v3
+            try
+                'get minpath edge
+            then (k)
+                if (d < k)
+                    'set minpath edge d
+            else
+                'set minpath edge d
+                ;
+            try
+                'get maxpath edge
+            then (k)
+                if (d > k)
+                    'set maxpath edge d
+            else
+                'set maxpath edge d
+                ;
+        i += 1
 
+#
+    tightly coupled paths: paths that have a min distance of 1
+    so every source that can be reached in a distance of 1 is tightly coupled
+
+    we assume the graph has only one source, and one sink
+
+    the canonical in-order Vi of a vertex V is its longest distance to the graph source
+    the canonical out-order Vo of a vertex V is its longest distance to the graph sink
+
+    the wiggle w of a vertex V is w = Ri - Vi - Vo where R is the graph sink.
+
+    based on wiggle numbers it should be possible to just iterate through all
+    possible configurations, by taking a still-wiggleable vertex from the
+    highest batch and incrementing its batch by 1.
+
+    eventually all vertices have visually "fallen down" (incremented) to their
+    last possible position, and we have seen and judged all configurations,
+    and chosen the best one.
+
+# wiggle range
+global wiggle : Array (tuple i32 i32)
+'resize wiggle NUM_VERTS
+LAST_N := NUM_VERTS - 1
+fdist := 'getdefault maxpath (Edge 0 LAST_N) 0
+for v1 in (range NUM_VERTS)
+    local d = 0
+    local best = (Edge v1 v1)
+    idist := 'getdefault maxpath (Edge 0 v1) 0
+    odist := 'getdefault maxpath (Edge v1 LAST_N) 0
+
+    p1 := idist
+    p2 := fdist - odist
+
+    try! wiggle @& v1 = tupleof p1 p2
+
+fn path? (v0 v1)
+    (Edge v0 v1) in maxpath
 
 struct Context
     seen : Set i32

          
@@ 83,14 168,256 @@ local waved : Array i32
 local dwaves : Array (Array i32)
 'resize waved NUM_VERTS
 for v in order
-    local w = 0
-    for src in (try! 'get sources v)
+    w := 'getdefault maxpath (Edge 0 v) 0
+    #for src in (try! 'get sources v)
         w = max w ((try! waved @& src) + 1)
     try! waved @& v = w
     if ((countof dwaves) <= w)
         'resize dwaves (w + 1)
     'append (try! dwaves @& w) v
 
+local waveq : Array i32
+local qwaves : Array (Array i32)
+'resize waveq NUM_VERTS
+for v in ('reverse order)
+    local w = 0
+    for src in (try! 'get sinks v)
+        w = max w ((try! waveq @& src) + 1)
+    try! waveq @& v = w
+    if ((countof qwaves) <= w)
+        'resize qwaves (w + 1)
+    'append (try! qwaves @& w) v
+
+fn hue2rgb (h l)
+    r := 0.5 + 0.5 * (max 0.0 (min 1.0 ((abs ((% (h * 6.0) 6.0) - 3.0)) - 1.0)))
+    g := 0.5 + 0.5 * (max 0.0 (min 1.0 ((abs ((% ((h * 6.0) + 4.0) 6.0) - 3.0)) - 1.0)))
+    b := 0.5 + 0.5 * (max 0.0 (min 1.0 ((abs ((% ((h * 6.0) + 2.0) 6.0) - 3.0)) - 1.0)))
+    l := 255.0 * l
+    +
+        ((r * l + 0.5) as i32 << 16)
+        ((g * l + 0.5) as i32 << 8)
+        (b * l + 0.5) as i32
+
+#float hue = fmodf(0.0 + (float)seen_paths.size() * 1.618033988749894, 1.0);
+
+@@ printer
+inline /reset (print)
+    print "\e[0m"
+
+inline /fg (hexcolor)
+    @@ printer
+    inline (print)
+        r := (hexcolor >> 16) & 0xff
+        g := (hexcolor >> 8) & 0xff
+        b := hexcolor & 0xff
+        print
+            /.. "\e[38;2;" (/dec r) ";" (/dec g) ";" (/dec b) "m"
+
+inline /bg (hexcolor)
+    @@ printer
+    inline (print)
+        r := (hexcolor >> 16) & 0xff
+        g := (hexcolor >> 8) & 0xff
+        b := hexcolor & 0xff
+        print
+            /.. "\e[48;2;" (/dec r) ";" (/dec g) ";" (/dec b) "m"
+
+fn init_pos_array ()
+    local pos : Array i32
+    'resize pos NUM_VERTS
+    local numwaves = 0
+    for v in (range NUM_VERTS)
+        p0 p1 := unpack (try! wiggle @ v)
+        numwaves = max numwaves p1
+        try! pos @& v = p0
+    pass pos (numwaves + 1)
+
+fn next_pos_array (pos)
+    local overflow = true
+    # bubble up one vertex (simulate an adder)
+    for v in (rrange NUM_VERTS)
+        p0 p1 := unpack (try! wiggle @ v)
+        if (p0 == p1)
+            continue;
+        p := try! pos @& v
+        pn := p + 1
+        blocked? := if (pn > p1) true
+        else
+            for w in (try! 'get sinks v)
+                q := try! pos @ w
+                if (pn == q)
+                    break true
+            else false
+        if blocked?
+            p = p0 # reset and continue
+        else
+            p += 1
+            overflow = false
+            break;
+    overflow
+
+@@ printer
+inline graph-printer (print)
+    tail_pack := true
+    phi := 1.618033988749894
+    local order : Array (tuple i32 i32)
+    do
+        pos numwaves := (init_pos_array)
+        local pos = pos
+        # optimal distribution
+        c := NUM_VERTS / numwaves
+        best_i := do
+            local best_i = 0
+            local worst_var1 = 0.0
+            local worst_var2 = 0.0
+            local best_var = inf
+            local attempts = 0
+            local failed_attempts = 0
+            local waves : Array i32
+            'resize waves numwaves
+            while true
+                attempts += 1
+                local valid? = true
+                for v0 in (range NUM_VERTS)
+                    p0 := try! pos @ v0
+                    for v1 in (try! 'get sinks v0)
+                        p1 := try! pos @ v1
+                        if (p1 <= p0)
+                            valid? = false
+                    if (not valid?)
+                        failed_attempts += 1
+                        break;
+                if valid?
+                    var1 := do
+                        # optimize for lowest wave width variance
+                        for w in waves
+                            w = 0
+                        # quantify distribution
+                        for v in (range NUM_VERTS)
+                            p := try! pos @ v
+                            try! waves @& p += 1
+                        # variance
+                        local var = 0.0
+                        for w in waves
+                            var += (c - w as f32) ** 2.0
+                        (sqrt var) / numwaves as f32
+                    worst_var1 = max worst_var1 var1
+                    var2 := do
+                        # optimize for shortest lifetime
+                        local var = 0.0
+                        for v0 in (range NUM_VERTS)
+                            if (v0 == 0) # ignore root node
+                                continue;
+                            p0 := try! pos @ v0
+                            local p1 = p0
+                            for v1 in (try! 'get sinks v0)
+                                p := try! pos @ v1
+                                p1 = max p1 p
+                            var += ((p1 - p0) as f32) ** 2.0
+                        (sqrt var) / (NUM_VERTS as f32)
+                    worst_var2 = max worst_var2 var2
+                    #var := (var1 / 0.1938188523054123) ** 2 + (var2 / 0.8906233310699463) ** 2
+                    var := var2
+                    real_var := var
+                    var := 1.0 / var
+                    if (var < best_var)
+                        best_i = attempts - 1
+                        best_var = var
+                        report "variance" real_var /n
+                if (next_pos_array pos)
+                    break;
+            report (attempts - failed_attempts) "combinations rated," failed_attempts "failed"
+                worst_var1 = worst_var1
+                worst_var2 = worst_var2
+                best_i = best_i
+            best_i
+
+        pos numwaves := (init_pos_array)
+        local pos = pos
+        for i in (range best_i)
+            next_pos_array pos
+        # map
+        for v in (range NUM_VERTS)
+            i := try! pos @ v
+            'append order (tupleof i v)
+        'sort order
+    numnodes := (countof order) as i32
+
+    inline print-row (v1 v1_ wave-breaker?)
+        local last_b = -1
+        local maxh = false
+        for v0_ in (range (v1_ + 1))
+            w0 v0 := unpack (copy (try! order @ v0_))
+            wbh := (w0 != last_b)
+            if wbh
+                last_b = w0
+                if wave-breaker?
+                    if (v0_ == v1_)
+                        print /reset /.. "┬" /..
+                    else
+                        print /reset /.. "┼" /..
+                else
+                    print /reset /.. "┊" /..
+            if (v0_ == v1_)
+                break;
+            local maxv := 0
+            for v_ in (range numnodes)
+                v := copy (try! order @ v_ @ 1)
+                if (((Edge v0 v) in edges) or ((Edge v v0) in edges))
+                    maxv = v_
+            col := hue2rgb ((v0 as f32 * phi) % 1.0) 1.0
+            colh := hue2rgb ((v0 as f32 * phi) % 1.0) 0.5
+            if wave-breaker?
+                print "╌" /..
+            else
+                u := ((Edge v1 v0) in edges) as i32
+                r := ((Edge v0 v1) in edges) as i32
+                hv := (maxh as i32 | ((v1_ < maxv) as i32 << 1))
+                switch (u | (r << 1))
+                case 0
+                    switch hv
+                    case 0
+                        print " " /..
+                    case 1
+                        print (/fg colh) /.. "─" /..
+                    case 2
+                        print (/fg colh) /.. "│" /..
+                    default
+                        print (/fg colh) /.. "┼" /..
+                case 1
+                    print (/fg 0xff0000) /.. "╙" /..
+                    maxh = true
+                case 2
+                    switch hv
+                    case 0
+                        print (/fg col) /.. "┕" /..
+                    case 1
+                        print (/fg col) /.. "┶" /..
+                    case 2
+                        print (/fg col) /.. "┝" /..
+                    default
+                        print (/fg col) /.. "┾" /..
+                    maxh = true
+                default
+                    print (/fg 0xffffff) /.. "*" /..
+
+    local last_b = -1
+    for v1_ in (range numnodes)
+        w1 v1 := unpack (copy (try! order @ v1_))
+        if (w1 != last_b)
+            last_b = w1
+            print-row v1 v1_ true
+            print /reset /.. "╌╌╌" "wave" (/dec w1) /n
+        print-row v1 v1_ false
+        col := hue2rgb ((v1 as f32 * phi) % 1.0) 1.0
+        print (/fg col) /.. "◆" /.. /reset
+            \ "V" /.. (/dec v1)
+            /do
+                p0 p1 := unpack (try! wiggle @ v1)
+                if (p0 != p1)
+                    print (/dec p0) /.. ".." /.. (/dec p1)
+            /n
+
 @@ printer
 inline dot-printer (print)
     using import compiler.header

          
@@ 118,7 445,7 @@ inline dot-printer (print)
                             """"shape=box;
                                 fontsize=12;
                                 fontname="mono";
-                                margin=0;
+                                margin=1;
                             /C:stmt "label="
                                 /C:string (/dec i)
                             /do

          
@@ 128,11 455,16 @@ inline dot-printer (print)
                                             /do
                                                 print
                                                     /.. "V" (/dec v)
-                                                    #/ps
+                                                    /ps
                                                         "label="
                                                         /..
                                                         /C:string
-                                                            'nameof self D
+                                                            /.. "V" (/dec v)
+                                                            /do
+                                                                w := try! wiggle @ v
+                                                                if (w > 0)
+                                                                    print "+" /..
+                                                                        /dec w
                 for v0 v1 in (unpack* edges)
                     print
                         /C:stmt

          
@@ 155,4 487,6 @@ inline show-graphviz (filebasepath opts.
     assert (err == 0)
     system (.. "eog " pngpath)
 
-show-graphviz "dag_scheduler"
+#show-graphviz "dag_scheduler"
+print
+    graph-printer
  No newline at end of file