Home /Modules/impl/originate.cpp

originate.cpp

impl/frontend/originate.cpp · 169 line(s) · c

// originate.cpp -- the "originated" source-document emitter (syntax 2.4).
// ===========================================================================
#include "originate.h"
#include "ast.h"
#include "../../ledger/ledger_core.h"
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <sys/stat.h>
#include <time.h>

namespace sleela {

// Base name of a path (strip directory), keeping the extension.
static std::string baseName(const std::string& path){
    size_t slash=path.find_last_of("/\\");
    return slash==std::string::npos?path:path.substr(slash+1);
}
// Directory part of a path (without trailing slash), or "" if none.
static std::string dirName(const std::string& path){
    size_t slash=path.find_last_of("/\\");
    return slash==std::string::npos?std::string():path.substr(0,slash);
}

// The document's edit date as YYYY-MM-DD, taken from the file's mtime. Falls
// back to the current date if the file cannot be stat'd.
static std::string editDate(const std::string& path){
    struct stat st; time_t t;
    if(stat(path.c_str(),&st)==0) t=st.st_mtime; else t=time(nullptr);
    struct tm tmv; 
#if defined(_WIN32)
    localtime_s(&tmv,&t);
#else
    localtime_r(&t,&tmv);
#endif
    char buf[16]; strftime(buf,sizeof(buf),"%Y-%m-%d",&tmv);
    return std::string(buf);
}

// The parameter signature restricted to int/String, comma-separated. A param
// whose type is neither int nor String is rendered as its own type token but
// marks the member ineligible for the duplicate allowance (see eligible()).
static std::string paramTypeList(const Method& m){
    std::string out; bool first=true;
    for(const auto& p:m.params){
        if(!first) out+=",";
        first=false;
        out+=p.type;
    }
    return out;
}
// A member is brander-eligible for the duplicate allowance when every parameter
// is int or String (the brief restricts the considered parameters to these).
static bool eligible(const Method& m){
    for(const auto& p:m.params) if(p.type!="int"&&p.type!="String") return false;
    return true;
}

// The SHA-256 brander over <doc>|<member>|<paramTypes>|<editDate>.
static std::string brand(const std::string& doc,const std::string& member,
                         const std::string& sig,const std::string& date){
    return ledger::sha256_hex(doc+"|"+member+"|"+sig+"|"+date);
}

// A valid default body for a method of the given return type, so the originated
// document stays compilable SLeeLa (the real body lives in the artifact twin).
// The brander comment above each method records its identity.
static std::string defaultBody(const std::string& ret){
    if(ret=="void")     return "{ }";
    if(ret=="int")      return "{ return 0; }";
    if(ret=="long")     return "{ return 0; }";
    if(ret=="float")    return "{ return 0.0; }";
    if(ret=="double")   return "{ return 0.0; }";
    if(ret=="boolean")  return "{ return false; }";
    if(ret=="String")   return "{ return \"\"; }";
    return "{ return null; }"; // reference types
}

std::string writeOriginatedDocument(const Program& prog,
                                    const std::string& srcPath,
                                    const std::string& originateDir){
    const std::string doc=baseName(srcPath);
    const std::string date=editDate(srcPath);

    // Choose the output path: originateDir if given, else the source directory.
    std::string outDir=originateDir.empty()?dirName(srcPath):originateDir;
    // Replace the final ".sleela" with ".originated.sleela" (or append it).
    std::string outBase=doc;
    const std::string ext=".sleela";
    if(outBase.size()>=ext.size()&&outBase.compare(outBase.size()-ext.size(),ext.size(),ext)==0)
        outBase=outBase.substr(0,outBase.size()-ext.size());
    std::string outPath=(outDir.empty()?outBase:outDir+"/"+outBase)+".originated.sleela";

    std::ofstream o(outPath,std::ios::trunc);
    if(!o){ std::cerr<<"originate: cannot write '"<<outPath<<"'\n"; return ""; }

    o<<"#sleela 2.4\n";
    o<<"<< Originated source document for "<<doc<<" (syntax 2.4). Generated by the\n";
    o<<"   standard compile. Every field and method is located and originated and\n";
    o<<"   carries a therefore-brander. The brander value is each member SHA-256\n";
    o<<"   hash over doc, member, paramTypes and editDate. Edit date: "<<date<<". >>\n";
    o<<"author;\n\n";

    // Per class, assign declaration-order ids (fields then methods, from 1) and
    // build the ordering table for any duplicated method name.
    for(const auto& c:prog.classes){
        o<<"class "<<c.name<<" {\n\n";

        int id=0;

        // Fields.
        for(const auto& f:c.fields){
            ++id;
            std::string h=brand(doc,f.name,"",date);
            o<<"  < \u2234 origin(id="<<id<<", hash="<<h.substr(0,16)
             <<", doc=\""<<doc<<"\", member=\""<<f.name<<"\", kind=field, edited=\""<<date<<"\") >\n";
            o<<"  "<<(f.isStatic?"static ":"")<<(f.isProtected?"protected ":"")
             <<f.type<<" "<<f.name<<";\n\n";
        }

        // Count method-name multiplicity for the ordering table.
        std::map<std::string,int> nameCount;
        for(const auto& m:c.methods) nameCount[m.name]++;
        std::map<std::string,int> nameSeen;

        // Methods.
        for(const auto& m:c.methods){
            ++id;
            std::string sig=paramTypeList(m);
            bool ok=eligible(m);
            std::string h=ok?brand(doc,m.name,sig,date):std::string("n/a");
            int dupTotal=nameCount[m.name];
            int dupSlot=++nameSeen[m.name]; // 1-based order among same-name peers
            o<<"  < \u2234 origin(id="<<id<<", hash="<<(ok?h.substr(0,16):h)
             <<", doc=\""<<doc<<"\", member=\""<<m.name<<"\", sig=\"("<<sig<<")\"";
            if(dupTotal>1) o<<", slot="<<dupSlot<<"/"<<dupTotal;
            o<<", edited=\""<<date<<"\") >\n";
            // The full param list for the printed signature (names included).
            std::string params; bool first=true;
            for(const auto& p:m.params){ if(!first)params+=", "; first=false; params+=p.type+" "+p.name; }
            o<<"  "<<(m.isStatic?"static ":"")<<(m.isProtected?"protected ":"")
             <<m.retType<<" "<<m.name<<"("<<params<<") "<<defaultBody(m.retType)<<"\n\n";
        }

        // Ordering table for duplicated method names (the dispatch map): an
        // ordered list of the declaration-order slots for each duplicated name.
        bool anyDup=false; for(auto& kv:nameCount) if(kv.second>1){anyDup=true;break;}
        if(anyDup){
            o<<"  < ---- duplicate-dispatch ordering table ("<<c.name<<") ---- >\n";
            for(auto& kv:nameCount){
                if(kv.second<=1) continue;
                o<<"  < order[\""<<kv.first<<"\"] = [";
                for(int s=1;s<=kv.second;++s){ if(s>1)o<<", "; o<<"slot "<<s; }
                o<<"]  (forward probe from slot 1; busy -> next) >\n";
            }
            o<<"\n";
        }

        o<<"}\n\n";
    }

    o<<"< End originated document. Original compiled artifact is the runnable twin. >\n";
    if(!o){ std::cerr<<"originate: write failed for '"<<outPath<<"'\n"; return ""; }
    return outPath;
}

} // namespace sleela