Home /Modules/impl/sleela_emit.cpp

sleela_emit.cpp

impl/nordshrift/sleela_emit.cpp · 640 line(s) · c

// ===========================================================================
// sleela_emit.cpp  --  Transpile a Sleela Program into Java / Sleela / C.
// ===========================================================================
#include "sleela_emit.h"
#include "lowering.h"

#include <sstream>
#include <stdexcept>
#include <typeinfo>

namespace nordshrift {
namespace {

using namespace sleela;

std::string esc(const std::string& s) {
    std::string o;
    for (char c : s) {
        switch (c) {
            case '"': o += "\\\""; break;
            case '\\': o += "\\\\"; break;
            case '\n': o += "\\n"; break;
            case '\t': o += "\\t"; break;
            case '\r': o += "\\r"; break;
            default: o += c;
        }
    }
    return o;
}


// Fail closed: a construct an emitter cannot reproduce must stop the emission,
// never vanish from the output (a silently dropped node changes behaviour).
[[noreturn]] void unsupported(const char* target, const char* what, const std::type_info* t = nullptr) {
    std::string m = std::string("the ") + target + " target cannot emit " + what;
    if (t) m += std::string(" (node ") + t->name() + ")";
    throw std::runtime_error(m);
}

// Declaration-level subset check shared by all targets. `inheritance` is true
// for a target that can print extends/implements (the Sleela target).
void requireDeclarationSubset(const Program& p, const char* target, bool inheritance) {
    for (const auto& c : p.classes) {
        if (c.java.kind != JavaTypeKind::Class) unsupported(target, "interfaces, enums and records");
        if (!inheritance && (!c.java.superclass.empty() || !c.java.interfaces.empty()))
            unsupported(target, "class inheritance (extends/implements)");
        for (const auto& m : c.methods)
            if (m.java.constructor) unsupported(target, "constructors");
    }
}

// ---------------------------------------------------------------------------
// Java emitter: Sleela is Java-like, so this is close to a pretty-printer.
// Each Sleela class -> a Java class; fields -> static fields; methods -> static
// methods; print(x) -> System.out.println(x). Java's own + already concatenates.
// ---------------------------------------------------------------------------
struct JavaGen {
    std::ostringstream out;
    std::string pkg;

    std::string mapType(const std::string& t) {
        if (t == "String") return "String";
        if (t == "int") return "long";       // Sleela ints are 64-bit
        if (t == "double") return "double";
        if (t == "boolean") return "boolean";
        if (t == "void") return "void";
        return "Object";
    }

    void run(const Program& p) {
        requireDeclarationSubset(p, "Java", false);
        out << "// Generated by Nordshrift (Java target)\n";
        for (const auto& a : p.annotations.all()) out << "// @" << a.name << " " << a.value << "\n";
        if (!pkg.empty()) out << "package " << pkg << ";\n\n";
        for (auto& c : p.classes) emitClass(c);
    }

    void ind(int n) { for (int i = 0; i < n; i++) out << "    "; }

    void emitClass(const ClassDecl& c) {
        out << "public final class " << c.name << " {\n";
        for (auto& f : c.fields) {
            ind(1); out << "static " << mapType(f.type) << " " << f.name;
            if (f.init) { out << " = "; emitExpr(f.init.get()); }
            out << ";\n";
        }
        if (!c.fields.empty()) out << "\n";
        for (auto& m : c.methods) emitMethod(m);
        // a Java entry point that calls Sleela main() if present
        for (auto& m : c.methods) if (m.name == "main" && m.params.empty()) {
            ind(1); out << "public static void main(String[] args) { " << c.name << ".main(); }\n";
            break;
        }
        out << "}\n\n";
    }

    void emitMethod(const Method& m) {
        ind(1); out << "static " << mapType(m.retType) << " " << m.name << "(";
        for (size_t i = 0; i < m.params.size(); i++) {
            if (i) out << ", ";
            out << mapType(m.params[i].type) << " " << m.params[i].name;
        }
        out << ") {\n";
        emitBlock(*m.body, 2);
        ind(1); out << "}\n";
    }

    void emitBlock(const Block& b, int n) { for (auto& s : b.stmts) emitStmt(s.get(), n); }
    void emitBody(const Stmt* s, int n) { if (auto b = dynamic_cast<const Block*>(s)) emitBlock(*b, n); else emitStmt(s, n); }
    // An expression whose value is discarded: assignments print without parentheses.
    void emitTop(const Expr* e) {
        if (auto a = dynamic_cast<const AssignmentExpr*>(e)) { emitAssign(a); return; }
        if (auto u = dynamic_cast<const Unary*>(e)) {
            if (u->op == "post++" || u->op == "post--") { emitExpr(u->operand.get()); out << u->op.substr(4); return; }
            if (u->op == "++" || u->op == "--") { out << u->op; emitExpr(u->operand.get()); return; }
        }
        emitExpr(e);
    }
    void emitAssign(const AssignmentExpr* a) {
        if (!dynamic_cast<const VarExpr*>(a->target.get()) && !dynamic_cast<const MemberAccess*>(a->target.get()))
            unsupported("Java", "this assignment target", &typeid(*a->target));
        emitExpr(a->target.get()); out << " " << a->op << " "; emitExpr(a->value.get());
    }
    void emitUnary(const Unary* x) {
        if (x->op == "post++" || x->op == "post--") { out << "("; emitExpr(x->operand.get()); out << x->op.substr(4) << ")"; return; }
        if (x->op == "++" || x->op == "--") { out << "(" << x->op; emitExpr(x->operand.get()); out << ")"; return; }
        out << x->op << "("; emitExpr(x->operand.get()); out << ")";
    }

