// =========================================================================== // driver.cpp -- Sleelvac™ command-line compiler/runtime front end. // =========================================================================== #include "lexer.h" #include "parser.h" #include "semantic.h" #include "language_handler.h" #include "compiler.h" #include "artifact.h" #include "originate.h" #include "wikigen.h" #include "native_api.h" #include "chemistry_api.h" #include "financial_api.h" #include "version.h" #include "library_index.h" #include "docs.h" #include "keyword_supporter.h" #include "../../registry/sleela_registry.h" #include "vm_config.h" #include "../annotation/AnnotationRuntime.hpp" #include "../catalog/sheet_catalog.h" #include "../xclass/xclass_loader.h" #include "../langin/langin.h" #include "../nordshrift/sleela_emit.h" #include "../nordshrift/native_method_emit.h" #include "http_server_cli.h" #include "../core/sleela_audio_bridge.h" #include "common_rails_banner.hpp" #include "../core/sleela_platform.h" #include "../core/sleela_os.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(_WIN32) # include #else # include #endif extern "C" { #include "../core/sleela_core.h" #include "../core/sleela_memmgr.h" #include "../core/sleela_terminal.h" #include "../core/sleela_design_activity.h" } #if defined(_WIN32) # include #elif defined(__APPLE__) # include # include # include #else # include # include #endif namespace fs=std::filesystem; // Absolute path of the running executable, or empty if it cannot be determined. // Used to make an *installed* binary find its support files (the /lib tree, the // SHA-256 manifest + verifier, the SHEET.sheet catalog) relative to its own // install location rather than only relative to the current working directory. static fs::path executablePath(){ std::error_code ec; #if defined(_WIN32) wchar_t buf[MAX_PATH]; DWORD n=GetModuleFileNameW(nullptr,buf,MAX_PATH); if(n==0||n>=MAX_PATH) return fs::path(); fs::path p(std::wstring(buf,buf+n)); fs::path c=fs::weakly_canonical(p,ec); return ec?p:c; #elif defined(__APPLE__) char buf[PATH_MAX]; uint32_t size=sizeof(buf); if(_NSGetExecutablePath(buf,&size)!=0) return fs::path(); fs::path p(buf); fs::path c=fs::weakly_canonical(p,ec); return ec?p:c; #else char buf[PATH_MAX]; ssize_t n=::readlink("/proc/self/exe",buf,sizeof(buf)-1); if(n<=0) return fs::path(); buf[n]='\0'; fs::path p(buf); fs::path c=fs::weakly_canonical(p,ec); return ec?p:c; #endif } // Derive the SLeeLa runtime root from the installed layout, where the binary // lives at /bin/ and its support tree at /lib/sleela. A // directory is accepted only when it carries the verifier the gate needs, so a // non-installed (build-tree) binary falls through to the env var / upward // search instead of guessing. Returns empty when no install root is found. static fs::path installRootFromExecutable(){ fs::path exe=executablePath(); if(exe.empty()) return fs::path(); std::error_code ec; fs::path bindir=exe.parent_path(); // /bin fs::path prefix=bindir.parent_path(); // // Primary installed layout: /lib/sleela. fs::path candidates[]={ prefix/"lib"/"sleela", // Fallbacks for less conventional layouts (bin and runtime side by side, // or the runtime tree sitting next to the executable). bindir/".."/"lib"/"sleela", bindir/"sleela", }; for(const auto& c:candidates){ fs::path d=fs::weakly_canonical(c,ec); if(ec){ec.clear();d=c;} if(fs::is_directory(d,ec) && fs::is_regular_file(d/"tools"/"verify-before-execution.py",ec)) return d; ec.clear(); } return fs::path(); } // The runtime (`sleela`) and the compiler (`sleelvac`) share this front-end // source, but each binary is built as an INDEPENDENT executable with its // product identity baked in at compile time (SLEELA_PRODUCT_SLEELVAC is defined // only for the sleelvac object). `sleela version` therefore always reports the // SLeeLa Language/Runtime, independent of argv[0], launchers, symlinks, or // aliases. Both banners carry the same release number. // The shared release number for both tools. static const char* kReleaseVersion="1.3.2-pro"; // Both banners derive the supported source-syntax range from the single source // of truth in version.h (minSupportedSyntax()/maxSupportedSyntax()), so the // reported range always matches what the toolchain actually drives. static std::string sleelaVersionBanner(){ return std::string("SLeeLa\u2122 Language/Runtime ")+kReleaseVersion +" (supported source syntax "+sleela::minSupportedSyntax().str() +" \u2013 "+sleela::maxSupportedSyntax().str() +"; native C/C++ Core VM)"; } static std::string sleelvacVersionBanner(){ return std::string("Sleelvac\u2122 ")+kReleaseVersion +" (SLeeLa compiler; compiles source syntax "+sleela::minSupportedSyntax().str() +" \u2013 "+sleela::maxSupportedSyntax().str() +"; executable native math/physics/economics/chemistry/financial modules;" " persistent .sleela Core artifacts; .xclass input; JVM-family langin input:" " Java/Kotlin/Scala/Groovy/Clojure; Nordshrift round-trip" " (SLeeLa->Nordshrift->back); OS Defender provisioning; SHA-256 execution gate)"; } // Compile-time product identity. The sleelvac object is compiled with // -DSLEELA_PRODUCT_SLEELVAC; every other build is the runtime (`sleela`). #if defined(SLEELA_PRODUCT_SLEELVAC) static const bool kBuiltAsCompiler=true; #else static const bool kBuiltAsCompiler=false; #endif static bool readFile(const std::string& path,std::string& out); static int runLangin(const std::vector&paths); static bool hasExt(const std::string& path,const std::string& ext){return path.size()>=ext.size()&&path.compare(path.size()-ext.size(),ext.size(),ext)==0;} static std::string shellQuote(const std::string&s){ #ifdef _WIN32 std::string q="\"";for(char c:s){if(c=='\"')q+="\\\"";else q+=c;}return q+"\""; #else std::string q="'";for(char c:s){if(c=='\'')q+="'\\''";else q+=c;}return q+"'"; #endif } // The command echo is a diagnostic: keep it on stderr so stdout stays clean for // machine-consumed output (e.g. `sleela aot --emit` C source piped to a compiler). static int runCommand(const std::string&cmd){std::cerr<<"[defender] $ "< (or --sha256 ) must be set to the // expected SHA-256 of the downloaded archive; the fetch fails closed if the // hash is missing or does not match. There is no "trust on first use". // * SLEELA_DEFENDER_ALLOW_ROOT=1 (or --allow-root) must be set before any // step that elevates privileges (sudo / pnputil). Elevation is never // performed implicitly. // --------------------------------------------------------------------------- struct DefenderOpts{bool optin=false;bool allowRoot=false;std::string sha256;}; static bool envFlag(const char*name){const char*v=std::getenv(name);return v&&(std::string(v)=="1"||std::string(v)=="true"||std::string(v)=="yes");} // Group a non-negative integer with thousands separators (1234567 -> "1,234,567) // for the TOOLCHAIN's own human-facing output (banners, version, diagnostics). // This is a SYSTEM-side presentation helper only: a running Sleela program's // own print(...) output is produced by the VM's value_to_text and is NEVER // routed through here, so user numeric output is unaffected. static std::string groupDigits(long long v){ bool neg=v<0; unsigned long long n=neg?(unsigned long long)(-(v+1))+1ull:(unsigned long long)v; std::string s=std::to_string(n), out; int c=0; for(int i=(int)s.size()-1;i>=0;--i){ out.push_back(s[(size_t)i]); if(++c%3==0 && i>0) out.push_back(','); } if(neg) out.push_back('-'); std::reverse(out.begin(),out.end()); return out; } static std::string groupDigits(unsigned long long v){ return groupDigits((long long)v); } // CommonRails banner surface (opt-in via SLEELA_RAILS=1). When enabled, the // compiler routes its human-facing progress banners through the shared // /lib/common-rails PrintRail look (component + state lines). The exact, // machine-parsed contract lines (e.g. "sleelvac: -> (runnable // Sleela Core artifact)") are ALWAYS emitted verbatim by their own call site; // the rails banner is additive decoration on stderr, so default output and the // test suite are byte-for-byte unchanged unless SLEELA_RAILS is set. static bool railsBannersEnabled(){return envFlag("SLEELA_RAILS");} static std::string toLowerHex(std::string s){for(char&c:s)c=(char)std::tolower((unsigned char)c);return s;} static std::string readSha256Env(){const char*v=std::getenv("SLEELA_DEFENDER_SHA256");return v?toLowerHex(v):std::string();} static bool sha256OfFile(const fs::path&path,std::string&hexOut){ // Delegate to a trusted external hasher so we never re-implement crypto here. #ifdef _WIN32 std::string cmd="certutil -hashfile "+shellQuote(path.string())+" SHA256"; #else std::string cmd="sha256sum "+shellQuote(path.string()); #endif std::string tmpName=(fs::temp_directory_path()/("sleela-defender-hash-"+std::to_string((unsigned long long)std::rand())+".txt")).string(); if(std::system((cmd+" > "+shellQuote(tmpName)+" 2>"+ #ifdef _WIN32 "NUL" #else "/dev/null" #endif ).c_str())!=0){std::error_code ec;fs::remove(tmpName,ec);return false;} std::ifstream f(tmpName);std::string content((std::istreambuf_iterator(f)),std::istreambuf_iterator());f.close();std::error_code ec;fs::remove(tmpName,ec); // Extract the first 64-hex-char token from the tool output. std::string cur;for(char c:content){bool hex=(c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F');if(hex){cur+=c;if(cur.size()==64){hexOut=toLowerHex(cur);return true;}}else{cur.clear();}} return false; } static bool verifyArchiveHash(const fs::path&archive,const std::string&expected){ if(expected.empty()){std::cerr<<"sleelvac: defender: refusing to use downloaded archive without an expected SHA-256.\n Provide one with --sha256 or SLEELA_DEFENDER_SHA256=.\n";return false;} if(expected.size()!=64){std::cerr<<"sleelvac: defender: expected SHA-256 must be 64 hex characters.\n";return false;} std::string actual;if(!sha256OfFile(archive,actual)){std::cerr<<"sleelvac: defender: unable to compute SHA-256 of downloaded archive.\n";return false;} if(actual!=expected){std::cerr<<"sleelvac: defender: downloaded archive SHA-256 mismatch.\n expected: "</bin/ -> /lib/sleela). This lets an // installed `sleela`/`sleelvac` find its support tree from the final install // location regardless of the current working directory or environment, which // is what a user expects when running the installed command rather than from // the git checkout. SLEELA_HOME above still wins as an explicit override. if(fs::path installed=installRootFromExecutable(); !installed.empty()) return installed; fs::path dir=fs::absolute(start,ec); if(ec){ec.clear();dir=start;} for(;;){ if(fs::is_regular_file(dir/"tools"/"verify-before-execution.py",ec)){ fs::path canonical=fs::weakly_canonical(dir,ec); return ec ? dir : canonical; } ec.clear(); fs::path parent=dir.parent_path(); if(parent.empty()||parent==dir)break; dir=parent; } return fs::path(); } // Resolve the authoritative /lib source-library root for the current invocation, // honoring (in order): $SLEELA_LIB, the installed /lib/sleela/lib, the // SLeeLa root found by findRepoRoot (SLEELA_HOME or the checkout), and finally // an empty string so Index::discover falls back to its cwd-relative search. // Centralizing this keeps the import validator (compiler.cpp) and the source // unit loader (loadReferencedLibraryUnits) in agreement about where /lib is. static std::string resolveLibraryRoot(){ if(const char* configured=std::getenv("SLEELA_LIB"); configured&&*configured) return configured; std::error_code ec; if(fs::path installed=installRootFromExecutable(); !installed.empty()){ fs::path lib=installed/"lib"; if(fs::is_directory(lib,ec)) return lib.string(); ec.clear(); } fs::path repo=findRepoRoot(fs::current_path()); if(!repo.empty()){ fs::path lib=repo/"lib"; if(fs::is_directory(lib,ec)) return lib.string(); ec.clear(); } return std::string(); } // A trusted SHA-256 manifest and the source tree it describes are COLOCATED: // the manifest lives at /security/sha256-manifest.json and lists every // file by a path relative to . Given an explicit manifest, the only root // it can faithfully describe is therefore the directory two levels up from the // manifest (/security/ -> ). Returns that directory when it // both resolves and carries the verifier tool; otherwise an empty path. static fs::path rootFromManifest(const fs::path&manifest){ std::error_code ec; fs::path securityDir=manifest.parent_path(); // /security if(securityDir.empty()) return fs::path(); fs::path candidate=securityDir.parent_path(); // if(candidate.empty()) return fs::path(); fs::path canonical=fs::weakly_canonical(candidate,ec); if(!ec) candidate=canonical; else ec.clear(); if(fs::is_directory(candidate,ec) && fs::is_regular_file(candidate/"tools"/"verify-before-execution.py",ec)) return candidate; return fs::path(); } static int verifyBeforeExecution(const fs::path&cwd, bool quiet=false){ // Resolve the SLeeLa root first so a configured installation works even // when the caller is a separate client project and has no local verifier. fs::path root=findRepoRoot(cwd); if(root.empty())root=cwd; const char* env=std::getenv("SLEELA_SHA256_MANIFEST"); fs::path manifest=(env&&*env)?fs::path(env):(root/"security"/"sha256-manifest.json"); if(!manifest.is_absolute())manifest=root/manifest; // Self-healing anchor: when the caller pins a specific manifest (via // SLEELA_SHA256_MANIFEST, as the repo's own `make` does), verify the tree // that manifest actually describes -- its colocated root -- rather than // whatever root findRepoRoot() guessed. Without this, a binary installed at // ~/.local/sleela would verify a freshly built checkout's manifest against // the STALE installed tree and fail closed on files the checkout added or // changed since install. We only re-anchor when the manifest's own root // carries the verifier (fail-safe), and never override an explicit // SLEELA_HOME, which remains the operator's deliberate last word. if(env&&*env){ if(fs::path manifestRoot=rootFromManifest(manifest); !manifestRoot.empty()){ const char* home=std::getenv("SLEELA_HOME"); bool homePinned = home && *home; if(!homePinned && manifestRoot!=root){ (quiet ? std::cerr : std::cout)<<"[security] anchoring verification to the manifest's own root: " <nul 2>&1")==0){tool="curl.exe";return true;} if(std::system("where wget.exe >nul 2>&1")==0){tool="wget.exe";return true;} #else if(std::system("command -v curl >/dev/null 2>&1")==0){tool="curl";return true;} if(std::system("command -v wget >/dev/null 2>&1")==0){tool="wget";return true;} #endif return false; } static int defenderFetch(const fs::path&base,const DefenderOpts&opts){ if(!defenderPlatformSupported()){std::cerr<<"sleelvac: defender: no privileged Defender backend is implemented for macOS.\n";return 1;} std::string dl;if(!findDownloader(dl)){std::cerr<<"sleelvac: defender: neither curl nor wget is installed\n";return 1;} fs::create_directories(base);fs::path archive=base/(std::string(defenderName())+".zip");fs::path source=base/defenderName(); if(fs::exists(source)){std::cout<<"[defender] source already exists: "< "< [directory] --allow-defender [options]\n" "\n" "Actions that fetch/build/install remote code require explicit opt-in:\n" " --allow-defender opt in to network/build/install actions\n" " (or SLEELA_DEFENDER_OPTIN=1)\n" " --sha256 expected SHA-256 of the downloaded archive; required\n" " for fetch/build/install/provision (or SLEELA_DEFENDER_SHA256)\n" " --allow-root authorize the privileged install step (sudo / pnputil);\n" " never performed implicitly (or SLEELA_DEFENDER_ALLOW_ROOT=1)\n"; } static int defenderCmd(int argc,char**argv){ std::string action=argc>=3?argv[2]:"detect"; // Parse action, optional directory, and the safety flags in any order. DefenderOpts opts;opts.optin=envFlag("SLEELA_DEFENDER_OPTIN");opts.allowRoot=envFlag("SLEELA_DEFENDER_ALLOW_ROOT");opts.sha256=readSha256Env(); fs::path base=fs::temp_directory_path()/"sleela-defender";bool baseSet=false; for(int i=3;i=argc){std::cerr<<"sleelvac: defender: --sha256 requires a hex value\n";return 2;}opts.sha256=toLowerHex(argv[++i]);} else if(a.rfind("--sha256=",0)==0)opts.sha256=toLowerHex(a.substr(9)); else if(a.rfind("--",0)==0){std::cerr<<"sleelvac: defender: unknown option '"< config file -> environment -> CLI. static constexpr size_t kDefaultMemoryLimit = 2048ull*1024ull*1024ull; static constexpr size_t kMinimumMemoryLimit = 256ull*1024ull*1024ull; static constexpr size_t kMaximumMemoryLimit = 2048ull*1024ull*1024ull; static bool parseByteSize(const std::string&in,size_t&out){ if(in.empty())return false; std::string low=toLowerHex(in); if(low=="on"||low=="true"||low=="yes"||low=="1"){out=kDefaultMemoryLimit;return true;} size_t i=0;unsigned long long v=0;bool any=false; for(;ikMaximumMemoryLimit)return false; out=(size_t)bytes; return true; } static bool loadMemoryConfig(const std::string&path,size_t&limit,bool&enabled){ std::ifstream f(path); if(!f)return false; std::string line; while(std::getline(f,line)){ auto hash=line.find('#'); if(hash!=std::string::npos)line.erase(hash); auto eq=line.find('='); if(eq==std::string::npos)continue; std::string key=line.substr(0,eq), value=line.substr(eq+1); auto trim=[](std::string&s){while(!s.empty()&&std::isspace((unsigned char)s.front()))s.erase(s.begin());while(!s.empty()&&std::isspace((unsigned char)s.back()))s.pop_back();}; trim(key);trim(value); if(key=="memory_manager"||key=="memory_limit"||key=="ram_limit"){ std::string low=toLowerHex(value); if(low=="off"||low=="false"||low=="no"||low=="0"){enabled=false;continue;} size_t parsed=0;if(!parseByteSize(value,parsed)){std::cerr<<"sleela: invalid memory setting in "< [args...]` runs a *native* OS executable from // the SLeeLa terminal, under a real pseudo-terminal (the same OS-aware PTY // primitive the runtime uses), relaying its output and preserving its exit // status. It honors the SHA-256 execution gate exactly like run/check/compile, // and it turns the Memory Manager on for the duration (on-need) so a runaway // native cannot silently exhaust host memory through the manager's allocations. // --------------------------------------------------------------------------- static void nativeUsage(){ std::cerr<<"Usage:\n" " sleela native [--config ] [--memory-manager[=]] [--] [args...]\n sleela design-activity \n" " sleela exec [--config ] [--memory-manager[=]] [--] [args...]\n" "\n" "Runs a native OS executable from the SLeeLa terminal under a real\n" "pseudo-terminal, relaying its output and preserving its exit status.\n" "--config selects a common properties/configuration file and exports\n" "its path to the child as SLEELA_CONFIG_FILE. Arguments after the\n" "executable are passed through unchanged, including numeric flags.\n" "The Memory Manager is enabled for the run; --memory-manager= sets\n" "a hard byte limit (accepts K/M/G suffixes).\n"; } static int nativeCmd(int argc,char**argv){ size_t mmLimit=kDefaultMemoryLimit;bool mmExplicit=false; std::string configFile; std::vector cmdArgs; bool endOpts=false; for(int i=2;i=argc){std::cerr<<"sleela native: --config requires a file\n";return 2;} configFile=argv[++i]; } else if(!endOpts&&a.rfind("--config=",0)==0){ configFile=a.substr(9); } else if(!endOpts&&(a=="--memory-manager"||a=="--mm")){mmExplicit=true;mmLimit=0;} else if(!endOpts&&(a.rfind("--memory-manager=",0)==0||a.rfind("--mm=",0)==0)){ std::string v=a.substr(a.find('=')+1);size_t l=0; if(!parseByteSize(v,l)){std::cerr<<"sleela native: invalid --memory-manager size '"<0)cols=(unsigned)v;} if(const char*r=std::getenv("LINES")){int v=std::atoi(r);if(v>0)rows=(unsigned)v;} SLTerminalHandle term=0; int rc=slterminal_spawn(&term,command.c_str(),cols,rows); if(rc!=0){std::cerr<<"sleela native: cannot start '"< candidates; if(const char* env=std::getenv("SLEELA_SHEET"); env&&*env) candidates.emplace_back(env); if(fs::path installed=installRootFromExecutable(); !installed.empty()) candidates.emplace_back((installed/"SHEET.sheet").string()); if(fs::path repo=findRepoRoot(fs::current_path()); !repo.empty()) candidates.emplace_back((repo/"SHEET.sheet").string()); candidates.emplace_back("SHEET.sheet"); candidates.emplace_back("../SHEET.sheet"); candidates.emplace_back("../../SHEET.sheet"); candidates.emplace_back("../../../SHEET.sheet"); for(const auto& p:candidates){ if(p.empty())continue; bool ok=false; catalog::Catalog c=catalog::parseCatalogFile(p.c_str(),&ok); if(ok)return c; } return catalog::Catalog{}; } /* ---- `sleela vm` : select the virtual machine --------------------------- * The Native VM (impl/core, what every other subcommand runs on) is the * default. `sleela vm` lets a user list and select one of the versioned VMs * under virtual-machine/vm-version/NNN, whose Sleela manifests * (SLVmVersionNNN.sleela) + registry (SLVmRegistry.sleela) describe each build * and name the native main the host would load. This table mirrors those * manifests; selection is validated here the same way the OP_VM_SELECT service * opcode validates it in the VM (1..10). Actually building+booting a selected * version's native main is a host/build action beyond the shipped `sleela` * binary; this subcommand resolves and reports the selection. */ // Directory for the originated source document (syntax 2.4). Empty means the // source file's own directory. Set by the compile subcommand's // --originate-dir= flag. static std::string g_originateDir; // Wikitext emanation (syntax 2.4, third output). Opt-in via --wiki; the // optional --wiki-dir= redirects the output (empty = source directory). // g_wiki enables it; it is implied when --wiki-dir is given. static bool g_wiki=false; static std::string g_wikiDir; static int compileFile(const std::string&sourcePath,const std::string&outputPath); static int runFile(const std::string&path); /* Where the VM-selection config lives. Honors SLEELA_VM_CONF; otherwise the * shipped template config/vm.conf, resolved relative to the current directory * (the repository/runtime root), matching the vm-config smoke test. */ static std::string vmConfigPath(){ const char* env=std::getenv("SLEELA_VM_CONF"); if(env&&*env) return std::string(env); return "config/vm.conf"; } /* Load the VM selection config, applying the SLEELA_VM_VERSION environment * override on top. Falls back to compiled defaults (version 11, unlocked) when * no config file is present, so the CLI works with or without a config. */ static void vmLoadConfig(SLEELA_VM_CONFIG* cfg){ sleela_vm_config_defaults(cfg); std::string path=vmConfigPath(); sleela_vm_config_load(path.c_str(), cfg); /* best-effort: keep defaults on miss */ sleela_vm_config_apply_environment(cfg); } static int vmCmd(int argc,char**argv){ struct VmEntry{int n;const char*id;const char*label;const char*dir;const char*mainEntry;}; static const VmEntry kVms[10]={ {1,"idea-vm-001","ground floor","virtual-machine/vm-version/001","vm_ground_test"}, {2,"idea-vm-002","memory hardening","virtual-machine/vm-version/002","vm_memory_test"}, {3,"idea-vm-003","typed results","virtual-machine/vm-version/003","vm_result_test"}, {4,"idea-vm-004","telemetry","virtual-machine/vm-version/004","vm_telemetry_test"}, {5,"idea-vm-005","gc quality","virtual-machine/vm-version/005","vm_gc_test"}, {6,"idea-vm-006","dispatch profiler","virtual-machine/vm-version/006","vm_profile_test"}, {7,"idea-vm-007","capability enforcement","virtual-machine/vm-version/007","vm_capability_test"}, {8,"idea-vm-008","platform parity","virtual-machine/vm-version/008","vm_platform_test"}, {9,"idea-vm-009","audit trail","virtual-machine/vm-version/009","vm_audit_test"}, {10,"idea-vm-010","consolidated","virtual-machine/vm-version/010","vm_runtime"}, }; /* Premium VMs: the eleven SLVM generations under sleela-virtual-machine. * Selected as `sleela vm select premium <1..11>` (or `pNN`). These are * substantial generation builds, distinct from the think-tank versions. * This table is mirrored by the SLeeLa-level premium catalogue * (sleela-virtual-machine/SLVmPremiumRegistry.sleela composing * SLVmPremiumVersion001..011), the premium sibling of the standard * virtual-machine/vm-version/SLVmRegistry; keep the two in step. */ struct PremiumVm{int n;const char*id;const char*label;const char*dir;}; static const PremiumVm kPremium[11]={ {1,"slvm-1","dedicated VM: broker, capabilities, security, OS boundary","sleela-virtual-machine/001"}, {2,"slvm-2","cryptographic and VM-link evolution","sleela-virtual-machine/002"}, {3,"slvm-3","isolation and verification","sleela-virtual-machine/003"}, {4,"slvm-4","authenticated/distributed execution","sleela-virtual-machine/004"}, {5,"slvm-5","reproducibility, policy, recovery, assurance","sleela-virtual-machine/005"}, {6,"slvm-6","continuous verification, lineage, attestation, leases, migration","sleela-virtual-machine/006"}, {7,"slvm-7","hardened management, failure handling, recovery","sleela-virtual-machine/007"}, {8,"slvm-8","supervised execution, admission, leases, transactions, audit","sleela-virtual-machine/008"}, {9,"slvm-9","filesystem and OS adaptation","sleela-virtual-machine/009"}, {10,"slvm-10","verified storage execution","sleela-virtual-machine/010"}, {11,"slvm-11","filesystem-module hosting, schema-driven extension","sleela-virtual-machine/011"}, }; std::string sub = (argc>=3)? argv[2] : "list"; if(sub=="list"||sub=="-h"||sub=="--help"){ std::cout<<"Available virtual machines (the Native VM is the default):\n"; std::cout<<" native Native VM (impl/core) — used unless you select another [default]\n"; std::cout<<"\nStandard (think-tank versions):\n"; for(const auto&v:kVms) std::cout<<" "< "< "< | sleela vm info <1..10|premium 1..11>\n"; std::cout<<" sleela vm run |native> (premium generations are real runnable VMs)\n"; std::cout<<" sleela vm lock [premium <1..11>] pin a generation (no arg = the advanced/highest VM)\n"; std::cout<<" sleela vm unlock clear the pin | sleela vm status show the current pin\n"; return 0; } // `sleela vm run premium ` actually boots the // selected premium SLVM generation (a real VM linking the shared Core // engine) and runs the program on it. The generation is built on demand // (make -C its dir) if its binary is missing, the source is compiled to a // Core artifact via this same sleela binary, then the generation VM is // exec'd on that artifact. Standard (think-tank) versions are not yet // bootable this way; use the Native VM (plain `sleela run`). if(sub=="run"){ // forms: vm run premium | vm run p | vm run native if(argc<4){std::cerr<<"sleela vm run: expected |p|native> \n";return 2;} std::string sel=argv[3]; std::string pnum; int progIdx=-1; if(sel=="premium"){ if(argc<6){std::cerr<<"sleela vm run: premium needs \n";return 2;} pnum=argv[4]; progIdx=5; } else if(sel.size()>=2 && (sel[0]=='p'||sel[0]=='P') && std::isdigit((unsigned char)sel[1])){ pnum=sel.substr(1); progIdx=4; } else if(sel=="native"){ if(argc<5){std::cerr<<"sleela vm run: native needs \n";return 2;} std::cout<<"Native VM: running on impl/core (the default engine).\n"; return runFile(argv[4]); } else { std::cerr<<"sleela vm run: '"< or native)\n"; return 2; } if(progIdx>=argc){std::cerr<<"sleela vm run: missing \n";return 2;} int n=std::atoi(pnum.c_str()); if(n<1||n>11){std::cerr<<"sleela vm run: premium '"<' or clear the lock with 'sleela vm unlock'.\n"; return 3; } } const PremiumVm&v=kPremium[n-1]; char nn[4]; std::snprintf(nn,sizeof(nn),"%02d",n); std::string vmbin=std::string(v.dir)+"/vm-build/slvm-"+nn; std::string prog=argv[progIdx]; // Build the generation VM on demand if its binary is not present. if(!fs::exists(vmbin)){ std::cout<<"Building premium VM "< | p | ]` pins a premium generation so // every later `vm run` uses it and refuses any other. With no argument it // locks in the ADVANCED (highest) generation. The choice is persisted to // the VM config (config/vm.conf or $SLEELA_VM_CONF) as vm.locked=true. if(sub=="lock"){ int n=SLEELA_VM_MAX_VERSION; // default: the advanced VM if(argc>=4){ std::string sel=argv[3]; std::string pnum; if(sel=="premium"){ if(argc<5){std::cerr<<"sleela vm lock: premium needs a number 1..11\n";return 2;} pnum=argv[4]; } else if(sel.size()>=2 && (sel[0]=='p'||sel[0]=='P') && std::isdigit((unsigned char)sel[1])) pnum=sel.substr(1); else pnum=sel; // bare number n=std::atoi(pnum.c_str()); if(nSLEELA_VM_MAX_VERSION){ std::cerr<<"sleela vm lock: premium '"<' may use any generation 1..11 again.\n"; return 0; } // `sleela vm status` reports the current pin. if(sub=="status"){ SLEELA_VM_CONFIG cfg; vmLoadConfig(&cfg); std::cout<<"SLeeLa VM selection:\n" <<" config : "<\n";return 2;} std::string sel=argv[3]; // premium tier: `premium ` or `pNN`. bool premium=false; std::string pnum; if(sel=="premium"){ if(argc<5){std::cerr<<"sleela vm "<=2 && (sel[0]=='p'||sel[0]=='P') && std::isdigit((unsigned char)sel[1])){ premium=true; pnum=sel.substr(1); } if(premium){ int n=std::atoi(pnum.c_str()); if(n<1||n>11){std::cerr<<"sleela vm "<\n"; { SLEELA_VM_CONFIG cfg; vmLoadConfig(&cfg); if(cfg.locked && n!=cfg.version) std::cout<<" NOTE: the VM is locked to premium "<10){std::cerr<<"sleela vm "<>n)|(x<<(32-n));}; static const uint32_t K[64]={ 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2}; uint32_t h[8]={0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19}; std::string data=msg; uint64_t bitlen=(uint64_t)data.size()*8; data.push_back((char)0x80); while(data.size()%64!=56) data.push_back((char)0x00); for(int i=7;i>=0;--i) data.push_back((char)((bitlen>>(i*8))&0xff)); for(size_t off=0;off>3); uint32_t s1=rotr(w[i-2],17)^rotr(w[i-2],19)^(w[i-2]>>10); w[i]=w[i-16]+s0+w[i-7]+s1; } uint32_t a=h[0],b=h[1],c=h[2],d=h[3],e=h[4],f=h[5],g=h[6],hh=h[7]; for(int i=0;i<64;++i){ uint32_t S1=rotr(e,6)^rotr(e,11)^rotr(e,25); uint32_t ch=(e&f)^((~e)&g); uint32_t t1=hh+S1+ch+K[i]+w[i]; uint32_t S0=rotr(a,2)^rotr(a,13)^rotr(a,22); uint32_t maj=(a&b)^(a&c)^(b&c); uint32_t t2=S0+maj; hh=g;g=f;f=e;e=d+t1;d=c;c=b;b=a;a=t1+t2; } h[0]+=a;h[1]+=b;h[2]+=c;h[3]+=d;h[4]+=e;h[5]+=f;h[6]+=g;h[7]+=hh; } static const char* hex="0123456789abcdef"; std::string out; out.reserve(64); for(int i=0;i<8;++i) for(int j=7;j>=0;--j) out.push_back(hex[(h[i]>>(j*4))&0xf]); return out; } } // namespace sleela /* ---- `sleela registry` : review/get/set the Sleela registry -------------- * A terminal front end to the registry core (registry/sleela_registry.*): a * Windows-style key tree of settings + feature flags with sealed provenance. * A fresh install seeds a baseline; this command reviews or edits it. The * backing store is a portable .sleelareg file (default ./sleela.sleelareg or * $SLEELA_REGISTRY). */ static std::string registryStorePath(){ const char* env=std::getenv("SLEELA_REGISTRY"); if(env&&*env) return std::string(env); return "sleela.sleelareg"; } /* ---- 100-million-digit pi catalog constant ------------------------------- * The Modium/Registry startup loads the large pi reference whose locator is the * registry Math-key default `piReferenceLargePath` (seeded in * lib/registry/SLRegistry.sleela and registry/sleela_registry.c). The registry * stores only the locator (per REGISTRY-3.0-MODIUM.md: Registry holds record * identity + locator metadata, never the bytes); Modium resolves it to the * actual file on this host and this helper performs the one-time load. * * Resolution is host-relative and fail-SOFT: it searches a short list of * conventional locations (the repo-relative path, the installed data dir, and * an upward walk like the modium scanner), and if the file is absent it simply * reports "deferred" and returns 0 digits -- a missing large reference never * blocks the registry/modium command. On success it returns the loaded * fractional-digit count. */ static const char* kPiLargeRelPath = "pi-generator/pi.100000000.digits"; static const long long kPiLargeExpectedDigits = 100000000LL; static std::string resolvePiLargePath(){ namespace fsx=std::filesystem; /* 1) installed data dir, if we were told where we live */ if(const char* home=std::getenv("SLEELA_HOME")){ fsx::path p=fsx::path(home)/"pi"/"pi.100000000.digits"; if(fsx::exists(p)) return p.string(); } /* 2) common installed data roots (mirrors do-install's $(DATA_DIR)/pi) */ const char* roots[]={"/usr/local/share/sleela/pi/pi.100000000.digits", nullptr}; for(int i=0;roots[i];++i){ if(fsx::exists(roots[i])) return std::string(roots[i]); } if(const char* h=std::getenv("HOME")){ fsx::path u=fsx::path(h)/".local"/"share"/"sleela"/"pi"/"pi.100000000.digits"; if(fsx::exists(u)) return u.string(); } /* 3) repo-relative: upward walk from CWD (like modiumScanOne) */ fsx::path base=fsx::current_path(); for(int up=0;up<8;++up){ fsx::path cand=base/kPiLargeRelPath; if(fsx::exists(cand)) return cand.string(); if(base.has_parent_path()) base=base.parent_path(); else break; } return std::string(); } /* Load + lightly validate the large pi file; returns fractional-digit count * (0 if absent/invalid). Validation is cheap and streaming: confirm it begins * "3." and count decimal digits -- we do NOT hold the whole 100MB in a single * std::string or hash it here (that is VERIFIED.md's job, run out-of-band). */ static long long loadPiLargeConstant(const std::string& path){ if(path.empty()) return 0; std::ifstream in(path,std::ios::binary); if(!in) return 0; char head[2]={0,0}; in.read(head,2); if(in.gcount()<2 || head[0]!='3' || head[1]!='.') return 0; // not a decimal pi value /* The 2-byte head "3." is already consumed above; count the FRACTIONAL * digits that follow (the part the digit count refers to). The leading '3' * is deliberately not re-counted here. */ long long frac=0; char buf[1<<16]; while(in){ in.read(buf,sizeof buf); std::streamsize g=in.gcount(); for(std::streamsize i=0;i='0'&&buf[i]<='9') ++frac; } } return frac; /* fractional-digit count (leading '3' excluded) */ } /* Print the transient red "Loading (TM)" banner (Option B: subsystem * startup only), load the large pi catalog constant, and report the outcome on * one calm line. TTY-gated throughout via the banner helper, so piped/test * output is unaffected. `subsystem` is "Modium" or "Registry". */ static void subsystemStartup(const char* subsystem){ sleela::rails::transientLoading(std::cout, 1, subsystem); // red flash, then vanishes std::string path=resolvePiLargePath(); long long frac=loadPiLargeConstant(path); // fractional-digit count if(!sleela::rails::brandColorEnabled(1)) return; // off-terminal: stay silent if(frac>0){ std::cout<<"\033[31m"<=3)?argv[2]:"review"; int rc=0; if(sub=="review"||sub=="-h"||sub=="--help"){ std::string path=(argc>=4)?argv[3]:""; std::string buf; buf.resize(1<<16); long n=sl_reg_review(r, path.empty()?nullptr:path.c_str(), &buf[0], buf.size()); if(n>0){ buf.resize((size_t)n); std::cout< \n";rc=2;} else { char v[512]; long iv; int bv; sl_reg_kind k; if(sl_reg_value_kind(r,argv[3],argv[4],&k)!=SL_REG_OK){std::cerr<<"not found\n";rc=1;} else if(k==SL_REG_STRING&&sl_reg_get_string(r,argv[3],argv[4],v,sizeof v)==SL_REG_OK) std::cout< [--int|--bool]\n";rc=2;} else { bool asInt=false,asBool=false; for(int i=6;i [on|off]\n";rc=2;} else if(argc>=5){ int on=(std::string(argv[4])=="on"||std::string(argv[4])=="1"); sl_reg_feature_set(r,argv[3],on); sl_reg_save(r,store.c_str()); std::cout<<"feature "<=4)?argv[3]:"registry.sql"; if(sl_reg_export_sql(r,out)==SL_REG_OK) std::cout<<"exported MySQL script -> "<nextp){ pos=q2+1; total++; continue; } size_t s1=text.find('"',sp+9); size_t s2=text.find('"',s1+1); std::string want=text.substr(s1+1,s2-s1-1); pos=q2+1; total++; fsx::path fp=root/rel; if(!fsx::exists(fp)){missing++;std::cerr<<" MISSING "< min. */ static int64_t modiumClampBytes(int64_t want){ if(want<=0) return SL_MODIUM_MIN_BYTES; if(want<=SL_MODIUM_MIN_BYTES) return SL_MODIUM_MIN_BYTES; if(want>=SL_MODIUM_MAX_BYTES) return SL_MODIUM_MAX_BYTES; int64_t step=SL_MODIUM_MIN_BYTES; while(stepSL_MODIUM_MAX_BYTES?SL_MODIUM_MAX_BYTES:step; } /* Parse a human byte size with K/M/G suffix (e.g. "256M", "64G", "1073741824"). */ static bool modiumParseBytes(const std::string& s,int64_t& out){ if(s.empty()) return false; char* end=nullptr; double v=std::strtod(s.c_str(),&end); if(end==s.c_str()||v<0) return false; double mult=1.0; if(*end){ char c=(char)std::tolower((unsigned char)*end); if(c=='k')mult=1024.0; else if(c=='m')mult=1024.0*1024; else if(c=='g')mult=1024.0*1024*1024; else return false; if(*(end+1)) return false; } out=(int64_t)(v*mult); return true; } static std::string modiumHumanBytes(int64_t b){ char buf[32]; if(b>= (int64_t)1024*1024*1024) std::snprintf(buf,sizeof buf,"%.0fG",(double)b/(1024.0*1024*1024)); else std::snprintf(buf,sizeof buf,"%.0fM",(double)b/(1024.0*1024)); return buf; } /* The `.modium` descriptor. `rebuild` reconstructs the exact JSON text, so the * descriptor is regenerable and diff-stable (keys emitted in sorted order). */ struct ModiumDesc { std::string modium; /* "storage-region" */ std::string format; /* "1.0" */ int64_t regionBytes=0; std::string created; /* ISO-8601 UTC */ std::string owner; std::string deviceSeal; /* sha256(volumeId | regionBytes | owner) */ std::string author; /* kModiumStoreAuthor */ }; static std::string modiumNowUtc(){ std::time_t t=std::time(nullptr); std::tm g{}; #if defined(_WIN32) gmtime_s(&g,&t); #else gmtime_r(&t,&g); #endif char buf[32]; std::strftime(buf,sizeof buf,"%Y-%m-%dT%H:%M:%SZ",&g); return buf; } /* A stable per-volume identity for the seal. Uses the mount root's canonical * path (the strongest cross-platform identity available without new deps); a * descriptor copied to a different mount root therefore fails the seal. */ static std::string modiumVolumeId(const std::string& mountRoot){ namespace fsx=std::filesystem; std::error_code ec; fsx::path c=fsx::weakly_canonical(fsx::path(mountRoot),ec); return ec?mountRoot:c.string(); } static std::string modiumSeal(const std::string& volumeId,int64_t bytes,const std::string& owner){ return sleela::sha256_hex(volumeId+"|"+std::to_string(bytes)+"|"+owner); } /* Render the descriptor to its canonical, rebuildable JSON text. */ static std::string modiumRebuild(const ModiumDesc& d){ std::ostringstream o; o<<"{\n" <<" \"author\": \""< modiumRemovableVolumes(std::string& howResolved){ std::vector vols; SLPlatform p=slplatform_current(); namespace fsx=std::filesystem; std::error_code ec; if(p==SL_PLATFORM_LINUX){ howResolved="Linux: /proc/self/mountinfo (removable mounts under /media,/run/media,/mnt)"; std::ifstream mi("/proc/self/mountinfo"); std::string line; while(std::getline(mi,line)){ /* mountinfo field 5 is the mount point. */ std::istringstream ls(line); std::string tok; int idx=0; std::string mp; while(ls>>tok){ if(idx==4){ mp=tok; break; } ++idx; } if(mp.empty()) continue; if(mp.rfind("/media/",0)==0||mp.rfind("/run/media/",0)==0||mp.rfind("/mnt/",0)==0) if(std::find(vols.begin(),vols.end(),mp)==vols.end()) vols.push_back(mp); } } else if(p==SL_PLATFORM_MACOS){ howResolved="macOS: /Volumes (mounted volumes; the boot volume is excluded)"; for(auto it=fsx::directory_iterator("/Volumes",ec); !ec && it!=fsx::directory_iterator(); it.increment(ec)){ std::error_code lec; if(!it->is_directory(lec)) continue; /* The boot volume is a symlink to "/"; skip it. */ if(it->is_symlink(lec)) continue; vols.push_back(it->path().string()); } } else if(p==SL_PLATFORM_WINDOWS){ howResolved="Windows: DRIVE_REMOVABLE via the OS volume API"; /* Ask the OS backend for the live set of removable (DRIVE_REMOVABLE) * volume roots -- the OS is the authority; we never guess drive letters. */ char list[4096]={0}; int n=slos_removable_volumes(list,sizeof list); if(n>0){ std::string s(list); size_t start=0; while(startpath().filename().string(); if(n=="."||n==".."||n=="System Volume Information"||n==".Trashes"||n==".Spotlight-V100") continue; return ModiumVolState::NonEmptyForeign; } return ModiumVolState::Empty; } static int modiumStoreUsbInspect(const std::string& mountRoot){ ModiumDesc d; bool sealOk=false; switch(modiumInspectVol(mountRoot,d,sealOk)){ case ModiumVolState::Missing: std::cerr<<"modium store usb inspect: '"< needs --claim; * non-empty foreign -> needs --claim-force. Both require terminal confirmation. */ static int modiumStoreUsbClaim(const std::string& mountRoot,int64_t wantBytes,bool optClaim,bool optForce,const std::string& owner){ ModiumDesc existing; bool sealOk=false; ModiumVolState st=modiumInspectVol(mountRoot,existing,sealOk); if(st==ModiumVolState::Missing){ std::cerr<<"modium store claim: '"<=4)?argv[3]:""; int64_t bytes=0; bool haveBytes=false; bool optClaim=false, optForce=false; std::string owner, positional; for(int i=4;i=argc||!modiumParseBytes(argv[++i],bytes)){std::cerr<<"modium store: bad --bytes value\n";return 2;} haveBytes=true; } else if(a.rfind("--owner=",0)==0) owner=a.substr(8); else if(a=="--owner"){ if(i+1>=argc){std::cerr<<"modium store: --owner needs a value\n";return 2;} owner=argv[++i]; } else if(a.rfind("--container=",0)==0) positional=a.substr(12); else if(a=="--container"){ if(i+1>=argc){std::cerr<<"modium store: --container needs a value\n";return 2;} positional=argv[++i]; } else if(a.rfind("--",0)==0){ std::cerr<<"modium store: unknown option '"<=5)?argv[4]:""; if(usbOp=="list") return modiumStoreUsbList(); /* for inspect/claim the mount root is the first non-flag positional after 'usb' */ std::string mount; for(int i=5;i\n";return 2;} return modiumStoreUsbInspect(mount); } if(usbOp=="claim"){ if(mount.empty()){std::cerr<<"modium store usb claim: expected \n";return 2;} return modiumStoreUsbClaim(mount,bytes,optClaim,optForce,owner); } std::cerr<<"modium store usb: use list | inspect | claim [--claim|--claim-force]\n"; return 2; } std::cout<<"sleela modium store -- addressable Modium storage region (256M .. 64G)\n" " sleela modium store open [--bytes 256M..64G] [--container DIR] [--owner NAME]\n" " sleela modium store usb list\n" " sleela modium store usb inspect \n" " sleela modium store usb claim [--bytes ...] [--claim | --claim-force]\n"; return (op.empty())?0:2; } static int modiumCmd(int argc,char**argv){ subsystemStartup("Modium"); // transient red "Loading Modium(TM)" + large-pi load std::string sub=(argc>=3)?argv[2]:"status"; if(sub=="store") return modiumStoreCmd(argc,argv); bool exact=false,sealMode=false; for(int i=2;i [--from-sql] reconstitute from rebuild.sql (explicit; reports first)\n" " sleela modium store ... addressable Modium storage region (256M..64G); see 'sleela modium store'\n"; return 0; } if(sub=="scan"){ std::string target=(argc>=4 && argv[3][0]!='-')?argv[3]:""; if(target=="native"){std::cout<<"Native VM (impl/core) is covered by the build SHA-256 gate, not modium.\n";return 0;} if(target.empty()){int rc=0;for(int n=1;n<=10;++n)rc|=modiumScanOne(n,exact,sealMode);return rc;} int n=std::atoi(target.c_str()); if(n<1||n>10){std::cerr<<"sleela modium scan: '"<\n";return 2;} int n=std::atoi(argv[3]); if(n<1||n>10){std::cerr<<"out of range\n";return 2;} std::cout<<"modium restore (idea-vm-"< \n";return 2;} std::string science=argv[2]; if(science.rfind("--science=",0)==0)science=science.substr(10); SLDA_ScienceDomain domain; if(slda_parse_domain(science.c_str(),&domain)!=0){std::cerr<<"sleela: unknown science domain '"<100){std::cerr<<"sleela: design activity score "<<(i+1)<<" must be 0..100\n";return 2;}} SLDA_Vector normalized,expected; SLDA_Result result{}; if(slda_normalize(raw,&normalized)!=0||slda_science_profile(domain,&expected)!=0||slda_compare(&normalized,&expected,&result)!=0){std::cerr<<"sleela: design activity calculation failed\n";return 1;} result.domain=domain; char json[1024];slda_format_json("sleela",&result,json,sizeof json); std::cout< [more.sleela ...] -o \n" << " Compile one or more Sleela source files to a runnable Core artifact\n" << " (author-marked documents also emit an originated source document;\n" << " add --wiki or --wiki-dir= to also emanate a MediaWiki page)\n" << " " << n << " check \n" << " Parse, resolve referenced library units, and check semantics (no output artifact)\n" << " " << n << " validate-artifact \n" << " Validate a compiled artifact's Core ABI and format\n" << " " << n << " version\n" << " Print the Sleelvac compiler version string\n" << "\n" << "Notes:\n" << " - `compile` writes a persistent Core artifact plus a sibling\n" << " .annotations metadata file.\n" << " - Native math/physics/economics/chemistry/financial module calls are lowered at compile time.\n" << " - Execution is gated by SHA-256 verification; the trusted manifest must verify before a build runs.\n" << " - The global memory limit may also be set by the SLeeLa configuration/environment.\n"; return 2; } static int usage(){ const std::string &n = cliProgramName; // When invoked as `sleelvac`, present the compiler's own surface rather than // the full `sleela` front end. Sleelvac is the SLeeLa *compiler*: it turns // source into runnable Core artifacts and checks/validates them. The run, // server, VM, registry and framework-input commands belong to the `sleela` // front end; sleelvac only documents what it is actually for. if(fs::path(cliProgramName).stem().string()=="sleelvac") return sleelvacUsage(); std::cerr << "Sleela - SLeeLa compiler and runtime front end" << " (syntax spec " << sleela::minSupportedSyntax().str() << " - " << sleela::maxSupportedSyntax().str() << ")\n" << "\n" << "Global options (before the command):\n" << " --memory-manager, --mm Enable the Memory Manager with the default 2 GiB limit\n" << " --memory-manager=SIZE Enable it with a byte limit; K, M, and G suffixes are accepted\n" << " --mm=SIZE Short form of --memory-manager=SIZE\n" << "\n" << "Source and artifact commands:\n" << " " << n << " [global-options] compile [more.sleela ...] -o \n" << " Compile one or more Sleela source files to a runnable Core artifact\n" << " " << n << " check \n" << " Parse, resolve referenced library units, and check semantics\n" << " " << n << " run [arguments ...]\n" << " " << n << " run --class-path [arguments ...]\n" << " " << n << " run --class [arguments ...]\n" << " Run SLeeLa input, Java source, runnable JAR, or compiled Java class\n" << " " << n << " validate-artifact \n" << " Validate the runnable artifact ABI and format\n" << " " << n << " version\n" << " Print the compiler/runtime version string\n" << "\n" << "Other commands:\n" << " " << n << " http-server <1|2|3> [--port N] [--threads N] [--root DIR] [--log FILE] [--once]\n" << " " << n << " xclass [--run|--emit|--info] [more-files ...]\n" << " " << n << " langin [--run|--emit-sleela|--emit-xclass|--info] [more-files ...]\n" << " " << n << " nordshrift [--emit|--roundtrip] [--target=sleela|java|c] \n" << " " << n << " vm [list|select |info |run |p|native> ]\n" << " " << n << " modium [scan [native|1..10] [--exact] [--seal]|status|restore <1..10>|store ...]\n" << " " << n << " registry [review [key-path]|get |set [--int|--bool]|feature [on|off]|save|export [file]]\n" << " " << n << " native [--config |-c ] [--memory-manager[=]|--mm[=]] [--] [args...]\n" << " " << n << " exec [--config |-c ] [--memory-manager[=]|--mm[=]] [--] [args...]\n" << " " << n << " design-activity \n" << " " << n << " defender [directory] [--allow-defender|--optin] [--allow-root] [--sha256 |--sha256=]\n" << " " << n << " docs [] [] | --generate [dir] | --live ... | --facade [--facade-root DIR] [--facade-max-mb N|--facade-max-files N|--facade-max-seconds N]\n" << " SleelaDoc in the terminal (docs crypto, docs stringbuilder); no args lists all topics; --generate writes the text corpus; --facade searches the OS at runtime for a facade topic's real files (default caps 6 MB / 6000 files / 6 min)\n" << "\n" << "Command-specific option details:\n" << " xclass: --run (default), --emit, --info\n" << " langin: --run (default), --emit-sleela (alias --emit), --emit-xclass, --info\n" << " nordshrift: --emit, --roundtrip, --target=sleela (default)|java|c\n" << " native/exec: --config FILE (alias -c; also --config=FILE); --memory-manager[=SIZE] or --mm[=SIZE]; -- ends option parsing\n" << " defender: detect is read-only; fetch/build/install/provision require --allow-defender or SLEELA_DEFENDER_OPTIN=1;\n" << " --sha256 HEX or --sha256=HEX (or SLEELA_DEFENDER_SHA256) supplies the expected archive hash;\n" << " --allow-root (or SLEELA_DEFENDER_ALLOW_ROOT=1) explicitly authorizes privileged installation\n" << " Global memory limit may also be set by the SLeeLa configuration/environment.\n"; return 2; } static bool checkSyntaxVersion(const std::string& path,const std::string& src){sleela::VersionResolution v=sleela::resolveSyntaxVersion(src);if(v.isError()){std::cerr<<"sleelvac: "<//) with a SUPPORT.md stub the // developer fills out. Folder creation is best-effort: a read-only or // unwritable tree must never fail a check/compile, so a materialize failure is // silently tolerated (the annotations are still attached in-memory). static void runKeywordSupporterPass(const std::string& path, sleela::Program& prog){ std::string rel = path; std::error_code ec; fs::path abs = fs::weakly_canonical(fs::path(path), ec); if(!ec){ fs::path r = fs::relative(abs, fs::current_path(), ec); if(!ec && !r.empty()) rel = r.generic_string(); } auto records = sleela::frontend::collectKeywordSupporters(prog, rel); if(records.empty()) return; sleela::frontend::attachSupporterAnnotations(prog, records); std::string docsRoot = (fs::current_path() / "docs").generic_string(); sleela::frontend::materializeSupporterFolders(records, docsRoot); // best-effort } static bool parseSource(const std::string&path,std::string&src,sleela::Program&prog,sleela::VersionResolution&version){if(!readFile(path,src)){std::cerr<<"sleelvac: cannot open '"< "< "+outputPath); // Author-marked documents (syntax 2.4) get a second, originated source // document alongside the artifact: every member located, originated, and // branded with a therefore-brander. Clean and united. if(prog.authorMarked){std::string op=sleela::writeOriginatedDocument(prog,sourcePath,g_originateDir);if(!op.empty())std::cout<<"sleelvac: originated source -> "< "<0)data.add(line.substr(0,eq),line.substr(eq+1));} sleela::annotation::AnnotationRuntime annotations;std::string annotationError; if(!annotations.install(data,annotationError)){std::cerr<<"sleelvac: artifact annotation runtime rejected: "< loadedPaths; std::string source=initialSource; for(const auto& c:program.classes) loadedPaths.insert(c.name); for(const auto& s:program.structs) loadedPaths.insert(s.name); // Identifier discovery is a hand-written scan, not std::regex: libstdc++'s regex // matcher recurses once per character, so one long identifier in the source // (50,000 characters is enough) overflowed the stack and crashed the compiler. // A match is a maximal run of [A-Za-z0-9_] that starts with a letter or '_' // (the same set the former pattern \b[A-Za-z_][A-Za-z0-9_]*\b produced). auto scanIdentifiers = [](const std::string& text) { std::vector> found; auto isWord = [](char ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_'; }; for (std::size_t at = 0; at < text.size();) { if (!isWord(text[at])) { ++at; continue; } std::size_t end = at + 1; while (end < text.size() && isWord(text[end])) ++end; if (!(text[at] >= '0' && text[at] <= '9')) found.emplace_back(text.substr(at, end - at), at); at = end; } return found; }; // Ignore comments and string/character literals during dependency discovery. // Documentation text must not trigger unrelated library loads (for example, // the word "Certificate" in a comment must not resolve Java API classes). auto dependencyScanText = [](const std::string& input) { std::string output = input; enum class State { Code, LineComment, BlockComment, AngleBlockComment, String, Character }; State state = State::Code; bool escaped = false; for (size_t i = 0; i < input.size(); ++i) { const char c = input[i]; const char next = (i + 1 < input.size()) ? input[i + 1] : '\0'; if (state == State::Code) { bool linePrefix = true; for (size_t p = i; p > 0 && input[p - 1] != '\n'; --p) { const char before = input[p - 1]; if (before != ' ' && before != '\t' && before != '\r') { linePrefix = false; break; } } if (linePrefix && c == '<' && next == '<') { output[i] = output[i + 1] = ' '; ++i; state = State::AngleBlockComment; } else if (linePrefix && c == '<' && next != '<') { size_t close = i + 1; while (close < input.size() && input[close] != '\n' && input[close] != '>') ++close; if (close < input.size() && input[close] == '>') { output[i] = ' '; state = State::LineComment; } } else if (c == '/' && next == '/') { output[i] = output[i + 1] = ' '; ++i; state = State::LineComment; } else if (c == '/' && next == '*') { output[i] = output[i + 1] = ' '; ++i; state = State::BlockComment; } else if (c == '"') { output[i] = ' '; state = State::String; escaped = false; } else if (c == '\'') { output[i] = ' '; state = State::Character; escaped = false; } } else if (state == State::LineComment) { if (c == '\n') state = State::Code; else output[i] = ' '; } else if (state == State::BlockComment) { if (c == '*' && next == '/') { output[i] = output[i + 1] = ' '; ++i; state = State::Code; } else if (c != '\n') output[i] = ' '; } else if (state == State::AngleBlockComment) { if (c == '>' && next == '>') { output[i] = output[i + 1] = ' '; ++i; state = State::Code; } else if (c != '\n') output[i] = ' '; } else { if (c != '\n') output[i] = ' '; if (escaped) escaped = false; else if (c == '\\') escaped = true; else if ((state == State::String && c == '"') || (state == State::Character && c == '\'')) state = State::Code; } } return output; }; // A nested Java type lives in a file named Outer.Inner.sleela that declares // a top-level `class Inner`. The parser spells nested types Outer__Inner // (syntax 1.11), so rewrite the declared name and every unqualified use of it // inside the unit to the mangled name. Identifiers after '.', and everything // inside comments and string literals, are left alone. auto renameNestedUnit = [&](const std::string& unitText, const std::string& stem) { const std::size_t lastDot = stem.rfind('.'); if(lastDot == std::string::npos || lastDot == 0 || lastDot + 1 >= stem.size()) return unitText; if(!std::isupper(static_cast(stem[0]))) return unitText; const std::string inner = stem.substr(lastDot + 1); std::string mangled; for(char ch : stem) { if(ch == '.') mangled += "__"; else mangled.push_back(ch); } const std::string masked = dependencyScanText(unitText); std::vector hits; std::size_t at = 0; while((at = masked.find(inner, at)) != std::string::npos) { const std::size_t end = at + inner.size(); auto wordChar = [](char c){ return std::isalnum(static_cast(c)) || c == '_'; }; bool boundaryBefore = (at == 0) || !wordChar(masked[at - 1]); bool boundaryAfter = (end >= masked.size()) || !wordChar(masked[end]); std::size_t back = at; while(back > 0 && (masked[back - 1] == ' ' || masked[back - 1] == '\t')) --back; const bool afterDot = back > 0 && masked[back - 1] == '.'; if(boundaryBefore && boundaryAfter && !afterDot) hits.push_back(at); at = end; } std::string out = unitText; for(std::size_t i = hits.size(); i-- > 0;) out.replace(hits[i], inner.size(), mangled); return out; }; // Resolve in passes so a loaded unit can pull in its own referenced units. // Names the loader must resolve even though no source text mentions them: // a method called on a String binds to class JavaStringMethods (syntax 3.0), // which only type analysis can detect. Each seed is tried once. std::set seeds; bool stringMethodsProbed=false; bool faultsSeeded=false; for(size_t pass=0;pass<64;++pass){ std::set names(seeds.begin(),seeds.end()); const std::string scanSource = dependencyScanText(source); for(const auto& identifierMatch:scanIdentifiers(scanSource)){ const std::string& name=identifierMatch.first; // A name that follows '.' is a member or the tail of a qualified // name (java.util.List): it is not a library unit reference. The // Java signature surface erases package-qualified types to Any. const std::size_t pos=identifierMatch.second; std::size_t back=pos; while(back>0 && (scanSource[back-1]==' '||scanSource[back-1]=='\t')) --back; if(!name.empty() && std::isupper(static_cast(name[0])) && back>0 && scanSource[back-1]=='.'){ // Nested Java types (Map.Entry, Base64.Encoder) live in files // named Outer.Inner.sleela. A capitalized name after `Outer.` is // the tail of a nested-type reference: seed the dotted unit name // so the loader finds the nested file. Unknown seeds are ignored. std::size_t q=back-1; while(q>0 && (scanSource[q-1]==' '||scanSource[q-1]=='\t')) --q; const std::size_t e=q; while(q>0 && (std::isalnum(static_cast(scanSource[q-1]))||scanSource[q-1]=='_')) --q; if(q(scanSource[q]))) names.insert(scanSource.substr(q,e-q)+"."+name); } if(back>0 && scanSource[back-1]=='.') continue; if(!name.empty() && std::isupper(static_cast(name[0]))) names.insert(name); } // Sleela.home / Sleela.VM / .System / .OS: the VM boot places Security2 above the VM. if(scanSource.find("Sleela.home")!=std::string::npos||scanSource.find("Sleela.VM")!=std::string::npos||scanSource.find("Sleela.System")!=std::string::npos||scanSource.find("Sleela.OS")!=std::string::npos) names.insert("Security2"); bool changed=false; for(const auto& name:names){ if(loadedPaths.count(name)) continue; const sleela::library::Symbol* match=nullptr; // A versioned library import such as `import gui.version-military;` // selects that source subtree for duplicate class names. A plain // single-segment import that names a real library package (for // example `import collections;`) is honored the same way, so a // program can pick the intended family when a bare class name is // defined in more than one package (for example SLStack, which the // spec assigns to collections but which also exists under cpu/ as // the hardware stack). std::vector preferredRoots; for(const auto& imported : program.imports){ std::string root=imported; std::replace(root.begin(),root.end(),'.','/'); if(root.find('/')!=std::string::npos) preferredRoots.push_back(root); else if(index.hasPackage(root)) preferredRoots.push_back(root); } auto underPreferredRoot=[&](const sleela::library::Symbol& symbol){ for(const auto& root:preferredRoots) if(symbol.path.rfind(root + "/",0)==0) return true; return false; }; bool hasPreferredMatch=false; for(const auto& symbol:index.symbols()) if(symbol.name==name && underPreferredRoot(symbol)) hasPreferredMatch=true; // Candidate narrowing for a library family that ships several kinds of // unit for the same simple name (real sources, generated reference // files, per-edition trees) is a language-handler policy // (lang::filterLibraryCandidates, e.g. the Java tier rules); with no // handler every candidate under the preferred roots stays. std::vector candidatePaths; for(const auto& symbol:index.symbols()){ if(symbol.name!=name) continue; if(hasPreferredMatch && !underPreferredRoot(symbol)) continue; candidatePaths.push_back(symbol.path); } const std::vector keptPaths=sleela::lang::filterLibraryCandidates(name,candidatePaths,preferredRoots); const std::set keep(keptPaths.begin(),keptPaths.end()); for(const auto& symbol:index.symbols()){ if(symbol.name!=name) continue; if(hasPreferredMatch && !underPreferredRoot(symbol)) continue; if(!keep.count(symbol.path)) continue; if(match && match->path!=symbol.path){ // Tie-break: a unit directly inside a preferred root (import // java.jdk-25.java.util;) beats one in a sub-package of it // (java/util/prefs/Base64 vs java/util/Base64). auto directlyUnder=[&](const sleela::library::Symbol& sy){ const std::string dir=fs::path(sy.path).parent_path().generic_string(); for(const auto& root:preferredRoots) if(dir==root) return true; return false; }; const bool dm=directlyUnder(*match), ds=directlyUnder(symbol); if(ds && !dm){ match=&symbol; continue; } if(dm && !ds) continue; std::cerr<<"sleelvac: ambiguous library symbol '"<path<<" and "<path).string(); std::string unitSource; if(!readFile(path,unitSource)){ std::cerr<<"sleelvac: cannot read library unit '"<name); sleela::Lexer lexer(unitSource); sleela::Parser parser(lexer.tokenize()); sleela::Program unit=parser.parseProgram(); // Tag every unit pulled from /lib with its provenance so the // compiler can drop library classes that no reachable code uses // (a transitive identifier scan over a very large /lib would // otherwise merge far more class layouts than the program needs // and exhaust the VM's 256-layout budget). for(auto& cls:unit.classes) cls.fromLibrary=true; for(auto& st:unit.structs) st.fromLibrary=true; // Mark the path before merging to prevent dependency cycles. loadedPaths.insert(name); for(const auto& cls:unit.classes) loadedPaths.insert(cls.name); for(const auto& st:unit.structs) loadedPaths.insert(st.name); source += "\n" + unitSource; mergeProgram(program,std::move(unit)); changed=true; }catch(const std::exception& ex){ std::cerr<<"sleelvac: library unit '"<& paths){ sleela::rails::brandSleela(std::cout,1); if(paths.empty())return 1; sleela::Program merged; sleela::VersionResolution firstSyntax; bool haveSyntax=false; for(const auto& path:paths){ std::string src; sleela::Program prog; sleela::VersionResolution syntax; if(!parseSource(path,src,prog,syntax))return 1; if(!loadReferencedLibraryUnits(src,prog,syntax.declared))return 1; if(!haveSyntax){firstSyntax=syntax;haveSyntax=true;} mergeProgram(merged,std::move(prog)); } catalog::Catalog cat=loadCatalog(); return compileAndRun(merged,cat,firstSyntax.declared); } // Compile one or more .sleela files into a single runnable artifact. static int compileFilesMulti(const std::vector& paths,const std::string& outputPath){ sleela::rails::brandSleelvac(std::cout,1); if(verifyBeforeExecution(fs::current_path()))return 1; if(paths.empty())return 1; sleela::Program merged; sleela::VersionResolution firstSyntax; bool haveSyntax=false; for(const auto& path:paths){ std::string src; sleela::Program prog; sleela::VersionResolution syntax; if(!parseSource(path,src,prog,syntax))return 1; if(!loadReferencedLibraryUnits(src,prog,syntax.declared))return 1; if(!haveSyntax){firstSyntax=syntax;haveSyntax=true;} mergeProgram(merged,std::move(prog)); } catalog::Catalog cat=loadCatalog(); try{ int rc=sleela::compileToArtifact(merged,outputPath,&cat,firstSyntax.declared); if(rc!=0)return 1; std::cout<<"sleelvac: "< "< "+outputPath); return 0; }catch(const std::exception&ex){std::cerr<<"sleelvac: "<&paths){catalog::Catalog cat=loadCatalog();try{sleela::xclass::Loaded loaded=sleela::xclass::loadFiles(paths);std::cout<<"[xclass] ingested "<files;for(int i=2;i&paths){catalog::Catalog cat=loadCatalog();try{sleela::langin::Loaded loaded=sleela::langin::loadFiles(paths);std::cout<<"[langin] ingested "<` static int langinCmd(int argc,char**argv){enum{RUN,EMIT_SLEELA,EMIT_XCLASS,INFO}mode=RUN;std::vectorfiles;for(int i=2;i` (SLeeLa -> Nordshrift) // `sleela nordshrift --roundtrip ` (SLeeLa -> Nordshrift(Sleela) -> re-parse -> run + verify) /* ---- `sleela aot` : independently addressable native method emission ------- * Emits a standalone typed-ABI C plugin, one C entry body per supported * annotated static method. Eligibility is deliberately fail-closed: no * instance receiver, VM objects, arrays, closures, raw pointers, method calls, * string literals/operations, or print side effects cross this first ABI. * The command emits source only; the host separately compiles, authorizes, * opens, and binds the resulting plugin. */ static bool methodHasNative(const sleela::Method& m){ for(const auto& a:m.java.annotations) if(a.name=="native" && a.marker) return true; return false; } /* Walk a @native method body and report the FIRST construct outside the * independently emitted ABI-v1 subset. This intentionally excludes calls, * print side effects, string literals/operators, division/remainder, VM * composites, and loop timing/spill annotations. The emitter performs a * second typed validation pass before writing any C source. */ static bool nativeAbiType(const std::string& t, bool result); static std::string nativeUnsupportedReason(const sleela::Expr* e); static std::string nativeUnsupportedReason(const sleela::Stmt* s); static std::string nativeUnsupportedReason(const sleela::Expr* e){ using namespace sleela; if(!e) return ""; if(dynamic_cast(e)||dynamic_cast(e)|| dynamic_cast(e)||dynamic_cast(e)) return ""; if(dynamic_cast(e)) return "null is not representable in native ABI v1"; if(dynamic_cast(e)) return "String literals are not in the @native subset yet"; if(auto u=dynamic_cast(e)){ if(u->op!="-" && u->op!="+" && u->op!="!") return "unsupported unary operator '"+u->op+"'"; return nativeUnsupportedReason(u->operand.get()); } if(auto b=dynamic_cast(e)){ static const char* ops[]={"+","-","*","/","%","==","!=","<","<=",">",">=","&&","||"}; bool supported=false; for(const char* op:ops) if(b->op==op) supported=true; if(!supported) return "unsupported binary operator '"+b->op+"'"; if(b->op=="/" || b->op=="%") return "division and remainder are not yet supported by native ABI v1"; std::string l=nativeUnsupportedReason(b->lhs.get()); if(!l.empty())return l; return nativeUnsupportedReason(b->rhs.get()); } if(auto as=dynamic_cast(e)){ std::string t=nativeUnsupportedReason(as->target.get()); if(!t.empty())return t; return nativeUnsupportedReason(as->value.get()); } if(auto cnd=dynamic_cast(e)){ std::string r=nativeUnsupportedReason(cnd->cond.get()); if(!r.empty())return r; r=nativeUnsupportedReason(cnd->thenE.get()); if(!r.empty())return r; return nativeUnsupportedReason(cnd->elseE.get()); } if(dynamic_cast(e)) return "calls to other methods are not yet supported in an independently emitted method"; if(dynamic_cast(e)) return "qualified/instance calls (receiver.method(...)) are not in the @native subset yet"; if(dynamic_cast(e)) return "object construction ('new') is not in the @native subset yet"; if(dynamic_cast(e)) return "array indexing is not in the @native subset yet"; return "an expression form outside the @native subset was used"; } static std::string nativeUnsupportedReason(const sleela::Stmt* s){ using namespace sleela; if(!s) return ""; if(auto b=dynamic_cast(s)){for(const auto&st:b->stmts){std::string r=nativeUnsupportedReason(st.get()); if(!r.empty())return r;}return "";} if(auto v=dynamic_cast(s)){ if(!nativeAbiType(v->type,false)) return "unsupported local type '"+v->type+"'"; return nativeUnsupportedReason(v->init.get()); } if(dynamic_cast(s)) return "labeled statements (syntax 3.1) are not in the @native subset yet"; if(auto a=dynamic_cast(s)){std::string r=nativeUnsupportedReason(a->value.get()); if(!r.empty())return r; return "";} if(auto e=dynamic_cast(s)) return nativeUnsupportedReason(e->expr.get()); if(dynamic_cast(s)) return "print side effects are not supported in independently emitted native methods"; if(auto r=dynamic_cast(s)) return nativeUnsupportedReason(r->value.get()); if(auto i=dynamic_cast(s)){std::string r=nativeUnsupportedReason(i->cond.get()); if(!r.empty())return r; r=nativeUnsupportedReason(i->thenS.get()); if(!r.empty())return r; return nativeUnsupportedReason(i->elseS.get());} if(auto w=dynamic_cast(s)){if(w->loopSleepMs>0 || w->spill.hasSpill)return "loop timing/spill annotations are not supported by native ABI v1";std::string r=nativeUnsupportedReason(w->cond.get()); if(!r.empty())return r; return nativeUnsupportedReason(w->body.get());} if(dynamic_cast(s)) return "the enhanced for is not supported by native ABI v1"; if(auto f=dynamic_cast(s)){if(f->loopSleepMs>0 || f->spill.hasSpill || f->threadStable || f->heapHealthy)return "loop timing/spill/stability annotations are not supported by native ABI v1";std::string r=nativeUnsupportedReason(f->init.get()); if(!r.empty())return r; r=nativeUnsupportedReason(f->cond.get()); if(!r.empty())return r; r=nativeUnsupportedReason(f->update.get()); if(!r.empty())return r; return nativeUnsupportedReason(f->body.get());} return "a statement form outside the @native subset was used"; } static bool nativeAbiType(const std::string& t, bool result){ return t=="int" || t=="double" || t=="boolean" || t=="String" || (result && t=="void"); } static void aotUsage(){ std::cerr<<"sleela aot — per-method native plugin source generation for @native methods\n" " sleela aot --list list @native methods and eligibility\n" " sleela aot --emit emit standalone typed-ABI C plugin source\n" " sleela aot same as --list\n" "\nABI v1: static methods; int, double, boolean, and length-delimited String values.\n" "Compile the emitted C source as a trusted shared library with native_loader.h on the include path.\n"; } static int aotCmd(int argc,char**argv){ enum{LIST,EMIT}mode=LIST; std::string file; for(int i=2;i\n";aotUsage();return 2;} if(verifyBeforeExecution(fs::current_path(), mode==EMIT))return 1; std::string src;sleela::Program prog;sleela::VersionResolution ver; if(!parseSource(file,src,prog,ver))return 1; // AOT is a code-generation path, not a semantic-analysis bypass. Load the // same referenced library units as check/compile, then run the normal // analyzer without requiring an executable entry point (AOT inputs may be // library units). Keep this before subset reporting/emission so invalid // source can never be advertised as eligible or translated. try{ if(!loadReferencedLibraryUnits(src,prog,ver.declared))return 1; sleela::SemanticResult sem=sleela::analyzeSemantics(prog,ver.declared,false); for(const auto&w:sem.warnings) std::cerr<<"sleela aot: "< found; for(const auto& c:prog.classes){ for(const auto& m:c.methods){ if(!methodHasNative(m)) continue; std::string reason; if(!m.isStatic) reason="instance methods are excluded until a receiver ABI is defined"; if(reason.empty() && !nativeAbiType(m.retType,true)) reason="unsupported native return type '"+m.retType+"'"; for(const auto& p:m.params) if(reason.empty() && !nativeAbiType(p.type,false)) reason="unsupported native parameter type '"+p.type+"'"; if(reason.empty()) reason=nativeUnsupportedReason(m.body.get()); found.push_back({c.name,m.name,reason}); } } // The per-method report is DIAGNOSTIC and goes to stderr, so that under // --emit the stdout stream carries ONLY the emitted C/C++ (clean enough to // redirect straight into a .c file and compile). std::ostream& rep = (mode==EMIT) ? std::cerr : std::cout; if(found.empty()){std::cout<<"sleela aot: no @native methods in "<0){ std::cerr<<"sleela aot: "<\n";return 2;} if(verifyBeforeExecution(fs::current_path()))return 1; // SLeeLa -> Nordshrift: parse the Sleela source and transpile via the emitter. std::string src;sleela::Program prog;sleela::VersionResolution ver; if(!parseSource(file,src,prog,ver))return 1; std::string nordshriftForm; try{nordshriftForm=nordshrift::emitProgram(prog,target,pkg);}catch(const std::exception&ex){std::cerr<<"sleelvac: nordshrift emit failed: "< Nordshrift(Sleela) -> re-parse: " <<(structurallyEqual?"structure preserved":"WARNING: structure changed") <<(textFixed?" (exact fixed point)":" (canonical form stable; re-emit normalizes)")<<"\n"; if(!structurallyEqual)return 1; catalog::Catalog cat=loadCatalog(); return compileAndRun(back,cat,ver.declared); } int main(int argc,char**argv){ if(argc>0 && argv[0] && *argv[0]) cliProgramName = fs::path(argv[0]).filename().string(); if(argc<2)return usage(); bool mmEnabled=true; size_t mmLimit=kDefaultMemoryLimit; std::string memoryConfig; if(const char*cfg=std::getenv("SLEELA_CONFIG_FILE"))memoryConfig=cfg; else if(fs::exists("sleela.conf"))memoryConfig="sleela.conf"; if(!memoryConfig.empty()){bool ce=mmEnabled;if(!loadMemoryConfig(memoryConfig,mmLimit,ce))return 2;mmEnabled=ce;} {size_t l=0;if(memoryManagerRequested(l)){mmEnabled=true;mmLimit=l;}} int start=1; while(start=argc)return usage(); std::string cmd=argv[start]; if(start>1){int n=argc-start;std::vector av;av.reserve((size_t)n+1);for(int i=start;i -o : collect every source path before "-o". std::vector files; std::string out; for(int i=2;i hostArgs;for(int i=2;ifiles;for(int i=2;ifiles;for(int i=2;i3){std::vectorfiles;for(int i=2;i