#include "native_method_emit.h" #include #include #include #include #include #include #include #include #include namespace nordshrift { namespace { using namespace sleela; static bool markedNative(const Method& m) { for (const auto& a : m.java.annotations) if (a.name == "native" && a.marker) return true; return false; } static bool scalarType(const std::string& t) { return t == "int" || t == "double" || t == "boolean" || t == "String"; } static std::string cType(const std::string& t) { if (t == "int") return "int64_t"; if (t == "double") return "double"; if (t == "boolean") return "int32_t"; if (t == "String") return "SLNativeString"; if (t == "void") return "void"; throw std::runtime_error("unsupported native ABI type '" + t + "'"); } static std::string cVar(const std::string& name) { return "slv_" + name; } static std::string cString(const std::string& s) { std::ostringstream o; for (unsigned char c : s) { switch (c) { case '\\': o << "\\\\"; break; case '"': o << "\\\""; break; case '\n': o << "\\n"; break; case '\r': o << "\\r"; break; case '\t': o << "\\t"; break; default: if (c < 32 || c >= 127) { const char* hex = "0123456789abcdef"; o << "\\x" << hex[c >> 4] << hex[c & 15] << "\"\""; } else o << static_cast(c); } } return o.str(); } static std::string signature(const ClassDecl& cls, const Method& m) { std::string key = cls.name + "::" + m.name; std::string s = key + "|static|argc=" + std::to_string(m.params.size()) + "|"; for (const auto& p : m.params) s += std::to_string(p.type.size()) + ":" + p.type; s += "|return=" + std::to_string(m.retType.size()) + ":" + m.retType + "|abi=1.0"; return s; } class MethodBodyEmitter { std::ostringstream out; std::map types; std::string returnType; int depth = 0; std::string typeOf(const Expr* e) const { if (dynamic_cast(e)) return "int"; if (dynamic_cast(e)) return "double"; if (dynamic_cast(e)) return "boolean"; if (auto v=dynamic_cast(e)) { auto i=types.find(v->name); if(i==types.end()) throw std::runtime_error("unknown native local '"+v->name+"'"); return i->second; } if (auto u=dynamic_cast(e)) { std::string t=typeOf(u->operand.get()); if(u->op=="!") { if(t=="String") throw std::runtime_error("String values do not support logical negation in ABI v1"); return "boolean"; } if((u->op=="-"||u->op=="+") && (t=="int"||t=="double")) return t; throw std::runtime_error("invalid native unary operand/operator"); } if (auto b=dynamic_cast(e)) { std::string a=typeOf(b->lhs.get()), z=typeOf(b->rhs.get()); if(a=="String"||z=="String") throw std::runtime_error("String arithmetic/comparison is outside native ABI v1"); if(b->op=="&&"||b->op=="||") return "boolean"; if(b->op=="=="||b->op=="!="||b->op=="<"||b->op=="<="||b->op==">"||b->op==">=") { bool numericA=(a=="int"||a=="double"), numericZ=(z=="int"||z=="double"); if(a!=z && !(numericA&&numericZ)) throw std::runtime_error("incompatible native comparison operands"); return "boolean"; } if(b->op=="+"||b->op=="-"||b->op=="*") { if((a!="int"&&a!="double")||(z!="int"&&z!="double")) throw std::runtime_error("native arithmetic requires numeric operands"); return (a=="double"||z=="double")?"double":"int"; } if(b->op=="/"||b->op=="%") throw std::runtime_error("division and remainder are excluded until native error semantics match the VM"); throw std::runtime_error("unsupported native binary operator"); } if (auto c=dynamic_cast(e)) { if(typeOf(c->cond.get())=="String") throw std::runtime_error("String condition is not supported"); std::string a=typeOf(c->thenE.get()),z=typeOf(c->elseE.get()); if(a!=z) throw std::runtime_error("native conditional branches must have the same type"); return a; } if (auto a=dynamic_cast(e)) { auto v=dynamic_cast(a->target.get()); if(!v||a->op!="=") throw std::runtime_error("unsupported native assignment expression"); std::string t=typeOf(v),z=typeOf(a->value.get()); if(t!=z) throw std::runtime_error("native assignment type mismatch"); return t; } throw std::runtime_error("unsupported native expression type"); } void ind() { for (int i=0;i(e)) { out << "INT64_C(" << x->value << ")"; return; } if (auto x=dynamic_cast(e)) { out << std::setprecision(17) << x->value; return; } if (auto x=dynamic_cast(e)) { out << (x->value ? "1" : "0"); return; } if (auto x=dynamic_cast(e)) { (void)typeOf(e); out << cVar(x->name); return; } if (auto x=dynamic_cast(e)) { if (x->op!="-" && x->op!="+" && x->op!="!") throw std::runtime_error("unsupported unary operator '"+x->op+"'"); std::string t=typeOf(e); if (x->op=="-" && t=="int") { out << "sl_i64_neg("; expr(x->operand.get()); out << ")"; } else { out << "(" << x->op; expr(x->operand.get()); out << ")"; } return; } if (auto x=dynamic_cast(e)) { static const char* ops[] = {"+","-","*","/","%","==","!=","<","<=",">",">=","&&","||"}; bool supported=false; for (const char* op:ops) if (x->op==op) supported=true; if (!supported) throw std::runtime_error("unsupported binary operator '"+x->op+"'"); std::string t=typeOf(e); if (x->op=="/" || x->op=="%") throw std::runtime_error("division and remainder are excluded until native error semantics match the VM"); if (t=="int" && x->op=="+") { out << "sl_i64_add("; expr(x->lhs.get()); out << ", "; expr(x->rhs.get()); out << ")"; return; } if (t=="int" && x->op=="-") { out << "sl_i64_sub("; expr(x->lhs.get()); out << ", "; expr(x->rhs.get()); out << ")"; return; } if (t=="int" && x->op=="*") { out << "sl_i64_mul("; expr(x->lhs.get()); out << ", "; expr(x->rhs.get()); out << ")"; return; } out << "("; expr(x->lhs.get()); out << " " << x->op << " "; expr(x->rhs.get()); out << ")"; return; } if (auto x=dynamic_cast(e)) { (void)typeOf(e); out << "("; expr(x->cond.get()); out << " ? "; expr(x->thenE.get()); out << " : "; expr(x->elseE.get()); out << ")"; return; } if (auto x=dynamic_cast(e)) { auto v=dynamic_cast(x->target.get()); if (!v || x->op != "=") throw std::runtime_error("native emitter supports only simple local assignment expressions"); (void)typeOf(e); out << "(" << cVar(v->name) << " = "; expr(x->value.get()); out << ")"; return; } throw std::runtime_error("native emitter encountered an unsupported expression"); } void inlineStmt(const Stmt* s) { if (auto d=dynamic_cast(s)) { if (!scalarType(d->type)) throw std::runtime_error("unsupported local type '" + d->type + "'"); if (types.count(d->name)) throw std::runtime_error("duplicate native local '" + d->name + "'"); if (d->init && typeOf(d->init.get()) != d->type) throw std::runtime_error("native local initializer type mismatch for '" + d->name + "'"); types[d->name]=d->type; out << cType(d->type) << " " << cVar(d->name); if (d->init) { out << " = "; expr(d->init.get()); } else if (d->type == "String") out << " = (SLNativeString){0}"; else out << " = 0"; return; } if (auto a=dynamic_cast(s)) { auto i=types.find(a->name); if(i==types.end()||i->second!=typeOf(a->value.get())) throw std::runtime_error("native assignment type mismatch for '"+a->name+"'"); out << cVar(a->name) << " = "; expr(a->value.get()); return; } if (auto e=dynamic_cast(s)) { expr(e->expr.get()); return; } throw std::runtime_error("unsupported for-loop initializer/update in native method"); } void stmt(const Stmt* s) { if (auto b=dynamic_cast(s)) { ind(); out << "{\n"; ++depth; for (const auto& x:b->stmts) stmt(x.get()); --depth; ind(); out << "}\n"; return; } if (auto d=dynamic_cast(s)) { ind(); inlineStmt(d); out << ";\n"; return; } if (auto a=dynamic_cast(s)) { ind(); inlineStmt(a); out << ";\n"; return; } if (auto e=dynamic_cast(s)) { ind(); inlineStmt(e); out << ";\n"; return; } if (auto r=dynamic_cast(s)) { if(returnType=="void" ? (bool)r->value : (!r->value || typeOf(r->value.get())!=returnType)) throw std::runtime_error("native return type mismatch"); ind(); out << "return"; if (r->value) { out << " "; expr(r->value.get()); } out << ";\n"; return; } if (auto i=dynamic_cast(s)) { if(typeOf(i->cond.get())=="String") throw std::runtime_error("String if-condition is not supported"); ind(); out << "if ("; expr(i->cond.get()); out << ")\n"; stmt(i->thenS.get()); if (i->elseS) { ind(); out << "else\n"; stmt(i->elseS.get()); } return; } if (auto w=dynamic_cast(s)) { if(typeOf(w->cond.get())=="String") throw std::runtime_error("String while-condition is not supported"); ind(); out << "while ("; expr(w->cond.get()); out << ")\n"; stmt(w->body.get()); return; } if (dynamic_cast(s)) throw std::runtime_error("the enhanced for is not supported by the native method emitter"); if (auto f=dynamic_cast(s)) { ind(); out << "for ("; if (f->init) inlineStmt(f->init.get()); out << "; "; if (f->cond && typeOf(f->cond.get())=="String") throw std::runtime_error("String for-condition is not supported"); if (f->cond) expr(f->cond.get()); out << "; "; if (f->update) inlineStmt(f->update.get()); out << ")\n"; stmt(f->body.get()); return; } throw std::runtime_error("native emitter encountered an unsupported statement"); } public: std::string emit(const Method& m, const std::string& symbol) { returnType=m.retType; for(const auto& p:m.params) { if(types.count(p.name)) throw std::runtime_error("duplicate native parameter '"+p.name+"'"); types[p.name]=p.type; } out << "static " << cType(m.retType) << " " << symbol << "("; if (m.params.empty()) out << "void"; for (size_t i=0;istmts) stmt(s.get()); ind(); if (m.retType == "void" && (m.body->stmts.empty() || !dynamic_cast(m.body->stmts.back().get()))) out << "return;\n"; out << "}\n\n"; return out.str(); } }; struct NativeMethod { const ClassDecl* cls; const Method* method; std::string signature; std::string symbol; }; static void validateMethod(const ClassDecl& cls, const Method& m) { if (!m.isStatic) throw std::runtime_error(cls.name+"."+m.name+": only static @native methods have an ABI-v1 receiver contract"); if (!scalarType(m.retType) && m.retType != "void") throw std::runtime_error(cls.name+"."+m.name+": unsupported return type '"+m.retType+"'"); for (const auto& p:m.params) if (!scalarType(p.type)) throw std::runtime_error(cls.name+"."+m.name+": unsupported parameter type '"+p.type+"'"); if (!m.body) throw std::runtime_error(cls.name+"."+m.name+": method has no body"); if (m.retType!="void" && (m.body->stmts.empty() || !dynamic_cast(m.body->stmts.back().get()))) throw std::runtime_error(cls.name+"."+m.name+": ABI-v1 non-void methods must end with a direct return statement"); for (const auto& s:m.body->stmts) { if (auto v=dynamic_cast(s.get())) if (!scalarType(v->type)) throw std::runtime_error(cls.name+"."+m.name+": unsupported local type '"+v->type+"'"); } } } // namespace std::string emitNativeMethods(const sleela::Program& program) { std::vector methods; std::set identities; for (const auto& cls:program.classes) for (const auto& method:cls.methods) { if (!markedNative(method)) continue; validateMethod(cls,method); std::string identity=signature(cls,method); if (!identities.insert(identity).second) throw std::runtime_error("duplicate canonical @native method identity: "+identity); methods.push_back({&cls,&method,identity,"sleela_native_method_"+std::to_string(methods.size())}); } if (methods.empty()) throw std::runtime_error("no @native methods to emit"); std::ostringstream out; out << "/* Generated by SLeeLa: independently addressable @native method plugin. */\n" "#include \n#include \n#include \n" "#include \"native_loader.h\"\n" "typedef struct { const uint8_t *data; uint32_t length; } SLNativeString;\n" "static inline int64_t sl_i64_add(int64_t a,int64_t b){uint64_t u=(uint64_t)a+(uint64_t)b;int64_t r;memcpy(&r,&u,sizeof r);return r;}\n" "static inline int64_t sl_i64_sub(int64_t a,int64_t b){uint64_t u=(uint64_t)a-(uint64_t)b;int64_t r;memcpy(&r,&u,sizeof r);return r;}\n" "static inline int64_t sl_i64_mul(int64_t a,int64_t b){uint64_t u=(uint64_t)a*(uint64_t)b;int64_t r;memcpy(&r,&u,sizeof r);return r;}\n" "static inline int64_t sl_i64_neg(int64_t a){uint64_t u=UINT64_C(0)-(uint64_t)a;int64_t r;memcpy(&r,&u,sizeof r);return r;}\n\n"; for (const auto& nm:methods) { MethodBodyEmitter body; out << body.emit(*nm.method,nm.symbol); } out << "SL_NATIVE_EXPORT uint32_t sl_native_abi_version(void) { return SL_NATIVE_ABI_VERSION; }\n" "SL_NATIVE_EXPORT uint32_t sl_native_typed_abi_version(void) { return SL_NATIVE_TYPED_ABI_VERSION; }\n" "SL_NATIVE_EXPORT int sl_native_run(int argc, const char *const argv[]) { (void)argc; (void)argv; return -1; }\n" "SL_NATIVE_EXPORT int sl_native_call(const char *method, uint32_t argc, const SLNativeValue *argv, SLNativeValue *out_result) {\n" " if (!method || !out_result) return SL_NATIVE_CALL_INVALID_ARGUMENT;\n" " memset(out_result, 0, sizeof(*out_result));\n"; for (const auto& nm:methods) { const Method& m=*nm.method; out << " if (strcmp(method, \"" << cString(nm.signature) << "\") == 0) {\n" " if (argc != " << m.params.size() << "u || (argc && !argv)) return SL_NATIVE_CALL_INVALID_ARGUMENT;\n"; for (size_t i=0;itag = SL_NATIVE_VALUE_NULL;\n"; else if (m.retType=="int") out << " out_result->tag = SL_NATIVE_VALUE_I64; out_result->as.i64 = slv_result;\n"; else if (m.retType=="double") out << " out_result->tag = SL_NATIVE_VALUE_F64; out_result->as.f64 = slv_result;\n"; else if (m.retType=="boolean") out << " out_result->tag = SL_NATIVE_VALUE_BOOL; out_result->as.boolean = slv_result ? 1 : 0;\n"; else out << " if (!slv_result.data && slv_result.length) return SL_NATIVE_CALL_ERROR; out_result->tag = SL_NATIVE_VALUE_UTF8; out_result->as.utf8.data = slv_result.data; out_result->as.utf8.length = slv_result.length;\n"; out << " return SL_NATIVE_CALL_OK;\n }\n"; } out << " return SL_NATIVE_CALL_NOT_HANDLED;\n}\n"; return out.str(); } } // namespace nordshrift