    void emitStmt(const Stmt* s, int n) {
        if (auto b = dynamic_cast<const Block*>(s)) { ind(n); out << "{\n"; emitBlock(*b, n+1); ind(n); out << "}\n"; return; }
        if (auto d = dynamic_cast<const VarDecl*>(s)) {
            ind(n); out << mapType(d->type) << " " << d->name;
            if (d->init) { out << " = "; emitExpr(d->init.get()); }
            out << ";\n"; return;
        }
        if (auto a = dynamic_cast<const Assign*>(s)) { ind(n); out << a->name << " = "; emitExpr(a->value.get()); out << ";\n"; return; }
        if (auto e = dynamic_cast<const ExprStmt*>(s)) { ind(n); emitTop(e->expr.get()); out << ";\n"; return; }
        if (auto p = dynamic_cast<const PrintStmt*>(s)) { ind(n); out << "System.out.println("; emitExpr(p->expr.get()); out << ");\n"; return; }
        if (auto r = dynamic_cast<const ReturnStmt*>(s)) { ind(n); out << "return"; if (r->value) { out << " "; emitExpr(r->value.get()); } out << ";\n"; return; }
        if (auto i = dynamic_cast<const IfStmt*>(s)) {
            ind(n); out << "if ("; emitExpr(i->cond.get()); out << ") {\n"; emitBody(i->thenS.get(), n+1); ind(n); out << "}";
            if (i->elseS) { out << " else {\n"; emitBody(i->elseS.get(), n+1); ind(n); out << "}"; }
            out << "\n"; return;
        }
        if (auto w = dynamic_cast<const WhileStmt*>(s)) { ind(n); out << "while ("; emitExpr(w->cond.get()); out << ") {\n"; emitBody(w->body.get(), n+1); ind(n); out << "}\n"; return; }
        if (auto fe = dynamic_cast<const ForEachStmt*>(s)) { ind(n); out << "for (" << fe->type << " " << fe->name << " : "; emitExpr(fe->iterable.get()); out << ") {\n"; emitBody(fe->body.get(), n+1); ind(n); out << "}\n"; return; }
        if (auto f = dynamic_cast<const ForStmt*>(s)) {
            ind(n); out << "for (";
            if (f->init) emitInline(f->init.get());
            out << "; ";
            if (f->cond) emitExpr(f->cond.get());
            out << "; ";
            if (f->update) emitInline(f->update.get());
            out << ") {\n"; emitBody(f->body.get(), n+1); ind(n); out << "}\n"; return;
        }
        unsupported("Java", "this statement", &typeid(*s));
    }

    // for-header init/update without indentation or trailing ';'
    void emitInline(const Stmt* s) {
        if (auto d = dynamic_cast<const VarDecl*>(s)) { out << mapType(d->type) << " " << d->name; if (d->init) { out << " = "; emitExpr(d->init.get()); } return; }
        if (auto a = dynamic_cast<const Assign*>(s)) { out << a->name << " = "; emitExpr(a->value.get()); return; }
        if (auto e = dynamic_cast<const ExprStmt*>(s)) { emitTop(e->expr.get()); return; }
        unsupported("Java", "this for-header statement", &typeid(*s));
    }

    void emitExpr(const Expr* e) {
        if (auto x = dynamic_cast<const IntLit*>(e)) { out << x->value << "L"; return; }
        if (auto x = dynamic_cast<const DoubleLit*>(e)) { out << x->value; return; }
        if (auto x = dynamic_cast<const BoolLit*>(e)) { out << (x->value ? "true" : "false"); return; }
        if (auto x = dynamic_cast<const StrLit*>(e)) { out << "\"" << esc(x->value) << "\""; return; }
        if (dynamic_cast<const NullLit*>(e)) { out << "null"; return; }
        if (auto x = dynamic_cast<const VarExpr*>(e)) { out << x->name; return; }
        if (auto x = dynamic_cast<const Unary*>(e)) { emitUnary(x); return; }
        if (auto x = dynamic_cast<const Binary*>(e)) { out << "("; emitExpr(x->lhs.get()); out << " " << x->op << " "; emitExpr(x->rhs.get()); out << ")"; return; }
        if (auto x = dynamic_cast<const AssignmentExpr*>(e)) { out << "("; emitAssign(x); out << ")"; return; }
        if (auto x = dynamic_cast<const ConditionalExpr*>(e)) { out << "("; emitExpr(x->cond.get()); out << " ? "; emitExpr(x->thenE.get()); out << " : "; emitExpr(x->elseE.get()); out << ")"; return; }
        if (auto x = dynamic_cast<const Call*>(e)) {
            out << x->callee << "(";
            for (size_t i = 0; i < x->args.size(); i++) { if (i) out << ", "; emitExpr(x->args[i].get()); }
            out << ")"; return;
        }
        if (dynamic_cast<const ArrayAccess*>(e) || dynamic_cast<const NewExpr*>(e))
            unsupported("Java", "arrays or object creation (a Java array prints as an identity hash and int widens to long, so the output would differ from the VM)", &typeid(*e));
        unsupported("Java", "this expression", &typeid(*e));
    }
};

// ---------------------------------------------------------------------------
// Sleela emitter: canonical pretty-print of the same AST (round-trip target).
// ---------------------------------------------------------------------------
struct SleelaGen {
    std::ostringstream out;

