compiler.cpp
impl/backup/any-dispatch-2026-11-13/compiler.cpp · 1979 line(s) · c
// ===========================================================================
// compiler.cpp -- AST -> Sleela Core bytecode.
// ===========================================================================
#include "compiler.h"
#include "semantic.h"
#include "java_compat.h"
#include "java_references.h"
#include <algorithm>
#include <tuple>
#include <optional>
#include "unsigned_integer.h"
#include "wide_integer.h"
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include "library_index.h"
#include "../core/sleela_ui_ids.h"
#include "../core/sleela_ui_vm.h"
namespace sleela {
namespace {
// Group a non-negative integer with thousands separators for the compiler's own
// diagnostic text (e.g. the layout-limit message). System-side presentation
// only; it never touches a running program's print(...) output.
static std::string groupDigits(long long v){
std::string s=std::to_string(v<0?-v:v);
std::string out; int n=(int)s.size();
for(int i=0;i<n;++i){ if(i>0 && (n-i)%3==0) out.push_back(','); out.push_back(s[(size_t)i]); }
return v<0 ? "-"+out : out;
}
struct MethodCtx {
std::map<std::string, int> locals;
int nextSlot = 0;
int slotOf(const std::string& name) const { auto it=locals.find(name); return it==locals.end()?-1:it->second; }
int declare(const std::string& name) { auto it=locals.find(name); if(it!=locals.end()) return it->second; int s=nextSlot++; locals[name]=s; return s; }
};
class Compiler {
public:
Compiler(const Program& prog, SLVM* vm, const catalog::Catalog* cat, const SyntaxVersion& syntax)
: prog_(prog), vm_(vm), cat_(cat), syntax_(syntax) {}
// Protected members are deliberately stronger than ordinary C++ access:
// Sleela protected source is admitted only as static protected and is bound
// to the VM's managed-handle memory model. Degree 2 means the declaration
// crosses two bounded relations: class member -> managed VM storage handle.
// It is NOT raw pointer arithmetic or a promise to dereference an address.
static constexpr int kProtectedSystemDegree = 2;
// `next` is System Degree 1; `next.next` is the bounded Degree 2 idiom.
// These are symbolic VM-safe relations, never pointer arithmetic.
static constexpr int kNextSystemDegree = 1;
// A static extension of a Degree-2 proposal gains a further two degrees
// of viewpoint: Degree 2 + static extension(2) = Viewpoint Degree 4.
static constexpr int kStaticExtensionViewpointDegree = 4;
int run() {
// Diagnostic (opt-in via SLEELA_DEBUG_LAYOUTS): report how many class /
// struct layouts this program will register with the VM, how many are
// library-merged vs the user's own, and whether any class name repeats.
// The VM caps distinct layouts at SL_MAX_STRUCT_TYPES; a program that
// overflows it almost always did so because the /lib identifier-scan
// resolver pulled a large transitive closure, not because the user
// wrote that many classes. This makes the cause visible without a
// debugger: compare "local" (your classes) against "library" (pulled).
if(std::getenv("SLEELA_DEBUG_LAYOUTS")){
std::map<std::string,int> dupc; int dups=0, lib=0, local=0;
for(const auto& c:prog_.classes){ if(++dupc[c.name]==2) ++dups; if(c.fromLibrary) ++lib; else ++local; }
fprintf(stderr,
"[debug-layouts] classes=%zu (local=%d library=%d) structs=%zu "
"distinct-class-names=%zu duplicate-named-classes=%d limit=%s\n",
prog_.classes.size(), local, lib, prog_.structs.size(),
dupc.size(), dups, groupDigits(SL_MAX_STRUCT_TYPES).c_str());
}
validateJavaCompatibilityMetadata(prog_);
library::Index libraryIndex = library::Index::discover();
library::validateImports(prog_.imports, libraryIndex);
// Protected source is admitted only when both language invariants hold:
// (1) the member is static, and (2) the runtime reports the managed VM
// memory model. The native core never exposes a raw pointer to Sleela
// source; struct values are bounded VM handles.
bool hasProtected = false;
for (const auto& cls : prog_.classes) {
for (const auto& f : cls.fields) hasProtected = hasProtected || f.isProtected;
for (const auto& m : cls.methods) hasProtected = hasProtected || m.isProtected;
}
if (hasProtected && !slvm_memory_safe_mode(vm_))
throw std::runtime_error("Semantic error: protected source requires the SLeeLa managed memory safety scheme");
for (const auto& cls : prog_.classes) {
for (const auto& f : cls.fields) {
if (f.isProtected && !f.isStatic)
throw std::runtime_error("Semantic error: protected field '" + f.name + "' must also be static (degree 2 safety rule)");
}
for (const auto& m : cls.methods) {
if (m.isProtected && !m.isStatic)
throw std::runtime_error("Semantic error: protected method '" + m.name + "' must also be static (degree 2 safety rule)");
}
}
(void)kProtectedSystemDegree;
(void)kNextSystemDegree;
(void)kStaticExtensionViewpointDegree;
// Nested classes (syntax 1.11): the parser hoists each lexically nested
// class into prog_.classes as "Outer__Inner" and records the count. Gate
// the feature on the declared syntax version, and re-assert the
// per-document cap of 42 as a defence in depth.
{
bool anyNested=false;
for(const auto& cls:prog_.classes) if(cls.isNested){ anyNested=true; break; }
if((anyNested||prog_.nestedClassCount>0) && syntax_<SyntaxVersion{1,11})
throw std::runtime_error("Semantic error: nested classes require #sleela 1.11");
if(prog_.nestedClassCount>42)
throw std::runtime_error("Semantic error: a single Sleela document may contain at most 42 nested classes");
}
// Struct declarations: register each layout with the VM and record a
// compiler-side layout (type index + ordered field names -> offsets).
for(const auto& st:prog_.structs){
// The VM admits at most SL_MAX_STRUCT_FIELDS (64) named fields per
// layout; slvm_declare_struct() rejects more by returning -1 BEFORE
// any diagnostic, which the generic registration error below would
// then misreport as a layout-COUNT overflow. Check the real cap here
// so the message names the true cause and the offending count.
if(st.fields.size()>SL_MAX_STRUCT_FIELDS) throw std::runtime_error("Semantic error: struct '"+st.name+"' declares "+std::to_string(st.fields.size())+" fields, but the VM admits at most "+std::to_string(SL_MAX_STRUCT_FIELDS)+" fields per struct/class layout. Reduce the field count (for example, group related fields into an array or a nested struct).");
if(structLayout_.count(st.name)) throw std::runtime_error("Semantic error: duplicate struct '"+st.name+"'");
if(syntax_<SyntaxVersion{1,2}) throw std::runtime_error("Semantic error: struct declarations require #sleela 1.2");
StructLayout layout; layout.name=st.name;
std::vector<const char*> fieldNames;
for(size_t i=0;i<st.fields.size();++i){
const auto& f=st.fields[i];
if(layout.fieldOffset.count(f.name)) throw std::runtime_error("Semantic error: duplicate field '"+f.name+"' in struct '"+st.name+"'");
layout.fieldOffset[f.name]=(int)i; layout.fieldType.push_back(f.type); fieldNames.push_back(f.name.c_str());
}
layout.typeIndex=slvm_declare_struct(vm_,st.name.c_str(),fieldNames.empty()?nullptr:fieldNames.data(),(int)fieldNames.size());
if(layout.typeIndex<0) throw std::runtime_error("Semantic error: could not register struct '"+st.name+"'. A 'layout' is one distinct class/struct type registered with the VM; the program exceeds the "+groupDigits(SL_MAX_STRUCT_TYPES)+" distinct class+struct types the VM admits.");
structLayout_[st.name]=layout;
}
// Class instances share the VM's managed struct allocator, but each
// class gets an independent layout and each object gets independent storage.
//
// OOD inheritance (syntax 1.10): a derived class's instance layout is the
// base class's inherited instance fields first, then the derived class's
// own fields (a same-name field is not duplicated). Base-first ordering
// keeps a base method's field offsets valid on a derived instance. The
// extends chain is resolved base-first; <=1.9 keeps the flat layout.
std::map<std::string,const ClassDecl*> classByName;
for(const auto& c:prog_.classes) classByName[c.name]=&c;
lineageClasses_=classByName;
const bool inheritance = !(syntax_<SyntaxVersion{1,10});
std::map<std::string,std::vector<const Field*>> instanceFieldsOf; // resolved, in layout order
std::set<std::string> laidOut; std::set<std::string> layoutInProgress;
std::function<void(const std::string&)> resolveFields=[&](const std::string& name){
if(laidOut.count(name)||!classByName.count(name)) return;
if(!layoutInProgress.insert(name).second) return; // cycle guard
const ClassDecl* cls=classByName[name];
std::vector<const Field*> ordered; std::set<std::string> seen;
if(inheritance){
const std::string sup=javaref::superclassOf(classByName,*cls);
if(!sup.empty()&&classByName.count(sup)&&!layoutInProgress.count(sup)){
resolveFields(sup);
for(const Field* bf:instanceFieldsOf[sup]) if(seen.insert(bf->name).second) ordered.push_back(bf);
}
}
for(const auto& f:cls->fields) if(!f.isStatic){ if(seen.insert(f.name).second) ordered.push_back(&f); }
instanceFieldsOf[name]=std::move(ordered);
layoutInProgress.erase(name);
laidOut.insert(name);
};
for(const auto& cls:prog_.classes) resolveFields(cls.name);
for(const auto& cls:prog_.classes){
if(structLayout_.count(cls.name)) throw std::runtime_error("Semantic error: class/struct name collision '"+cls.name+"'");
StructLayout layout; layout.name=cls.name; std::vector<const char*> names;
for(const Field* fp:instanceFieldsOf[cls.name]){
const auto& f=*fp;
if(layout.fieldOffset.count(f.name)) throw std::runtime_error("Semantic error: duplicate instance field '"+f.name+"' in class '"+cls.name+"'");
layout.fieldOffset[f.name]=(int)layout.fieldType.size(); layout.fieldType.push_back(f.type); names.push_back(f.name.c_str());
}
// The VM admits at most SL_MAX_STRUCT_FIELDS (64) instance fields
// per layout. slvm_declare_struct() rejects an over-wide layout by
// returning -1 at its FIRST guard -- before the layout-table growth
// path and its diagnostics -- so the generic registration error
// below would misreport a too-many-FIELDS class as a too-many-
// LAYOUTS (65,536) overflow. (This was the earlier 'exceeds 128
// instance fields' check, whose 128 did not match the VM's real 64
// cap, letting 65..128-field classes slip through to that confusing
// error.) Check the true cap here, naming the class, its field
// count, and a concrete remedy.
if(layout.fieldType.size()>SL_MAX_STRUCT_FIELDS) throw std::runtime_error("Semantic error: class '"+cls.name+"' has "+std::to_string(layout.fieldType.size())+" instance fields, but the VM admits at most "+std::to_string(SL_MAX_STRUCT_FIELDS)+" fields per class/struct layout. Reduce the field count -- for example, pack a group of related fields into a single array field reached through accessor methods (methods cost no layout slot), or split the class.");
layout.typeIndex=slvm_declare_struct(vm_,cls.name.c_str(),names.empty()?nullptr:names.data(),(int)names.size());
// With the field-cap pre-check above, a -1 here is a genuine
// layout-COUNT overflow (too many distinct class+struct types), not
// a too-wide single layout.
if(layout.typeIndex<0) throw std::runtime_error("Semantic error: could not register class layout '"+cls.name+"'. A 'layout' is one distinct class/struct type registered with the VM (not bytes); the program defines/pulls more than the "+groupDigits(SL_MAX_STRUCT_TYPES)+" distinct class+struct types the VM admits. (If this fires with only a handful of classes, the running sleelvac's VM core is stale/mismatched -- rebuild with 'rm -rf impl/build && make all' and reinstall.)");
structLayout_[cls.name]=layout;
}
if(inheritance) {
for(const auto& cls:prog_.classes) {
const std::string parent=javaref::superclassOf(classByName,cls);
if(parent.empty() || !structLayout_.count(parent) || !structLayout_.count(cls.name)) continue;
const int rc=slvm_set_struct_parent(vm_,structLayout_.at(cls.name).typeIndex,structLayout_.at(parent).typeIndex);
if(rc!=0) throw std::runtime_error("Semantic error: could not register runtime parent class for '"+cls.name+"'");
}
}
for(const auto& cls:prog_.classes) for(const auto& f:cls.fields) if(f.isStatic){
const std::string key=cls.name+"::"+f.name;
fieldGlobal_[key]=slvm_declare_global(vm_,key.c_str()); staticFieldType_[key]=f.type; fieldProtected_[key]=f.isProtected; fieldOwner_[key]=cls.name; fields_.push_back(&f);
if(structLayout_.count(f.type)) varType_[key]=f.type;
}
std::map<std::string,int> overloadCount;
for(const auto& cls:prog_.classes) for(const auto& m:cls.methods){
const std::string baseKey=cls.name+"::"+m.name;
// Each overload gets its own function; the first keeps the plain
// key, later ones "Class::name#k". The plain key stays bound to
// the last declaration (the pre-overload behavior) for callers
// that resolve by name alone.
const int k=overloadCount[baseKey]++;
const std::string key = k==0 ? baseKey : baseKey+"#"+std::to_string(k);
MethodInfo mi; mi.method=&m; mi.nlocals=countLocals(m)+(m.isStatic?0:1);
methodKeyByPtr_[&m]=key; methodOwner_[key]=cls.name; methodOwner_[baseKey]=cls.name;
if(m.isProtected) protectedMethods_.insert(key);
funcIndexByPtr_[&m]=(int)methods_.size();
funcIndex_[key]=(int)methods_.size(); funcIndex_[baseKey]=(int)methods_.size(); methods_.push_back(mi);
if(m.name=="main") funcIndex_["main"]=(int)methods_.size()-1;
}
// OOD inheritance (syntax 1.10): make a base method callable as
// Derived::method when the derived class does not override it. The
// inherited method shares the base's compiled body (its field accesses
// resolve against the base-first layout, which the derived instance
// shares). Resolved base-first so multi-level chains inherit fully.
if(inheritance){
std::set<std::string> aliased; std::set<std::string> aliasInProgress;
std::function<void(const std::string&)> inheritMethods=[&](const std::string& name){
if(aliased.count(name)||!classByName.count(name)) return;
if(!aliasInProgress.insert(name).second) return; // cycle guard
const std::string sup=javaref::superclassOf(classByName,*classByName[name]);
if(sup.empty()||!classByName.count(sup)||aliasInProgress.count(sup)){ aliasInProgress.erase(name); aliased.insert(name); return; }
inheritMethods(sup);
// Alias the base's RESOLVED function set (its own + inherited),
// so multi-level chains carry grandparent methods down.
const std::string pfx=sup+"::";
std::vector<std::pair<std::string,int>> toAlias;
for(const auto& kv:funcIndex_){ const std::string& bk=kv.first; if(bk.rfind(pfx,0)!=0) continue; std::string mname=bk.substr(pfx.size()); if(mname=="main") continue; const std::string dk=name+"::"+mname; if(funcIndex_.count(dk)) continue; toAlias.push_back({dk,kv.second}); auto ow=methodOwner_.find(bk); if(ow!=methodOwner_.end()) methodOwner_[dk]=ow->second; }
for(auto& e:toAlias) funcIndex_[e.first]=e.second;
aliasInProgress.erase(name);
aliased.insert(name);
};
for(const auto& cls:prog_.classes) inheritMethods(cls.name);
}
if(funcIndex_.find("main")==funcIndex_.end()) throw std::runtime_error("Semantic error: no 'main' method found");
for(auto& mi:methods_) emitMethod(mi);
int entry=funcIndex_["main"];
const Method* entryMethod=methods_[entry].method;
if(!entryMethod->isStatic){
// Legacy Sleela main methods may be instance methods. Synthesize a
// zero-argument VM entry wrapper that creates the owning class and
// invokes main on that instance.
currentClass_=methodOwner_.at(methodKeyByPtr_.at(entryMethod));
slvm_begin_func(vm_,"__sleela_entry",0,0);
NewExpr instance(currentClass_); emitNew(instance); emit(OP_CALL,entry);
emit(OP_POP); emit(OP_CONST,addNullConst()); emit(OP_RET); slvm_end_func(vm_);
entry=(int)methods_.size();
}
slvm_set_entry(vm_,entry); return entry;
}
private:
struct MethodInfo { const Method* method; int nlocals; };
// A struct's compile-time layout: its VM type index, and each field's
// position (offset) and declared type, in declaration order.
struct StructLayout { std::string name; int typeIndex=-1; std::map<std::string,int> fieldOffset; std::vector<std::string> fieldType; };
const Program& prog_; SLVM* vm_; const catalog::Catalog* cat_; SyntaxVersion syntax_;
std::map<std::string,int> funcIndex_; std::map<std::string,std::string> methodOwner_; std::map<const Method*,std::string> methodKeyByPtr_; std::map<const Method*,int> funcIndexByPtr_; std::set<std::string> protectedMethods_; std::vector<MethodInfo> methods_;
std::map<std::string,int> fieldGlobal_; std::map<std::string,std::string> staticFieldType_; std::map<std::string,bool> fieldProtected_; std::map<std::string,std::string> fieldOwner_; std::vector<const Field*> fields_; MethodCtx* ctx_=nullptr;
std::string currentClass_;
// Sleela.home lineage (SLEELA.syntax section 42), resolved against the loaded classes.
std::map<std::string,const ClassDecl*> lineageClasses_;
// The lineage logic lives in java_references.cpp (javaref::lineage*).
std::string lineageValue(const LineageExpr& x) const { return javaref::lineageValue(lineageClasses_,currentClass_,x); }
std::map<std::string,StructLayout> structLayout_;
// Track the declared type of each in-scope local/global so member access
// can resolve `x.field` to the right struct layout. Names not present are
// untyped (dynamic); member access then defers field resolution to runtime.
std::map<std::string,std::string> varType_;
std::string currentRetType_;
int fieldSlot(const std::string& name) const { auto it=fieldGlobal_.find(currentClass_+"::"+name); if(it!=fieldGlobal_.end())return it->second;it=fieldGlobal_.find(name);return it==fieldGlobal_.end()?-1:it->second; }
int instanceFieldOffset(const std::string& name) const { auto it=structLayout_.find(currentClass_);if(it==structLayout_.end())return -1;auto f=it->second.fieldOffset.find(name);return f==it->second.fieldOffset.end()?-1:f->second; }
int runtimeTypeOperand(const std::string& name) const {
// String is always the built-in type, as in the type checker (typeOf):
// the generated /lib/java envelope class java.lang.String must not
// turn a (String) cast or instanceof into a class check. utf16 names the
// VM-owned Java UTF-16 String kind (syntax 3.0, `x instanceof utf16`).
if(name=="String" || name=="string") return -(SL_STR+1);
if(name=="utf16") return -(SL_UTF16+1);
auto st=structLayout_.find(name);
if(st!=structLayout_.end()) return st->second.typeIndex;
// The base-2 signed series int32..int16777216 (syntax 2.7) rides the
// narrowest native integer slot that holds its width: widths <= 64
// (int32, int64) use SL_INT, widths >= 128 (int128 and up) use the
// 128-bit SL_INT128. `int64`/`int128` are also keyword-spelled; routing
// by width keeps the keyword and pattern spellings consistent.
if(SignedWideInteger::isValidTypeName(name))
return SignedWideInteger::fitsNativeNarrow(name) ? -(SL_INT+1) : -(SL_INT128+1);
// The base-2 unsigned series uint32..uint16777216 (syntax 2.8) backs on
// the same native-slot split as the signed series (positive-only
// semantics are enforced in the analyzer, not the runtime tag).
if(UnsignedWideInteger::isValidTypeName(name))
return UnsignedWideInteger::fitsNativeNarrow(name) ? -(SL_INT+1) : -(SL_INT128+1);
if(name=="int128") return -(SL_INT128+1);
// The arbitrary-width U<width> family rides the 64-bit slot.
if(name=="int" || name=="long" || name=="int64" || UnsignedInteger::isValidTypeName(name)) return -(SL_INT+1);
if(name=="double" || name=="float") return -(SL_DOUBLE+1);
if(name=="char" || name=="byte" || name=="short") return -(SL_INT+1);
if(name=="bool" || name=="boolean") return -(SL_BOOL+1);
if(name.size()>=2 && name.compare(name.size()-2,2,"[]")==0) return -(SL_ARRAY+1);
throw std::runtime_error("Semantic error: no runtime type descriptor for '"+name+"'");
}
// Emit a widening coercion for the value on top of the stack when it is
// being stored into / passed as a declared `double` or `int128` target, so
// `double d = 3;` holds 3.0 (Java int->double widening) and `int128 c = 5;`
// holds a real 128-bit value. The runtime OP_CHECKCAST coerces ints and
// passes non-ints through, so this is safe to emit unconditionally at a
// double/int128-typed store. Other target types need no coercion (int, long,
// int64 share the 64-bit representation; class/array/String stores are
// exact).
// Java operand semantics for the fixed-width integral types. SLeeLa keeps
// every integer in one 64-bit slot, so the Java widths byte (8), short (16),
// char (16, unsigned) and int32 (32) are enforced where a value is stored
// into, or cast to, one of those types. Signed widths sign-extend by shifting
// left then arithmetic-right (existing OP_BSHL/OP_BSHR); char masks to 16 bits.
// `int` and `long` are unchanged: `int` stays the 64-bit workhorse the rest of
// the library relies on, so Java 32-bit `int` wrap-around is requested with
// int32 or an explicit (int32) cast.
static int javaNarrowBits(const std::string& t){
if(t=="byte") return 8;
if(t=="short") return 16;
if(t=="int32") return 32;
return 0;
}
void emitJavaNarrow(const std::string& t){
if(t=="char"){ emit(OP_CONST,slvm_add_const_int(vm_,0xFFFF)); emit(OP_BAND); return; }
const int bits=javaNarrowBits(t);
if(!bits) return;
emit(OP_CONST,slvm_add_const_int(vm_,64-bits)); emit(OP_BSHL);
emit(OP_CONST,slvm_add_const_int(vm_,64-bits)); emit(OP_BSHR);
}
void coerceToDeclared(const std::string& declType, bool narrow=true){
if(narrow && (declType=="char" || javaNarrowBits(declType))){ emitJavaNarrow(declType); return; }
// Widen into a double, or into a 128-bit-backed signed integer (int128
// and the wider base-2 series members int256..int16777216). Narrow
// series members (int32, int64) share the 64-bit representation and need
// no coercion, exactly like `int`/`long`/`int64`.
const bool wide128 = declType=="int128"
|| (SignedWideInteger::isValidTypeName(declType) && !SignedWideInteger::fitsNativeNarrow(declType))
|| (UnsignedWideInteger::isValidTypeName(declType) && !UnsignedWideInteger::fitsNativeNarrow(declType));
if(declType=="double"||declType=="float"||wide128)
emit(OP_CHECKCAST,runtimeTypeOperand(declType));
}
// Emit call arguments, widening each integer argument to a declared double
// or int128 parameter (so half(9) passes 9.0, not 9).
void emitArgsCoerced(const std::vector<ExprP>& args, const Method* target){
for(size_t i=0;i<args.size();++i){
emitExpr(args[i].get());
if(target && i<target->params.size()) coerceToDeclared(target->params[i].type);
}
}
void emitThis(){if(!ctx_||ctx_->slotOf("this")<0)throw std::runtime_error("Semantic error: instance member requires an instance context");emit(OP_LOADL,ctx_->slotOf("this"));}
int countLocals(const Method& m){int n=(int)m.params.size();countInBlock(*m.body,n);return n;}
void countInBlock(const Block& b,int& n){for(const auto& s:b.stmts)countInStmt(s.get(),n);}
void countInStmt(const Stmt* s,int& n){
if(dynamic_cast<const VarDecl*>(s)) n++;
else if(auto b=dynamic_cast<const Block*>(s)) countInBlock(*b,n);
else if(auto i=dynamic_cast<const IfStmt*>(s)){countInStmt(i->thenS.get(),n);if(i->elseS)countInStmt(i->elseS.get(),n);}
else if(auto w=dynamic_cast<const WhileStmt*>(s)) countInStmt(w->body.get(),n);
else if(auto f=dynamic_cast<const ForStmt*>(s)){if(f->init)countInStmt(f->init.get(),n);countInStmt(f->body.get(),n);}
else if(auto d=dynamic_cast<const DoStmt*>(s)) countInStmt(d->body.get(),n);
else if(auto fe=dynamic_cast<const ForEachStmt*>(s)){ n+=3; /* loop variable, source, index/iterator */ countInStmt(fe->body.get(),n); }
else if(auto sy=dynamic_cast<const SynchronizedStmt*>(s)) countInBlock(*sy->body,n);
else if(auto lb=dynamic_cast<const LabeledStmt*>(s)) countInStmt(lb->body.get(),n);
else if(auto tr=dynamic_cast<const TryStmt*>(s)){n+=2;/* thrown-value temp + __retval */countInBlock(*tr->body,n);for(const auto& c:tr->catches){n++;countInBlock(*c.body,n);}if(tr->finallyBlock){/* finally is emitted up to 4 times (normal, after a catch, before a rethrow, from a catch body) */for(int k=0;k<4;++k)countInBlock(*tr->finallyBlock,n);}}
else if(auto sw=dynamic_cast<const SwitchStmt*>(s)){n++;/* selector temp */for(const auto& c:sw->cases)for(const auto& st:c.statements)countInStmt(st.get(),n);}
}
int here(){return slvm_here(vm_);} int emit(SLOp op,int a=0){return slvm_emit(vm_,op,a);} void patch(int at,int target){slvm_patch(vm_,at,target);}
bool hasNativeAnnotation(const Method& method) const {
for (const auto& annotation : method.java.annotations)
if (annotation.name == "native" && annotation.marker) return true;
return false;
}
std::string nativeMethodSignature(const std::string& key, const Method& method) const {
std::string signature = key;
signature += method.isStatic ? "|static|argc=" : "|instance|argc=";
signature += std::to_string(method.params.size()) + "|";
for (const auto& parameter : method.params) {
signature += std::to_string(parameter.type.size()) + ":" + parameter.type;
}
signature += "|return=" + std::to_string(method.retType.size()) + ":" + method.retType;
signature += "|abi=1.0";
return signature;
}
void emitMethod(MethodInfo& mi){
const Method& m=*mi.method; const std::string key=methodKeyByPtr_.at(&m); currentClass_=methodOwner_.at(key);
MethodCtx ctx; if(!m.isStatic)ctx.declare("this"); for(const auto& p:m.params)ctx.declare(p.name);
std::map<std::string,std::string> savedTypes=varType_;
for(const auto& p:m.params) varType_[p.name]=p.type;
if(!m.isStatic)varType_["this"]=currentClass_;
const std::string savedRet=currentRetType_; currentRetType_=m.retType;
const int functionIndex=slvm_begin_func(vm_,key.c_str(),(int)m.params.size()+(m.isStatic?0:1),mi.nlocals);
if(hasNativeAnnotation(m)){
const uint32_t flags=SL_NATIVE_METHOD_FLAG_ANNOTATED |
(m.isStatic?SL_NATIVE_METHOD_FLAG_STATIC:SL_NATIVE_METHOD_FLAG_INSTANCE);
const std::string signature=nativeMethodSignature(key,m);
if(slvm_set_func_native_metadata(vm_,functionIndex,flags,
SL_NATIVE_METHOD_ABI_VERSION,signature.c_str())!=0)
throw std::runtime_error("Compiler error: could not register unique @native method identity for '"+key+"'");
}
ctx_=&ctx;
// Initialise static fields before main runs. These compile to VM
// globals; their initialisers must execute regardless of which class
// declares them, so a static read from a non-entry class (e.g. a
// library class's `static final int` constant) sees its value rather
// than null. Every class's statics are initialised here, in program
// declaration order, when the entry `main` begins. (Previously only the
// entry class's statics were initialised, leaving every other class's
// static constants null.)
if(m.name=="main"){
const std::string savedClass=currentClass_;
for(const auto& cls:prog_.classes) for(const auto& f:cls.fields) if(f.isStatic){
currentClass_=cls.name; // a static initialiser referencing a sibling static resolves against its own class
if(f.init)emitExpr(f.init.get());else emit(OP_CONST,addNullConst());
emit(OP_STOREG,fieldGlobal_[cls.name+"::"+f.name]);
}
currentClass_=savedClass;
}
if(m.java.constructor && !(syntax_<SyntaxVersion{3,0}) && !startsWithConstructorInvocation(m) && !isLibraryClass(currentClass_)){
// Java implicit super() (43.6) before the constructor body. Only for
// the program's own classes: /lib units construct themselves (their
// constructors set inherited state, and unimplemented library
// constructors throw UnsupportedOperationException).
std::string owner; if(const Method* bc=implicitBaseCtor(currentClass_,owner)){ emitThis(); emit(OP_CALL,ctorFuncIndex(owner,bc)); emit(OP_POP); }
}
emitBlock(*m.body);ctx_=nullptr;emit(OP_CONST,addNullConst());emit(OP_RET);slvm_end_func(vm_);
varType_=savedTypes; currentRetType_=savedRet;
}
int addNullConst(){if(nullConst_<0){SLExchangeArg a{};a.value=slval_null();slcore_exchange(vm_,SLX_ADD_CONST,&a);nullConst_=a.out;}return nullConst_;}
int nullConst_=-1;
void emitStmt(const Stmt* s){
if(auto b=dynamic_cast<const Block*>(s)){emitBlock(*b);return;} if(auto d=dynamic_cast<const VarDecl*>(s)){emitVarDecl(*d);return;}
if(auto a=dynamic_cast<const Assign*>(s)){emitAssign(*a);return;} if(auto e=dynamic_cast<const ExprStmt*>(s)){emitExpr(e->expr.get());emit(OP_POP);return;}
if(auto p=dynamic_cast<const PrintStmt*>(s)){emitExpr(p->expr.get());if(p->charArg)emit(OP_CHARSTR);emit(OP_PRINT);return;} if(auto r=dynamic_cast<const ReturnStmt*>(s)){emitReturn(*r);return;}
if(auto gh=dynamic_cast<const GcHintStmt*>(s)){emitGcHint(*gh);return;}
if(auto i=dynamic_cast<const IfStmt*>(s)){emitIf(*i);return;} if(auto w=dynamic_cast<const WhileStmt*>(s)){emitWhile(*w);return;} if(auto f=dynamic_cast<const ForStmt*>(s)){emitFor(*f);return;} if(auto fe=dynamic_cast<const ForEachStmt*>(s)){emitForEach(*fe);return;}
if(auto fa=dynamic_cast<const FieldAssign*>(s)){emitFieldAssign(*fa);return;}
if(auto d=dynamic_cast<const DoStmt*>(s)){emitDo(*d);return;}
if(auto sw=dynamic_cast<const SwitchStmt*>(s)){emitSwitch(*sw);return;}
if(auto sy=dynamic_cast<const SynchronizedStmt*>(s)){emitSynchronized(*sy);return;}
if(auto tr=dynamic_cast<const TryStmt*>(s)){emitTry(*tr);return;}
if(auto t=dynamic_cast<const ThrowStmt*>(s)){emitExpr(t->value.get());emit(OP_THROW);return;}
if(auto a=dynamic_cast<const AssertStmt*>(s)){emitExpr(a->cond.get());emit(OP_POP);return;}
if(auto y=dynamic_cast<const YieldStmt*>(s)){emitExpr(y->value.get());emit(OP_POP);return;}
if(auto bs=dynamic_cast<const BreakStmt*>(s)){emitBreak(bs->label);return;}
if(auto cs=dynamic_cast<const ContinueStmt*>(s)){emitContinue(cs->label);return;}
if(auto ls=dynamic_cast<const LabeledStmt*>(s)){emitLabeled(*ls);return;}
throw std::runtime_error("Semantic error: unknown statement kind");
}
void emitBlock(const Block& b){for(const auto& s:b.stmts)emitStmt(s.get());}
void emitVarDecl(const VarDecl& d){
int slot=ctx_->declare(d.name);
// Record the declared type so later assignments can apply the same
// widening coercion (double / int128). Previously only struct/class
// types were tracked; primitives are needed for double/int128 locals.
if(d.type!="let") varType_[d.name]=d.type;
if(d.type=="let" && d.init){
if(auto created=dynamic_cast<const NewExpr*>(d.init.get())){
if(structLayout_.count(created->typeName)) varType_[d.name]=created->typeName;
} else if(auto existing=dynamic_cast<const VarExpr*>(d.init.get())){
auto known=varType_.find(existing->name);
if(known!=varType_.end()) varType_[d.name]=known->second;
}
}
if(d.init){
emitExpr(d.init.get());
coerceToDeclared(d.type);
} else emit(OP_CONST,addNullConst());
emit(OP_STOREL,slot);
}
// Declared type of an instance field of the current class ("" if unknown).
std::string instanceFieldType(const std::string& name) const {
auto it=structLayout_.find(currentClass_); if(it==structLayout_.end()) return "";
auto f=it->second.fieldOffset.find(name); if(f==it->second.fieldOffset.end()) return "";
if(f->second>=0 && f->second<(int)it->second.fieldType.size()) return it->second.fieldType[(size_t)f->second];
return "";
}
void emitAssign(const Assign& a){int slot=ctx_->slotOf(a.name);if(slot>=0){emitExpr(a.value.get());{auto t=varType_.find(a.name);if(t!=varType_.end())coerceToDeclared(t->second);}emit(OP_STOREL,slot);return;}int off=instanceFieldOffset(a.name);if(off>=0){emitThis();emitExpr(a.value.get());coerceToDeclared(instanceFieldType(a.name));emit(OP_SETFIELD,off);emit(OP_POP);return;}int g=fieldSlot(a.name);if(g>=0){emitExpr(a.value.get());emit(OP_STOREG,g);return;}throw std::runtime_error("Semantic error: assignment to undeclared variable '"+a.name+"'");}
// GC hint (syntax 1.9): `x = gc N;` / `x = mem N;`. The target must name an
// in-scope value the developer is finished using (a local, instance field,
// or static field), which keeps the hint honest: it marks a real binding as
// releasable. The hint lowers to a single OP_GC_HINT whose operand is the
// 0..100 aggressiveness; the VM runs a short-term collection of unreachable
// allocations at that strength. No value is pushed or popped.
void emitGcHint(const GcHintStmt& h){
bool known = ctx_ && ctx_->slotOf(h.target)>=0;
if(!known) known = instanceFieldOffset(h.target)>=0;
if(!known) known = fieldSlot(h.target)>=0;
if(!known) throw std::runtime_error("Semantic error: GC hint target '"+h.target+"' is not an in-scope variable");
int level=h.aggressiveness; if(level<0)level=0; if(level>100)level=100;
emit(OP_GC_HINT, level);
}
// `ran::<word>` value reference. `ran::mem` lowers to OP_RAN_MEM, which
// pushes the current live system memory in bytes. Unknown words are rejected
// in semantic analysis; this emitter handles the value forms.
void emitRanRef(const RanRefExpr& r){
if(r.word=="mem"){emit(OP_RAN_MEM);return;}
throw std::runtime_error("Semantic error: unknown system reference 'ran::"+r.word+"'");
}
void emitReturn(const ReturnStmt& r){
if(r.value){emitExpr(r.value.get());coerceToDeclared(currentRetType_);}else emit(OP_CONST,addNullConst());
if(!regions_.empty()){
// Syntax 3.1: leave every enclosing try region (running its finally) before returning.
const int slot=ctx_->declare("__retval"); emit(OP_STOREL,slot);
unwindTo(0);
emit(OP_LOADL,slot);
}
emit(OP_RET);
}
void emitFieldAssign(const FieldAssign& fa){int off=-1;const StructLayout& ml=memberLayout(fa.base.get(),fa.field,off);std::string ft=(off>=0&&off<(int)ml.fieldType.size())?ml.fieldType[(size_t)off]:"";emitExpr(fa.base.get());emitExpr(fa.value.get());coerceToDeclared(ft);emit(OP_SETFIELD,off);emit(OP_POP);}
void emitIf(const IfStmt& s){emitExpr(s.cond.get());int jf=emit(OP_JMPF,0);emitStmt(s.thenS.get());if(s.elseS){int jend=emit(OP_JMP,0);patch(jf,here());emitStmt(s.elseS.get());patch(jend,here());}else patch(jf,here());}
// Loop context for break/continue: each enclosing loop records the jump
// sites that must be patched to the loop exit (break) and to the loop's
// continue target (continue). We patch them when the loop finishes.
struct LoopCtx{std::vector<int> breaks;std::vector<int> continues;int tryDepth=0;std::string label;bool isSwitch=false;bool isBlock=false;};
// Syntax 3.1: a label applies to the next loop/switch context pushed.
std::string pendingLabel_;
LoopCtx newCtx(bool sw=false,bool blk=false){LoopCtx c;c.tryDepth=tryDepth_;c.isSwitch=sw;c.isBlock=blk;c.label=pendingLabel_;pendingLabel_.clear();return c;}
// One entry per live OP_TRY_PUSH frame, innermost last. `fin` is the finally
// block that must run when control leaves the region by break, continue or
// return (syntax 3.1; SLEELA.syntax 44.4). tryDepth_ == regions_.size().
struct Region{const Block* fin;};
std::vector<Region> regions_;
void pushRegion(const Block* fin){regions_.push_back({fin});++tryDepth_;}
void popRegion(){regions_.pop_back();--tryDepth_;}
// Leave every region above index `downTo`: pop its handler frame and run its
// finally inline, innermost first. While one finally is emitted only the
// regions outside it are live, so a jump inside that finally unwinds
// correctly and an exception from it propagates outward.
void unwindTo(size_t downTo){
const std::vector<Region> saved=regions_; const int savedDepth=tryDepth_; const int savedGuard=finallyGuard_;
for(size_t i=saved.size();i>downTo;--i){
regions_.assign(saved.begin(),saved.begin()+(long)(i-1)); tryDepth_=(int)(i-1);
emit(OP_TRY_POP);
if(saved[i-1].fin) emitBlock(*saved[i-1].fin);
}
regions_=saved; tryDepth_=savedDepth; finallyGuard_=savedGuard;
}
int findTarget(const std::string& label,bool forContinue){
for(size_t i=loops_.size();i-->0;){
const LoopCtx& c=loops_[i];
if(!label.empty()){ if(c.label==label){ if(forContinue&&(c.isSwitch||c.isBlock)) return -2; return (int)i; } continue; }
if(c.isBlock) continue;
if(forContinue&&c.isSwitch) continue;
return (int)i;
}
return -1;
}
std::vector<LoopCtx> loops_;
int tryDepth_=0;
void emitBreak(const std::string& label=""){
if(!label.empty()&&syntax_<SyntaxVersion{3,1}) throw std::runtime_error("Semantic error: labeled break requires #sleela 3.1");
int t=findTarget(label,false);
if(t<0) throw std::runtime_error(label.empty()?"Semantic error: 'break' used outside a loop or switch":"Semantic error: break to undefined label '"+label+"'");
unwindTo((size_t)loops_[(size_t)t].tryDepth);
loops_[(size_t)t].breaks.push_back(emit(OP_JMP,0));
}
void emitContinue(const std::string& label=""){
if(!label.empty()&&syntax_<SyntaxVersion{3,1}) throw std::runtime_error("Semantic error: labeled continue requires #sleela 3.1");
int t=findTarget(label,true);
if(t==-2) throw std::runtime_error("Semantic error: continue to label '"+label+"' which does not label a loop");
if(t<0) throw std::runtime_error(label.empty()?"Semantic error: 'continue' used outside a loop":"Semantic error: continue to undefined label '"+label+"'");
unwindTo((size_t)loops_[(size_t)t].tryDepth);
loops_[(size_t)t].continues.push_back(emit(OP_JMP,0));
}
void emitLabeled(const LabeledStmt& l){
const Stmt* b=l.body.get();
const bool loopLike=dynamic_cast<const WhileStmt*>(b)||dynamic_cast<const DoStmt*>(b)||dynamic_cast<const ForStmt*>(b)||dynamic_cast<const ForEachStmt*>(b)||dynamic_cast<const SwitchStmt*>(b);
if(loopLike){ pendingLabel_=l.label; emitStmt(b); pendingLabel_.clear(); return; }
pendingLabel_=l.label; loops_.push_back(newCtx(false,true));
emitStmt(b);
for(int br:loops_.back().breaks)patch(br,here());
loops_.pop_back();
}
// Per-iteration delay requested by a loop-timing annotation (@loopDelay /
// @loopBudget). Emits `push <ms>; OP_SLEEP`, which the VM executes each
// iteration. Emitted at the top of the loop body so the delay happens once
// per pass. ms<=0 emits nothing.
void emitLoopDelay(long ms){if(ms>0){emit(OP_CONST,slvm_add_const_int(vm_,(int64_t)ms));emit(OP_SLEEP);}}
// A @spill annotation "counts as a timer start itself": it marks the loop
// entry as a timer-start checkpoint and pauses ONCE before the loop begins
// iterating (as opposed to emitLoopDelay, which sleeps every iteration).
// Emitted before the loop's initializer/top so the pause happens a single
// time up front. A spill with pause 0 is a pure checkpoint and emits no
// sleep. The judges/witnesses subjects are retained as AST metadata only and
// have no runtime effect. ms<=0 emits nothing.
void emitSpillStart(const LoopSpill& spill){if(spill.hasSpill && spill.spillPauseMs>0){emit(OP_CONST,slvm_add_const_int(vm_,(int64_t)spill.spillPauseMs));emit(OP_SLEEP);}}
void emitWhile(const WhileStmt& s){emitSpillStart(s.spill);loops_.push_back(newCtx());int top=here();emitExpr(s.cond.get());int jf=emit(OP_JMPF,0);emitLoopDelay(s.loopSleepMs);emitStmt(s.body.get());for(int c:loops_.back().continues)patch(c,top);emit(OP_JMP,top);patch(jf,here());for(int b:loops_.back().breaks)patch(b,here());loops_.pop_back();}
void emitDo(const DoStmt& s){emitSpillStart(s.spill);loops_.push_back(newCtx());int top=here();emitLoopDelay(s.loopSleepMs);emitStmt(s.body.get());int contTarget=here();for(int c:loops_.back().continues)patch(c,contTarget);emitExpr(s.cond.get());int jf=emit(OP_JMPF,0);emit(OP_JMP,top);patch(jf,here());for(int b:loops_.back().breaks)patch(b,here());loops_.pop_back();}
void emitFor(const ForStmt& s){emitSpillStart(s.spill);loops_.push_back(newCtx());if(s.init)emitStmt(s.init.get());int top=here();std::vector<int> exits;if(s.cond){emitExpr(s.cond.get());exits.push_back(emit(OP_JMPF,0));}if(s.threadStable){emitExpr(s.threadStable.get());exits.push_back(emit(OP_JMPF,0));}if(s.heapHealthy){emitExpr(s.heapHealthy.get());exits.push_back(emit(OP_JMPF,0));}emitLoopDelay(s.loopSleepMs);emitStmt(s.body.get());int contTarget=here();for(int c:loops_.back().continues)patch(c,contTarget);if(s.update)emitStmt(s.update.get());emit(OP_JMP,top);int end=here();for(int j:exits)patch(j,end);for(int b:loops_.back().breaks)patch(b,end);loops_.pop_back();}
// Enhanced for (SLEELA.syntax 43.6). Array: index loop with OP_ARRLEN /
// OP_ARRGET. Object: xs.iterator(), then hasNext()/next() (virtual calls).
int forEachCounter_=0;
void emitForEach(const ForEachStmt& s){
if(syntax_<SyntaxVersion{3,0}) throw std::runtime_error("Semantic error: the enhanced for requires #sleela 3.0");
const std::string tag=std::to_string(forEachCounter_++);
const int vSlot=ctx_->declare(s.name);
const int srcSlot=ctx_->declare("__fe_src#"+tag);
const int curSlot=ctx_->declare("__fe_cur#"+tag);
const auto savedType=varType_.find(s.name)!=varType_.end()?std::optional<std::string>(varType_[s.name]):std::nullopt;
varType_[s.name]=s.type;
loops_.push_back(newCtx());
std::vector<int> exits; int top=0;
emitExpr(s.iterable.get());
const std::vector<ExprP> noArgs;
if(!s.overIterable){
emit(OP_STOREL,srcSlot);
emit(OP_CONST,slvm_add_const_int(vm_,0)); emit(OP_STOREL,curSlot);
top=here();
emit(OP_LOADL,curSlot); emit(OP_LOADL,srcSlot); emit(OP_ARRLEN); emit(OP_LT); exits.push_back(emit(OP_JMPF,0));
emit(OP_LOADL,srcSlot); emit(OP_LOADL,curSlot); emit(OP_ARRGET); coerceToDeclared(s.type,false); emit(OP_STOREL,vSlot);
} else {
if(!s.iteratorM||!s.hasNextM||!s.nextM) throw std::runtime_error("Semantic error: enhanced for over '"+s.iterableType+"' was not resolved");
emitInstanceCall(s.iterableType,s.iteratorM,methodFuncIndex(s.iterableType,s.iteratorM),noArgs);
emit(OP_STOREL,curSlot);
top=here();
emit(OP_LOADL,curSlot); emitInstanceCall(s.iteratorType,s.hasNextM,methodFuncIndex(s.iteratorType,s.hasNextM),noArgs); exits.push_back(emit(OP_JMPF,0));
emit(OP_LOADL,curSlot); emitInstanceCall(s.iteratorType,s.nextM,methodFuncIndex(s.iteratorType,s.nextM),noArgs); coerceToDeclared(s.type,false); emit(OP_STOREL,vSlot);
}
emitStmt(s.body.get());
const int contTarget=here(); for(int c:loops_.back().continues) patch(c,contTarget);
if(!s.overIterable){ emit(OP_LOADL,curSlot); emit(OP_CONST,slvm_add_const_int(vm_,1)); emit(OP_ADD); emit(OP_STOREL,curSlot); }
emit(OP_JMP,top);
const int end=here(); for(int j:exits) patch(j,end); for(int b:loops_.back().breaks) patch(b,end);
loops_.pop_back();
if(savedType) varType_[s.name]=*savedType; else varType_.erase(s.name);
}
// Function index of an instance method resolved by semantic analysis.
int methodFuncIndex(const std::string& owner,const Method* m){
int fi=resolvedIndex(m);
if(fi<0){ auto t=funcIndex_.find(owner+"::"+m->name); if(t!=funcIndex_.end()) fi=t->second; }
if(fi<0) throw std::runtime_error("Semantic error: method '"+owner+"::"+m->name+"' is not registered");
return fi;
}
void emitSynchronized(const SynchronizedStmt& s){emitExpr(s.monitor.get());emit(OP_POP);emitBlock(*s.body);}
void emitTry(const TryStmt& s){
if(syntax_<SyntaxVersion{3,0}){ emitTryMilestone(s); return; }
emitTryJava(s);
}
// Below syntax 3.0: the first exception milestone, unchanged -- one
// catch-all clause whose binding is Any, no finally.
void emitTryMilestone(const TryStmt& s){
if(s.catches.size()!=1)
throw std::runtime_error("Semantic error: this exception milestone supports exactly one catch clause");
if(s.finallyBlock)
throw std::runtime_error("Semantic error: finally lowering is not yet supported by the VM exception milestone");
const CatchClause& clause=s.catches.front();
if(ctx_->slotOf(clause.variable)>=0)
throw std::runtime_error("Semantic error: catch variable shadows an existing method local; use a distinct name in this exception milestone");
if(clause.type!="Any")
throw std::runtime_error("Semantic error: catch-all exception binding must use type Any until typed exception matching is implemented");
const int catchSlot=ctx_->declare(clause.variable);
const auto priorType=varType_.find(clause.variable);
const bool hadPriorType=priorType!=varType_.end();
const std::string savedType=hadPriorType?priorType->second:std::string();
varType_[clause.variable]="Any";
const int push=emit(OP_TRY_PUSH,0);
pushRegion(nullptr);
emitBlock(*s.body);
popRegion();
emit(OP_TRY_POP);
const int skipHandler=emit(OP_JMP,0);
patch(push,here());
// OP_THROW restores the operand stack and pushes the thrown value for
// the selected handler. Store it immediately so it is rooted in a
// normal local slot before the catch body can allocate or call out.
emit(OP_STOREL,catchSlot);
emitBlock(*clause.body);
patch(skipHandler,here());
if(hadPriorType) varType_[clause.variable]=savedType;
else varType_.erase(clause.variable);
}
// Syntax 3.0 Java try (SLEELA.syntax 43.6 rule 11). One VM handler catches
// everything; the clauses then test the thrown value with OP_INSTANCEOF in
// source order, and an unmatched value is rethrown with OP_THROW. finally
// runs on normal completion, after a matched catch body, and before any
// rethrow (including an exception thrown by a catch body). A return, break
// or continue that would leave a finally-protected block is rejected,
// because it would skip the finally.
int tryCounter_=0;
int finallyGuard_=0;
void emitTryJava(const TryStmt& s){
const std::string tag=std::to_string(tryCounter_++);
const int exSlot=ctx_->declare("__try_ex#"+tag);
const bool hasFinally=(bool)s.finallyBlock;
// Resolve each clause's alternatives to runtime type operands.
struct Clause{ const CatchClause* c; bool catchAll; std::vector<int> ops; std::string varType; };
std::vector<Clause> clauses;
for(const auto& c:s.catches){
Clause cl{&c,false,{},"Any"};
for(const auto& alt:c.types.empty()?std::vector<std::string>{c.type}:c.types){
const std::string t=javaref::resolveBaseName(lineageClasses_,alt);
if(t=="Any"){ cl.catchAll=true; continue; }
if(!structLayout_.count(t)) throw std::runtime_error("Semantic error: catch type '"+alt+"' is not a loaded class");
cl.ops.push_back(runtimeTypeOperand(t));
}
if(c.types.size()==1 && !cl.catchAll) cl.varType=javaref::resolveBaseName(lineageClasses_,c.types[0]);
clauses.push_back(std::move(cl));
}
auto emitFinally=[&]{ if(hasFinally) emitBlock(*s.finallyBlock); };
int rethrowHandlerPush=-1;
// After OP_TRY_POP of the catch-phase frame its region is no longer live.
auto emitFinallyPopped=[&]{
if(rethrowHandlerPush>=0){ const std::vector<Region> saved=regions_; const int d=tryDepth_; regions_.pop_back(); --tryDepth_; emitFinally(); regions_=saved; tryDepth_=d; }
else emitFinally();
};
std::vector<int> toEnd;
// try body
const int push=emit(OP_TRY_PUSH,0);
pushRegion(hasFinally?s.finallyBlock.get():nullptr); if(hasFinally) ++finallyGuard_;
emitBlock(*s.body);
popRegion(); if(hasFinally) --finallyGuard_;
emit(OP_TRY_POP);
emitFinally();
toEnd.push_back(emit(OP_JMP,0));
// handler
patch(push,here());
emit(OP_STOREL,exSlot);
if(hasFinally && !clauses.empty()){
// An exception from a catch body must still run finally.
rethrowHandlerPush=emit(OP_TRY_PUSH,0); pushRegion(s.finallyBlock.get());
}
for(const auto& cl:clauses){
std::vector<int> nextClause;
if(!cl.catchAll){
std::vector<int> matched;
for(size_t k=0;k<cl.ops.size();++k){
emit(OP_LOADL,exSlot); emit(OP_INSTANCEOF,cl.ops[k]);
if(k+1<cl.ops.size()){ const int jf=emit(OP_JMPF,0); matched.push_back(emit(OP_JMP,0)); patch(jf,here()); }
else nextClause.push_back(emit(OP_JMPF,0));
}
for(int m:matched) patch(m,here());
}
const int slot=ctx_->declare(cl.c->variable);
const auto prior=varType_.find(cl.c->variable); const bool had=prior!=varType_.end(); const std::string saved=had?prior->second:std::string();
varType_[cl.c->variable]=cl.varType;
emit(OP_LOADL,exSlot); emit(OP_STOREL,slot);
if(hasFinally) ++finallyGuard_;
emitBlock(*cl.c->body);
if(hasFinally) --finallyGuard_;
if(had) varType_[cl.c->variable]=saved; else varType_.erase(cl.c->variable);
if(rethrowHandlerPush>=0) emit(OP_TRY_POP);
emitFinallyPopped();
toEnd.push_back(emit(OP_JMP,0));
for(int n:nextClause) patch(n,here());
}
// no clause matched: finally, then rethrow
if(rethrowHandlerPush>=0) emit(OP_TRY_POP);
emitFinallyPopped();
emit(OP_LOADL,exSlot); emit(OP_THROW);
if(rethrowHandlerPush>=0){
popRegion();
// exception raised inside a catch body: finally, then propagate it
patch(rethrowHandlerPush,here());
emit(OP_STOREL,exSlot);
emitFinally();
emit(OP_LOADL,exSlot); emit(OP_THROW);
}
for(int e:toEnd) patch(e,here());
}
void emitSwitch(const SwitchStmt& s){
// Lower a switch to a dispatch chain: evaluate the selector once into a
// temp local, test each label with ==, and jump to the matching case
// body. Fall-through follows source order; `break` jumps to the end.
loops_.push_back(newCtx(true));
int sel=ctx_->nextSlot++; emitExpr(s.selector.get()); emit(OP_STOREL,sel);
// Dispatch section: for each label, (selector==label) ? enter body.
// Record one enter-jump per label, tagged with its owning case index.
std::vector<int> enterJump; std::vector<int> enterCase; int defaultIdx=-1;
for(size_t i=0;i<s.cases.size();++i){
const auto& c=s.cases[i];
if(c.isDefault){defaultIdx=(int)i;continue;}
for(const auto& lab:c.labels){
emit(OP_LOADL,sel); emitExpr(lab.get()); emit(OP_EQ);
int jf=emit(OP_JMPF,0); // no match -> next label test
enterJump.push_back(emit(OP_JMP,0)); enterCase.push_back((int)i);
patch(jf,here());
}
}
int toDefault=emit(OP_JMP,0); // no label matched
// Case bodies, in source order; record each body's start address.
std::vector<int> bodyStart(s.cases.size(),-1);
for(size_t i=0;i<s.cases.size();++i){bodyStart[i]=here();for(const auto& st:s.cases[i].statements)emitStmt(st.get());}
int endPos=here();
patch(toDefault, defaultIdx>=0?bodyStart[defaultIdx]:endPos);
for(size_t j=0;j<enterJump.size();++j)patch(enterJump[j],bodyStart[enterCase[j]]);
for(int b:loops_.back().breaks)patch(b,endPos);
loops_.pop_back();
}
void emitExpr(const Expr* e){
if(auto x=dynamic_cast<const IntLit*>(e)){emit(OP_CONST,slvm_add_const_int(vm_,x->value));return;} if(auto x=dynamic_cast<const DoubleLit*>(e)){emit(OP_CONST,slvm_add_const_double(vm_,x->value));return;}
if(auto x=dynamic_cast<const BoolLit*>(e)){emit(OP_CONST,slvm_add_const_bool(vm_,x->value?1:0));return;} if(auto x=dynamic_cast<const StrLit*>(e)){emit(OP_CONST,slvm_add_const_str(vm_,x->value.c_str()));return;}
if(dynamic_cast<const NullLit*>(e)){emit(OP_CONST,addNullConst());return;} if(auto x=dynamic_cast<const VarExpr*>(e)){emitVar(*x);return;} if(auto x=dynamic_cast<const Unary*>(e)){emitUnary(*x);return;}
if(auto x=dynamic_cast<const RanRefExpr*>(e)){emitRanRef(*x);return;}
if(auto x=dynamic_cast<const Binary*>(e)){
// ::: structural-offload send: lower source then receiver, then the
// OP_SSEND transport opcode (the VM frames the source element-by-
// element into the receiver). The receiver expression evaluates to a
// reach handle; OP_SSEND pushes it back so a ::: chain stays fluent.
if(x->op==":::"){emitExpr(x->lhs.get());emitExpr(x->rhs.get());emit(OP_SSEND);return;}
emitBinary(*x);return;
} if(auto x=dynamic_cast<const Call*>(e)){emitCall(*x);return;}
if(auto x=dynamic_cast<const LineageExpr*>(e); x&&x->kind==LineageExpr::Boot){
// VM boot: place Security2 above the VM and walk it boot -> init -> start -> ready.
if(!lineageClasses_.count("Security2")){emit(OP_CONST,addNullConst());return;}
MethodCall boot(std::make_unique<NewExpr>("Security2"),"boot"); boot.args.push_back(std::make_unique<StrLit>("Sleela.System"));
emitExpr(&boot); return;
}
if(auto x=dynamic_cast<const LineageExpr*>(e)){emit(OP_CONST,slvm_add_const_str(vm_,lineageValue(*x).c_str()));return;}
if(auto x=dynamic_cast<const NewExpr*>(e)){emitNew(*x);return;} if(auto x=dynamic_cast<const MemberAccess*>(e)){emitMember(*x);return;}
if(auto x=dynamic_cast<const MethodCall*>(e)){emitMethodCall(*x);return;}
if(auto x=dynamic_cast<const AssignmentExpr*>(e)){emitAssignmentExpr(*x);return;}
if(auto x=dynamic_cast<const ConditionalExpr*>(e)){emitConditional(*x);return;}
if(auto x=dynamic_cast<const CastExpr*>(e)){
emitExpr(x->operand.get());
if(x->typeName!="Any") emit(OP_CHECKCAST,runtimeTypeOperand(x->typeName));
// Java narrowing cast: (byte)/(short)/(char)/(int32) wrap to their width
// after the double->integer truncation that OP_CHECKCAST(int) performs.
if(x->typeName=="char" || javaNarrowBits(x->typeName)) emitJavaNarrow(x->typeName);
return;
}
if(auto x=dynamic_cast<const InstanceOfExpr*>(e)){
emitExpr(x->value.get());
emit(OP_INSTANCEOF,runtimeTypeOperand(x->typeName));
return;
}
if(dynamic_cast<const SuperExpr*>(e)){ if(ctx_&&ctx_->slotOf("this")>=0) emitThis(); else emit(OP_CONST,addNullConst()); return; }
if(dynamic_cast<const ThisExpr*>(e)){emitThis();return;}
if(auto x=dynamic_cast<const ArrayAccess*>(e)){emitExpr(x->base.get());emitExpr(x->index.get());emit(OP_ARRGET);return;}
if(auto x=dynamic_cast<const MethodReferenceExpr*>(e)){emitExpr(x->base.get());return;}
if(auto x=dynamic_cast<const GuideChainExpr*>(e)){emitGuideChain(*x);return;}
throw std::runtime_error("Semantic error: unknown expression kind");
}
// Lower a (possibly compound) assignment expression. The result value is
// left on the stack. Compound ops expand to `target = target <op> value`.
// Syntax 3.2: `s += c` with a char value c appends the character, not its number.
unsigned compoundCharMask_=0;
bool narrowCharStore_=false;
void emitBinOpC(const std::string& o){ if(o=="+"&&compoundCharMask_){ emit(OP_ADDCHAR,(int)compoundCharMask_); return; } emitBinOp(o); }
void emitAssignmentExpr(const AssignmentExpr& a){
const unsigned savedCharMask=compoundCharMask_; compoundCharMask_=a.charMask;
struct Restore{unsigned& r;unsigned v;~Restore(){r=v;}} restoreCharMask{compoundCharMask_,savedCharMask};
const bool savedNarrow=narrowCharStore_; narrowCharStore_=a.narrowChar;
struct RestoreB{bool& r;bool v;~RestoreB(){r=v;}} restoreNarrow{narrowCharStore_,savedNarrow};
emitAssignTo(a.target.get(), a.op=="=" ? std::string() : a.op.substr(0,a.op.size()-1), [&]{ emitExpr(a.value.get()); });
}
// Assign to `target` (local, field, static, member, array element), with an
// optional compound operator `bin`; leaves the assigned value on the stack.
void emitAssignTo(const Expr* target,const std::string& bin,const std::function<void()>& emitValue){
if(auto v=dynamic_cast<const VarExpr*>(target)){
// Resolve the target before emitting the RHS. Assignment expressions
// are also used for statement-level assignments, so instance fields
// must follow the same resolution path as Assign statements.
int slot=ctx_->slotOf(v->name);
if(slot>=0){
if(!bin.empty()){emit(OP_LOADL,slot);emitValue();emitBinOpC(bin);}
else emitValue();
{auto t=varType_.find(v->name);if(t!=varType_.end())coerceToDeclared(t->second);}
emit(OP_STOREL,slot);emit(OP_LOADL,slot);return;
}
int off=instanceFieldOffset(v->name);
if(off>=0){
emitThis(); // [this]
if(!bin.empty()){emit(OP_DUP);emit(OP_GETFIELD,off);emitValue();emitBinOpC(bin);}
else emitValue();
coerceToDeclared(instanceFieldType(v->name));
emit(OP_SETFIELD,off); // leaves assigned value
return;
}
int g=fieldSlot(v->name);
if(g>=0){
const std::string key=fieldOwner_.count(v->name)?v->name:currentClass_+"::"+v->name;
if(fieldProtected_[key]&&fieldOwner_[key]!=currentClass_)throw std::runtime_error("protected field access denied");
if(!bin.empty()){emit(OP_LOADG,g);emitValue();emitBinOpC(bin);}
else emitValue();
emit(OP_STOREG,g);emit(OP_LOADG,g);return;
}
throw std::runtime_error("Semantic error: assignment to undeclared variable '"+v->name+"'");
}
if(auto m=dynamic_cast<const MemberAccess*>(target)){
{ std::string sc; if(isStaticClassRef(m->base.get(),sc)){ auto g=fieldGlobal_.find(sc+"::"+m->field);
if(g!=fieldGlobal_.end()){
if(!bin.empty()){emit(OP_LOADG,g->second);emitValue();emitBinOpC(bin);}
else emitValue();
emit(OP_STOREG,g->second);emit(OP_LOADG,g->second);return;
} } }
int off=-1;const StructLayout& ml=memberLayout(m->base.get(),m->field,off);
std::string ft=(off>=0&&off<(int)ml.fieldType.size())?ml.fieldType[(size_t)off]:"";
// SETFIELD expects [struct, newval] and leaves newval on the stack.
emitExpr(m->base.get()); // [struct]
if(!bin.empty()){emit(OP_DUP);emit(OP_GETFIELD,off);emitValue();emitBinOpC(bin);} // [struct, newval]
else emitValue(); // [struct, newval]
coerceToDeclared(ft);
emit(OP_SETFIELD,off); // [newval]
return;
}
if(auto aa=dynamic_cast<const ArrayAccess*>(target)){
// OP_ARRSET expects [array, index, value] and leaves value on the stack.
emitExpr(aa->base.get()); // [array]
emitExpr(aa->index.get()); // [array, index]
if(!bin.empty()){
// compound read-modify-write. Duplicate the already-evaluated
// (array, index) pair with OP_DUP2 and read through the copy,
// so the base and index sub-expressions are evaluated EXACTLY
// ONCE. Re-emitting them here would run their side effects a
// second time (e.g. a[i++] += 1 would increment i twice).
emit(OP_DUP2); // [array, index, array, index]
emit(OP_ARRGET); // [array, index, cur]
emitValue(); // [array, index, cur, val]
emitBinOpC(bin); // [array, index, newval]
} else {
emitValue(); // [array, index, value]
}
if(narrowCharStore_){ emit(OP_CONST,slvm_add_const_int(vm_,0xFFFF)); emit(OP_BAND); } // syntax 3.2: char[] element store keeps 16 bits
emit(OP_ARRSET); // [value]
return;
}
throw std::runtime_error("Semantic error: assignment target must be a variable, struct field, or array element");
}
void emitConditional(const ConditionalExpr& c){emitExpr(c.cond.get());int jf=emit(OP_JMPF,0);emitExpr(c.thenE.get());int jend=emit(OP_JMP,0);patch(jf,here());emitExpr(c.elseE.get());patch(jend,here());}
void emitBinOp(const std::string& o){if(o=="+")emit(OP_ADD);else if(o=="-")emit(OP_SUB);else if(o=="*")emit(OP_MUL);else if(o=="/")emit(OP_DIV);else if(o=="%")emit(OP_MOD);else if(o=="&")emit(OP_BAND);else if(o=="|")emit(OP_BOR);else if(o=="^")emit(OP_BXOR);else if(o=="<<")emit(OP_BSHL);else if(o==">>")emit(OP_BSHR);else if(o==">>>")emit(OP_BUSHR);else throw std::runtime_error("Semantic error: unsupported compound assignment operator '"+o+"='");}
// Determine the struct type name an expression evaluates to, or "" if it is
// not statically known to be a struct. Used to resolve field offsets.
std::string exprStructType(const Expr* e){
if(auto v=dynamic_cast<const VarExpr*>(e)){
auto it=varType_.find(v->name);
if(it!=varType_.end()) return it->second;
// Fall back to an instance field of the current class: a bare field
// read (parsed as a VarExpr) carries a known struct/class type even
// though it is not a local/param. This lets a method call resolve on
// a class-typed field receiver -- e.g. `this.engine.rating()` written
// as `engine.rating()` -- the same way emitVar resolves the field's
// offset. The field's declared type is read from the current class's
// layout; empty when the field is scalar or the name is not a field.
if(!currentClass_.empty()){
auto lit=structLayout_.find(currentClass_);
if(lit!=structLayout_.end()){
auto oit=lit->second.fieldOffset.find(v->name);
if(oit!=lit->second.fieldOffset.end()){
const std::string& ft=lit->second.fieldType[oit->second];
if(structLayout_.count(ft)) return ft;
}
}
}
return "";
}
if(dynamic_cast<const ThisExpr*>(e))return currentClass_;
if(dynamic_cast<const SuperExpr*>(e))return javaref::lineageParentOf(lineageClasses_,currentClass_);
if(auto m=dynamic_cast<const MemberAccess*>(e)){
{ std::string sc; if(isStaticClassRef(m->base.get(),sc)){ auto ft=staticFieldType_.find(sc+"::"+m->field); if(ft!=staticFieldType_.end()) return structLayout_.count(ft->second)?ft->second:std::string(); } }
std::string bt=exprStructType(m->base.get());if(bt.empty())return "";auto lit=structLayout_.find(bt);if(lit==structLayout_.end())return "";int idx=-1;auto oit=lit->second.fieldOffset.find(m->field);if(oit!=lit->second.fieldOffset.end())idx=oit->second;if(idx<0)return "";return lit->second.fieldType[idx];}
if(auto ca=dynamic_cast<const CastExpr*>(e))return ca->typeName;
if(auto n=dynamic_cast<const NewExpr*>(e))return n->typeName;
// A Guide chain evaluates to its constructed head instance, so its
// struct type is the head's type -- this lets `(new T() :: g).m()`
// resolve the trailing method on T.
if(auto g=dynamic_cast<const GuideChainExpr*>(e))return exprStructType(g->head.get());
// A method-call receiver carries the called method's declared return
// type, so a chained call -- obj.getX().method() -- resolves: find the
// receiver's type, look up receiverType::method, and return that
// method's return type when it names a known struct/class. Empty when
// the return type is scalar or the method cannot be resolved.
if(auto mc=dynamic_cast<const MethodCall*>(e)){
// A String-receiver call returns its JavaStringMethods method's type.
if(mc->stringReceiver && mc->resolved){ const std::string& ret=mc->resolved->retType; return structLayout_.count(ret)?ret:std::string(); }
std::string rt;
bool viaClassName=false;
{ std::string sc; if(isStaticClassRef(mc->receiver.get(),sc)){ rt=sc; viaClassName=true; } }
if(rt.empty()) rt=exprStructType(mc->receiver.get());
if(rt.empty()) return "";
auto fi=funcIndex_.find(rt+"::"+mc->method);
if(fi==funcIndex_.end()){
if(viaClassName && mc->method=="deref" && structLayout_.count(rt)) return rt;
return "";
}
const std::string& ret = mc->resolved ? mc->resolved->retType : methods_[fi->second].method->retType;
if(structLayout_.count(ret)) return ret;
return "";
}
return "";
}
// Resolve (layout, offset) for base.field; throws a clear semantic error if
// the base's struct type or the field cannot be determined at compile time.
const StructLayout& memberLayout(const Expr* base,const std::string& field,int& offset){
std::string tn=exprStructType(base);
if(tn.empty()) throw std::runtime_error("Semantic error: cannot access field '"+field+"' -- the value is not a known struct type (declare the variable with its struct type)");
auto lit=structLayout_.find(tn);
if(lit==structLayout_.end()) throw std::runtime_error("Semantic error: '"+tn+"' is not a struct type");
auto oit=lit->second.fieldOffset.find(field);
if(oit==lit->second.fieldOffset.end()) throw std::runtime_error("Semantic error: struct '"+tn+"' has no field '"+field+"'");
offset=oit->second; return lit->second;
}
// Resolve the single constructor declared for `className` that accepts
// `argc` arguments. Syntax 1.8 supports constructor arguments but NOT
// overload resolution or this()/base delegation, so there must be exactly
// one constructor and its arity must match. Returns nullptr when the class
// declares no constructor at all (the zero-arg field-init path applies).
const Method* findConstructor(const std::string& className,size_t argc){
const Method* match=nullptr; int ctorCount=0;
for(const auto& cls:prog_.classes) if(cls.name==className)
for(const auto& m:cls.methods) if(m.java.constructor){
ctorCount++;
if(m.params.size()==argc) match=&m;
}
if(ctorCount==0) return nullptr;
if(ctorCount>1 && syntax_<SyntaxVersion{3,0}) throw std::runtime_error("Semantic error: class '"+className+"' declares multiple constructors; constructor overload resolution requires syntax 3.0");
if(!match) throw std::runtime_error("Semantic error: no constructor of '"+className+"' takes "+std::to_string(argc)+" argument(s)");
return match;
}
// ---- Java constructor chaining and virtual dispatch (SLEELA.syntax 43.6) ----
// Function index of a constructor declared in `owner`.
int ctorFuncIndex(const std::string& owner,const Method* ctor){
int fi=resolvedIndex(ctor);
if(fi<0){ auto t=funcIndex_.find(owner+"::"+ctor->name); if(t!=funcIndex_.end()) fi=t->second; }
if(fi<0) throw std::runtime_error("Semantic error: constructor of '"+owner+"' is not registered");
return fi;
}
bool isLibraryClass(const std::string& n) const { auto it=lineageClasses_.find(n); return it!=lineageClasses_.end()&&it->second->fromLibrary; }
// Java's implicit super(): the no-arg constructor of the nearest loaded
// ancestor of `cls` that declares any constructor (nullptr when there is
// none, or when that ancestor has no no-arg constructor). Sets `owner`.
const Method* implicitBaseCtor(const std::string& cls,std::string& owner){
std::set<std::string> seen; std::string c=javaref::lineageParentOf(lineageClasses_,cls);
while(!c.empty() && seen.insert(c).second){
const ClassDecl* d=lineageClasses_.at(c); bool any=false;
for(const auto& m:d->methods) if(m.java.constructor){ any=true; if(m.params.empty()){ owner=c; return &m; } }
if(any) return nullptr;
c=javaref::lineageParentOf(lineageClasses_,c);
}
return nullptr;
}
// True when a constructor body starts with an explicit super(...) / this(...)
// (including the lineage-only super("constructor") of section 42.5).
static bool startsWithConstructorInvocation(const Method& m){
if(!m.body||m.body->stmts.empty()) return false;
const Stmt* s=m.body->stmts.front().get();
if(auto a=dynamic_cast<const Assign*>(s)) return a->name=="__lin_root";
if(auto b=dynamic_cast<const Block*>(s)) for(const auto& x:b->stmts) if(auto es=dynamic_cast<const ExprStmt*>(x.get())) if(auto mc=dynamic_cast<const MethodCall*>(es->expr.get())) if(mc->superConstructor) return true;
if(auto es=dynamic_cast<const ExprStmt*>(s)) if(auto mc=dynamic_cast<const MethodCall*>(es->expr.get())) return mc->superConstructor||mc->thisConstructor;
return false;
}
// super(args) / this(args): call the resolved constructor on `this`.
void emitConstructorInvocation(const MethodCall& mc){
if(syntax_<SyntaxVersion{3,0}) return; // below 3.0 the arguments are not evaluated (42.7)
if(!mc.resolved) return; // implicit default constructor: nothing to run
const std::string owner = mc.superConstructor ? javaref::lineageParentOf(lineageClasses_,currentClass_) : currentClass_;
emitThis(); emitArgsCoerced(mc.args,mc.resolved); emit(OP_CALL,ctorFuncIndex(owner,mc.resolved));
// leave a value: the ExprStmt pops it
}
// Overrides of `method` (declared in or inherited by `staticType`) in loaded
// subclasses / implementors, deepest first, as (runtime type, function).
std::vector<std::pair<int,int>> virtualTargets(const std::string& staticType,const Method* method){
std::vector<std::tuple<int,int,int>> found; // depth, typeIndex, funcIndex
for(const auto& cls:prog_.classes){
if(cls.name==staticType || !javaref::isSubtypeOf(lineageClasses_,cls.name,staticType)) continue;
auto lay=structLayout_.find(cls.name); if(lay==structLayout_.end()) continue;
for(const auto& dm:cls.methods){
if(dm.isStatic||dm.java.constructor||dm.name!=method->name||dm.params.size()!=method->params.size()||&dm==method) continue;
bool sameParams=true; for(size_t i=0;i<dm.params.size();++i) if(dm.params[i].type!=method->params[i].type){sameParams=false;break;}
if(!sameParams) continue;
auto fi=funcIndexByPtr_.find(&dm); if(fi==funcIndexByPtr_.end()) continue;
found.emplace_back(javaref::inheritanceDepth(lineageClasses_,cls.name),lay->second.typeIndex,fi->second);
break;
}
}
std::stable_sort(found.begin(),found.end(),[](const auto& a,const auto& b){return std::get<0>(a)>std::get<0>(b);});
std::vector<std::pair<int,int>> out; for(const auto& f:found) out.emplace_back(std::get<1>(f),std::get<2>(f));
return out;
}
// Receiver is on the stack. Java virtual dispatch (43.6): test it against
// each loaded override, deepest first, else call `fidx`.
void emitInstanceCall(const std::string& staticType,const Method* method,int fidx,const std::vector<ExprP>& args){
if(!(syntax_<SyntaxVersion{3,0})){
const auto targets=virtualTargets(staticType,method);
if(!targets.empty()){
std::vector<int> ends;
for(const auto& t:targets){
emit(OP_DUP); emit(OP_INSTANCEOF,t.first); const int skip=emit(OP_JMPF,0);
emitArgsCoerced(args,method); emit(OP_CALL,t.second); ends.push_back(emit(OP_JMP,0));
patch(skip,here());
}
emitArgsCoerced(args,method); emit(OP_CALL,fidx);
for(int e:ends) patch(e,here());
return;
}
}
emitArgsCoerced(args,method); emit(OP_CALL,fidx);
}
// Element default for `new T[n]`: Java numeric and boolean arrays start at
// zero/false, not null (see OP_NEWARRAY operand a).
static int arrayFillKind(const std::string& elem){
if(elem=="int"||elem=="long"||elem=="short"||elem=="byte"||elem=="char"||elem=="int64") return 1;
// The 64-bit-backed series members (int32, uint32, uint64, U<width>) start
// at 0 too; the 128-bit-backed members keep the null default.
if((SignedWideInteger::isValidTypeName(elem)&&SignedWideInteger::fitsNativeNarrow(elem))
||(UnsignedWideInteger::isValidTypeName(elem)&&UnsignedWideInteger::fitsNativeNarrow(elem))
||UnsignedInteger::isValidTypeName(elem)) return 1;
if(elem=="double"||elem=="float") return 2;
if(elem=="bool"||elem=="boolean") return 3;
return 0;
}
void emitNew(const NewExpr& n){
if(n.hasInit){
// Syntax 3.1 array initializer: allocate, then store each element.
const std::string et=n.typeName.substr(0,n.typeName.size()-2);
emit(OP_CONST,slvm_add_const_int(vm_,(int64_t)n.init.size()));
emit(OP_NEWARRAY,arrayFillKind(et));
for(size_t i=0;i<n.init.size();++i){
emit(OP_DUP); emit(OP_CONST,slvm_add_const_int(vm_,(int64_t)i));
emitExpr(n.init[i].get()); coerceToDeclared(et);
emit(OP_ARRSET); emit(OP_POP);
}
return;
}
if(n.args.size()>=2 && n.typeName.size()>=2 && n.typeName.compare(n.typeName.size()-2,2,"[]")==0){
// Syntax 3.2 multi-dimensional creation: new T[a][b]... / new T[a][b][]
std::string base=n.typeName; size_t rank=0;
while(base.size()>=2 && base.compare(base.size()-2,2,"[]")==0){ base.erase(base.size()-2); ++rank; }
for(const auto& d:n.args) emitExpr(d.get());
const int fill=(n.args.size()==rank)?arrayFillKind(base):0;
emit(OP_NEWARRAYND,(int)n.args.size()|(fill<<8));
return;
}
if(n.typeName.size()>=2 && n.typeName.compare(n.typeName.size()-2,2,"[]")==0){if(!n.args.empty())emitExpr(n.args[0].get());else emit(OP_CONST,slvm_add_const_int(vm_,0));emit(OP_NEWARRAY,arrayFillKind(n.typeName.substr(0,n.typeName.size()-2)));return;}
auto it=structLayout_.find(n.typeName);if(it==structLayout_.end())throw std::runtime_error("Semantic error: 'new' of unknown class or struct '"+n.typeName+"'");
// Resolve a matching constructor before allocating so an arity/overload
// error is reported without leaving a half-built instance plan.
const Method* ctor = n.resolved ? n.resolved : (n.args.empty() ? findConstructor(n.typeName,0) : findConstructor(n.typeName,n.args.size()));
if(!n.args.empty() && !ctor) throw std::runtime_error("Semantic error: class '"+n.typeName+"' has no constructor to accept "+std::to_string(n.args.size())+" argument(s)");
emit(OP_NEWSTRUCT,it->second.typeIndex);
// Initialize class fields per instance. A duplicated handle is consumed
// by SETFIELD while the original stays on the stack as the new value.
// Initialize instance fields base-first along the extends chain (43.6):
// a class's inherited fields get their declared initializers too.
std::vector<std::string> chain{n.typeName};
if(!(syntax_<SyntaxVersion{3,0})){ std::set<std::string> seen{n.typeName}; std::string c=javaref::lineageParentOf(lineageClasses_,n.typeName); while(!c.empty()&&seen.insert(c).second){ chain.insert(chain.begin(),c); c=javaref::lineageParentOf(lineageClasses_,c); } }
for(const auto& chainName:chain) for(const auto& cls:prog_.classes) if(cls.name==chainName){
for(const auto& f:cls.fields) if(!f.isStatic){
auto off=it->second.fieldOffset.find(f.name);if(off==it->second.fieldOffset.end())continue;
emit(OP_DUP);
if(f.init) emitExpr(f.init.get());
else if(f.type=="int") emit(OP_CONST,slvm_add_const_int(vm_,0));
else if(f.type=="double") emit(OP_CONST,slvm_add_const_double(vm_,0.0));
else if(f.type=="bool"||f.type=="boolean") emit(OP_CONST,slvm_add_const_bool(vm_,0));
else if(f.type=="string"||f.type=="String") emit(OP_CONST,slvm_add_const_str(vm_,""));
else emit(OP_CONST,addNullConst());
emit(OP_SETFIELD,off->second);emit(OP_POP);
}
}
// Syntax 1.8 constructor invocation. After field initialization the
// fresh instance is on top of the stack. Duplicate it as the `this`
// receiver, push the constructor arguments, and call the constructor
// method; its (null) return value is discarded so the fully initialized
// instance remains on the stack as the value of `new Type(args)`.
if(!ctor && !(syntax_<SyntaxVersion{3,0}) && !isLibraryClass(n.typeName)){
// Java default constructor: runs the implicit super() chain.
std::string owner; if(const Method* bc=implicitBaseCtor(n.typeName,owner)){ emit(OP_DUP); emit(OP_CALL,ctorFuncIndex(owner,bc)); emit(OP_POP); }
}
if(ctor){
int fidx=resolvedIndex(ctor);
if(fidx<0){ auto target=funcIndex_.find(n.typeName+"::"+ctor->name); if(target!=funcIndex_.end()) fidx=target->second; }
if(fidx<0) throw std::runtime_error("Semantic error: constructor of '"+n.typeName+"' is not registered");
emit(OP_DUP);
emitArgsCoerced(n.args,ctor);
emit(OP_CALL,fidx);
emit(OP_POP);
}
}
// Guide chain `new T(...) :: G1 :: G2 ...` (syntax 2.3). Lower the head to
// its instance (emitNew leaves the initialized instance on the stack), then
// apply each Guide as a zero-arg method call on that instance, in order:
// DUP the instance as `this`, CALL T::Gi, POP the (discarded) return. The
// instance itself remains on the stack, so the chain is fluent and the
// whole expression evaluates to the constructed object.
void emitGuideChain(const GuideChainExpr& g){
if(syntax_<SyntaxVersion{2,3}) throw std::runtime_error("Semantic error: Guide chains require #sleela 2.3");
emitExpr(g.head.get());
std::string owner=exprStructType(g.head.get());
for(const std::string& gn:g.guides){
auto target=funcIndex_.find(owner+"::"+gn);
if(target==funcIndex_.end()) throw std::runtime_error("Semantic error: Guide '"+gn+"' is not a method of class '"+owner+"'");
emit(OP_DUP); // [instance, instance] -- instance as `this`
emit(OP_CALL,target->second); // [instance, ret]
emit(OP_POP); // [instance] -- discard the Guide's return
}
}
// Static access through a class name (Java Class.member): the name is not
// a local, an instance field or a static of the current class, and the
// class declares the member.
// Function index of the overload chosen by semantic analysis, or -1.
int resolvedIndex(const Method* m) const {
if(!m) return -1;
auto f=funcIndexByPtr_.find(m); return f==funcIndexByPtr_.end()?-1:f->second;
}
bool isStaticClassRef(const Expr* e, std::string& cls) const {
auto v=dynamic_cast<const VarExpr*>(e);
if(!v) return false;
if(ctx_ && ctx_->slotOf(v->name)>=0) return false;
if(instanceFieldOffset(v->name)>=0) return false;
if(fieldGlobal_.count(currentClass_+"::"+v->name)) return false;
if(!structLayout_.count(v->name)) return false;
cls=v->name;
return true;
}
void emitMember(const MemberAccess& m){
if(m.arrayLength){ emitExpr(m.base.get()); emit(OP_ARRLEN); return; } // syntax 3.2: a.length
// Back-propagate the terminal degree requirement to the origin.
// next.next is the Degree-2 proposal. When that proposal is itself
// static, its viewpoint extends by another two degrees to Degree 4.
// The four-step form is therefore explicit and bounded.
if(auto base=dynamic_cast<const VarExpr*>(m.base.get())){
if(base->name=="next" && m.field=="next"){
emit(OP_CONST,slvm_add_const_int(vm_,kProtectedSystemDegree));
return;
}
}
if(auto a=dynamic_cast<const MemberAccess*>(m.base.get())){
if(auto b=dynamic_cast<const MemberAccess*>(a->base.get())){
if(auto root=dynamic_cast<const VarExpr*>(b->base.get())){
if(root->name=="next" && b->field=="next" &&
a->field=="next" && m.field=="next"){
emit(OP_CONST,slvm_add_const_int(vm_,kStaticExtensionViewpointDegree));
return;
}
}
}
}
{ std::string sc; if(isStaticClassRef(m.base.get(),sc)){ auto g=fieldGlobal_.find(sc+"::"+m.field);
if(g!=fieldGlobal_.end()){ emit(OP_LOADG,g->second); return; } } }
if(m.field=="ref"){
// Implicit object reference: x.ref. A declared field named ref wins.
const std::string rtn=exprStructType(m.base.get());
auto rl=rtn.empty()?structLayout_.end():structLayout_.find(rtn);
if(rl!=structLayout_.end() && !rl->second.fieldOffset.count("ref")){
emitExpr(m.base.get()); emit(OP_REF,SLREF_PACK(SLREF_OF,0)); return;
}
}
int off=-1;memberLayout(m.base.get(),m.field,off);emitExpr(m.base.get());emit(OP_GETFIELD,off);
}
// True when `e` is the bare name `Ptr` and nothing named Ptr is in scope, so
// the builtin Ptr namespace applies (mirrors how Munction is recognised).
bool isRefNamespace(const Expr* e) const {
auto v=dynamic_cast<const VarExpr*>(e);
if(!v||v->name!="Ptr") return false;
if(ctx_ && ctx_->slotOf("Ptr")>=0) return false;
if(instanceFieldOffset("Ptr")>=0) return false;
if(fieldGlobal_.count(currentClass_+"::Ptr")) return false;
if(structLayout_.count("Ptr")) return false;
return true;
}
// Lower Ptr.<fn>(...). Each is one OP_REF whose operand selects the view.
void emitRefCall(const MethodCall& mc){
struct Fn{ const char* name; int sel; int argc; };
static const Fn fns[]={
{"valid",SLREF_VALID,1},{"old",SLREF_OLD,1},{"id",SLREF_ID,1},{"gen",SLREF_GEN,1},
{"type",SLREF_TYPE,1},{"fields",SLREF_FIELDS,1},{"bytes",SLREF_BYTES,1},{"age",SLREF_AGE,1},
{"live",SLREF_LIVE,0},{"limit",SLREF_LIMIT,0}};
for(const Fn& f:fns){
if(mc.method!=f.name) continue;
if((int)mc.args.size()!=f.argc) throw std::runtime_error("Semantic error: Ptr."+mc.method+"() expects "+std::to_string(f.argc)+" argument(s), got "+std::to_string(mc.args.size()));
if(f.argc==1) emitExpr(mc.args[0].get());
emit(OP_REF,SLREF_PACK(f.sel,0)); return;
}
throw std::runtime_error("Semantic error: Ptr has no function '"+mc.method+"'");
}
// Lower a fluent `.method(args)` call. Munction reach verbs consume the
// receiver's reach handle and push it back (so the chain keeps flowing);
// closeWithReceipt/reception push a String. This is the source surface for
// the reach-composition sentence (syntax 1.3).
void emitMethodCall(const MethodCall& mc){
if(mc.superConstructor||mc.thisConstructor){ emitConstructorInvocation(mc); if(syntax_<SyntaxVersion{3,0}||!mc.resolved) emit(OP_CONST,addNullConst()); return; }
const std::string& m=mc.method;
auto oneArgStr=[&](const char* verb){ if(mc.args.size()!=1) throw std::runtime_error("Semantic error: Munction "+std::string(verb)+"(...) takes exactly one argument"); };
auto noArg=[&](const char* verb){ if(!mc.args.empty()) throw std::runtime_error("Semantic error: Munction "+std::string(verb)+"() takes no arguments"); };
// The reach opener `Munction.start(name)` begins a chain and yields a
// reach handle. It parses as MethodCall(VarExpr("Munction"), "start").
if(m=="start"){
if(auto recv=dynamic_cast<const VarExpr*>(mc.receiver.get())){
if(recv->name=="Munction"){
if(syntax_<SyntaxVersion{1,3}) throw std::runtime_error("Semantic error: Munction requires #sleela 1.3");
oneArgStr("start"); emitExpr(mc.args[0].get()); emit(OP_MUN_START); return;
}
}
}
// The Munction reach verbs. Each expects the receiver to evaluate to a
// reach handle; the op leaves the handle (or a String) on the stack.
if(m=="connect"||m=="enable"||m=="send"||m=="thatch"||m=="consume"||m=="latch"||m=="closeWithReceipt"||m=="close"||m=="reception"){
if(syntax_<SyntaxVersion{1,3}) throw std::runtime_error("Semantic error: Munction requires #sleela 1.3");
emitExpr(mc.receiver.get());
if(m=="connect"){oneArgStr("connect");emitExpr(mc.args[0].get());emit(OP_MUN_CONNECT);return;}
if(m=="enable"){oneArgStr("enable");emitExpr(mc.args[0].get());emit(OP_MUN_ENABLE);return;}
if(m=="send"){oneArgStr("send");emitExpr(mc.args[0].get());emit(OP_MUN_SEND);return;}
if(m=="thatch"){oneArgStr("thatch");emitExpr(mc.args[0].get());emit(OP_MUN_THATCH);return;}
if(m=="consume"){noArg("consume");emit(OP_MUN_CONSUME);return;}
if(m=="latch"){noArg("latch");emit(OP_MUN_LATCH);return;}
if(m=="reception"){noArg("reception");emit(OP_MUN_RECEPTION);return;}
/* close / closeWithReceipt */ noArg(m.c_str());emit(OP_MUN_CLOSE);return;
}
if(isRefNamespace(mc.receiver.get())){ emitRefCall(mc); return; }
{ std::string sc; if(isStaticClassRef(mc.receiver.get(),sc)){
auto st=funcIndex_.find(sc+"::"+m);
if(st==funcIndex_.end() && m=="deref"){
// Implicit Class.deref(ref): the object if the ref is valid and an
// instance of Class, else null.
if(mc.args.size()!=1) throw std::runtime_error("Semantic error: '"+sc+".deref' expects 1 argument, got "+std::to_string(mc.args.size()));
emitExpr(mc.args[0].get());
emit(OP_REF,SLREF_PACK(SLREF_DEREF,structLayout_.at(sc).typeIndex)); return;
}
int ri=resolvedIndex(mc.resolved);
if(ri>=0 || (st!=funcIndex_.end() && methods_[st->second].method->isStatic)){
const int fi = ri>=0 ? ri : st->second;
const Method* sm=methods_[fi].method;
if(sm->isStatic){
if((int)mc.args.size()!=(int)sm->params.size())throw std::runtime_error("Semantic error: method '"+sc+"::"+m+"' expects "+std::to_string(sm->params.size())+" argument(s), got "+std::to_string(mc.args.size()));
emitArgsCoerced(mc.args,sm);emit(OP_CALL,fi);return;
}
} } }
// Java String instance method (semantic analysis bound it to the static
// JavaStringMethods.<m>(String self, ...)): push the receiver as the
// first argument, then the arguments, and call the resolved function.
if(mc.stringReceiver){
int fi=resolvedIndex(mc.resolved);
if(fi<0)throw std::runtime_error("Semantic error: String method '"+m+"' did not resolve to a JavaStringMethods function");
const Method* sm=methods_[fi].method;
if((int)mc.args.size()+1!=(int)sm->params.size())throw std::runtime_error("Semantic error: String method '"+m+"' expects "+std::to_string(sm->params.size()>0?sm->params.size()-1:0)+" argument(s), got "+std::to_string(mc.args.size()));
emitExpr(mc.receiver.get());
for(size_t i=0;i<mc.args.size();++i){ emitExpr(mc.args[i].get()); coerceToDeclared(sm->params[i+1].type); }
emit(OP_CALL,fi);
return;
}
const std::string receiverType=exprStructType(mc.receiver.get());
auto target=funcIndex_.find(receiverType+"::"+m);
int fidx = target==funcIndex_.end() ? -1 : target->second;
{ int ri=resolvedIndex(mc.resolved); if(ri>=0 && target!=funcIndex_.end()) fidx=ri; }
if(fidx<0)throw std::runtime_error("Semantic error: class '"+(receiverType.empty()?std::string("<unknown>"):receiverType)+"' has no method '"+m+"'");
const Method* method=methods_[fidx].method;
if(method->isStatic)throw std::runtime_error("Semantic error: static method '"+receiverType+"::"+m+"' must be called through its class");
if((int)mc.args.size()!=(int)method->params.size())throw std::runtime_error("Semantic error: method '"+receiverType+"::"+m+"' expects "+std::to_string(method->params.size())+" argument(s), got "+std::to_string(mc.args.size()));
if(method->isProtected&&receiverType!=currentClass_)throw std::runtime_error("protected method access denied");
emitExpr(mc.receiver.get());
// `super.m()` is never virtual.
if(dynamic_cast<const SuperExpr*>(mc.receiver.get())){ emitArgsCoerced(mc.args,method); emit(OP_CALL,fidx); return; }
emitInstanceCall(receiverType,method,fidx,mc.args);
}
void emitVar(const VarExpr& v){
if(v.name=="next"){emit(OP_CONST,slvm_add_const_int(vm_,kNextSystemDegree));return;}
int slot=ctx_->slotOf(v.name);if(slot>=0){emit(OP_LOADL,slot);return;}
int off=instanceFieldOffset(v.name);if(off>=0){emitThis();emit(OP_GETFIELD,off);return;}
int g=fieldSlot(v.name);if(g>=0){emit(OP_LOADG,g);return;}
throw std::runtime_error("Semantic error: use of undeclared variable '"+v.name+"'");
}
void emitUnary(const Unary& u){
// Java ++ / -- (SLEELA.syntax 43.6 rule 12): x += 1 leaves the new value;
// the postfix form then undoes the step on the stack copy (old value).
if(u.op=="++"||u.op=="--"||u.op=="post++"||u.op=="post--"){
const bool inc=(u.op=="++"||u.op=="post++"); const bool post=u.op.rfind("post",0)==0;
emitAssignTo(u.operand.get(), inc?"+":"-", [&]{ emit(OP_CONST,slvm_add_const_int(vm_,1)); });
if(post){ emit(OP_CONST,slvm_add_const_int(vm_,1)); emit(inc?OP_SUB:OP_ADD); }
return;
}
emitExpr(u.operand.get());if(u.op=="-")emit(OP_NEG);else if(u.op=="!")emit(OP_NOT);else if(u.op=="~")emit(OP_BNOT);else throw std::runtime_error("Semantic error: unknown unary operator '"+u.op+"'");}
void emitBinary(const Binary& b){
const std::string&o=b.op;
// Short-circuit boolean operators: the right side must NOT be evaluated
// when the left already decides the result (Java/C semantics). This also
// means side effects / calls on the right are skipped, as required.
if(o=="&&"){
// lhs; if false -> result false (skip rhs); else result = rhs.
emitExpr(b.lhs.get());
int jf=emit(OP_JMPF,0); // lhs false -> short-circuit
emitExpr(b.rhs.get()); // result is rhs (a bool)
int jend=emit(OP_JMP,0);
patch(jf,here());
emit(OP_CONST,slvm_add_const_bool(vm_,0)); // false
patch(jend,here());
return;
}
if(o=="||"){
// lhs; if false -> result = rhs; else (lhs true) -> result true,
// skipping rhs. Uses only OP_JMPF (no jump-if-true opcode needed).
emitExpr(b.lhs.get());
int jf=emit(OP_JMPF,0); // lhs false -> go evaluate rhs
emit(OP_CONST,slvm_add_const_bool(vm_,1)); // lhs true -> result true
int jend=emit(OP_JMP,0);
patch(jf,here());
emitExpr(b.rhs.get()); // result is rhs
patch(jend,here());
return;
}
emitExpr(b.lhs.get());emitExpr(b.rhs.get());
if(o=="+"){ if(b.charMask)emit(OP_ADDCHAR,(int)b.charMask); else emit(OP_ADD); }else if(o=="-")emit(OP_SUB);else if(o=="*")emit(OP_MUL);else if(o=="/")emit(OP_DIV);else if(o=="%")emit(OP_MOD);else if(o=="&")emit(OP_BAND);else if(o=="|")emit(OP_BOR);else if(o=="^")emit(OP_BXOR);else if(o=="<<")emit(OP_BSHL);else if(o==">>")emit(OP_BSHR);else if(o==">>>")emit(OP_BUSHR);else if(o=="==")emit(OP_EQ);else if(o=="!=")emit(OP_NE);else if(o=="<")emit(OP_LT);else if(o=="<=")emit(OP_LE);else if(o==">")emit(OP_GT);else if(o==">=")emit(OP_GE);else throw std::runtime_error("Semantic error: unknown binary operator '"+o+"'");}
// SleelaUI (ui*) built-ins: map the SLeeLa-facing name to its bridge id,
// arity-check, emit the args, then OP_UI_CALL<id>. Returns true if handled.
bool tryEmitUiBuiltin(const Call& c){
const std::string& n=c.callee;
static const std::map<std::string,int> uiIds = {
{"uiAppCreate",SLUI_FN_APP_CREATE},{"uiAppRun",SLUI_FN_APP_RUN},{"uiAppPump",SLUI_FN_APP_PUMP},
{"uiAppQuit",SLUI_FN_APP_QUIT},{"uiAppDestroy",SLUI_FN_APP_DESTROY},{"uiBackend",SLUI_FN_BACKEND},
{"uiBackendName",SLUI_FN_BACKEND_NAME},{"uiVersion",SLUI_FN_VERSION},
{"uiWindowCreate",SLUI_FN_WINDOW_CREATE},{"uiWindowShow",SLUI_FN_WINDOW_SHOW},{"uiWindowHide",SLUI_FN_WINDOW_HIDE},
{"uiWindowRoot",SLUI_FN_WINDOW_ROOT},{"uiWindowSetTitle",SLUI_FN_WINDOW_SET_TITLE},
{"uiWindowClosed",SLUI_FN_WINDOW_CLOSED},
{"uiWindowSetTheme",SLUI_FN_WINDOW_SET_THEME},{"uiWindowRedraw",SLUI_FN_WINDOW_REDRAW},
{"uiWindowSetBuffering",SLUI_FN_WINDOW_SET_BUFFERING},{"uiWindowBuffering",SLUI_FN_WINDOW_BUFFERING},
{"uiWindowSetMinSize",SLUI_FN_WINDOW_SET_MIN_SIZE},{"uiWindowSetMaxSize",SLUI_FN_WINDOW_SET_MAX_SIZE},
{"uiWindowSetSizeLimits",SLUI_FN_WINDOW_SET_SIZE_LIMITS},
{"uiWindowMinWidth",SLUI_FN_WINDOW_MIN_WIDTH},{"uiWindowMinHeight",SLUI_FN_WINDOW_MIN_HEIGHT},
{"uiWindowMaxWidth",SLUI_FN_WINDOW_MAX_WIDTH},{"uiWindowMaxHeight",SLUI_FN_WINDOW_MAX_HEIGHT},
{"uiBox",SLUI_FN_BOX},{"uiGrid",SLUI_FN_GRID},{"uiFrame",SLUI_FN_FRAME},{"uiCard",SLUI_FN_CARD},
{"uiHeaderBar",SLUI_FN_HEADER_BAR},{"uiStatusBar",SLUI_FN_STATUS_BAR},{"uiSeparator",SLUI_FN_SEPARATOR},
{"uiScrolledView",SLUI_FN_SCROLLED_VIEW},{"uiScrolledScrollTo",SLUI_FN_SCROLLED_SCROLL_TO},
{"uiScrolledScrollBy",SLUI_FN_SCROLLED_SCROLL_BY},{"uiScrolledScrollX",SLUI_FN_SCROLLED_SCROLL_X},
{"uiScrolledScrollY",SLUI_FN_SCROLLED_SCROLL_Y},
{"uiSpacer",SLUI_FN_SPACER},{"uiButton",SLUI_FN_BUTTON},{"uiLinkButton",SLUI_FN_LINK_BUTTON},
{"uiToggle",SLUI_FN_TOGGLE},{"uiCheckBox",SLUI_FN_CHECK_BOX},{"uiRadioButton",SLUI_FN_RADIO_BUTTON},
{"uiComboBox",SLUI_FN_COMBO_BOX},{"uiComboBoxAdd",SLUI_FN_COMBO_BOX_ADD},{"uiSpinButton",SLUI_FN_SPIN_BUTTON},
{"uiEntry",SLUI_FN_ENTRY},{"uiSearchEntry",SLUI_FN_SEARCH_ENTRY},{"uiPasswordEntry",SLUI_FN_PASSWORD_ENTRY},
{"uiSlider",SLUI_FN_SLIDER},{"uiScrollBar",SLUI_FN_SCROLL_BAR},{"uiProgressBar",SLUI_FN_PROGRESS_BAR},
{"uiLevelBar",SLUI_FN_LEVEL_BAR},{"uiSpinner",SLUI_FN_SPINNER},{"uiLabel",SLUI_FN_LABEL},
{"uiHeading",SLUI_FN_HEADING},{"uiImage",SLUI_FN_IMAGE},{"uiAvatar",SLUI_FN_AVATAR},
{"uiBadge",SLUI_FN_BADGE},{"uiChip",SLUI_FN_CHIP},{"uiInfoBar",SLUI_FN_INFO_BAR},{"uiTooltip",SLUI_FN_TOOLTIP},
{"uiThrobber",SLUI_FN_THROBBER},{"uiThrobberSetWidth",SLUI_FN_THROBBER_SET_WIDTH},
{"uiThrobberSetIntensity",SLUI_FN_THROBBER_SET_INTENSITY},{"uiThrobberSetHue",SLUI_FN_THROBBER_SET_HUE},
{"uiWidgetMargin",SLUI_FN_WIDGET_SET_MARGIN},{"uiWidgetAlign",SLUI_FN_WIDGET_SET_ALIGN},
{"uiWidgetExpand",SLUI_FN_WIDGET_SET_EXPAND},{"uiWidgetSizeRequest",SLUI_FN_WIDGET_SET_SIZE_REQ},
{"uiWidgetSensitive",SLUI_FN_WIDGET_SET_SENSITIVE},{"uiWidgetVisible",SLUI_FN_WIDGET_SET_VISIBLE},
{"uiWidgetSuggested",SLUI_FN_WIDGET_SET_SUGGESTED},{"uiWidgetDestructive",SLUI_FN_WIDGET_SET_DESTRUCT},
{"uiWidgetSetText",SLUI_FN_WIDGET_SET_TEXT},{"uiWidgetSetIcon",SLUI_FN_WIDGET_SET_ICON},
{"uiPopupCreate",SLUI_FN_POPUP_CREATE},{"uiPopupSetOpen",SLUI_FN_POPUP_SET_OPEN},{"uiPopupIsOpen",SLUI_FN_POPUP_IS_OPEN},
{"uiPopupSetAnchor",SLUI_FN_POPUP_SET_ANCHOR},{"uiPopupAnchorTo",SLUI_FN_POPUP_ANCHOR_TO},
{"uiWifiOpenSettings",SLUI_FN_WIFI_OPEN_SETTINGS},
{"uiWifiScan",SLUI_FN_WIFI_SCAN},{"uiWifiNetworkCount",SLUI_FN_WIFI_NETWORK_COUNT},
{"uiWifiNetworkSsid",SLUI_FN_WIFI_NETWORK_SSID},{"uiWifiNetworkBssid",SLUI_FN_WIFI_NETWORK_BSSID},
{"uiWifiNetworkSignal",SLUI_FN_WIFI_NETWORK_SIGNAL},{"uiWifiNetworkSecurity",SLUI_FN_WIFI_NETWORK_SECURITY},
{"uiWifiConnect",SLUI_FN_WIFI_CONNECT},{"uiWifiDisconnect",SLUI_FN_WIFI_DISCONNECT},
{"uiWifiStatusName",SLUI_FN_WIFI_STATUS_NAME},
{"uiBallumSupported",SLUI_FN_BALLUM_SUPPORTED},{"uiBallumBackendName",SLUI_FN_BALLUM_BACKEND_NAME},
{"uiBallumEnumerate",SLUI_FN_BALLUM_ENUMERATE},{"uiBallumDisplayCount",SLUI_FN_BALLUM_DISPLAY_COUNT},
{"uiBallumDisplayId",SLUI_FN_BALLUM_DISPLAY_ID},{"uiBallumDisplayName",SLUI_FN_BALLUM_DISPLAY_NAME},
{"uiBallumDisplayWidth",SLUI_FN_BALLUM_DISPLAY_WIDTH},{"uiBallumDisplayHeight",SLUI_FN_BALLUM_DISPLAY_HEIGHT},
{"uiBallumDisplayPrimary",SLUI_FN_BALLUM_DISPLAY_PRIMARY},{"uiBallumDisplayCaps",SLUI_FN_BALLUM_DISPLAY_CAPS},
{"uiBallumSetPixel",SLUI_FN_BALLUM_SET_PIXEL},{"uiBallumGetPixel",SLUI_FN_BALLUM_GET_PIXEL},
{"uiBallumSetBrightness",SLUI_FN_BALLUM_SET_BRIGHTNESS},{"uiBallumSetWarmth",SLUI_FN_BALLUM_SET_WARMTH},
{"uiBallumSetGamma",SLUI_FN_BALLUM_SET_GAMMA},{"uiBallumStatusName",SLUI_FN_BALLUM_STATUS_NAME},
{"uiBallumHasInput",SLUI_FN_BALLUM_HAS_INPUT},{"uiBallumPoll",SLUI_FN_BALLUM_POLL},
{"uiBallumEventX",SLUI_FN_BALLUM_EVENT_X},{"uiBallumEventY",SLUI_FN_BALLUM_EVENT_Y},
{"uiBallumEventButton",SLUI_FN_BALLUM_EVENT_BUTTON},{"uiBallumEventSource",SLUI_FN_BALLUM_EVENT_SOURCE},
{"uiBallumEventContact",SLUI_FN_BALLUM_EVENT_CONTACT},{"uiBallumEventModifiers",SLUI_FN_BALLUM_EVENT_MODIFIERS},
{"uiBallumEventTypeName",SLUI_FN_BALLUM_EVENT_TYPE_NAME},
{"uiBallumHasKeyboard",SLUI_FN_BALLUM_HAS_KEYBOARD},{"uiBallumPollKey",SLUI_FN_BALLUM_POLL_KEY},
{"uiBallumLogoReady",SLUI_FN_BALLUM_LOGO_READY},{"uiBallumLogoBlend",SLUI_FN_BALLUM_LOGO_BLEND},
{"uiBallumLogoLoad",SLUI_FN_BALLUM_LOGO_LOAD},{"uiBallumLogoSetEffect",SLUI_FN_BALLUM_LOGO_SET_EFFECT},
{"uiBallumFxCount",SLUI_FN_BALLUM_FX_COUNT},{"uiBallumFxName",SLUI_FN_BALLUM_FX_NAME},
{"uiBallumFxByName",SLUI_FN_BALLUM_FX_BY_NAME},
{"uiBallumHasSurface",SLUI_FN_BALLUM_HAS_SURFACE},{"uiBallumClaimSurface",SLUI_FN_BALLUM_CLAIM_SURFACE},
{"uiBallumPresent",SLUI_FN_BALLUM_PRESENT},{"uiBallumReleaseSurface",SLUI_FN_BALLUM_RELEASE_SURFACE},
{"uiWidgetSetToggle",SLUI_FN_WIDGET_SET_TOGGLE},
{"uiWidgetSetValue",SLUI_FN_WIDGET_SET_VALUE},{"uiWidgetGetText",SLUI_FN_WIDGET_GET_TEXT},
{"uiWidgetGetToggle",SLUI_FN_WIDGET_GET_TOGGLE},{"uiWidgetGetValue",SLUI_FN_WIDGET_GET_VALUE},
{"uiWidgetTakeActivated",SLUI_FN_WIDGET_TAKE_ACTIVATED},{"uiWidgetIsHovered",SLUI_FN_WIDGET_IS_HOVERED},
{"uiWidgetTakePressed",SLUI_FN_WIDGET_TAKE_PRESSED},{"uiWidgetTakeReleased",SLUI_FN_WIDGET_TAKE_RELEASED},
{"uiWidgetTakeHoverEntered",SLUI_FN_WIDGET_TAKE_HOVER_ENTERED},{"uiWidgetTakeHoverLeft",SLUI_FN_WIDGET_TAKE_HOVER_LEFT},
{"uiThemePreset",SLUI_FN_THEME_PRESET},
{"uiThemeDestroy",SLUI_FN_THEME_DESTROY},{"uiThemeLoadConfig",SLUI_FN_THEME_LOAD_CONFIG},
{"uiThemeSetBaseColor",SLUI_FN_THEME_SET_BASE},{"uiThemeSetBg",SLUI_FN_THEME_SET_BG},
{"uiThemeSetSurface",SLUI_FN_THEME_SET_SURFACE},{"uiThemeSetSurfaceHi",SLUI_FN_THEME_SET_SURFACE_HI},
{"uiThemeSetChrome",SLUI_FN_THEME_SET_CHROME},{"uiThemeSetBorder",SLUI_FN_THEME_SET_BORDER},
{"uiThemeSetFg",SLUI_FN_THEME_SET_FG},{"uiThemeSetFgDim",SLUI_FN_THEME_SET_FG_DIM},
{"uiThemeSetAccent",SLUI_FN_THEME_SET_ACCENT},{"uiThemeSetAccentFg",SLUI_FN_THEME_SET_ACCENT_FG},
{"uiThemeSetDanger",SLUI_FN_THEME_SET_DANGER},{"uiThemeSetRadius",SLUI_FN_THEME_SET_RADIUS},
{"uiThemeSetControlHeight",SLUI_FN_THEME_SET_CONTROL_H},{"uiThemeSetFont",SLUI_FN_THEME_SET_FONT},
{"uiScreenWidth",SLUI_FN_SCREEN_WIDTH},{"uiScreenHeight",SLUI_FN_SCREEN_HEIGHT},
};
auto it=uiIds.find(n);
if(it==uiIds.end())return false;
int id=it->second;
int want=sleela_ui_arity(id);
if((int)c.args.size()!=want)
throw std::runtime_error("Semantic error: "+n+"() expects "+std::to_string(want)+" argument(s), got "+std::to_string(c.args.size()));
for(const auto& a:c.args) emitExpr(a.get());
emit(OP_UI_CALL,id);
return true;
}
bool tryEmitBuiltin(const Call& c){
const std::string& n=c.callee;
if(n.size()>2 && n[0]=='u' && n[1]=='i' && n[2]>='A' && n[2]<='Z'){ if(tryEmitUiBuiltin(c)) return true; }
auto litInt=[&](const Expr*e,const char*what)->int{auto il=dynamic_cast<const IntLit*>(e);if(!il)throw std::runtime_error("Semantic error: "+std::string(what)+" must be an integer literal");return(int)il->value;};
// Host-authorized Native Drive. nativeOpen/nativeClose manage a
// VM-owned opaque module handle; nativeCall crosses only the versioned
// scalar/UTF-8 ABI and falls back to a same-name SLeeLa method when the
// plugin has no typed entry (or arguments are VM-owned composites).
if(n=="nativeOpen"){
if(syntax_<SyntaxVersion{3,0})throw std::runtime_error("Semantic error: Native Drive requires #sleela 3.0");
if(c.args.size()!=1)throw std::runtime_error("Semantic error: nativeOpen(path) takes exactly one String argument");
emitExpr(c.args[0].get()); emit(OP_NATIVE_OPEN); return true;
}
if(n=="nativeClose"){
if(syntax_<SyntaxVersion{3,0})throw std::runtime_error("Semantic error: Native Drive requires #sleela 3.0");
if(c.args.size()!=1)throw std::runtime_error("Semantic error: nativeClose(handle) takes exactly one argument");
emitExpr(c.args[0].get()); emit(OP_NATIVE_CLOSE); return true;
}
// Java String construction from explicit UTF-16 code units. This is
// intentionally a compile-time constructor: each argument must be an
// integer literal in [0, 65535], so embedded NUL and isolated surrogate
// code units are represented losslessly without a C-string boundary.
// The resulting constant is an SL_UTF16 value, not a legacy SL_STR.
if(n=="javaStringFromCodeUnits"){
if(syntax_<SyntaxVersion{3,0})throw std::runtime_error("Semantic error: javaStringFromCodeUnits requires #sleela 3.0");
if(c.args.size()>65535)throw std::runtime_error("Semantic error: javaStringFromCodeUnits accepts at most 65535 UTF-16 code units");
std::vector<uint16_t> units; units.reserve(c.args.size());
for(size_t i=0;i<c.args.size();++i){
auto literal=dynamic_cast<const IntLit*>(c.args[i].get());
if(!literal)throw std::runtime_error("Semantic error: javaStringFromCodeUnits argument "+std::to_string(i+1)+" must be an integer literal");
if(literal->value<0 || literal->value>65535)throw std::runtime_error("Semantic error: javaStringFromCodeUnits argument "+std::to_string(i+1)+" is outside the UTF-16 code-unit range 0..65535");
units.push_back(static_cast<uint16_t>(literal->value));
}
emit(OP_CONST,slvm_add_const_utf16(vm_,units.data(),units.size()));
return true;
}
// Convert a runtime legacy UTF-8 String to a VM-owned Java UTF-16 String.
// The current SL_STR storage is NUL-terminated, so embedded NUL must be
// created with javaStringFromCodeUnits; malformed UTF-8 fails closed.
if(n=="javaStringFromUtf8"){
if(syntax_<SyntaxVersion{3,0})throw std::runtime_error("Semantic error: javaStringFromUtf8 requires #sleela 3.0");
if(c.args.size()!=1)throw std::runtime_error("Semantic error: javaStringFromUtf8(value) takes exactly one argument");
emitExpr(c.args[0].get()); emit(OP_JSTR_FROM_UTF8); return true;
}
// Convert a VM-owned Java UTF-16 String back to a legacy UTF-8 String.
// Lossless or refused at run time: unpaired surrogates, embedded NUL
// and text beyond SL_MAX_STRTEXT bytes fail closed.
if(n=="javaStringToUtf8"){
if(syntax_<SyntaxVersion{3,0})throw std::runtime_error("Semantic error: javaStringToUtf8 requires #sleela 3.0");
if(c.args.size()!=1)throw std::runtime_error("Semantic error: javaStringToUtf8(value) takes exactly one argument");
emitExpr(c.args[0].get()); emit(OP_JSTR_TO_UTF8); return true;
}
// Build a one-unit Java UTF-16 String from a run-time code unit 0..65535
// (the run-time companion of the compile-time javaStringFromCodeUnits).
if(n=="javaStringFromCodeUnit"){
if(syntax_<SyntaxVersion{3,0})throw std::runtime_error("Semantic error: javaStringFromCodeUnit requires #sleela 3.0");
if(c.args.size()!=1)throw std::runtime_error("Semantic error: javaStringFromCodeUnit(codeUnit) takes exactly one argument");
emitExpr(c.args[0].get()); emit(OP_JSTR_FROM_CODE_UNIT); return true;
}
// Runtime operations on VM-owned Java UTF-16 String values.
if(n=="javaStringLength" || n=="javaStringHashCode"){
if(syntax_<SyntaxVersion{3,0})throw std::runtime_error("Semantic error: Java UTF-16 String operations require #sleela 3.0");
if(c.args.size()!=1)throw std::runtime_error("Semantic error: "+n+"(value) takes exactly one argument");
emitExpr(c.args[0].get()); emit(n=="javaStringLength"?OP_JSTR_LENGTH:OP_JSTR_HASH_CODE); return true;
}
if(n=="javaStringCharAt" || n=="javaStringCodePointAt"){
if(syntax_<SyntaxVersion{3,0})throw std::runtime_error("Semantic error: Java UTF-16 String operations require #sleela 3.0");
if(c.args.size()!=2)throw std::runtime_error("Semantic error: "+n+"(value, index) takes exactly two arguments");
emitExpr(c.args[0].get()); emitExpr(c.args[1].get()); emit(n=="javaStringCharAt"?OP_JSTR_CHAR_AT:OP_JSTR_CODE_POINT_AT); return true;
}
if(n=="javaStringCodePointCount" || n=="javaStringOffsetByCodePoints" || n=="javaStringSubstring"){
if(syntax_<SyntaxVersion{3,0})throw std::runtime_error("Semantic error: Java UTF-16 String operations require #sleela 3.0");
if(c.args.size()!=3)throw std::runtime_error("Semantic error: "+n+"(value, index, count/end) takes exactly three arguments");
for(const auto& a:c.args)emitExpr(a.get());
emit(n=="javaStringCodePointCount"?OP_JSTR_CODE_POINT_COUNT:(n=="javaStringOffsetByCodePoints"?OP_JSTR_OFFSET_BY_CODE_POINTS:OP_JSTR_SUBSTRING)); return true;
}
if(n=="javaStringConcat" || n=="javaStringCompareTo"){
if(syntax_<SyntaxVersion{3,0})throw std::runtime_error("Semantic error: Java UTF-16 String operations require #sleela 3.0");
if(c.args.size()!=2)throw std::runtime_error("Semantic error: "+n+"(left, right) takes exactly two arguments");
emitExpr(c.args[0].get()); emitExpr(c.args[1].get());
emit(n=="javaStringConcat"?OP_JSTR_CONCAT:OP_JSTR_COMPARE_TO); return true;
}
if(n=="nativeCall"){
if(syntax_<SyntaxVersion{3,0})throw std::runtime_error("Semantic error: Native Drive requires #sleela 3.0");
if(c.args.size()<2 || c.args.size()>4096)throw std::runtime_error("Semantic error: nativeCall(handle, method, ...args) requires a handle, method String, and at most 4094 arguments");
for(const auto& argument : c.args) emitExpr(argument.get());
emit(OP_NATIVE_CALL, (int)c.args.size()-2); return true;
}
if(n=="spawn"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: spawn(method) takes exactly one argument");auto var=dynamic_cast<const VarExpr*>(c.args[0].get());if(!var)throw std::runtime_error("Semantic error: spawn(method) argument must be a method name");auto it=funcIndex_.find(var->name);if(it==funcIndex_.end())it=funcIndex_.find(currentClass_+"::"+var->name);if(it==funcIndex_.end())throw std::runtime_error("Semantic error: spawn of unknown method '"+var->name+"'");if(!methods_[it->second].method->isStatic)throw std::runtime_error("Semantic error: spawn target '"+var->name+"' must be static because a thread has no instance receiver");if(!methods_[it->second].method->params.empty())throw std::runtime_error("Semantic error: spawn target '"+var->name+"' must take no parameters");emit(OP_SPAWN,it->second);return true;}
if(n=="join"){if(!c.args.empty())throw std::runtime_error("Semantic error: join() takes no arguments");emit(OP_JOINALL);emit(OP_CONST,addNullConst());return true;}
if(n=="lock"||n=="unlock"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: "+n+"(id) takes exactly one argument");int id=litInt(c.args[0].get(),(n+" id").c_str());emit(n=="lock"?OP_LOCK:OP_UNLOCK,id);emit(OP_CONST,addNullConst());return true;}
if(n=="send"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: send(slot, value) takes two arguments");int slot=litInt(c.args[0].get(),"send slot");emitExpr(c.args[1].get());emit(OP_SEND,slot);emit(OP_CONST,addNullConst());return true;}
if(n=="recv"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: recv(slot) takes exactly one argument");emit(OP_RECV,litInt(c.args[0].get(),"recv slot"));return true;}
// Native big-integer multiply: bigmul(a, b, result). a, b, result are
// int[] of base-1,000,000,000 little-endian limbs. Multiplies a * b
// with the native Karatsuba kernel directly over the limb buffers (one
// opcode, no per-limb bytecode loop) and writes the product into
// result, which must hold at least len(a)+len(b) limbs. Evaluates to
// the int count of significant result limbs.
if(n=="bigmul"){
if(c.args.size()!=3)throw std::runtime_error("Semantic error: bigmul(a, b, result) takes exactly three int[] arguments");
emitExpr(c.args[0].get()); // a
emitExpr(c.args[1].get()); // b
emitExpr(c.args[2].get()); // result (top of stack)
emit(OP_BIGMUL);
return true;
}
// Native big-integer add: bigadd(a, b, result). Adds base-1e9 limb
// arrays a + b into result (needs max(len(a),len(b))+1 limbs). Evaluates
// to the significant result-limb count.
if(n=="bigadd"){
if(c.args.size()!=3)throw std::runtime_error("Semantic error: bigadd(a, b, result) takes exactly three int[] arguments");
emitExpr(c.args[0].get()); // a
emitExpr(c.args[1].get()); // b
emitExpr(c.args[2].get()); // result (top of stack)
emit(OP_BIGADD);
return true;
}
// Native big-integer divide by a small integer:
// bigdivmod(dividend, divisor, result). Divides the base-1e9 limb array
// `dividend` by the small int `divisor` (1..1e9-1), writes the quotient
// limbs into result (len(dividend) suffices), and evaluates to the
// integer remainder.
if(n=="bigdivmod"){
if(c.args.size()!=3)throw std::runtime_error("Semantic error: bigdivmod(dividend, divisor, result) takes exactly three arguments");
emitExpr(c.args[0].get()); // dividend (deepest)
emitExpr(c.args[1].get()); // divisor (int)
emitExpr(c.args[2].get()); // result (top of stack)
emit(OP_BIGDIVMOD);
return true;
}
// Native big-integer subtract: bigsub(a, b, result). Computes a - b
// (requires a >= b) over base-1e9 limb arrays into result (needs len(a)
// limbs). Evaluates to the significant result-limb count.
if(n=="bigsub"){
if(c.args.size()!=3)throw std::runtime_error("Semantic error: bigsub(a, b, result) takes exactly three int[] arguments");
emitExpr(c.args[0].get()); // a (deepest)
emitExpr(c.args[1].get()); // b
emitExpr(c.args[2].get()); // result (top of stack)
emit(OP_BIGSUB);
return true;
}
// Native big-integer divide of big by big:
// bigdiv(num, den, quoOut, remOut). Writes num/den into quoOut (needs
// len(num) limbs) and num%den into remOut (needs len(den) limbs).
// Evaluates to the significant quotient-limb count.
if(n=="bigdiv"){
if(c.args.size()!=4)throw std::runtime_error("Semantic error: bigdiv(num, den, quoOut, remOut) takes exactly four int[] arguments");
emitExpr(c.args[0].get()); // num (deepest)
emitExpr(c.args[1].get()); // den
emitExpr(c.args[2].get()); // quoOut
emitExpr(c.args[3].get()); // remOut (top of stack)
emit(OP_BIGDIV);
return true;
}
// Native big-integer floor square root: bigisqrt(a, result). Writes
// floor(sqrt(a)) into result (needs (len(a)+1)/2 + 1 limbs). Evaluates
// to the significant result-limb count.
if(n=="bigisqrt"){
if(c.args.size()!=2)throw std::runtime_error("Semantic error: bigisqrt(a, result) takes exactly two int[] arguments");
emitExpr(c.args[0].get()); // a (deepest)
emitExpr(c.args[1].get()); // result (top of stack)
emit(OP_BIGISQRT);
return true;
}
if(n=="structPack"||n=="structUnpack"){
if(syntax_<SyntaxVersion{1,2})throw std::runtime_error("Semantic error: struct transport built-ins require #sleela 1.2");
}
if(n=="structPack"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: structPack(instance) takes exactly one argument");emitExpr(c.args[0].get());emit(OP_STRUCTPACK);return true;}
if(n=="structUnpack"){
if(c.args.size()!=2)throw std::runtime_error("Semantic error: structUnpack(TypeName, json) takes exactly two arguments");
auto typeVar=dynamic_cast<const VarExpr*>(c.args[0].get());
if(!typeVar)throw std::runtime_error("Semantic error: structUnpack first argument must be a struct type name");
auto it=structLayout_.find(typeVar->name);
if(it==structLayout_.end())throw std::runtime_error("Semantic error: structUnpack of unknown struct type '"+typeVar->name+"'");
emitExpr(c.args[1].get());emit(OP_STRUCTUNPACK,it->second.typeIndex);return true;
}
if(n=="listen"||n=="accept"||n=="connect"||n=="sockread"||n=="sockwrite"||n=="sockclose"){
if(syntax_<SyntaxVersion{1,1})throw std::runtime_error("Semantic error: network built-ins require #sleela 1.1");
}
if(n=="listen"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: listen(port) takes exactly one argument");emitExpr(c.args[0].get());emit(OP_LISTEN);return true;}
if(n=="accept"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: accept(socket) takes exactly one argument");emitExpr(c.args[0].get());emit(OP_ACCEPT);return true;}
if(n=="connect"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: connect(host, port) takes exactly two arguments");emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_CONNECT);return true;}
if(n=="sockread"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: sockread(socket) takes exactly one argument");emitExpr(c.args[0].get());emit(OP_SOCKREAD);return true;}
if(n=="sockwrite"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: sockwrite(socket, data) takes exactly two arguments");emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_SOCKWRITE);return true;}
if(n=="sockclose"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: sockclose(socket) takes exactly one argument");emitExpr(c.args[0].get());emit(OP_SOCKCLOSE);return true;}
// Linux file/I/O built-ins. Version 1.1 adds a POSIX-oriented
// descriptor layer; handles are VM-local integers, never raw FDs.
if(n=="pipe"||n=="pipePeer"||n=="fifoCreate"||n=="npfsCreate"||n=="openFile"||n=="read"||n=="write"||n=="close"||n=="unlinkFile"){
if(syntax_<SyntaxVersion{1,1})throw std::runtime_error("Semantic error: file I/O built-ins require #sleela 1.1");
}
if(n=="pipe"){
if(!c.args.empty())throw std::runtime_error("Semantic error: pipe() takes no arguments");
emit(OP_PIPE);return true;
}
if(n=="pipePeer"){
if(c.args.size()!=1)throw std::runtime_error("Semantic error: pipePeer(handle) takes one argument");
emitExpr(c.args[0].get());emit(OP_PIPEPEER);return true;
}
if(n=="fifoCreate"||n=="npfsCreate"){
if(c.args.size()!=2)throw std::runtime_error("Semantic error: "+n+"(path, mode) takes two arguments");
emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_FIFO_MK);return true;
}
if(n=="openFile"){
if(c.args.size()!=2)throw std::runtime_error("Semantic error: openFile(path, mode) takes two arguments");
emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_FILEOPEN);return true;
}
if(n=="read"){
if(c.args.size()!=1)throw std::runtime_error("Semantic error: read(handle) takes one argument");
emitExpr(c.args[0].get());emit(OP_FILEREAD);return true;
}
if(n=="write"){
if(c.args.size()!=2)throw std::runtime_error("Semantic error: write(handle, data) takes two arguments");
emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_FILEWRITE);return true;
}
if(n=="close"){
if(c.args.size()!=1)throw std::runtime_error("Semantic error: close(handle) takes one argument");
emitExpr(c.args[0].get());emit(OP_FILECLOSE);return true;
}
if(n=="unlinkFile"){
if(c.args.size()!=1)throw std::runtime_error("Semantic error: unlinkFile(path) takes one argument");
emitExpr(c.args[0].get());emit(OP_FILEUNLINK);return true;
}
if(n=="timeUtcMillis"){if(!c.args.empty())throw std::runtime_error("Semantic error: timeUtcMillis() takes no arguments");emit(OP_TIME_UTC_MS);return true;}
if(n=="timeUtcNanos"){if(!c.args.empty())throw std::runtime_error("Semantic error: timeUtcNanos() takes no arguments");emit(OP_TIME_UTC_NS);return true;}
if(n=="timeMonotonicNanos"){if(!c.args.empty())throw std::runtime_error("Semantic error: timeMonotonicNanos() takes no arguments");emit(OP_TIME_MONO_NS);return true;}
if(n=="timePrecisionMillis"){if(!c.args.empty())throw std::runtime_error("Semantic error: timePrecisionMillis() takes no arguments");emit(OP_TIME_PRECISION_MS);return true;}
if(n=="timeLocation"){if(!c.args.empty())throw std::runtime_error("Semantic error: timeLocation() takes no arguments");emit(OP_TIME_LOCATION);return true;}
if(n=="timeHttpDate"){if(!c.args.empty())throw std::runtime_error("Semantic error: timeHttpDate() takes no arguments");emit(OP_TIME_HTTP_DATE);return true;}
if(n=="timeJson"){if(!c.args.empty())throw std::runtime_error("Semantic error: timeJson() takes no arguments");emit(OP_TIME_JSON);return true;}
if(n=="timeNtp"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: timeNtp(host) takes one argument");emitExpr(c.args[0].get());emit(OP_TIME_NTP);return true;}
if(n=="timeSetLocation"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: timeSetLocation(country, timezone) takes two arguments");emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_TIME_SET_LOCATION);return true;}
if(n=="sleep"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: sleep(milliseconds) takes one argument");emitExpr(c.args[0].get());emit(OP_SLEEP);emit(OP_CONST,addNullConst());return true;}
// ---- Munction (syntax 1.3): the reach-composition opener. ----
// Munction.start(name) opens a reach and yields a reach handle; the
// fluent verbs (.connect/.send/...) are lowered by emitMethodCall.
if(n=="Munction.start"){
if(syntax_<SyntaxVersion{1,3})throw std::runtime_error("Semantic error: Munction requires #sleela 1.3");
if(c.args.size()!=1)throw std::runtime_error("Semantic error: Munction.start(name) takes exactly one argument");
emitExpr(c.args[0].get());emit(OP_MUN_START);return true;
}
// ---- Synchro (syntax 1.3): honest packet dispatch + measurement. ----
if(n=="synchroOpen"||n=="synchroDispatch"||n=="synchroReport"||n=="synchroClose"||
n=="synchroSent"||n=="synchroReceived"||n=="synchroMean"||n=="synchroMin"||
n=="synchroMax"||n=="synchroP95"||n=="synchroLoss"){
if(syntax_<SyntaxVersion{1,3})throw std::runtime_error("Semantic error: Synchro built-ins require #sleela 1.3");
}
if(n=="synchroOpen"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: synchroOpen(host, port) takes two arguments");emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_SYN_OPEN);return true;}
if(n=="synchroDispatch"){if(c.args.size()!=3)throw std::runtime_error("Semantic error: synchroDispatch(handle, len, timeoutMs) takes three arguments");emitExpr(c.args[0].get());emitExpr(c.args[1].get());emitExpr(c.args[2].get());emit(OP_SYN_DISPATCH);return true;}
if(n=="synchroReport"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: synchroReport(handle) takes one argument");emitExpr(c.args[0].get());emit(OP_SYN_REPORT);return true;}
if(n=="synchroClose"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: synchroClose(handle) takes one argument");emitExpr(c.args[0].get());emit(OP_SYN_CLOSE);return true;}
{
struct { const char* name; int sel; } synStats[] = {
{"synchroSent",0},{"synchroReceived",1},{"synchroMean",2},{"synchroMin",3},
{"synchroMax",4},{"synchroP95",5},{"synchroLoss",6}
};
for(const auto& st:synStats){ if(n==st.name){ if(c.args.size()!=1)throw std::runtime_error("Semantic error: "+n+"(handle) takes one argument");emitExpr(c.args[0].get());emit(OP_SYN_STAT,st.sel);return true; } }
}
// ---- Best-of (syntax 1.3): configurable route/accuracy selection ----
if(n=="bestOfNew"||n=="bestOfWeight"||n=="bestOfMinVersion"||n=="bestOfCostBudget"||
n=="bestOfCandidate"||n=="bestOfRecord"||n=="bestOfScore"||n=="bestOfBest"||
n=="bestOfChoice"||n=="bestOfReport"||n=="bestOfClose"||
n=="bestOfMean"||n=="bestOfLoss"||n=="bestOfJitter"||n=="bestOfCertainty"||
n=="bestOfCandidateArch"||n=="bestOfArchRealized"||
n=="bestOfArch"||n=="bestOfArchParam"||n=="bestOfArchState"){
if(syntax_<SyntaxVersion{1,3})throw std::runtime_error("Semantic error: best-of built-ins require #sleela 1.3");
}
auto emitArgs=[&](const Call& call){ for(const auto& a:call.args) emitExpr(a.get()); };
// ---- Idea System(TM) realtime canvas (native-CPU render + physics) ----
if(n=="ideaCanvasCreate"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: ideaCanvasCreate(cols, rows) takes two arguments");emitArgs(c);emit(OP_IC_CREATE);return true;}
if(n=="ideaCanvasDestroy"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: ideaCanvasDestroy(handle) takes one argument");emitArgs(c);emit(OP_IC_DESTROY);return true;}
if(n=="ideaCanvasCols"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: ideaCanvasCols(handle) takes one argument");emitArgs(c);emit(OP_IC_COLS);return true;}
if(n=="ideaCanvasRows"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: ideaCanvasRows(handle) takes one argument");emitArgs(c);emit(OP_IC_ROWS);return true;}
if(n=="ideaCanvasCount"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: ideaCanvasCount(handle) takes one argument");emitArgs(c);emit(OP_IC_COUNT);return true;}
if(n=="ideaCanvasSetParams"){if(c.args.size()!=5)throw std::runtime_error("Semantic error: ideaCanvasSetParams(handle, decay, flowGain, hueBase, coupling) takes five arguments");emitArgs(c);emit(OP_IC_SETPARAMS);return true;}
if(n=="ideaCanvasExcite"){if(c.args.size()!=4)throw std::runtime_error("Semantic error: ideaCanvasExcite(handle, col, row, amount) takes four arguments");emitArgs(c);emit(OP_IC_EXCITE);return true;}
if(n=="ideaCanvasStep"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: ideaCanvasStep(handle, dt) takes two arguments");emitArgs(c);emit(OP_IC_STEP);return true;}
if(n=="ideaCanvasAdvance"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: ideaCanvasAdvance(handle, frameDt) takes two arguments");emitArgs(c);emit(OP_IC_ADVANCE);return true;}
if(n=="ideaCanvasTimestep"){if(!c.args.empty())throw std::runtime_error("Semantic error: ideaCanvasTimestep() takes no arguments");emit(OP_IC_TIMESTEP);return true;}
if(n=="ideaCanvasIntensityAt"){if(c.args.size()!=3)throw std::runtime_error("Semantic error: ideaCanvasIntensityAt(handle, col, row) takes three arguments");emitArgs(c);emit(OP_IC_INTENSITY);return true;}
if(n=="ideaCanvasHasRenderer"){if(!c.args.empty())throw std::runtime_error("Semantic error: ideaCanvasHasRenderer() takes no arguments");emit(OP_IC_HASREND);return true;}
if(n=="ideaCanvasOpenWindow"){if(c.args.size()!=4)throw std::runtime_error("Semantic error: ideaCanvasOpenWindow(handle, width, height, title) takes four arguments");emitArgs(c);emit(OP_IC_OPENWIN);return true;}
if(n=="ideaCanvasShouldClose"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: ideaCanvasShouldClose(handle) takes one argument");emitArgs(c);emit(OP_IC_SHOULDCLOSE);return true;}
if(n=="ideaCanvasPresent"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: ideaCanvasPresent(handle) takes one argument");emitArgs(c);emit(OP_IC_PRESENT);return true;}
if(n=="ideaCanvasRun"){if(c.args.size()!=4)throw std::runtime_error("Semantic error: ideaCanvasRun(handle, width, height, title) takes four arguments");emitArgs(c);emit(OP_IC_RUN);return true;}
if(n=="ideaCanvasSetBackendPolicy"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: ideaCanvasSetBackendPolicy(handle, policy) takes two arguments");emitArgs(c);emit(OP_IC_SETPOLICY);return true;}
if(n=="ideaCanvasPolicy"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: ideaCanvasPolicy(handle) takes one argument");emitArgs(c);emit(OP_IC_POLICY);return true;}
if(n=="ideaCanvasActiveBackend"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: ideaCanvasActiveBackend(handle) takes one argument");emitArgs(c);emit(OP_IC_BACKEND);return true;}
if(n=="ideaCanvasGpuAvailable"){if(!c.args.empty())throw std::runtime_error("Semantic error: ideaCanvasGpuAvailable() takes no arguments");emit(OP_IC_GPUAVAIL);return true;}
if(n=="ideaCanvasMeasuredHz"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: ideaCanvasMeasuredHz(handle) takes one argument");emitArgs(c);emit(OP_IC_MEASHZ);return true;}
if(n=="ideaCanvasMigrate"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: ideaCanvasMigrate(handle, target) takes two arguments");emitArgs(c);emit(OP_IC_MIGRATE);return true;}
if(n=="audioNew"){
if(c.args.size()!=2)throw std::runtime_error("Semantic error: audioNew(sampleRate, outputPath) takes two arguments");
emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_AUDIO_NEW);return true;
}
if(n=="audioAdd"){
if(c.args.size()!=4)throw std::runtime_error("Semantic error: audioAdd(handle, path, startSeconds, gainDb) takes four arguments");
emitArgs(c);emit(OP_AUDIO_ADD);return true;
}
if(n=="audioControls"){
if(c.args.size()!=8)throw std::runtime_error("Semantic error: audioControls(handle, bass, mid, treble, masterGain, pan, leftGain, rightGain) takes eight arguments");
emitArgs(c);emit(OP_AUDIO_CONTROLS);return true;
}
if(n=="audioValidate"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: audioValidate(handle) takes one argument");emitExpr(c.args[0].get());emit(OP_AUDIO_VALIDATE);return true;}
if(n=="audioRender"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: audioRender(handle) takes one argument");emitExpr(c.args[0].get());emit(OP_AUDIO_RENDER);return true;}
if(n=="audioClose"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: audioClose(handle) takes one argument");emitExpr(c.args[0].get());emit(OP_AUDIO_CLOSE);return true;}
if(n=="audioPlatform"){if(!c.args.empty())throw std::runtime_error("Semantic error: audioPlatform() takes no arguments");emit(OP_AUDIO_PLATFORM);return true;}
// Array built-ins (syntax 1.4). arrayNew(n) pops size; the index ops
// mirror a[i] / a[i]=v and are also exposed as named builtins.
if(n=="arrayNew"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: arrayNew(size) takes one argument");emitExpr(c.args[0].get());emit(OP_NEWARRAY);return true;}
if(n=="arrayLength"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: arrayLength(array) takes one argument");emitExpr(c.args[0].get());emit(OP_ARRLEN);return true;}
if(n=="arrayGet"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: arrayGet(array, index) takes two arguments");emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_ARRGET);return true;}
if(n=="arraySet"){if(c.args.size()!=3)throw std::runtime_error("Semantic error: arraySet(array, index, value) takes three arguments");emitExpr(c.args[0].get());emitExpr(c.args[1].get());emitExpr(c.args[2].get());emit(OP_ARRSET);return true;}
if(n=="arrayPush"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: arrayPush(array, value) takes two arguments");emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_ARRPUSH);return true;}
// ---- Operating-system system calls (syntax 1.5). The os* built-ins
// reach the genuine host System API (Win32 / POSIX / Apple) through the
// VM's sleela_os backend. A spawned process is a VM-local handle, the
// same bounded-handle discipline as sockets/files. ----
if(n=="osPlatform"||n=="osCapability"||n=="osGetEnv"||n=="osSetEnv"||n=="osCurrentDir"||
n=="osChangeDir"||n=="osHostName"||n=="osUserName"||n=="osTempDir"||n=="osProcessId"||
n=="osExists"||n=="osIsDir"||n=="osFileSize"||n=="osMakeDir"||n=="osRemove"||n=="osRename"||
n=="osRun"||n=="osSpawn"||n=="osWait"||n=="osKill"||n=="osProcessClose"){
if(syntax_<SyntaxVersion{1,5})throw std::runtime_error("Semantic error: operating-system built-ins require #sleela 1.5");
}
if(n=="osPlatform"){if(!c.args.empty())throw std::runtime_error("Semantic error: osPlatform() takes no arguments");emit(OP_OS_PLATFORM);return true;}
if(n=="osCapability"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osCapability(capability) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_CAPABILITY);return true;}
if(n=="osGetEnv"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osGetEnv(name) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_GETENV);return true;}
if(n=="osSetEnv"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: osSetEnv(name, value) takes two arguments");emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_OS_SETENV);return true;}
if(n=="osCurrentDir"){if(!c.args.empty())throw std::runtime_error("Semantic error: osCurrentDir() takes no arguments");emit(OP_OS_CWD);return true;}
if(n=="osChangeDir"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osChangeDir(path) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_CHDIR);return true;}
if(n=="osHostName"){if(!c.args.empty())throw std::runtime_error("Semantic error: osHostName() takes no arguments");emit(OP_OS_HOSTNAME);return true;}
if(n=="osUserName"){if(!c.args.empty())throw std::runtime_error("Semantic error: osUserName() takes no arguments");emit(OP_OS_USERNAME);return true;}
if(n=="osTempDir"){if(!c.args.empty())throw std::runtime_error("Semantic error: osTempDir() takes no arguments");emit(OP_OS_TEMPDIR);return true;}
if(n=="osProcessId"){if(!c.args.empty())throw std::runtime_error("Semantic error: osProcessId() takes no arguments");emit(OP_OS_PID);return true;}
if(n=="osExists"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osExists(path) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_EXISTS);return true;}
if(n=="osIsDir"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osIsDir(path) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_ISDIR);return true;}
if(n=="osFileSize"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osFileSize(path) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_FILESIZE);return true;}
if(n=="osMakeDir"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osMakeDir(path) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_MKDIR);return true;}
if(n=="osRemove"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osRemove(path) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_REMOVE);return true;}
if(n=="osRename"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: osRename(from, to) takes two arguments");emitExpr(c.args[0].get());emitExpr(c.args[1].get());emit(OP_OS_RENAME);return true;}
if(n=="osRun"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osRun(command) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_RUN);return true;}
if(n=="osSpawn"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osSpawn(command) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_SPAWN);return true;}
if(n=="osWait"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osWait(process) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_WAIT);return true;}
if(n=="osKill"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osKill(process) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_KILL);return true;}
if(n=="osProcessClose"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: osProcessClose(process) takes one argument");emitExpr(c.args[0].get());emit(OP_OS_PCLOSE);return true;}
// ---- OSLS native ABI calls (syntax 2.5). Every call is dispatched
// through the registered typed binding table; record/array results
// cross the VM boundary as bounded JSON Strings.
static const std::map<std::string,int> oslsIds = {
{"oslsSystemInfo",0},{"oslsProcessInfo",1},{"oslsEnumerateProcesses",2},
{"oslsGetEnvironmentValue",3},{"oslsEnumerateEnvironment",4},
{"oslsGetFileInfo",5},{"oslsListDirectory",6},{"oslsGetCPUInfo",7},
{"oslsGetTimezoneInfo",8},{"oslsGetNetworkInterfaces",9},
{"oslsCronValidate",10},{"oslsCronNextAfter",11},
{"oslsGetMemoryInfo",12},{"oslsGetAvailableMemory",13},
{"oslsGetDiskSpace",14},{"oslsGetVolumeInfo",15},
{"oslsGetSystemLoad",16},{"oslsGetCapabilities",17},
{"oslsGetRuntimeInfo",18},{"oslsGetNativeError",19},
{"oslsPathNormalize",20},{"oslsPathJoin",21},
{"oslsPathResolve",22},{"oslsGetPathInfo",23},
{"oslsNetworkResolve",24}
};
{
auto osls = oslsIds.find(n);
if (osls != oslsIds.end()) {
if (syntax_ < SyntaxVersion{2,5})
throw std::runtime_error("Semantic error: OSLS native bindings require #sleela 2.5");
static const int arity[] = {0,1,0,1,0,1,1,0,0,0,1,2,
0,0,1,1,0,0,0,0,1,2,1,1,1};
if ((int)c.args.size() != arity[osls->second])
throw std::runtime_error("Semantic error: OSLS binding has the wrong argument count");
emitArgs(c);
emit(OP_OSLS_CALL, osls->second);
return true;
}
}
if(n=="bestOfNew"){if(!c.args.empty())throw std::runtime_error("Semantic error: bestOfNew() takes no arguments");emit(OP_BEST_NEW);return true;}
if(n=="bestOfWeight"){if(c.args.size()!=3)throw std::runtime_error("Semantic error: bestOfWeight(handle, axis, weight) takes three arguments");emitArgs(c);emit(OP_BEST_WEIGHT);return true;}
if(n=="bestOfMinVersion"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: bestOfMinVersion(handle, minVersion) takes two arguments");emitArgs(c);emit(OP_BEST_MINVER);return true;}
if(n=="bestOfCostBudget"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: bestOfCostBudget(handle, budget) takes two arguments");emitArgs(c);emit(OP_BEST_BUDGET);return true;}
if(n=="bestOfCandidate"){if(c.args.size()!=10)throw std::runtime_error("Semantic error: bestOfCandidate(handle, name, route, timeoutMs, payloadLen, gapMs, flags, version, cost, replays) takes ten arguments");emitArgs(c);emit(OP_BEST_CAND);return true;}
if(n=="bestOfRecord"){if(c.args.size()!=3)throw std::runtime_error("Semantic error: bestOfRecord(handle, idx, rttUs) takes three arguments");emitArgs(c);emit(OP_BEST_RECORD);return true;}
if(n=="bestOfScore"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: bestOfScore(handle, idx) takes two arguments");emitArgs(c);emit(OP_BEST_SCORE);return true;}
if(n=="bestOfBest"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: bestOfBest(handle) takes one argument");emitArgs(c);emit(OP_BEST_BEST);return true;}
if(n=="bestOfChoice"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: bestOfChoice(handle) takes one argument");emitArgs(c);emit(OP_BEST_CHOICE);return true;}
if(n=="bestOfReport"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: bestOfReport(handle) takes one argument");emitArgs(c);emit(OP_BEST_REPORT);return true;}
if(n=="bestOfCandidateArch"){if(c.args.size()!=5)throw std::runtime_error("Semantic error: bestOfCandidateArch(handle, idx, architecture, param, realized) takes five arguments");emitArgs(c);emit(OP_BEST_ARCH);return true;}
if(n=="bestOfArchRealized"){if(c.args.size()!=3)throw std::runtime_error("Semantic error: bestOfArchRealized(handle, idx, realized) takes three arguments");emitArgs(c);emit(OP_BEST_ARCH_STATE);return true;}
if(n=="bestOfClose"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: bestOfClose(handle) takes one argument");emitArgs(c);emit(OP_BEST_CLOSE);return true;}
{
struct { const char* name; int sel; } bestStats[] = {
{"bestOfMean",0},{"bestOfLoss",1},{"bestOfJitter",2},{"bestOfCertainty",3},
{"bestOfArch",4},{"bestOfArchParam",5},{"bestOfArchState",6}
};
for(const auto& st:bestStats){ if(n==st.name){ if(c.args.size()!=2)throw std::runtime_error("Semantic error: "+n+"(handle, idx) takes two arguments");emitArgs(c);emit(OP_BEST_STAT,st.sel);return true; } }
}
auto litStr=[&](const Expr*e,const char*what)->std::string{auto sl=dynamic_cast<const StrLit*>(e);if(!sl)throw std::runtime_error("Semantic error: "+std::string(what)+" must be a string literal (an object name)");return sl->value;};
auto emitStr=[&](const std::string&s){emit(OP_CONST,slvm_add_const_str(vm_,s.c_str()));};
auto emitBool=[&](bool b){emit(OP_CONST,slvm_add_const_bool(vm_,b?1:0));};
if(n=="conduct"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: conduct(name) takes one argument");std::string name=litStr(c.args[0].get(),"conduct name");emitBool(cat_&&cat_->find(name)!=nullptr);return true;}
if(n=="role"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: role(name) takes one argument");std::string name=litStr(c.args[0].get(),"role name");const auto*o=cat_?cat_->find(name):nullptr;emitStr(o?o->role:"");return true;}
if(n=="insight"){if(c.args.size()!=1)throw std::runtime_error("Semantic error: insight(name) takes one argument");std::string name=litStr(c.args[0].get(),"insight name");const auto*o=cat_?cat_->find(name):nullptr;emitStr(o?o->note:"");return true;}
if(n=="congruent"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: congruent(a, b) takes two arguments");std::string a=litStr(c.args[0].get(),"congruent a"),b=litStr(c.args[1].get(),"congruent b");emitBool(cat_&&cat_->congruent(a,b));return true;}
if(n=="route"){if(c.args.size()!=2)throw std::runtime_error("Semantic error: route(a, b) takes two arguments");std::string a=litStr(c.args[0].get(),"route a"),b=litStr(c.args[1].get(),"route b");emitStr(cat_&&cat_->congruent(a,b)?a+" -> "+b:"");return true;}
if(n=="sysdepth"){if(!c.args.empty())throw std::runtime_error("Semantic error: sysdepth() takes no arguments");emit(OP_CONST,slvm_add_const_int(vm_,cat_?cat_->depth:0));return true;}
if(n=="degreemax"){if(!c.args.empty())throw std::runtime_error("Semantic error: degreemax() takes no arguments");emit(OP_CONST,slvm_add_const_int(vm_,cat_?cat_->complexityDegreeMax:0));return true;}
return false;
}
void emitCall(const Call& c){
if(tryEmitBuiltin(c))return;
auto it=funcIndex_.find(currentClass_+"::"+c.callee);
if(it!=funcIndex_.end()){
int fidx=it->second; { int ri=resolvedIndex(c.resolved); if(ri>=0) fidx=ri; }
const Method* target=methods_[fidx].method;
if((int)c.args.size()!=(int)target->params.size())throw std::runtime_error("Semantic error: method '"+currentClass_+"::"+c.callee+"' expects "+std::to_string(target->params.size())+" argument(s), got "+std::to_string(c.args.size()));
if(target->isProtected&&methodOwner_[currentClass_+"::"+c.callee]!=currentClass_)throw std::runtime_error("protected method access denied");
if(!target->isStatic){ emitThis(); emitInstanceCall(currentClass_,target,fidx,c.args); return; }
emitArgsCoerced(c.args,target);emit(OP_CALL,fidx);return;
}
// Native subject helpers are synthesized as qualified class methods.
// Resolve all __Native* helper names consistently with semantic analysis.
if(it==funcIndex_.end()&&c.callee.rfind("__native_",0)==0){
const std::string suffix="::"+c.callee;
for(const auto& entry:funcIndex_){
if(entry.first.size()>=suffix.size()&&entry.first.compare(entry.first.size()-suffix.size(),suffix.size(),suffix)==0&&entry.first.rfind("__Native",0)==0){
it=funcIndex_.find(entry.first);
break;
}
}
}
if(it==funcIndex_.end())it=funcIndex_.find(c.callee);
if(it==funcIndex_.end())throw std::runtime_error("Semantic error: call to unknown method '"+c.callee+"'");
const Method* target=methods_[it->second].method;
if((int)c.args.size()!=(int)target->params.size())throw std::runtime_error("Semantic error: method '"+c.callee+"' expects "+std::to_string(target->params.size())+" argument(s), got "+std::to_string(c.args.size()));
emitArgsCoerced(c.args,target);emit(OP_CALL,it->second);
}
};
} // anonymous namespace
int compile(const Program& prog, SLVM* vm, const catalog::Catalog* cat, const SyntaxVersion& syntax){
SemanticResult semantic = analyzeSemantics(prog, syntax);
if(!semantic.ok()){
// Surface every semantic error, not just the first. The analyzer
// collects all of them; reporting only errors.front() hid the rest and
// forced a fix-one-recompile loop. The first line stays the primary
// message (callers that show one line still get the most relevant one);
// any additional errors follow on their own lines.
std::string msg = semantic.errors.front();
for(size_t i=1;i<semantic.errors.size();++i) msg += "\n " + semantic.errors[i];
if(semantic.errors.size()>1)
msg += "\n(" + std::to_string(semantic.errors.size()) + " semantic errors)";
throw std::runtime_error(msg);
}
Compiler c(prog,vm,cat,syntax);
return c.run();
}
} // namespace sleela