    static std::string modifiers(bool isProtected, bool isStatic) {
        std::string m;
        if (isProtected) m += "protected ";
        if (isStatic) m += "static ";
        return m;
    }
    void run(const Program& p) {
        requireDeclarationSubset(p, "Sleela", true);
        out << "// Generated by Nordshrift (Sleela target)\n";
        auto annotation = [&](const annotation::Annotation& a) { out << "@" << a.name; if (!a.marker) out << "(" << a.value << ")"; out << "\n"; };
        for (const auto& a : p.annotations.all()) annotation(a);
        bool first = true;
        for (auto& c : p.classes) {
            // Annotations written directly before `class` bind to that class on reading, so a document annotation
            // must be followed by a modifier to stay a document annotation. `public` is that modifier. A first class
            // that has annotations of its own as well could not be told apart from the document's: refuse.
            const bool documentFirst = first && !p.annotations.all().empty();
            if (documentFirst && !c.java.annotations.empty()) unsupported("Sleela", "document annotations together with annotations on the first class");
            for (const auto& a : c.java.annotations) annotation(a);
            out << (documentFirst ? "public class " : "class ") << c.name;
            first = false;
            if (!c.java.superclass.empty()) out << " extends " << c.java.superclass;
            for (size_t i = 0; i < c.java.interfaces.size(); i++) out << (i ? ", " : " implements ") << c.java.interfaces[i];
            out << " {\n";
            for (auto& f : c.fields) {
                out << "    " << modifiers(f.isProtected, f.isStatic) << f.type << " " << f.name;
                if (f.init) { out << " = "; emitInitializer(f.init.get()); }
                out << ";\n";
            }
            if (!c.fields.empty()) out << "\n";
            for (auto& m : c.methods) emitMethod(m);
            out << "}\n\n";
        }
    }
    void ind(int n) { for (int i = 0; i < n; i++) out << "    "; }
    // A declaration's initializer. An array initializer `{a, b, c}` (syntax 3.1) is only legal here and
    // nested inside another one, so it is printed by this function and refused anywhere else.
    void emitInitializer(const Expr* e) {
        auto n = dynamic_cast<const NewExpr*>(e);
        if (!n || !n->hasInit) { emitExpr(e); return; }
        out << "{";
        for (size_t i = 0; i < n->init.size(); i++) { if (i) out << ", "; emitInitializer(n->init[i].get()); }
        out << "}";
    }
    void emitMethod(const Method& m) {
        ind(1); out << modifiers(m.isProtected, m.isStatic) << m.retType << " " << m.name << "(";
        for (size_t i = 0; i < m.params.size(); i++) { if (i) out << ", "; out << m.params[i].type << " " << m.params[i].name; }
        out << ") {\n"; emitBlock(*m.body, 2); ind(1); out << "}\n";
    }
    void emitBlock(const Block& b, int n) { for (auto& s : b.stmts) emitStmt(s.get(), n); }
    void emitBody(const Stmt* s, int n) { if (auto b = dynamic_cast<const Block*>(s)) emitBlock(*b, n); else emitStmt(s, n); }
    // An expression whose value is discarded: assignments print without parentheses.
    void emitTop(const Expr* e) {
        if (auto a = dynamic_cast<const AssignmentExpr*>(e)) { emitAssign(a); return; }
        if (auto u = dynamic_cast<const Unary*>(e)) {
            if (u->op == "post++" || u->op == "post--") { emitExpr(u->operand.get()); out << u->op.substr(4); return; }
            if (u->op == "++" || u->op == "--") { out << u->op; emitExpr(u->operand.get()); return; }
        }
        emitExpr(e);
    }
    void emitAssign(const AssignmentExpr* a) {
        if (!dynamic_cast<const VarExpr*>(a->target.get()) && !dynamic_cast<const MemberAccess*>(a->target.get()) &&
            !dynamic_cast<const ArrayAccess*>(a->target.get()))
            unsupported("Sleela", "this assignment target", &typeid(*a->target));
        emitExpr(a->target.get()); out << " " << a->op << " "; emitExpr(a->value.get());
    }
    void emitUnary(const Unary* x) {
        if (x->op == "post++" || x->op == "post--") { out << "("; emitExpr(x->operand.get()); out << x->op.substr(4) << ")"; return; }
        if (x->op == "++" || x->op == "--") { out << "(" << x->op; emitExpr(x->operand.get()); out << ")"; return; }
        out << x->op << "("; emitExpr(x->operand.get()); out << ")";
    }
    void emitStmt(const Stmt* s, int n) {
        if (auto b = dynamic_cast<const Block*>(s)) { ind(n); out << "{\n"; emitBlock(*b, n+1); ind(n); out << "}\n"; return; }
        if (auto d = dynamic_cast<const VarDecl*>(s)) { ind(n); out << d->type << " " << d->name; if (d->init) { out << " = "; emitInitializer(d->init.get()); } out << ";\n"; return; }
        if (auto a = dynamic_cast<const Assign*>(s)) { ind(n); out << a->name << " = "; emitExpr(a->value.get()); out << ";\n"; return; }
        if (auto fa = dynamic_cast<const FieldAssign*>(s)) { ind(n); emitExpr(fa->base.get()); out << "." << fa->field << " = "; emitExpr(fa->value.get()); out << ";\n"; return; }
        if (auto e = dynamic_cast<const ExprStmt*>(s)) { ind(n); emitTop(e->expr.get()); out << ";\n"; return; }
        if (auto p = dynamic_cast<const PrintStmt*>(s)) { ind(n); out << "print("; emitExpr(p->expr.get()); out << ");\n"; return; }
        if (auto r = dynamic_cast<const ReturnStmt*>(s)) { ind(n); out << "return"; if (r->value) { out << " "; emitExpr(r->value.get()); } out << ";\n"; return; }
        if (auto i = dynamic_cast<const IfStmt*>(s)) { ind(n); out << "if ("; emitExpr(i->cond.get()); out << ") {\n"; emitBody(i->thenS.get(), n+1); ind(n); out << "}"; if (i->elseS) { out << " else {\n"; emitBody(i->elseS.get(), n+1); ind(n); out << "}"; } out << "\n"; return; }
        if (auto w = dynamic_cast<const WhileStmt*>(s)) { ind(n); out << "while ("; emitExpr(w->cond.get()); out << ") {\n"; emitBody(w->body.get(), n+1); ind(n); out << "}\n"; return; }
        if (auto fe = dynamic_cast<const ForEachStmt*>(s)) { ind(n); out << "for (" << fe->type << " " << fe->name << " : "; emitExpr(fe->iterable.get()); out << ") {\n"; emitBody(fe->body.get(), n+1); ind(n); out << "}\n"; return; }
        if (auto f = dynamic_cast<const ForStmt*>(s)) { ind(n); out << "for ("; if (f->init) emitInline(f->init.get()); out << "; "; if (f->cond) emitExpr(f->cond.get()); out << "; "; if (f->update) emitInline(f->update.get()); out << ") {\n"; emitBody(f->body.get(), n+1); ind(n); out << "}\n"; return; }
        unsupported("Sleela", "this statement", &typeid(*s));
    }
    void emitInline(const Stmt* s) {
        if (auto d = dynamic_cast<const VarDecl*>(s)) { out << d->type << " " << d->name; if (d->init) { out << " = "; emitInitializer(d->init.get()); } return; }
        if (auto a = dynamic_cast<const Assign*>(s)) { out << a->name << " = "; emitExpr(a->value.get()); return; }
        if (auto e = dynamic_cast<const ExprStmt*>(s)) { emitTop(e->expr.get()); return; }
        unsupported("Sleela", "this for-header statement", &typeid(*s));
    }
    void emitExpr(const Expr* e) {
        if (auto x = dynamic_cast<const IntLit*>(e)) { out << x->value; return; }
        if (auto x = dynamic_cast<const DoubleLit*>(e)) { out << x->value; return; }
        if (auto x = dynamic_cast<const BoolLit*>(e)) { out << (x->value ? "true" : "false"); return; }
        if (auto x = dynamic_cast<const StrLit*>(e)) { out << "\"" << esc(x->value) << "\""; return; }
        if (dynamic_cast<const NullLit*>(e)) { out << "null"; return; }
        if (auto x = dynamic_cast<const VarExpr*>(e)) { out << x->name; return; }
        if (auto x = dynamic_cast<const Unary*>(e)) { emitUnary(x); return; }
        if (auto x = dynamic_cast<const Binary*>(e)) { out << "("; emitExpr(x->lhs.get()); out << " " << x->op << " "; emitExpr(x->rhs.get()); out << ")"; return; }
        if (auto x = dynamic_cast<const AssignmentExpr*>(e)) { out << "("; emitAssign(x); out << ")"; return; }
        if (auto x = dynamic_cast<const ConditionalExpr*>(e)) { out << "("; emitExpr(x->cond.get()); out << " ? "; emitExpr(x->thenE.get()); out << " : "; emitExpr(x->elseE.get()); out << ")"; return; }
        if (auto x = dynamic_cast<const Call*>(e)) { out << x->callee << "("; for (size_t i=0;i<x->args.size();i++){ if(i) out<<", "; emitExpr(x->args[i].get()); } out << ")"; return; }
        if (dynamic_cast<const ThisExpr*>(e)) { out << "this"; return; }
        if (dynamic_cast<const SuperExpr*>(e)) { out << "super"; return; }
        if (auto x = dynamic_cast<const MethodCall*>(e)) {
            emitExpr(x->receiver.get()); out << "." << x->method << "(";
            for (size_t i=0;i<x->args.size();i++){ if(i) out<<", "; emitExpr(x->args[i].get()); }
            out << ")"; return;
        }
        if (auto x = dynamic_cast<const MemberAccess*>(e)) { emitExpr(x->base.get()); out << "." << x->field; return; }
        if (auto x = dynamic_cast<const ArrayAccess*>(e)) { emitExpr(x->base.get()); out << "["; emitExpr(x->index.get()); out << "]"; return; }
        if (auto x = dynamic_cast<const NewExpr*>(e)) {
            if (x->hasInit) unsupported("Sleela", "an array initializer outside a declaration", &typeid(*e));
            if (x->typeName.find('[') != std::string::npos) {
                // `new T[a][b][]`: typeName carries the full rank ("T[][][]"); the sizes are the arguments
                std::string elem = x->typeName; size_t rank = 0;
                while (elem.size() >= 2 && elem.compare(elem.size() - 2, 2, "[]") == 0) { elem.resize(elem.size() - 2); rank++; }
                if (x->args.empty() || x->args.size() > rank) unsupported("Sleela", "this array creation", &typeid(*e));
                out << "new " << elem;
                for (const auto& d : x->args) { out << "["; emitExpr(d.get()); out << "]"; }
                for (size_t k = x->args.size(); k < rank; k++) out << "[]";
                return;
            }
            out << "new " << x->typeName << "(";
            for (size_t i=0;i<x->args.size();i++){ if(i) out<<", "; emitExpr(x->args[i].get()); }
            out << ")"; return;
        }
        unsupported("Sleela", "this expression", &typeid(*e));
    }
};

// ---------------------------------------------------------------------------
// C emitter: a tiny tagged-value runtime (nsv) carries int/double/bool/string,
// mirroring the Sleela core's value model so + concatenates like Sleela.
// ---------------------------------------------------------------------------
const char* kCPrelude = R"PRE(/* Generated by Nordshrift (C target) */
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef enum { NSV_INT, NSV_DBL, NSV_BOOL, NSV_STR, NSV_NULL, NSV_ARR } nsv_tag;
typedef struct nsv_array nsv_array;
typedef struct { nsv_tag t; long long i; double d; int b; char* s; nsv_array* a; } nsv;
struct nsv_array { long long n; nsv* v; };
static nsv nsv_blank(nsv_tag t){ nsv x; memset(&x,0,sizeof x); x.t=t; return x; }
static nsv nsv_int(long long v){ nsv x=nsv_blank(NSV_INT); x.i=v; return x; }
static nsv nsv_dbl(double v){ nsv x=nsv_blank(NSV_DBL); x.d=v; return x; }
static nsv nsv_bool(int v){ nsv x=nsv_blank(NSV_BOOL); x.b=v?1:0; return x; }
static nsv nsv_str(const char* v){ nsv x=nsv_blank(NSV_STR); x.s=strdup(v); return x; }
static nsv nsv_null(void){ return nsv_blank(NSV_NULL); }
static void nsv_fail(const char* m){ fflush(stdout); fprintf(stderr,"runtime error: %s\n",m); exit(1); }
static double nsv_num(nsv v){ return v.t==NSV_INT?(double)v.i:v.t==NSV_DBL?v.d:v.t==NSV_BOOL?v.b:0; }
static int nsv_truth(nsv v){ return v.t==NSV_INT?v.i!=0:v.t==NSV_DBL?v.d!=0:v.t==NSV_BOOL?v.b:(v.t==NSV_STR||v.t==NSV_ARR)?1:0; }
/* Arrays render like the VM: [e0, e1, ...], nested arrays recursively. */
static void nsv_render_depth(nsv v,char*b,size_t n,int depth){ switch(v.t){case NSV_INT:snprintf(b,n,"%lld",v.i);break;case NSV_DBL:snprintf(b,n,"%g",v.d);break;case NSV_BOOL:snprintf(b,n,"%s",v.b?"true":"false");break;case NSV_STR:snprintf(b,n,"%s",v.s?v.s:"");break;case NSV_NULL:snprintf(b,n,"null");break;
  case NSV_ARR:{ size_t p=0; if(n==0)return; if(depth>=16){snprintf(b,n,"[...]");return;} if(p+1<n)b[p++]='['; for(long long k=0;k<v.a->n&&p+2<n;k++){ char e[256]; size_t l,j; if(k>0&&p+2<n){b[p++]=',';b[p++]=' ';} nsv_render_depth(v.a->v[k],e,sizeof e,depth+1); l=strlen(e); for(j=0;j<l&&p+2<n;j++)b[p++]=e[j]; } if(p+1<n)b[p++]=']'; b[p]=0; }break;} }
static void nsv_render(nsv v,char*b,size_t n){ nsv_render_depth(v,b,n,0); }
static nsv nsv_add(nsv a,nsv b){ if(a.t==NSV_STR||b.t==NSV_STR){char x[256],y[256],o[512];nsv_render(a,x,sizeof x);nsv_render(b,y,sizeof y);snprintf(o,sizeof o,"%s%s",x,y);return nsv_str(o);} if(a.t==NSV_INT&&b.t==NSV_INT)return nsv_int((long long)((unsigned long long)a.i+(unsigned long long)b.i)); return nsv_dbl(nsv_num(a)+nsv_num(b)); }
static nsv nsv_sub(nsv a,nsv b){ if(a.t==NSV_INT&&b.t==NSV_INT)return nsv_int((long long)((unsigned long long)a.i-(unsigned long long)b.i)); return nsv_dbl(nsv_num(a)-nsv_num(b)); }
static nsv nsv_mul(nsv a,nsv b){ if(a.t==NSV_INT&&b.t==NSV_INT)return nsv_int((long long)((unsigned long long)a.i*(unsigned long long)b.i)); return nsv_dbl(nsv_num(a)*nsv_num(b)); }
static nsv nsv_div(nsv a,nsv b){ if(a.t==NSV_INT&&b.t==NSV_INT)return nsv_int(a.i/b.i); return nsv_dbl(nsv_num(a)/nsv_num(b)); }
static nsv nsv_mod(nsv a,nsv b){ return nsv_int(a.i%b.i); }
static nsv nsv_neg(nsv a){ return a.t==NSV_INT?nsv_int((long long)(0ull-(unsigned long long)a.i)):nsv_dbl(-nsv_num(a)); }
static nsv nsv_lt(nsv a,nsv b){ return nsv_bool(nsv_num(a)<nsv_num(b)); }
static nsv nsv_le(nsv a,nsv b){ return nsv_bool(nsv_num(a)<=nsv_num(b)); }
static nsv nsv_gt(nsv a,nsv b){ return nsv_bool(nsv_num(a)>nsv_num(b)); }
static nsv nsv_ge(nsv a,nsv b){ return nsv_bool(nsv_num(a)>=nsv_num(b)); }
static nsv nsv_eq(nsv a,nsv b){ if(a.t==NSV_STR&&b.t==NSV_STR)return nsv_bool(strcmp(a.s,b.s)==0); if(a.t==NSV_NULL||b.t==NSV_NULL||a.t==NSV_ARR||b.t==NSV_ARR)return nsv_bool(a.t==b.t&&(a.t==NSV_NULL||a.a==b.a)); return nsv_bool(nsv_num(a)==nsv_num(b)); }
static nsv nsv_ne(nsv a,nsv b){ nsv e=nsv_eq(a,b); return nsv_bool(!e.b); }
static nsv nsv_and(nsv a,nsv b){ return nsv_bool(nsv_truth(a)&&nsv_truth(b)); }
static nsv nsv_or(nsv a,nsv b){ return nsv_bool(nsv_truth(a)||nsv_truth(b)); }
static nsv nsv_not(nsv a){ return nsv_bool(!nsv_truth(a)); }
static long long nsv_int_of(nsv v){ return v.t==NSV_INT?v.i:v.t==NSV_BOOL?v.b:(long long)nsv_num(v); }
static nsv nsv_band(nsv a,nsv b){ return nsv_int(nsv_int_of(a)&nsv_int_of(b)); }
static nsv nsv_bor(nsv a,nsv b){ return nsv_int(nsv_int_of(a)|nsv_int_of(b)); }
static nsv nsv_bxor(nsv a,nsv b){ return nsv_int(nsv_int_of(a)^nsv_int_of(b)); }
static nsv nsv_shl(nsv a,nsv b){ return nsv_int((long long)((unsigned long long)nsv_int_of(a)<<(nsv_int_of(b)&63))); }
static nsv nsv_shr(nsv a,nsv b){ return nsv_int(nsv_int_of(a)>>(nsv_int_of(b)&63)); }
static nsv nsv_ushr(nsv a,nsv b){ return nsv_int((long long)((unsigned long long)nsv_int_of(a)>>(nsv_int_of(b)&63))); }
static nsv nsv_bnot(nsv a){ return nsv_int(~nsv_int_of(a)); }
static void nsv_print(nsv v){ char b[512]; nsv_render(v,b,sizeof b); printf("%s\n",b); }

/* Arrays. C leaves the order of function arguments unspecified, so array
 * operands are sequenced with the comma operator through two small stacks:
 * the base is pushed before the index is evaluated, exactly as the VM
 * evaluates base, then index, then (for a[i] = v) the value. */
#define NSV_STACK 4096
static nsv nsv_vs[NSV_STACK]; static int nsv_vn;
static nsv* nsv_ps[NSV_STACK]; static int nsv_pn;
static nsv nsv_vpush(nsv v){ if(nsv_vn>=NSV_STACK)nsv_fail("expression nesting too deep"); nsv_vs[nsv_vn++]=v; return v; }
static nsv nsv_vpop(void){ return nsv_vs[--nsv_vn]; }
static nsv* nsv_ppush(nsv* p){ if(nsv_pn>=NSV_STACK)nsv_fail("expression nesting too deep"); nsv_ps[nsv_pn++]=p; return p; }
static nsv* nsv_ppop(void){ return nsv_ps[--nsv_pn]; }
static nsv nsv_arr_new(long long n, nsv fill){ nsv x=nsv_blank(NSV_ARR); long long k; if(n<0)nsv_fail("negative array size"); x.a=(nsv_array*)malloc(sizeof *x.a); if(!x.a)nsv_fail("out of memory"); x.a->n=n; x.a->v=(nsv*)calloc(n?(size_t)n:1u,sizeof(nsv)); if(!x.a->v)nsv_fail("out of memory"); for(k=0;k<n;k++)x.a->v[k]=fill; return x; }
static nsv nsv_arr_build(const long long* d,int k,int nd,nsv leaf){ nsv x; long long j; if(k==nd-1)return nsv_arr_new(d[k],leaf); x=nsv_arr_new(d[k],nsv_null()); for(j=0;j<d[k];j++)x.a->v[j]=nsv_arr_build(d,k+1,nd,leaf); return x; }
static long long nsv_int_of(nsv v);
/* new T[d0][d1]...: the nd sized dimensions were pushed in order. */
static nsv nsv_arr_dims(int nd, nsv leaf){ long long d[8]; int k; for(k=nd-1;k>=0;k--)d[k]=nsv_int_of(nsv_vpop()); return nsv_arr_build(d,0,nd,leaf); }
/* {e0, e1, ...}: the n elements were pushed in order. */
static nsv nsv_arr_lit(int n){ nsv x=nsv_arr_new(n,nsv_null()); int k; for(k=n-1;k>=0;k--)x.a->v[k]=nsv_vpop(); return x; }
static nsv* nsv_slot_in(nsv a, nsv i){ long long k; if(a.t!=NSV_ARR)nsv_fail("index access on a non-array value"); k=nsv_int_of(i); if(k<0||k>=a.a->n)nsv_fail("array index out of range"); return &a.a->v[k]; }
/* The base is on the value stack; i was evaluated after it. */
static nsv* nsv_slot(nsv i){ return nsv_slot_in(nsv_vpop(), i); }
static nsv nsv_index(nsv i){ return *nsv_slot(i); }
/* a[i] = v: base and index are on the value stack; v was evaluated last. */
static nsv nsv_store(nsv v){ nsv i=nsv_vpop(); nsv a=nsv_vpop(); *nsv_slot_in(a,i)=v; return v; }
/* a[i] op= v: the element slot (read before v, as in the VM) is on the pointer stack. */
static nsv nsv_compound(nsv (*f)(nsv,nsv), nsv v){ nsv* p=nsv_ppop(); *p=f(*p,v); return *p; }
static nsv nsv_len(nsv a){ if(a.t!=NSV_ARR)nsv_fail("length of a non-array value"); return nsv_int(a.a->n); }
static nsv nsv_add(nsv a,nsv b);
static nsv nsv_sub(nsv a,nsv b);
/* ++x / x++ (and on array elements): returns the new / the old value. */
static nsv nsv_pre(nsv* p, int up){ *p = up ? nsv_add(*p,nsv_int(1)) : nsv_sub(*p,nsv_int(1)); return *p; }
static nsv nsv_post(nsv* p, int up){ nsv old=*p; *p = up ? nsv_add(*p,nsv_int(1)) : nsv_sub(*p,nsv_int(1)); return old; }
)PRE";

struct CGen {
    std::ostringstream out;
    int foreachId_ = 0;   // makes the helper variables of nested enhanced-for loops distinct
    std::string curClass;   // class currently being emitted (to qualify calls)

    void run(const Program& p) {
        requireDeclarationSubset(p, "C", false);
        out << kCPrelude << "\n";
        // forward declarations (with real parameter arity)
        for (auto& c : p.classes)
            for (auto& m : c.methods) {
                out << "static nsv " << c.name << "_" << m.name << "(";
                if (m.params.empty()) out << "void";
                else for (size_t i = 0; i < m.params.size(); i++) { if (i) out << ", "; out << "nsv"; }
                out << ");\n";
            }
        // fields as globals
        for (auto& c : p.classes)
            for (auto& f : c.fields)
                out << "static nsv " << f.name << ";\n";
        out << "\n";
        for (auto& c : p.classes) { curClass = c.name; for (auto& m : c.methods) emitMethod(c.name, m); }
        // main()
        out << "int main(void) {\n";
        for (auto& c : p.classes)
            for (auto& f : c.fields) { out << "    " << f.name << " = "; if (f.init) emitExpr(f.init.get()); else out << "nsv_int(0)"; out << ";\n"; }
        for (auto& c : p.classes)
            for (auto& m : c.methods)
                if (m.name == "main") { out << "    " << c.name << "_main();\n"; }
        out << "    return 0;\n}\n";
    }
    void ind(int n) { for (int i = 0; i < n; i++) out << "    "; }
    void emitMethod(const std::string& cls, const Method& m) {
        out << "static nsv " << cls << "_" << m.name << "(";
        if (m.params.empty()) out << "void";
        else for (size_t i = 0; i < m.params.size(); i++) { if (i) out << ", "; out << "nsv " << m.params[i].name; }
        out << ") {\n";
        emitBlock(*m.body, 1);
        ind(1); out << "return nsv_int(0);\n";
        out << "}\n\n";
    }
    void emitBlock(const Block& b, int n) { for (auto& s : b.stmts) emitStmt(s.get(), n); }
    void emitBody(const Stmt* s, int n) { if (auto b = dynamic_cast<const Block*>(s)) emitBlock(*b, n); else emitStmt(s, n); }
    // An expression whose value is discarded: ++/-- may use the cheaper prefix form.
    void emitTop(const Expr* e) {
        if (auto u = dynamic_cast<const Unary*>(e)) {
            if ((u->op == "post++" || u->op == "post--") && dynamic_cast<const VarExpr*>(u->operand.get())) {
                emitIncDec(static_cast<const VarExpr*>(u->operand.get())->name, u->op[4] == '+'); return;
            }
        }
        emitExpr(e);
    }
    void emitIncDec(const std::string& name, bool inc) {
        out << "(" << name << " = " << (inc ? "nsv_add(" : "nsv_sub(") << name << ", nsv_int(1)))";
    }
    // `(nsv_vpush(base), fn(nsv_slot(index)<rest>))`: base is evaluated before
    // index, and fn receives the element's address (bounds-checked).
    void emitOnSlot(const ArrayAccess* aa, const char* fn, const char* rest) {
        out << "(nsv_vpush("; emitExpr(aa->base.get()); out << "), " << fn << "(nsv_slot("; emitExpr(aa->index.get()); out << ")" << rest << "))";
    }
    // Default element of a new array, by element type: 0, 0.0, false, or null.
    static const char* elementDefault(const std::string& elem) {
        if (elem == "double" || elem == "float") return "nsv_dbl(0)";
        if (elem == "boolean" || elem == "bool") return "nsv_bool(0)";
        if (elem == "int" || elem == "long" || elem == "int64" || elem == "int128" || elem == "char" ||
            elem == "short" || elem == "byte") return "nsv_int(0)";
        return "nsv_null()";   // String, classes and arrays
    }
    void emitNewArray(const NewExpr* x) {
        if (x->hasInit) {
            out << "(";
            for (const auto& v : x->init) { out << "nsv_vpush("; emitExpr(v.get()); out << "), "; }
            out << "nsv_arr_lit(" << x->init.size() << "))";
            return;
        }
        std::string elem = x->typeName; size_t rank = 0;
        while (elem.size() >= 2 && elem.compare(elem.size() - 2, 2, "[]") == 0) { elem.resize(elem.size() - 2); rank++; }
        if (x->args.empty() || x->args.size() > 8) unsupported("C", "this array creation", &typeid(*x));
        // fully sized: elements get the type default; `new T[a][]`: the last sized level holds null
        const char* leaf = x->args.size() < rank ? "nsv_null()" : elementDefault(elem);
        out << "(";
        for (const auto& d : x->args) { out << "nsv_vpush("; emitExpr(d.get()); out << "), "; }
        out << "nsv_arr_dims(" << x->args.size() << ", " << leaf << "))";
    }
    void emitAssignC(const AssignmentExpr* a) {
        static const std::pair<const char*, const char*> kCompound[] = {
            {"+=","nsv_add"},{"-=","nsv_sub"},{"*=","nsv_mul"},{"/=","nsv_div"},{"%=","nsv_mod"},
            {"&=","nsv_band"},{"|=","nsv_bor"},{"^=","nsv_bxor"},{"<<=","nsv_shl"},{">>=","nsv_shr"},{">>>=","nsv_ushr"}};
        const char* fn = nullptr;
        if (a->op != "=") {
            for (const auto& kv : kCompound) if (a->op == kv.first) { fn = kv.second; break; }
            if (!fn) unsupported("C", ("assignment operator '" + a->op + "'").c_str());
        }
        if (auto aa = dynamic_cast<const ArrayAccess*>(a->target.get())) {
            if (!fn) {
                // VM order: base, index, value; the bounds check comes after the value.
                out << "(nsv_vpush("; emitExpr(aa->base.get()); out << "), nsv_vpush("; emitExpr(aa->index.get());
                out << "), nsv_store("; emitExpr(a->value.get()); out << "))";
            } else {
                // VM order: base, index, read the element (bounds check), then the value.
                out << "(nsv_vpush("; emitExpr(aa->base.get()); out << "), nsv_ppush(nsv_slot("; emitExpr(aa->index.get());
                out << ")), nsv_compound(" << fn << ", "; emitExpr(a->value.get()); out << "))";
            }
            return;
        }
        auto v = dynamic_cast<const VarExpr*>(a->target.get());
        if (!v) unsupported("C", "an assignment to anything but a variable, field name or array element", &typeid(*a->target));
        out << "(" << v->name << " = ";
        if (!fn) emitExpr(a->value.get());
        else { out << fn << "(" << v->name << ", "; emitExpr(a->value.get()); out << ")"; }
        out << ")";
    }
    void emitStmt(const Stmt* s, int n) {
        if (auto b = dynamic_cast<const Block*>(s)) { ind(n); out << "{\n"; emitBlock(*b, n+1); ind(n); out << "}\n"; return; }
        if (auto d = dynamic_cast<const VarDecl*>(s)) { ind(n); out << "nsv " << d->name << " = "; if (d->init) emitExpr(d->init.get()); else out << "nsv_int(0)"; out << ";\n"; return; }
        if (auto a = dynamic_cast<const Assign*>(s)) { ind(n); out << a->name << " = "; emitExpr(a->value.get()); out << ";\n"; return; }
        if (auto e = dynamic_cast<const ExprStmt*>(s)) { ind(n); emitTop(e->expr.get()); out << ";\n"; return; }
        if (auto p = dynamic_cast<const PrintStmt*>(s)) { ind(n); out << "nsv_print("; emitExpr(p->expr.get()); out << ");\n"; return; }
        if (auto r = dynamic_cast<const ReturnStmt*>(s)) { ind(n); out << "return "; if (r->value) emitExpr(r->value.get()); else out << "nsv_int(0)"; out << ";\n"; return; }
        if (auto i = dynamic_cast<const IfStmt*>(s)) { ind(n); out << "if (nsv_truth("; emitExpr(i->cond.get()); out << ")) {\n"; emitBody(i->thenS.get(), n+1); ind(n); out << "}"; if (i->elseS) { out << " else {\n"; emitBody(i->elseS.get(), n+1); ind(n); out << "}"; } out << "\n"; return; }
        if (auto w = dynamic_cast<const WhileStmt*>(s)) { ind(n); out << "while (nsv_truth("; emitExpr(w->cond.get()); out << ")) {\n"; emitBody(w->body.get(), n+1); ind(n); out << "}\n"; return; }
        if (auto fe = dynamic_cast<const ForEachStmt*>(s)) {
            // Over an array only: the iterable is evaluated once, its length is read once (an array cannot change
            // length) and each element is read with the bounds-checked slot access. An Iterable object needs the
            // object model the C target does not have.
            if (fe->overIterable) unsupported("C", "an enhanced for over an object (only arrays are supported)", &typeid(*s));
            const std::string id = std::to_string(foreachId_++);
            ind(n); out << "{\n";
            ind(n+1); out << "nsv nsf_a" << id << " = "; emitExpr(fe->iterable.get()); out << ";\n";
            ind(n+1); out << "long long nsf_n" << id << " = nsv_int_of(nsv_len(nsf_a" << id << "));\n";
            ind(n+1); out << "for (long long nsf_i" << id << " = 0; nsf_i" << id << " < nsf_n" << id << "; ++nsf_i" << id << ") {\n";
            ind(n+2); out << "nsv " << fe->name << " = *nsv_slot_in(nsf_a" << id << ", nsv_int(nsf_i" << id << "));\n";
            emitBody(fe->body.get(), n+2);
            ind(n+1); out << "}\n"; ind(n); out << "}\n"; return;
        }
        if (auto f = dynamic_cast<const ForStmt*>(s)) {
            ind(n); out << "{\n";
            if (f->init) { ind(n+1); emitInlineDecl(f->init.get()); out << ";\n"; }
            ind(n+1); out << "while ("; if (f->cond) { out << "nsv_truth("; emitExpr(f->cond.get()); out << ")"; } else out << "1"; out << ") {\n";
            emitBody(f->body.get(), n+2);
            if (f->update) { ind(n+2); emitInlineDecl(f->update.get()); out << ";\n"; }
            ind(n+1); out << "}\n"; ind(n); out << "}\n"; return;
        }
        unsupported("C", "this statement", &typeid(*s));
    }
    void emitInlineDecl(const Stmt* s) {
        if (auto d = dynamic_cast<const VarDecl*>(s)) { out << "nsv " << d->name << " = "; if (d->init) emitExpr(d->init.get()); else out << "nsv_int(0)"; return; }
        if (auto a = dynamic_cast<const Assign*>(s)) { out << a->name << " = "; emitExpr(a->value.get()); return; }
        if (auto e = dynamic_cast<const ExprStmt*>(s)) { emitTop(e->expr.get()); return; }
        unsupported("C", "this for-header statement", &typeid(*s));
    }
    void emitExpr(const Expr* e) {
        if (auto x = dynamic_cast<const IntLit*>(e)) { out << "nsv_int(" << x->value << ")"; return; }
        if (auto x = dynamic_cast<const DoubleLit*>(e)) { out << "nsv_dbl(" << x->value << ")"; return; }
        if (auto x = dynamic_cast<const BoolLit*>(e)) { out << "nsv_bool(" << (x->value?1:0) << ")"; return; }
        if (auto x = dynamic_cast<const StrLit*>(e)) { out << "nsv_str(\"" << esc(x->value) << "\")"; return; }
        if (dynamic_cast<const NullLit*>(e)) { out << "nsv_null()"; return; }
        if (auto x = dynamic_cast<const VarExpr*>(e)) { out << x->name; return; }
        if (auto x = dynamic_cast<const ArrayAccess*>(e)) {
            out << "(nsv_vpush("; emitExpr(x->base.get()); out << "), nsv_index("; emitExpr(x->index.get()); out << "))"; return;
        }
        if (auto x = dynamic_cast<const MemberAccess*>(e)) {
            // The emitter may run without semantic analysis, so `arrayLength`
            // can be unset. The C target has no objects, so `.length` can only
            // be an array length (nsv_len fails at run time on a non-array).
            if (!x->arrayLength && x->field != "length") unsupported("C", "member access other than an array's length", &typeid(*e));
            out << "nsv_len("; emitExpr(x->base.get()); out << ")"; return;
        }
        if (auto x = dynamic_cast<const NewExpr*>(e)) {
            if (!x->hasInit && x->typeName.find('[') == std::string::npos) unsupported("C", "object creation", &typeid(*e));
            emitNewArray(x); return;
        }
        if (auto x = dynamic_cast<const Unary*>(e)) {
            const bool post = x->op == "post++" || x->op == "post--";
            if (post || x->op == "++" || x->op == "--") {
                const bool up = x->op[post ? 4 : 0] == '+';
                const char* rest = up ? ", 1" : ", 0";
                if (auto aa = dynamic_cast<const ArrayAccess*>(x->operand.get())) { emitOnSlot(aa, post ? "nsv_post" : "nsv_pre", rest); return; }
                auto v = dynamic_cast<const VarExpr*>(x->operand.get());
                if (!v) unsupported("C", "++/-- on anything but a variable or array element");
                if (post) { out << "nsv_post(&" << v->name << rest << ")"; return; }
                emitIncDec(v->name, up); return;
            }
            const char* fn = x->op=="-"?"nsv_neg":x->op=="!"?"nsv_not":x->op=="~"?"nsv_bnot":nullptr;
            if (!fn) unsupported("C", ("unary operator '" + x->op + "'").c_str());
            out << fn << "("; emitExpr(x->operand.get()); out << ")"; return;
        }
        if (auto x = dynamic_cast<const Binary*>(e)) {
            const std::string& o = x->op;
            static const std::pair<const char*, const char*> kOps[] = {
                {"+","nsv_add"},{"-","nsv_sub"},{"*","nsv_mul"},{"/","nsv_div"},{"%","nsv_mod"},
                {"==","nsv_eq"},{"!=","nsv_ne"},{"<","nsv_lt"},{"<=","nsv_le"},{">","nsv_gt"},{">=","nsv_ge"},
                {"&&","nsv_and"},{"||","nsv_or"},
                {"&","nsv_band"},{"|","nsv_bor"},{"^","nsv_bxor"},{"<<","nsv_shl"},{">>","nsv_shr"},{">>>","nsv_ushr"}};
            std::string fn;
            for (const auto& kv : kOps) if (o == kv.first) { fn = kv.second; break; }
            if (fn.empty()) unsupported("C", ("binary operator '" + o + "'").c_str());
            out << fn << "("; emitExpr(x->lhs.get()); out << ", "; emitExpr(x->rhs.get()); out << ")"; return;
        }
        if (auto x = dynamic_cast<const Call*>(e)) {
            // Sleela calls are unqualified within a class; C functions are
            // named Class_method, so qualify with the current class.
            out << curClass << "_" << x->callee << "(";
            for (size_t i = 0; i < x->args.size(); i++) { if (i) out << ", "; emitExpr(x->args[i].get()); }
            out << ")"; return;
        }
        if (auto x = dynamic_cast<const AssignmentExpr*>(e)) { emitAssignC(x); return; }
        if (auto x = dynamic_cast<const ConditionalExpr*>(e)) { out << "(nsv_truth("; emitExpr(x->cond.get()); out << ") ? "; emitExpr(x->thenE.get()); out << " : "; emitExpr(x->elseE.get()); out << ")"; return; }
        unsupported("C", "this expression", &typeid(*e));
    }
};

} // namespace

std::string emitProgram(const sleela::Program& prog, TargetLang lang,
                        const std::string& packageRoot) {
    // All target backends share one target-neutral lowering gate. This keeps
    // unsupported AST nodes from silently diverging between Java/Sleela/C.
    LoweredProgram lowered = lowerProgram(prog);
    if (!lowered.ok()) throw std::runtime_error("Nordshrift lowering failed: " + lowered.error);
    if (lang == TargetLang::Java) { JavaGen g; g.pkg = packageRoot; g.run(prog); return g.out.str(); }
    if (lang == TargetLang::C)    { CGen g; g.run(prog); return g.out.str(); }
    SleelaGen g; g.run(prog); return g.out.str();
}

} // namespace nordshrift