parser.cpp
impl/frontend/parser.cpp · 1196 line(s) · c
// ===========================================================================
// parser.cpp -- Recursive-descent parser for the Java-like Sleela subset.
// ===========================================================================
#include "parser.h"
#include "language_handler.h"
#include "wide_integer.h"
#include "unsigned_integer.h"
#include <stdexcept>
#include <cctype>
namespace sleela {
// Parse a GC-hint aggressiveness level that is already clamped to a small band
// (0..1000000) at the call site, tolerating an absurdly long digit run without
// throwing std::out_of_range from std::stoll. Returns the clamp ceiling for any
// value that would overflow, which the caller clamps again.
static long long parseHintLevel(const std::string& s){
try{ return std::stoll(s); }
catch(const std::out_of_range&){ return 1000000; }
catch(const std::invalid_argument&){ return 0; }
}
const Token& Parser::peek(int off) const { size_t p=i_+(size_t)off; if(p>=toks_.size()) return toks_.back(); return toks_[p]; }
bool Parser::accept(Tok k){if(check(k)){i_++;return true;}return false;}
const Token& Parser::expect(Tok k,const char* what){if(!check(k)) error(std::string("expected ")+what+" but found '"+(cur().text.empty()?tokName(cur().kind):cur().text)+"'");return toks_[i_++];}
void Parser::error(const std::string& msg) const {const Token&t=cur();throw std::runtime_error("Syntax error (line "+std::to_string(t.line)+", col "+std::to_string(t.col)+"): "+msg);}
// Pre-pass: refuse source whose shape would exhaust the native stack. The parser,
// the semantic pass and the code generator all recurse over the syntax tree, so a
// few thousand nested parentheses (or a statement of tens of thousands of chained
// operators, which builds a left-deep tree) crashed the compiler with a segmentation
// fault instead of reporting an error. The limits are far above any real program.
// Returns the index of the first offending token, or toks.size() when the source is fine.
namespace {
constexpr int kMaxNesting = 1000; // levels of ( ), [ ] and { } at one point
constexpr int kMaxOperatorRun = 5000; // operators between two statement separators
constexpr int kMaxPrefixRun = 1000; // prefix operators in a row (- - - ... x)
constexpr int kMaxCastRun = 1000; // back-to-back casts, (int)(int)(int)...x
bool isChainOperator(Tok k){
switch(k){
case Tok::Plus: case Tok::Minus: case Tok::Star: case Tok::Slash: case Tok::Percent:
case Tok::ShiftLeft: case Tok::ShiftRight: case Tok::UnsignedShiftRight:
case Tok::EqEq: case Tok::NotEq: case Tok::Lt: case Tok::Le: case Tok::Gt: case Tok::Ge:
case Tok::AndAnd: case Tok::OrOr: case Tok::BitAnd: case Tok::BitOr: case Tok::BitXor:
case Tok::TripleColon: case Tok::Question: case Tok::Assign: case Tok::Dot: case Tok::Colon:
case Tok::PlusAssign: case Tok::MinusAssign: case Tok::StarAssign: case Tok::SlashAssign:
case Tok::PercentAssign: case Tok::AndAssign: case Tok::OrAssign: case Tok::XorAssign:
case Tok::ShlAssign: case Tok::ShrAssign: case Tok::UshrAssign:
return true;
default: return false;
}
}
bool isPrefixOperator(Tok k){
return k==Tok::Not||k==Tok::BitNot||k==Tok::Increment||k==Tok::Decrement||k==Tok::Minus||k==Tok::Plus;
}
size_t findStackHazard(const std::vector<Token>& toks,std::string& why){
int depth=0; long ops=0, prefix=0, casts=0;
for(size_t k=0;k<toks.size();++k){
const Tok t=toks[k].kind;
if(t==Tok::LParen||t==Tok::LBracket||t==Tok::LBrace){
if(++depth>kMaxNesting){ why="nesting is too deep (limit "+std::to_string(kMaxNesting)+" levels of (), [] and {})"; return k; }
} else if(t==Tok::RParen||t==Tok::RBracket||t==Tok::RBrace){
if(depth>0) --depth;
}
if(t==Tok::Semicolon||t==Tok::LBrace||t==Tok::RBrace||t==Tok::Comma){ ops=0; casts=0; }
else {
if(t==Tok::LParen && k>0 && toks[k-1].kind==Tok::RParen && ++casts>kMaxCastRun){
why="too many chained casts or calls in one statement (limit "+std::to_string(kMaxCastRun)+")"; return k;
}
if(isChainOperator(t) && ++ops>kMaxOperatorRun){
why="expression is too long (more than "+std::to_string(kMaxOperatorRun)+" operators in one statement)"; return k;
}
}
if(isPrefixOperator(t)){ if(++prefix>kMaxPrefixRun){ why="too many prefix operators in a row (limit "+std::to_string(kMaxPrefixRun)+")"; return k; } }
else prefix=0;
}
return toks.size();
}
} // namespace
// Pre-pass: record every `struct Name` so that Name is recognised as a type
// name throughout parsing, regardless of declaration order (C/C++-like: a
// struct type may be referenced before or after its definition here).
void Parser::collectStructNames(){for(size_t k=0;k+1<toks_.size();++k){if(toks_[k].kind==Tok::KwStruct&&toks_[k+1].kind==Tok::Ident)structNames_.insert(toks_[k+1].text);}}
unsigned Parser::parseJavaModifiers(){
unsigned m=0;
bool again=true;
while(again){again=false;switch(cur().kind){
case Tok::KwPublic:m|=JavaPublic;break; case Tok::KwProtected:m|=JavaProtected;break;
case Tok::KwPrivate:m|=JavaPrivate;break; case Tok::KwStatic:m|=JavaStatic;break;
case Tok::KwFinal:m|=JavaFinal;break; case Tok::KwAbstract:m|=JavaAbstract;break;
case Tok::KwNative:m|=JavaNative;break; case Tok::KwSynchronized:m|=JavaSynchronized;break;
case Tok::KwVolatile:m|=JavaVolatile;break; case Tok::KwTransient:m|=JavaTransient;break;
case Tok::KwStrictfp:m|=JavaStrictfp;break; case Tok::KwSealed:m|=JavaSealed;break;
case Tok::KwNonSealed:m|=JavaNonSealed;break; case Tok::KwConst:m|=JavaConst;break;
case Tok::KwUsualMem:m|=JavaMemUsual;break; case Tok::KwAccurateMem:m|=JavaMemAccurate;break;
case Tok::KwDefault:m|=JavaDefault;break;
default: continue;
} i_++; again=true;}
return m;
}
JavaTypeKind Parser::tokenTypeKind(Tok k) const {
if(k==Tok::KwInterface)return JavaTypeKind::Interface;
if(k==Tok::KwEnum)return JavaTypeKind::Enum;
if(k==Tok::KwRecord)return JavaTypeKind::Record;
return JavaTypeKind::Class;
}
std::string Parser::parseQualifiedName(){
std::string n=expect(Tok::Ident,"qualified name").text;
// Stop before "..." (varargs) so java.lang.Object... parses as a type.
while(check(Tok::Dot) && !(peek(1).kind==Tok::Dot)){
++i_;
// A segment of a qualified name may spell a SLeeLa keyword
// (java.lang.String, javax.print.Doc): accept any word token here.
const Token& seg=cur();
bool word=!seg.text.empty() && (std::isalpha(static_cast<unsigned char>(seg.text[0]))||seg.text[0]=='_');
if(seg.kind!=Tok::Ident && word){ n+="."+seg.text; ++i_; continue; }
n+="."+expect(Tok::Ident,"identifier after '.'").text;
}
return n;
}
// Nested-class name mangling (syntax 1.11). The source spells a nested class
// type with a dot ("Outer.Inner"), but the core VM reserves '.' for numeric
// literals and uses it in no identifier, so a dotted name must never reach the
// VM as a struct/function name. Every type name is normalised here by replacing
// '.' with "__", giving the identifier-safe internal name "Outer__Inner". The
// same transform is applied where nested classes are hoisted, so source
// references and the registered class name always agree.
std::string Parser::mangleTypeName(const std::string& t){
std::string out; out.reserve(t.size());
for(char ch:t){ if(ch=='.') out+="__"; else out.push_back(ch); }
return out;
}
std::vector<std::string> Parser::parseTypeList(Tok terminator){
std::vector<std::string> out;
if(check(terminator)) return out;
do { out.push_back(parseQualifiedName()); } while(accept(Tok::Comma));
return out;
}
std::vector<std::string> Parser::parseTypeParameters(){
std::vector<std::string> out; if(!accept(Tok::Lt)) return out;
do { std::string p=expect(Tok::Ident,"type parameter name").text;
if(accept(Tok::KwExtends)){ p += " extends "; p += parseGenericType(); while(accept(Tok::AndAnd)||accept(Tok::BitAnd)) p += " & " + parseGenericType(); }
out.push_back(p);
} while(accept(Tok::Comma));
splitAngleClosers();
expect(Tok::Gt,"'>'");
return out;
}
std::string Parser::parseGenericType(){
std::string t=parseQualifiedName();
if(accept(Tok::Lt)){ t += "<"; do {
if(accept(Tok::Question)){ t += "?"; if(accept(Tok::KwExtends)) t += " extends " + parseTypeArgument(); else if(accept(Tok::KwSuper)) t += " super " + parseTypeArgument(); }
else t += parseTypeArgument();
} while(accept(Tok::Comma));
// A nested type-argument list may close with '>>' or '>>>' (Java lexes them
// as shift operators); consume one '>' and leave the rest for the caller.
splitAngleClosers();
expect(Tok::Gt,"'>'"); t += ">"; }
return t;
}
// Java lexes '>>' / '>>>' as shift operators; in a type-argument list they
// close nested lists. Split the token into single '>' tokens (permanently, so
// a lookahead rewind re-reads the same tokens).
void Parser::splitAngleClosers(){
int n = check(Tok::ShiftRight) ? 2 : (check(Tok::UnsignedShiftRight) ? 3 : 0);
if(n==0) return;
Token gt=toks_[i_]; gt.kind=Tok::Gt; gt.text=">";
toks_[i_]=gt;
for(int k=1;k<n;++k) toks_.insert(toks_.begin()+static_cast<std::ptrdiff_t>(i_)+k, gt);
}
// One type argument: a reference type (possibly generic), a keyword type
// (String, int, ...), each optionally followed by array brackets.
std::string Parser::parseTypeArgument(){
std::string t;
if(check(Tok::Ident)) t=parseGenericType();
else if(isTypeStart()){ t=cur().text; ++i_; }
else t=parseGenericType();
while(check(Tok::LBracket) && peek(1).kind==Tok::RBracket){ i_+=2; t+="[]"; }
return t;
}
// Varargs (T... name) is the Java spelling of an array parameter.
bool Parser::acceptEllipsis(){
if(check(Tok::Dot) && peek(1).kind==Tok::Dot && peek(2).kind==Tok::Dot){ i_+=3; return true; }
return false;
}
// Signature types are erased to the VM types SLeeLa supports by whichever
// language handler claims them (language_handler.h); with none registered the
// declared spelling is kept. Array suffixes are preserved by the handler.
std::string Parser::eraseSignatureType(const std::string& source){
return lang::eraseSignatureType(source,typeVars_);
}
void Parser::parseThrows(std::vector<std::string>& out){
if(!accept(Tok::KwThrows)) return;
do { out.push_back(parseQualifiedName()); } while(accept(Tok::Comma));
}
annotation::Annotation Parser::parseAnnotation(annotation::UseSite site){
expect(Tok::At,"'@'");
// An annotation name lives in its own namespace after '@', so a word that is
// a reserved modifier keyword elsewhere is still a valid annotation name.
// @native in particular reuses the `native` modifier keyword (Tok::KwNative)
// as the ahead-of-time-native marker; accept it (and any single keyword
// token) as the annotation name rather than requiring a bare identifier.
std::string name;
if(check(Tok::KwNative)){ name="native"; ++i_; }
else name=parseQualifiedName();
std::string value;
bool marker=true;
if(accept(Tok::LParen)){
marker=false; int depth=1;
while(depth>0 && !check(Tok::Eof)){
if(check(Tok::LParen)){ value += "("; ++depth; ++i_; }
else if(check(Tok::RParen)){ --depth; ++i_; if(depth>0) value += ")"; }
else { if(!value.empty()) value += " "; value += cur().text; ++i_; }
}
if(depth!=0) error("unterminated annotation '"+name+"'");
}
return annotation::Annotation{name,value,site,marker};
}
std::vector<annotation::Annotation> Parser::parseAnnotations(annotation::UseSite site){
std::vector<annotation::Annotation> out;
while(check(Tok::At)) out.push_back(parseAnnotation(site));
return out;
}
std::vector<annotation::Annotation> Parser::parseTypeAnnotations(){
return parseAnnotations(annotation::UseSite::TypeUse);
}
// Resolve the loop-timing annotations into a per-iteration sleep in ms.
//
// @loopDelay(<N>) sleep N milliseconds per iteration
// @loopDelay(ms = <N>) sleep N milliseconds per iteration
// @loopDelay(seconds = <N>) sleep N seconds per iteration
// @loopBudget(seconds = <T>, iterations = <K>) spread K iterations over T
// seconds -> per-iteration sleep = T/K ms
// @loopBudget(ms = <T>, iterations = <K>) total T ms over K iterations
//
// The annotation argument text is captured by parseAnnotation as a loose,
// space-joined string; this reads unsigned integers keyed by the words
// "ms"/"milliseconds", "seconds", and "iterations" (a bare number defaults to
// milliseconds). Unknown annotations are ignored here (validated elsewhere).
long Parser::loopTimingMillis(const std::vector<annotation::Annotation>& anns){
long resultMs=0;
bool sawTiming=false;
for(const auto& a:anns){
if(a.name!="loopDelay" && a.name!="loopBudget") continue;
sawTiming=true;
// Pull "<word> <number>" pairs and standalone numbers from the value.
long ms=-1, seconds=-1, iters=-1, bareNum=-1;
const std::string& v=a.value;
size_t i=0;
std::string pendingKey;
while(i<v.size()){
unsigned char ch=(unsigned char)v[i];
if(std::isalpha(ch)){
size_t j=i; while(j<v.size() && std::isalpha((unsigned char)v[j])) ++j;
pendingKey=v.substr(i,j-i);
for(char& c:pendingKey) c=(char)std::tolower((unsigned char)c);
i=j;
} else if(std::isdigit(ch)){
size_t j=i; long num=0; while(j<v.size() && std::isdigit((unsigned char)v[j])){ num=num*10+(v[j]-'0'); ++j; }
if(pendingKey=="ms"||pendingKey=="millis"||pendingKey=="milliseconds") ms=num;
else if(pendingKey=="seconds"||pendingKey=="sec"||pendingKey=="s") seconds=num;
else if(pendingKey=="iterations"||pendingKey=="iters"||pendingKey=="count") iters=num;
else bareNum=num;
pendingKey.clear();
i=j;
} else { ++i; }
}
if(a.name=="loopDelay"){
long perIter=0;
if(ms>=0) perIter=ms;
else if(seconds>=0) perIter=seconds*1000;
else if(bareNum>=0) perIter=bareNum; // bare number defaults to ms
else error("@loopDelay requires a delay, e.g. @loopDelay(250) or @loopDelay(seconds = 2)");
resultMs+=perIter;
} else { // loopBudget
long totalMs=-1;
if(ms>=0) totalMs=ms;
else if(seconds>=0) totalMs=seconds*1000;
else if(bareNum>=0) totalMs=bareNum; // bare number defaults to total ms
if(totalMs<0||iters<=0)
error("@loopBudget requires a total time and a positive iteration count, e.g. @loopBudget(seconds = 10, iterations = 1000)");
resultMs+=totalMs/iters; // even per-iteration share
}
}
if(sawTiming && resultMs<0) resultMs=0;
return resultMs;
}
// Resolve a loop's leading @spill annotation into a LoopSpill.
//
// @spill a bare timer-start checkpoint
// (pause of 0 ms before iteration)
// @spill(ms = <N>) pause N ms once before iterating
// @spill(<N>) bare number defaults to ms
// @spill(seconds = <N>) pause N seconds once
// @spill(judges = <subject>) name the judge "of performs"
// @spill(witnesses = <subject>) name the witness "of performs"
// @spill(seconds = 1, judges = Panel, witnesses = AuditLog) all together
//
// A @spill "counts as a timer start itself": unlike @loopDelay/@loopBudget
// (which sleep every iteration), the spill pause fires ONCE before the loop's
// first iteration, so the loop can seemingly pause before it starts. The two
// optional subjects -- the judges and witnesses of the loop's performs -- are
// retained as loop metadata and are each single annotation tokens (values with
// embedded whitespace are collapsed, matching the loose annotation grammar).
//
// Only one @spill may appear on a loop, and each of judges/witnesses may be
// named at most once. The argument text is the same loose, space-joined string
// produced by parseAnnotation; this reads "<key> <value>" pairs plus a bare
// number (defaulting to ms), mirroring loopTimingMillis.
LoopSpill Parser::loopSpill(const std::vector<annotation::Annotation>& anns){
LoopSpill out;
bool sawSpill=false;
for(const auto& a:anns){
if(a.name!="spill") continue;
if(sawSpill) error("a loop may carry only one @spill annotation");
sawSpill=true; out.hasSpill=true;
long ms=-1, seconds=-1, bareNum=-1;
bool sawJudges=false, sawWitnesses=false;
const std::string& v=a.value;
size_t i=0; std::string pendingKey;
while(i<v.size()){
unsigned char ch=(unsigned char)v[i];
if(std::isspace(ch)){ ++i; continue; }
if(std::isdigit(ch)){
size_t j=i; long num=0; while(j<v.size() && std::isdigit((unsigned char)v[j])){ num=num*10+(v[j]-'0'); ++j; }
if(pendingKey=="ms"||pendingKey=="millis"||pendingKey=="milliseconds") ms=num;
else if(pendingKey=="seconds"||pendingKey=="sec"||pendingKey=="s") seconds=num;
else if(pendingKey.empty()) bareNum=num;
else error("@spill does not understand a number for '"+pendingKey+"'");
pendingKey.clear(); i=j; continue;
}
// Read a bareword token (identifier / collapsed subject value).
size_t j=i; while(j<v.size() && !std::isspace((unsigned char)v[j])) ++j;
std::string word=v.substr(i,j-i); i=j;
if(word=="="||word==",") continue; // separators between key/value pairs
std::string lw=word; for(char& c:lw) c=(char)std::tolower((unsigned char)c);
if(lw=="ms"||lw=="millis"||lw=="milliseconds"||lw=="seconds"||lw=="sec"||lw=="s"){ pendingKey=lw; continue; }
if(lw=="judges"||lw=="judge"){ pendingKey="judges"; continue; }
if(lw=="witnesses"||lw=="witness"){ pendingKey="witnesses"; continue; }
// Otherwise this word is a value for the pending subject key.
if(pendingKey=="judges"){
if(sawJudges) error("@spill names 'judges' more than once");
out.spillJudges=word; sawJudges=true; pendingKey.clear();
} else if(pendingKey=="witnesses"){
if(sawWitnesses) error("@spill names 'witnesses' more than once");
out.spillWitnesses=word; sawWitnesses=true; pendingKey.clear();
} else {
error("@spill does not understand '"+word+"'; expected ms/seconds, judges, or witnesses");
}
}
if(ms>=0) out.spillPauseMs=ms;
else if(seconds>=0) out.spillPauseMs=seconds*1000;
else if(bareNum>=0) out.spillPauseMs=bareNum; // bare number defaults to ms
else out.spillPauseMs=0; // marker spill: checkpoint, no sleep
}
return out;
}
Program Parser::parseProgram(){
{ std::string why; const size_t at=findStackHazard(toks_,why); if(at<toks_.size()){ i_=at; error(why); } }
collectStructNames(); Program p; bool contentStarted=false;
while(!check(Tok::Eof)){
if(check(Tok::At)){
auto anns=parseAnnotations(annotation::UseSite::Declaration);
if(check(Tok::KwClass)||check(Tok::KwInterface)||check(Tok::KwEnum)||check(Tok::KwRecord)){
contentStarted=true; unsigned mods=parseJavaModifiers(); p.classes.push_back(parseClass(mods,std::move(anns)));
} else {
if(contentStarted) error("declaration annotations must precede their declaration");
for(auto &a:anns) p.annotations.add(std::move(a));
}
} else if(accept(Tok::KwImport)){ contentStarted=true;
bool parsedDynamite=false;
if(check(Tok::Ident)&&cur().text=="dynamite"&&peek(1).kind==Tok::Ident&&peek(1).text=="connector"){
i_+=2; std::string first; std::string path; bool named=false;
if(check(Tok::Ident)&&peek(1).kind==Tok::Assign){ first=cur().text; i_+=2; named=true; }
while(!check(Tok::Semicolon)&&!check(Tok::Eof)){ path += cur().text; ++i_; }
expect(Tok::Semicolon,"';'");
if(path.empty()) error("Dynamite Connector import requires a source path");
p.dynamiteImports.push_back({named?first:"",path}); parsedDynamite=true;
} else if(check(Tok::DoubleColon)){
size_t save=i_; ++i_;
if(check(Tok::Ident)&&cur().text=="dynamite"){ ++i_;
if(check(Tok::DoubleColon)){ ++i_;
if(check(Tok::Ident)&&cur().text=="connector"){ ++i_;
if(check(Tok::DoubleColon)){ ++i_;
std::string reference;
if(check(Tok::Ident)&&peek(1).kind==Tok::DoubleColon){ reference=cur().text; i_+=2; }
std::string path;
while(!check(Tok::Semicolon)&&!check(Tok::Eof)){ path += cur().text; ++i_; }
expect(Tok::Semicolon,"';'");
if(path.empty()) error("Dynamite Connector import requires a source path");
p.dynamiteImports.push_back({reference,path}); parsedDynamite=true;
}
}
}
}
if(!parsedDynamite) i_=save;
}
if(!parsedDynamite && p.dynamiteImports.size()>1) {
// No-op: ordinary imports remain independent of Dynamite references.
}
if(!parsedDynamite && check(Tok::Ident)&&cur().text=="permissible"&&peek(1).kind==Tok::Ident&&peek(1).text=="connector") {
i_+=2; std::string first; std::string path; bool named=false;
if(check(Tok::Ident)&&peek(1).kind==Tok::Assign){first=cur().text;i_+=2;named=true;}
while(!check(Tok::Semicolon)&&!check(Tok::Eof)){path+=cur().text;++i_;}
expect(Tok::Semicolon,"';'"); if(path.empty()) error("Permissible Connector import requires a source path");
p.permissibleImports.push_back({named?first:"",path}); parsedDynamite=true;
} else if(!parsedDynamite && check(Tok::DoubleColon)) {
size_t save=i_; ++i_;
if(check(Tok::Ident)&&cur().text=="permissible"){++i_;
if(check(Tok::DoubleColon)){++i_;
if(check(Tok::Ident)&&cur().text=="connector"){++i_;
if(check(Tok::DoubleColon)){++i_; std::string reference;
if(check(Tok::Ident)&&peek(1).kind==Tok::DoubleColon){reference=cur().text;i_+=2;}
std::string path; while(!check(Tok::Semicolon)&&!check(Tok::Eof)){path+=cur().text;++i_;}
expect(Tok::Semicolon,"';'"); if(path.empty()) error("Permissible Connector import requires a source path");
p.permissibleImports.push_back({reference,path}); parsedDynamite=true;
}
}
}
}
if(!parsedDynamite)i_=save;
}
if(!parsedDynamite) {
std::string module=expect(Tok::Ident,"module name").text;
// Permit qualified library roots (for example
// gui.version-military) as well as simple native modules.
while(!check(Tok::Semicolon)&&!check(Tok::Eof)){
module += cur().text;
++i_;
}
expect(Tok::Semicolon,"';'");
p.imports.push_back(std::move(module));
}
}
else if(check(Tok::KwExtends)){ contentStarted=true; p.documentExtensions.push_back(parseDocumentExtension()); }
else if(check(Tok::KwStruct)){ contentStarted=true; p.structs.push_back(parseStruct()); }
else if(check(Tok::Ident)&&(cur().text=="author"||cur().text=="authorial")){
// Author marker (syntax 2.4). A single, modifier-less, type-less word
// at document scope -- a static class of the document itself -- that
// marks the document as handled by professional council and permits
// duplicate members (see SLEELA.syntax section 18). `author` and
// `authorial` are exact synonyms. A trailing ';' is optional; a
// repeat marker is harmless (the flag is already set). It is a
// contextual word, not a reserved keyword, so below 2.4 (or anywhere
// else) `author`/`authorial` remain ordinary identifiers.
++i_;
accept(Tok::Semicolon);
p.authorMarked=true;
}
else if(check(Tok::Ident)&&cur().text=="material"){
// Material marker (syntax 2.5). A single, modifier-less, type-less
// word at document scope that DECLARES the document material -- well
// considered, present to its author as its own Source (see
// SLEELA.syntax section 19). Declarative only: it changes nothing
// about parsing/typing/codegen. A trailing ';' is optional; a repeat
// marker is harmless. Like author/authorial it is contextual, not a
// reserved keyword, so `material` stays an ordinary identifier
// anywhere else (and in any document below 2.5).
++i_;
accept(Tok::Semicolon);
p.materialMarked=true;
}
else if(check(Tok::Ident)&&cur().text=="memory"){
// Memory marker (syntax 2.5). A single, modifier-less, type-less
// word at document scope that DECLARES the document a document of
// memory -- authored by and for the Graduates of Supply of the New
// York State Department of Commerce (section 20 of SLEELA.syntax).
// Declarative only: it changes nothing about parsing/typing/codegen.
// A trailing ';' is optional; a repeat marker is harmless. Like
// author/authorial and material it is contextual, not a reserved
// keyword, so `memory` stays an ordinary identifier anywhere else
// (and in any document below 2.5).
++i_;
accept(Tok::Semicolon);
p.memoryMarked=true;
}
else if(check(Tok::Ident)&&cur().text=="determine"){
// Determine marker (syntax 2.6). A single, modifier-less, type-less
// word at document scope that DECLARES the document a determine
// document (see SLEELA.syntax section 23). Declarative only: it
// changes nothing about parsing/typing/codegen. The ideal, as-is:
// the document is open to be processed to further by a doctor,
// physician, or ghost toward completion; the procurement of term is
// held ideal as real for the torturement (completion by legal hand)
// as required by further processor review; science practitioners
// should and could can use it. A trailing ';' is optional; a repeat
// marker is harmless. Like author/authorial, material, and memory it
// is contextual, not a reserved keyword, so `determine` stays an
// ordinary identifier anywhere else (and in any document below 2.6).
++i_;
accept(Tok::Semicolon);
p.determineMarked=true;
}
else if(check(Tok::Ident)&&cur().text=="object"){
// Object marker (syntax 2.6). A single, modifier-less, type-less
// word at document scope that DECLARES the document an object
// document -- a member of the Natural Process family of markers
// (author/authorial, material, memory, determine; see SLEELA.syntax
// section 24). It names the document as an Object: a settled thing
// standing in the catalogue of what is, to which its author and the
// field relate. Declarative only: it changes nothing about
// parsing/typing/codegen. A trailing ';' is optional; a repeat
// marker is harmless. Contextual, not a reserved keyword, so
// `object` stays an ordinary identifier anywhere else (and in any
// document below 2.6). Recognised only here, at top-level document
// scope before content begins, so a field access or a class member
// named `object` is unaffected.
++i_;
accept(Tok::Semicolon);
p.objectMarked=true;
}
else if(check(Tok::Ident)&&cur().text=="field"&&!contentStarted){
// Field marker (syntax 2.6). A single, modifier-less, type-less word
// at document scope that DECLARES the document a field document -- a
// member of the Natural Process family (author/authorial, material,
// memory, determine, object; see SLEELA.syntax section 24). It names
// the document as the Field: the ground of relation in which objects
// stand and move. Declarative only: it changes nothing about
// parsing/typing/codegen. A trailing ';' is optional; a repeat
// marker is harmless. Contextual, not a reserved keyword, and
// recognised ONLY at top-level document scope BEFORE any content has
// begun, so the ordinary `field-decl` grammar inside a class and
// every `.field` access remain exactly as before.
++i_;
accept(Tok::Semicolon);
p.fieldMarked=true;
}
else if(check(Tok::Ident)&&cur().text=="pure"){
// Pure marker (syntax 3.0). A single, modifier-less, type-less word
// at document scope that DECLARES the document pure -- steered by,
// and standing on, its OWN honesty: clean, unmixed, and true to
// itself (see SLEELA.syntax section 27). Declarative only: it
// changes nothing about parsing/typing/codegen. A trailing ';' is
// optional; a repeat marker is harmless. Like the other Preonem
// markers it is contextual, not a reserved keyword, so `pure` stays
// an ordinary identifier anywhere else (and in any document below
// 3.0). `pure` and `gasoline` mean nearly the same thing.
++i_;
accept(Tok::Semicolon);
p.pureMarked=true;
}
else if(check(Tok::Ident)&&cur().text=="gasoline"){
// Gasoline marker (syntax 3.0). The near-synonym of `pure`: the same
// claim of a document steered by its own honesty, in the sense of a
// refined, usable grade (see SLEELA.syntax section 27). Declarative
// only: it changes nothing about parsing/typing/codegen. A trailing
// ';' is optional; a repeat marker is harmless. Contextual, not a
// reserved keyword, so `gasoline` stays an ordinary identifier
// anywhere else (and in any document below 3.0).
++i_;
accept(Tok::Semicolon);
p.gasolineMarked=true;
}
else if(check(Tok::Ident)&&cur().text=="artifact"){
// Artifact marker (syntax 3.0). A single, modifier-less, type-less
// word at document scope that DECLARES the document an artifact --
// enacted, legislature-grade text, graded unto time and space (see
// SLEELA.syntax section 35). It states the document's standing: not
// loose prose but an enacted artifact of a body, binding for the
// moment and place it is read until superseded by a later enactment.
// Declarative only: it changes nothing about parsing/typing/codegen.
// A trailing ';' is optional; a repeat marker is harmless. Like the
// other Preonem markers it is contextual, not a reserved keyword, so
// `artifact` stays an ordinary identifier anywhere else (and in any
// document below 3.0).
++i_;
accept(Tok::Semicolon);
p.artifactMarked=true;
}
else if(check(Tok::Ident)&&!contentStarted&&lang::isDocumentMarker(cur().text)){
// A document marker claimed by a registered language handler
// (language_handler.h), e.g. the Java handler's `spark` (syntax 3.0,
// SLEELA.syntax section 43). Contextual: only before content begins,
// so the same word elsewhere is an ordinary identifier. ';' optional;
// a repeat marker is harmless. Declarative: no change to parsing,
// typing or codegen; the syntax-version gate is semantic analysis.
p.markers.insert(cur().text);
++i_;
accept(Tok::Semicolon);
}
else {
unsigned mods=parseJavaModifiers();
if(check(Tok::KwClass)||check(Tok::KwInterface)||check(Tok::KwEnum)||check(Tok::KwRecord)){
contentStarted=true; p.classes.push_back(parseClass(mods));
} else error("expected annotation, import, struct, or Java type declaration at top level");
}
}
if(p.classes.empty()) error("program contains no classes");
// Append nested classes (syntax 1.11) hoisted during parseClass to the flat
// Program.classes list. Each is already named "Outer__Inner" and flagged, so
// the semantic analyzer and compiler treat it as an ordinary class. The
// "rule of two" has already bounded lexical nesting to depth 2; here we
// enforce the per-document cap of 42 nested classes and record the count.
if(hoistedNested_.size()>42) error("a single Sleela document may contain at most 42 nested classes (found "+std::to_string(hoistedNested_.size())+")");
p.nestedClassCount=(int)hoistedNested_.size();
for(auto& h:hoistedNested_) p.classes.push_back(std::move(h));
for(const auto& u:uses31_) p.syntax31Uses.push_back(u);
return p;
}
StructDecl Parser::parseStruct(){expect(Tok::KwStruct,"'struct'");StructDecl s;s.name=expect(Tok::Ident,"struct name").text;expect(Tok::LBrace,"'{'");while(!check(Tok::RBrace)&&!check(Tok::Eof)){Field f;f.type=parseType();f.name=expect(Tok::Ident,"field name").text;expect(Tok::Semicolon,"';'");s.fields.push_back(std::move(f));}expect(Tok::RBrace,"'}'");return s;}
// Document extension (syntax 1.10):
// extends to <Target> <grouper> ;
// extends to { <Target> (, <Target>)* } <grouper> [<Server>] ;
// `to` and the grouper (linear | group | services) are ordinary identifiers,
// not keywords, so they stay free elsewhere. Recognition is anchored on the
// top-level `extends` token (which is only valid inside a class otherwise).
DocumentExtension Parser::parseDocumentExtension(){
expect(Tok::KwExtends,"'extends'");
if(!(check(Tok::Ident)&&cur().text=="to")) error("document extension expects 'extends to ...'");
++i_; // consume 'to'
DocumentExtension ext;
if(accept(Tok::LBrace)){
if(!check(Tok::RBrace)){
do{ ext.targets.push_back(parseQualifiedName()); }while(accept(Tok::Comma));
}
expect(Tok::RBrace,"'}'");
} else {
ext.targets.push_back(parseQualifiedName());
}
if(ext.targets.empty()) error("document extension names no target document");
std::string g=expect(Tok::Ident,"a grouper (linear | group | services)").text;
if(g=="linear") ext.grouper=Grouper::Linear;
else if(g=="group") ext.grouper=Grouper::Group;
else if(g=="services") ext.grouper=Grouper::Services;
else error("unknown grouper '"+g+"' (expected linear | group | services)");
if(ext.grouper==Grouper::Services){
if(check(Tok::Ident)) ext.server=parseQualifiedName();
else error("the 'services' grouper requires a Server-of-Services name");
}
expect(Tok::Semicolon,"';'");
return ext;
}
ClassDecl Parser::parseClass(unsigned classModifiers,std::vector<annotation::Annotation> annotations,int depth){
const bool savedLineage=usesLineage_; usesLineage_=false;
Tok kind=cur().kind; ClassDecl c; c.java.kind=tokenTypeKind(kind); c.java.modifiers=classModifiers; c.java.annotations=std::move(annotations);
if(kind!=Tok::KwClass&&kind!=Tok::KwInterface&&kind!=Tok::KwEnum&&kind!=Tok::KwRecord) error("expected Java type declaration");
i_++; if(check(Tok::KwStringT)){ c.name=cur().text; ++i_; } else c.name=expect(Tok::Ident,"type name").text; c.java.qualifiedName=c.name; c.java.typeParameters=parseTypeParameters();
{ std::vector<std::string> vars; for(const auto& tp:c.java.typeParameters) vars.push_back(tp.substr(0,tp.find(' '))); typeVars_.push_back(vars); }
if(accept(Tok::KwExtends)){
c.java.superclass=parseQualifiedName();
// SLEELA.syntax 43.8: an interface may extend several interfaces
// (JLS 9.1.3). The first stays the parent edge it always was; the
// others join the interface's supertype list, which the subtype rule,
// method lookup and the runtime type table follow.
if(kind==Tok::KwInterface && check(Tok::Comma)){
++i_;
for(const auto& t:parseTypeList(Tok::LBrace)) c.java.interfaces.push_back(t);
}
}
if(accept(Tok::KwImplements)){ for(const auto& t:parseTypeList(Tok::LBrace)) c.java.interfaces.push_back(t); }
expect(Tok::LBrace,"'{'");
const bool savedInterface=inInterface_; inInterface_=(kind==Tok::KwInterface);
while(!check(Tok::RBrace)&&!check(Tok::Eof)){
auto annotations=parseAnnotations(annotation::UseSite::Declaration);
unsigned mods=parseJavaModifiers();
// Nested class (syntax 1.11): a `class` keyword inside a class body
// declares a nested class. The "rule of two" caps lexical nesting at
// depth 2 (the enclosing class + one nested class). Deeper nesting is
// rejected with guidance to use a reference instead: a field typed as
// the deeper class, declared at top level, held inside the parent.
if(check(Tok::KwClass)||check(Tok::KwInterface)||check(Tok::KwEnum)||check(Tok::KwRecord)){
if(depth>=2) error("nested classes follow the rule of two: a document nests at most two deep (the enclosing class and one nested class). To go deeper, declare the deeper class at top level and hold a reference to it (a field of that type) inside this nested class, rather than nesting a third level inline");
ClassDecl nested=parseClass(mods,std::move(annotations),depth+1);
nested.isNested=true; nested.enclosingName=c.name;
// Internal name uses the identifier-safe mangling "Outer__Inner";
// source type references ("Outer.Inner") are mangled the same way in
// parseType / the `new` path, so the names always agree.
nested.name=c.name+"__"+nested.name; nested.java.qualifiedName=nested.name;
hoistedNested_.push_back(std::move(nested));
continue;
}
if(check(Tok::Lt)){
// Generic method (Java): <T> T[] toArray(T[] a)
bool stat=(mods&JavaStatic)!=0, prot=(mods&JavaProtected)!=0;
c.methods.push_back(parseMethod(stat,prot,mods,std::move(annotations)));
continue;
}
if(!isTypeStart() && !(check(Tok::Ident)&&peek(1).kind==Tok::LParen)) error("expected a type/member declaration");
if(check(Tok::Ident)&&peek(1).kind==Tok::LParen&&cur().text==c.name){
Method m; m.isStatic=false; m.isProtected=(mods&JavaProtected)!=0; m.java.modifiers=mods; m.java.constructor=true; m.java.annotations=std::move(annotations);
m.retType=c.name; m.name=expect(Tok::Ident,"constructor name").text; expect(Tok::LParen,"'('");
if(!check(Tok::RParen)){do{Param p; p.annotations=parseAnnotations(annotation::UseSite::Parameter); p.type=parseType(&p.typeAnnotations); if(acceptEllipsis()) p.type+="[]"; p.name=expect(Tok::Ident,"parameter name").text; m.params.push_back(std::move(p));}while(accept(Tok::Comma));}
expect(Tok::RParen,"')'"); parseThrows(m.java.thrownTypes); m.body=parseBlock(); c.methods.push_back(std::move(m)); continue;
}
if(!isTypeStart()) error("expected a field or method type");
size_t save=i_; parseType(); if(!check(Tok::Ident)){i_=save; error("expected a field or method name");}
Tok after=peek(1).kind; i_=save;
bool stat=(mods&JavaStatic)!=0, prot=(mods&JavaProtected)!=0;
if(after==Tok::LParen)c.methods.push_back(parseMethod(stat,prot,mods,std::move(annotations)));
else c.fields.push_back(parseField(stat,prot,mods,std::move(annotations)));
}
expect(Tok::RBrace,"'}'"); typeVars_.pop_back(); inInterface_=savedInterface;
if(usesLineage_){
// Implied lineage fields (SLEELA.syntax section 42): static, so they add no layout slots.
const std::pair<const char*,LineageExpr::Kind> lf[3]={{"__lin_parent",LineageExpr::InitParent},{"__lin_child",LineageExpr::InitChild},{"__lin_root",LineageExpr::InitRoot}};
{ Field f; f.type="Any"; f.name="__lin_security"; f.isStatic=true; f.init=std::make_unique<LineageExpr>(LineageExpr::Boot); c.fields.push_back(std::move(f)); }
for(const auto& p:lf){Field f;f.type="String";f.name=p.first;f.isStatic=true;f.init=std::make_unique<LineageExpr>(p.second);c.fields.push_back(std::move(f));}
}
usesLineage_=savedLineage; return c;
}
Field Parser::parseField(bool isStatic,bool isProtected,unsigned modifiers,std::vector<annotation::Annotation> annotations){Field f;f.isStatic=isStatic;f.isProtected=isProtected;f.java.modifiers=modifiers;f.annotations=std::move(annotations);f.type=parseType(&f.typeAnnotations);f.name=expect(Tok::Ident,"field name").text;if(accept(Tok::Assign))f.init=parseInitializer(f.type);expect(Tok::Semicolon,"';'");return f;}
// A type is one of the scalar keywords, or an identifier naming a declared struct.
bool Parser::isTypeStart()const{Tok k=cur().kind;if(k==Tok::KwVoid||k==Tok::KwIntT||k==Tok::KwLongT||k==Tok::KwInt64T||k==Tok::KwInt128T||k==Tok::KwDoubleT||k==Tok::KwBoolT||k==Tok::KwStringT)return true;return k==Tok::Ident;}
std::string Parser::parseType(std::vector<annotation::Annotation>* typeAnnotations){
if(typeAnnotations){auto a=parseTypeAnnotations(); typeAnnotations->insert(typeAnnotations->end(),a.begin(),a.end());}
if(!isTypeStart()) error("expected a type");
std::string t;
if(check(Tok::Ident)){ std::string g=parseGenericType(); std::string e=eraseSignatureType(g); t = (e==g) ? mangleTypeName(g) : e; } else { t=cur().text; i_++; }
while(accept(Tok::LBracket)){ if(typeAnnotations){auto a=parseTypeAnnotations(); typeAnnotations->insert(typeAnnotations->end(),a.begin(),a.end());} expect(Tok::RBracket,"']'");t+="[]"; }
return t;
}
Method Parser::parseMethod(bool isStatic,bool isProtected,unsigned modifiers,std::vector<annotation::Annotation> annotations){
Method m;m.isStatic=isStatic;m.isProtected=isProtected;m.java.modifiers=modifiers;m.java.annotations=std::move(annotations);
m.java.typeParameters=parseTypeParameters();
{ std::vector<std::string> vars; for(const auto& tp:m.java.typeParameters) vars.push_back(tp.substr(0,tp.find(' '))); typeVars_.push_back(vars); }
m.retType=parseType(&m.java.typeAnnotations);m.name=expect(Tok::Ident,"method name").text;expect(Tok::LParen,"'('");
if(!check(Tok::RParen)){do{Param p;p.annotations=parseAnnotations(annotation::UseSite::Parameter);p.type=parseType(&p.typeAnnotations);if(acceptEllipsis())p.type+="[]";p.name=expect(Tok::Ident,"parameter name").text;m.params.push_back(std::move(p));}while(accept(Tok::Comma));}
expect(Tok::RParen,"')'");parseThrows(m.java.thrownTypes);
// Bodiless abstract / interface method (SLEELA.syntax 43.6): `T name(...);`
// gets a synthesized body returning T's default value. A call reaches the
// concrete override through virtual dispatch.
if(check(Tok::Semicolon) && ((modifiers&JavaAbstract)!=0 || (inInterface_ && (modifiers&(JavaStatic|JavaDefault))==0))){
++i_; m.java.modifiers|=JavaAbstract;
auto b=std::make_unique<Block>();
const std::string& r=m.retType;
if(r!="void"){
auto ret=std::make_unique<ReturnStmt>();
if(r=="int"||r=="long"||r=="short"||r=="byte"||r=="char"||r=="int64"
||SignedWideInteger::isValidTypeName(r)||UnsignedWideInteger::isValidTypeName(r)||UnsignedInteger::isValidTypeName(r)) ret->value=std::make_unique<IntLit>(0);
else if(r=="double"||r=="float") ret->value=std::make_unique<DoubleLit>(0.0);
else if(r=="boolean"||r=="bool") ret->value=std::make_unique<BoolLit>(false);
else ret->value=std::make_unique<NullLit>();
b->stmts.push_back(std::move(ret));
}
m.body=std::move(b); typeVars_.pop_back(); return m;
}
m.body=parseBlock();typeVars_.pop_back();return m;
}
// Parse one "simple statement" without its trailing ';': a local variable
// declaration (`Type name [= expr]`), an assignment to a variable or struct
// field, or a bare expression statement. Used by parseStatement() and by the
// for-statement init/update clauses.
StmtP Parser::parseSimpleStatement(){
// GC hint, ran:: qualified form (syntax 1.9): `x = ran::gc [N];` or
// `x = ran::mem [N];`. The explicit, system-scoped spelling: `ran::` names
// the System meaning so the compiler decides the author's intent instantly
// and the words gc/mem stay usable as identifiers. Shape: target `=` `ran`
// `::` (gc|mem) [int] `;`.
if(cur().kind==Tok::Ident && peek(1).kind==Tok::Assign
&& peek(2).kind==Tok::Ident && peek(2).text=="ran"
&& peek(3).kind==Tok::DoubleColon
&& peek(4).kind==Tok::Ident && isGcHintWord(peek(4).text)){
bool bareHint = (peek(5).kind==Tok::Semicolon);
bool levelHint = (peek(5).kind==Tok::Int && peek(6).kind==Tok::Semicolon);
if(bareHint || levelHint){
auto h=std::make_unique<GcHintStmt>();
h->ranQualified=true;
h->target=cur().text; // the value being released
i_+=2; // consume target and '='
i_+=2; // consume `ran` and `::`
h->spelling=cur().text; // "gc" or "mem"
i_++; // consume the GC-hint word
if(levelHint){
long long n=parseHintLevel(cur().text); i_++;
if(n>1000000) n=1000000;
h->aggressiveness=(int)n;
} else {
h->aggressiveness=50;
}
return h;
}
}
// GC hint (syntax 1.9): `x = gc [N];` or `x = mem [N];`. Recognised
// positionally before ordinary assignment: target identifier, `=`, then the
// contextual word `gc`/`mem` as the WHOLE right-hand side, optionally with a
// 0..100 aggressiveness int, then `;`. The lookahead requires the terminator
// to immediately follow the word (or the word + one int literal), so a real
// expression RHS that merely begins with a variable named `gc`/`mem`
// (e.g. `x = gc + 1;` or `x = gc.field;`) is NOT taken as a hint.
if(cur().kind==Tok::Ident && peek(1).kind==Tok::Assign
&& peek(2).kind==Tok::Ident && isGcHintWord(peek(2).text)){
bool bareHint = (peek(3).kind==Tok::Semicolon);
bool levelHint = (peek(3).kind==Tok::Int && peek(4).kind==Tok::Semicolon);
if(bareHint || levelHint){
auto h=std::make_unique<GcHintStmt>();
h->target=cur().text; // the value being released
i_+=2; // consume target and '='
h->spelling=cur().text; // "gc" or "mem"
i_++; // consume the GC-hint word
if(levelHint){
// Preserve the raw level so the semantic analyzer can reject an
// out-of-range band (0..100) rather than silently clamping it.
long long n=parseHintLevel(cur().text); i_++; // consume the int level
if(n>1000000) n=1000000; // guard only absurd input for int fit
h->aggressiveness=(int)n;
} else {
// Bare `x = gc;` defaults to a modest short-term cleanup.
h->aggressiveness=50;
}
return h; // the terminating ';' is consumed by parseStatement()
}
}
// Declaration: `Type name [= expr]`. A struct type name is a valid Type.
// Disambiguate from `structVar.field = ...` / `structVar = ...` by requiring
// the token after a bare-identifier "type" to be another identifier. A
// qualified (dotted) type name — e.g. a nested class `Outer.Inner name`
// (syntax 1.11) — is detected by scanning `Ident (Dot Ident)*` and checking
// the token immediately after that run is another identifier (the var name).
bool localDecl=false;
if(isTypeStart()){
if(cur().kind!=Tok::Ident){ localDecl=true; } // scalar keyword type
else if(peek(1).kind==Tok::Ident){ localDecl=true; } // bare `Type name`
else if(peek(1).kind==Tok::Dot){ // dotted `A.B[.C] name`
size_t k=1; // peek offset: at first Dot
while(peek((int)k).kind==Tok::Dot&&peek((int)(k+1)).kind==Tok::Ident) k+=2;
if(peek((int)k).kind==Tok::Ident) localDecl=true; // run followed by the var name
}
else if(peek(1).kind==Tok::LBracket){ // array of an Ident type: `T[] name` / `T[][] name`
// Distinguish a declaration `U256[] xs` / `int256[][] m` from an
// indexing expression `arr[i] = ...`: a declaration's brackets are
// all empty (`[` immediately followed by `]`) and the run is
// followed by the variable name. An indexing expression has a
// subscript between the brackets, so this never misfires on it.
size_t k=1; // peek offset: at first '['
while(peek((int)k).kind==Tok::LBracket&&peek((int)(k+1)).kind==Tok::RBracket) k+=2;
if(k>1 && peek((int)k).kind==Tok::Ident) localDecl=true; // one+ empty `[]` then the var name
}
}
if(localDecl){auto d=std::make_unique<VarDecl>();d->type=parseType();d->name=expect(Tok::Ident,"variable name").text;if(accept(Tok::Assign))d->init=parseInitializer(d->type);return d;}
// Otherwise parse an expression; if `=` follows, it is an assignment whose
// target must be an lvalue (a plain name or a struct member access).
if(check(Tok::KwSuper)&&peek(1).kind==Tok::LParen){
// super("constructor") goes to the backmost class (SLEELA.syntax section 42.5):
// it records the root of the lineage in this class's implied root link.
// Java constructor invocation (SLEELA.syntax 43.6): any other argument list
// ALSO invokes the base-class constructor with those arguments; the exact
// single literal "constructor" stays lineage-only (42.5).
i_+=2; std::vector<ExprP> args; if(!check(Tok::RParen)){do{args.push_back(parseExpr());}while(accept(Tok::Comma));} expect(Tok::RParen,"')'");
usesLineage_=true; auto a=std::make_unique<Assign>(); a->name="__lin_root"; a->value=std::make_unique<LineageExpr>(LineageExpr::Parents,1000000);
const StrLit* only = args.size()==1 ? dynamic_cast<const StrLit*>(args[0].get()) : nullptr;
if(only && only->value=="constructor") return a;
auto call=std::make_unique<MethodCall>(std::make_unique<SuperExpr>(),"super"); call->args=std::move(args); call->superConstructor=true;
auto b=std::make_unique<Block>(); b->stmts.push_back(std::move(a)); b->stmts.push_back(std::make_unique<ExprStmt>(std::move(call))); return b;
}
if(check(Tok::KwThis)&&peek(1).kind==Tok::LParen){
// this(args): delegate to another constructor of the same class (43.6).
i_+=2; std::vector<ExprP> args; if(!check(Tok::RParen)){do{args.push_back(parseExpr());}while(accept(Tok::Comma));} expect(Tok::RParen,"')'");
auto call=std::make_unique<MethodCall>(std::make_unique<ThisExpr>(),"this"); call->args=std::move(args); call->thisConstructor=true;
return std::make_unique<ExprStmt>(std::move(call));
}
ExprP lhs=parseExpr();
if(check(Tok::Arrow)){
// value -> Sleela.home.parent / child / root : the lineage set operator (left to right).
i_++; ExprP target=parseExpr(); auto* tv=dynamic_cast<VarExpr*>(target.get());
if(!tv||(tv->name!="__lin_parent"&&tv->name!="__lin_child"&&tv->name!="__lin_root")) error("'->' sets only Sleela.home.parent, Sleela.home.child or Sleela.home.root");
auto a=std::make_unique<Assign>(); a->name=tv->name;
// A bare capitalised name on the left is a class name: the link holds that name.
if(auto lv=dynamic_cast<VarExpr*>(lhs.get()); lv && !lv->name.empty() && std::isupper((unsigned char)lv->name[0])) a->value=std::make_unique<StrLit>(lv->name); else a->value=std::move(lhs);
return a;
}
if(check(Tok::Assign)){
i_++;
if(auto v=dynamic_cast<VarExpr*>(lhs.get())){auto a=std::make_unique<Assign>();a->name=v->name;a->value=parseExpr();return a;}
if(auto m=dynamic_cast<MemberAccess*>(lhs.get())){auto fa=std::make_unique<FieldAssign>();fa->base=std::move(m->base);fa->field=m->field;fa->value=parseExpr();return fa;}
error("assignment target must be a variable or a struct field");
}
auto e=std::make_unique<ExprStmt>();e->expr=std::move(lhs);return e;
}
ExprP Parser::parseExpr(){return parseAssignment();}
ExprP Parser::parseAssignment(){
ExprP e=parseGuideChain();
if(check(Tok::Assign)||check(Tok::PlusAssign)||check(Tok::MinusAssign)||check(Tok::StarAssign)||check(Tok::SlashAssign)||check(Tok::PercentAssign)||check(Tok::AndAssign)||check(Tok::OrAssign)||check(Tok::XorAssign)||check(Tok::ShlAssign)||check(Tok::ShrAssign)||check(Tok::UshrAssign)){
std::string op=cur().text; i_++; return std::make_unique<AssignmentExpr>(op,std::move(e),parseAssignment());
}
return e;
}
// Guide chain (syntax 2.3): `new T(...) :: Guide :: Guide ...`.
// Sits just below assignment, above `:::`. It only engages when the parsed head
// is a constructor call (NewExpr) AND the next tokens are `:: <Ident>`, so it
// never shadows the three existing `::` uses -- method references (obj::method),
// the `ran::` GC-hint scope, and qualified `::dynamite`/`::permissible` imports --
// all of which are consumed earlier, inside parsePrimary/parsePostfix or at the
// top level, on a non-NewExpr head. A trailing `::` after `new T()` is not eaten
// by parsePostfix, so it reaches this level cleanly.
ExprP Parser::parseGuideChain(){
ExprP e=parseStructOffload();
if(dynamic_cast<NewExpr*>(e.get())
&& check(Tok::DoubleColon) && peek(1).kind==Tok::Ident){
auto gc=std::make_unique<GuideChainExpr>(std::move(e));
while(check(Tok::DoubleColon) && peek(1).kind==Tok::Ident){
++i_; // consume '::'
gc->guides.push_back(cur().text); ++i_; // consume the Guide name
}
return gc;
}
return e;
}
// Structural-offload send: `source ::: receiver(args)`. The `:::` operator tells
// the VM to perform a structured, element-by-element transfer of the left
// operand's data into the right-hand receiver (framing done by the interpreter,
// not a source for-loop). Low precedence, left-associative, so it composes:
// a ::: b(n) ::: c(m) == (a ::: b(n)) ::: c(m).
ExprP Parser::parseStructOffload(){
ExprP e=parseConditional();
while(accept(Tok::TripleColon)){ e=std::make_unique<Binary>(":::",std::move(e),parseConditional()); }
return e;
}
ExprP Parser::parseConditional(){
ExprP e=parseOr();
if(accept(Tok::Question)){ExprP t=parseExpr();expect(Tok::Colon,"':'");return std::make_unique<ConditionalExpr>(std::move(e),std::move(t),parseConditional());}
return e;
}
ExprP Parser::parseOr(){ExprP e=parseAnd();while(accept(Tok::OrOr))e=std::make_unique<Binary>("||",std::move(e),parseAnd());return e;}
ExprP Parser::parseAnd(){ExprP e=parseBitOr();while(accept(Tok::AndAnd))e=std::make_unique<Binary>("&&",std::move(e),parseBitOr());return e;}
ExprP Parser::parseBitOr(){ExprP e=parseBitXor();while(accept(Tok::BitOr))e=std::make_unique<Binary>("|",std::move(e),parseBitXor());return e;}
ExprP Parser::parseBitXor(){ExprP e=parseBitAnd();while(accept(Tok::BitXor))e=std::make_unique<Binary>("^",std::move(e),parseBitAnd());return e;}
ExprP Parser::parseBitAnd(){ExprP e=parseEquality();while(accept(Tok::BitAnd))e=std::make_unique<Binary>("&",std::move(e),parseEquality());return e;}
ExprP Parser::parseEquality(){ExprP e=parseComparison();for(;;){if(accept(Tok::EqEq))e=std::make_unique<Binary>("==",std::move(e),parseComparison());else if(accept(Tok::NotEq))e=std::make_unique<Binary>("!=",std::move(e),parseComparison());else break;}return e;}
ExprP Parser::parseComparison(){
ExprP e=parseShift();
for(;;){
if(accept(Tok::Lt))e=std::make_unique<Binary>("<",std::move(e),parseShift());
else if(accept(Tok::Le))e=std::make_unique<Binary>("<=",std::move(e),parseShift());
else if(accept(Tok::Gt))e=std::make_unique<Binary>(">",std::move(e),parseShift());
else if(accept(Tok::Ge))e=std::make_unique<Binary>(">=",std::move(e),parseShift());
else if(accept(Tok::KwInstanceof)){std::string type=parseType();e=std::make_unique<InstanceOfExpr>(std::move(e),type);}
else break;
}
return e;
}
ExprP Parser::parseShift(){ExprP e=parseAdditive();for(;;){if(accept(Tok::ShiftLeft))e=std::make_unique<Binary>("<<",std::move(e),parseAdditive());else if(accept(Tok::ShiftRight))e=std::make_unique<Binary>(">>",std::move(e),parseAdditive());else if(accept(Tok::UnsignedShiftRight))e=std::make_unique<Binary>(">>>",std::move(e),parseAdditive());else break;}return e;}
ExprP Parser::parseAdditive(){ExprP e=parseMultiplicative();for(;;){if(accept(Tok::Plus))e=std::make_unique<Binary>("+",std::move(e),parseMultiplicative());else if(accept(Tok::Minus))e=std::make_unique<Binary>("-",std::move(e),parseMultiplicative());else break;}return e;}
ExprP Parser::parseMultiplicative(){ExprP e=parseUnary();for(;;){if(accept(Tok::Star))e=std::make_unique<Binary>("*",std::move(e),parseUnary());else if(accept(Tok::Slash))e=std::make_unique<Binary>("/",std::move(e),parseUnary());else if(accept(Tok::Percent))e=std::make_unique<Binary>("%",std::move(e),parseUnary());else break;}return e;}
ExprP Parser::parseUnary(){
if(accept(Tok::Minus))return std::make_unique<Unary>("-",parseUnary());
if(accept(Tok::Plus))return std::make_unique<Unary>("+",parseUnary());
if(accept(Tok::Not))return std::make_unique<Unary>("!",parseUnary());
if(accept(Tok::BitNot))return std::make_unique<Unary>("~",parseUnary());
if(accept(Tok::Increment))return std::make_unique<Unary>("++",parseUnary());
if(accept(Tok::Decrement))return std::make_unique<Unary>("--",parseUnary());
return parsePrimary();
}
// Syntax 3.1 array initializer: `{a, b, c}` for an array type "T[]". Nested
// braces build the elements of an array-of-arrays. Trailing comma allowed.
ExprP Parser::parseArrayLiteral(const std::string& arrayType){
if(arrayType.size()<2||arrayType.compare(arrayType.size()-2,2,"[]")!=0)
error("an array initializer '{...}' needs an array type, but the declared type is '"+arrayType+"'");
uses31_.insert("array initializer");
const std::string elemType=arrayType.substr(0,arrayType.size()-2);
expect(Tok::LBrace,"'{'");
auto n=std::make_unique<NewExpr>(arrayType);
n->hasInit=true;
while(!check(Tok::RBrace)){
if(check(Tok::Eof))error("unterminated array initializer");
if(check(Tok::LBrace))n->init.push_back(parseArrayLiteral(elemType));
else n->init.push_back(parseExpr());
if(!accept(Tok::Comma))break;
}
expect(Tok::RBrace,"'}'");
return n;
}
ExprP Parser::parseInitializer(const std::string& declType){
if(check(Tok::LBrace))return parseArrayLiteral(declType);
return parseExpr();
}
ExprP Parser::parsePrimary(){
const Token&t=cur();
switch(t.kind){
case Tok::Int:{
// Capture position before advancing so an overflow/format failure is
// reported as a located "Syntax error (line,col)" naming the literal,
// not an uncaught std::stoll exception whose what() is just "stoll".
int ln=t.line,cl=t.col;const std::string nt=t.text;i_++;long long iv;
try{
if(nt.size()>2&&nt[0]=='0'&&(nt[1]=='b'||nt[1]=='B'))iv=std::stoll(nt.substr(2),nullptr,2);
else iv=std::stoll(nt,nullptr,0);
}catch(const std::out_of_range&){throw std::runtime_error("Syntax error (line "+std::to_string(ln)+", col "+std::to_string(cl)+"): integer literal '"+nt+"' is out of range for a 64-bit integer");}
catch(const std::invalid_argument&){throw std::runtime_error("Syntax error (line "+std::to_string(ln)+", col "+std::to_string(cl)+"): malformed integer literal '"+nt+"'");}
return parsePostfix(std::make_unique<IntLit>(iv));
}
case Tok::Char:{
// Syntax 3.1: 'x' is the integer code of the character.
uses31_.insert("character literal");
long long cv=std::stoll(t.text);i_++;
auto lit=std::make_unique<IntLit>(cv); lit->isChar=true;
return parsePostfix(std::move(lit));
}
case Tok::Double:{
int ln=t.line,cl=t.col;const std::string nt=t.text;i_++;double dv;
try{dv=std::stod(nt);}
catch(const std::out_of_range&){throw std::runtime_error("Syntax error (line "+std::to_string(ln)+", col "+std::to_string(cl)+"): floating-point literal '"+nt+"' is out of range");}
catch(const std::invalid_argument&){throw std::runtime_error("Syntax error (line "+std::to_string(ln)+", col "+std::to_string(cl)+"): malformed floating-point literal '"+nt+"'");}
return parsePostfix(std::make_unique<DoubleLit>(dv));
}
case Tok::Str:i_++;return parsePostfix(std::make_unique<StrLit>(t.text));
case Tok::KwTrue:i_++;return parsePostfix(std::make_unique<BoolLit>(true));
case Tok::KwFalse:i_++;return parsePostfix(std::make_unique<BoolLit>(false));
case Tok::KwNull:i_++;return parsePostfix(std::make_unique<NullLit>());
case Tok::KwSuper:i_++;return parsePostfix(std::make_unique<SuperExpr>());
case Tok::KwThis:i_++;return parsePostfix(std::make_unique<ThisExpr>());
case Tok::LParen:{
i_++;
// Java cast disambiguation for a simple/qualified type: (Type) expression.
if(check(Tok::Ident)||check(Tok::KwIntT)||check(Tok::KwLongT)||check(Tok::KwInt64T)||check(Tok::KwInt128T)||check(Tok::KwDoubleT)||check(Tok::KwBoolT)||check(Tok::KwStringT)){
size_t save=i_; std::string type;
try { type=parseType(); if(check(Tok::RParen)){i_++; return std::make_unique<CastExpr>(type,parseUnary());} }
catch(const std::exception&) {}
i_=save;
}
ExprP e=parseExpr();expect(Tok::RParen,"')'");return parsePostfix(std::move(e));
}
case Tok::KwNew:{
i_++;
// Accept both class names (qualified) and the scalar keyword types
// (int/double/boolean/String/void) as the element type, so
// `new int[n]` and `new String[n]` parse like `new Point()`.
std::string type;
if(check(Tok::Ident)) type=mangleTypeName(parseGenericType());
else if(check(Tok::KwIntT)||check(Tok::KwLongT)||check(Tok::KwInt64T)||check(Tok::KwInt128T)||check(Tok::KwDoubleT)||check(Tok::KwBoolT)||check(Tok::KwStringT)||check(Tok::KwVoid)){ type=cur().text; i_++; }
else { error("expected a type after 'new'"); }
auto n=std::make_unique<NewExpr>(type);
if(accept(Tok::LBracket)){
if(check(Tok::RBracket)){
// Syntax 3.1: new T[]{a, b, c}; syntax 3.1 also new T[][]{{..},{..}} (any rank)
i_++;
std::string arrType=n->typeName+"[]";
while(check(Tok::LBracket)&&peek(1).kind==Tok::RBracket){ i_+=2; arrType+="[]"; uses31_.insert("multi-dimensional array creation"); }
if(!check(Tok::LBrace))error("expected '{' after 'new "+n->typeName+"[]' (an array creation needs a size or an initializer)");
return parsePostfix(parseArrayLiteral(arrType));
}
n->typeName += "[]"; n->args.push_back(parseExpr()); expect(Tok::RBracket,"']'");
// Syntax 3.1: further dimensions `new T[a][b]...`; trailing empty `[]` are unsized
// (their elements start null): `new T[a][]`. A sized dimension may not follow an unsized one.
bool sawUnsized=false;
while(check(Tok::LBracket)){
i_++;
if(check(Tok::RBracket)){ i_++; sawUnsized=true; n->typeName += "[]"; }
else {
if(sawUnsized) error("array dimension expression after an empty '[]' in 'new "+n->typeName+"'");
n->args.push_back(parseExpr()); expect(Tok::RBracket,"']'"); n->typeName += "[]";
}
uses31_.insert("multi-dimensional array creation");
}
if(n->args.size()>8) error("array creation with more than 8 sized dimensions");
return parsePostfix(std::move(n));
}
expect(Tok::LParen,"'('");if(!check(Tok::RParen)){do{n->args.push_back(parseExpr());}while(accept(Tok::Comma));}expect(Tok::RParen,"')'");
return parsePostfix(std::move(n));
}
case Tok::Ident:{
// `ran::<word>` -- the System / already-Ran-in-RAM reference, used as a
// value (e.g. `let b = ran::mem;`). Recognised only when the identifier
// is exactly `ran` and is immediately followed by `::` and a word, so a
// variable named `ran` and ordinary `base::method` references are
// unaffected. The system word is validated in semantic analysis.
if(t.text=="ran" && peek(1).kind==Tok::DoubleColon && peek(2).kind==Tok::Ident){
i_+=2; // consume `ran` and `::`
std::string word=cur().text; i_++; // consume the system word
return parsePostfix(std::make_unique<RanRefExpr>(word));
}
if(t.text=="Sleela" && peek(1).kind==Tok::Dot && peek(2).kind==Tok::Ident){
i_+=2; std::string w=cur().text; i_++;
usesLineage_=true;
if(w=="VM"||w=="System"||w=="OS") return parsePostfix(std::make_unique<LineageExpr>(LineageExpr::Vm));
if(w!="home") error("'Sleela."+w+"' is not defined; expected Sleela.home, Sleela.VM, Sleela.System or Sleela.OS");
expect(Tok::Dot,"'.' after Sleela.home"); std::string m=expect(Tok::Ident,"parent, child, root or parents after Sleela.home.").text;
if(m=="parent") return parsePostfix(std::make_unique<VarExpr>("__lin_parent"));
if(m=="child") return parsePostfix(std::make_unique<VarExpr>("__lin_child"));
if(m=="root") return parsePostfix(std::make_unique<VarExpr>("__lin_root"));
if(m=="security") return parsePostfix(std::make_unique<VarExpr>("__lin_security"));
if(m=="parents"){
expect(Tok::LParen,"'(' after parents"); if(!check(Tok::Str)) error("Sleela.home.parents takes a string of dashes or dots, for example \"---\" or \"...\"");
std::string d=cur().text; i_++; expect(Tok::RParen,"')'");
for(char ch:d) if(ch!='-'&&ch!='.') error("Sleela.home.parents takes only dashes or dots; each - or . is one level up");
return parsePostfix(std::make_unique<LineageExpr>(LineageExpr::Parents,(int)d.size()));
}
error("Sleela.home."+m+" is not defined; expected parent, child, root or parents");
}
std::string name=t.text;i_++;
ExprP base=std::make_unique<VarExpr>(name);
while(accept(Tok::Dot)){
std::string part=expect(Tok::Ident,"identifier after '.'").text;
if(check(Tok::DoubleColon)){i_++;base=std::make_unique<MethodReferenceExpr>(std::move(base),part);continue;}
if(check(Tok::LParen)){
i_++;auto c=std::make_unique<MethodCall>(std::move(base),part);
if(!check(Tok::RParen)){do{c->args.push_back(parseExpr());}while(accept(Tok::Comma));}
expect(Tok::RParen,"')'");base=std::move(c);
}else base=std::make_unique<MemberAccess>(std::move(base),part);
}
if(accept(Tok::LParen)){
auto c=std::make_unique<Call>(name);
if(!check(Tok::RParen)){do{c->args.push_back(parseExpr());}while(accept(Tok::Comma));}
expect(Tok::RParen,"')'");base=std::move(c);
}
if(accept(Tok::DoubleColon)){
std::string member=expect(Tok::Ident,"method name after '::'").text;
base=std::make_unique<MethodReferenceExpr>(std::move(base),member);
}
// A call result may be followed by member access or a method call
// (`word().trim()`); parsePostfix consumes the rest. (A former lookahead
// here used accept(), which ate the '.' whenever its condition failed.)
return parsePostfix(std::move(base));
}
default:error(std::string("unexpected token '")+(t.text.empty()?tokName(t.kind):t.text)+"' in expression");
}
}
ExprP Parser::parsePostfix(ExprP base){
for(;;){
if(accept(Tok::LBracket)){ExprP idx=parseExpr();expect(Tok::RBracket,"']'");base=std::make_unique<ArrayAccess>(std::move(base),std::move(idx));continue;}
if(accept(Tok::Increment)){base=std::make_unique<Unary>("post++",std::move(base));continue;}
if(accept(Tok::Decrement)){base=std::make_unique<Unary>("post--",std::move(base));continue;}
if(!check(Tok::Dot)||peek(1).kind!=Tok::Ident)break;
i_++;std::string member=expect(Tok::Ident,"member name after '.'").text;
if(accept(Tok::LParen)){
auto mc=std::make_unique<MethodCall>(std::move(base),member);
if(!check(Tok::RParen)){do{mc->args.push_back(parseExpr());}while(accept(Tok::Comma));}
expect(Tok::RParen,"')'");base=std::move(mc);
}else if(accept(Tok::DoubleColon)){
base=std::make_unique<MethodReferenceExpr>(std::move(base),member);
}else base=std::make_unique<MemberAccess>(std::move(base),member);
}
return base;
}
std::unique_ptr<Block> Parser::parseBlock(){expect(Tok::LBrace,"'{'");auto b=std::make_unique<Block>();while(!check(Tok::RBrace)&&!check(Tok::Eof))b->stmts.push_back(parseStatement());expect(Tok::RBrace,"'}'");return b;}
StmtP Parser::parseIf(){expect(Tok::KwIf,"'if'");expect(Tok::LParen,"'('");auto s=std::make_unique<IfStmt>();s->cond=parseExpr();expect(Tok::RParen,"')'");s->thenS=parseStatement();if(accept(Tok::KwElse))s->elseS=parseStatement();return s;}
StmtP Parser::parseWhile(){expect(Tok::KwWhile,"'while'");expect(Tok::LParen,"'('");auto s=std::make_unique<WhileStmt>();s->cond=parseExpr();expect(Tok::RParen,"')'");s->body=parseStatement();return s;}
StmtP Parser::parseDo(){expect(Tok::KwDo,"'do'");auto s=std::make_unique<DoStmt>();s->body=parseStatement();expect(Tok::KwWhile,"'while'");expect(Tok::LParen,"'('");s->cond=parseExpr();expect(Tok::RParen,"')'");expect(Tok::Semicolon,"';'");return s;}
StmtP Parser::parseFor(){expect(Tok::KwFor,"'for'");expect(Tok::LParen,"'('");
{ // Enhanced for (43.6): `for ([final] T v : expr) body`.
const size_t save=i_;
if(check(Tok::KwFinal)) ++i_;
if(isTypeStart()){
bool each=false; std::string t;
try{ t=parseType(); each=check(Tok::Ident)&&peek(1).kind==Tok::Colon; }catch(...){ each=false; }
if(each){
auto e=std::make_unique<ForEachStmt>(); e->type=t; e->name=expect(Tok::Ident,"loop variable name").text; expect(Tok::Colon,"':'");
e->iterable=parseExpr(); expect(Tok::RParen,"')'"); e->body=parseStatement(); return e;
}
}
i_=save;
}
auto s=std::make_unique<ForStmt>();if(!check(Tok::Semicolon))s->init=parseSimpleStatement();expect(Tok::Semicolon,"';'");if(!check(Tok::Semicolon))s->cond=parseExpr();expect(Tok::Semicolon,"';'");if(!check(Tok::Semicolon)&&!check(Tok::RParen))s->update=std::make_unique<ExprStmt>(parseExpr());if(accept(Tok::Semicolon)){if(check(Tok::Semicolon)||check(Tok::RParen))error("four-term for loop requires a thread-stability Boolean expression");s->threadStable=parseExpr();if(accept(Tok::Semicolon)){if(check(Tok::RParen))error("five-term for loop requires a VM heap-health Boolean expression");s->heapHealthy=parseExpr();}}expect(Tok::RParen,"')'");s->body=parseStatement();return s;}
StmtP Parser::parseSynchronized(){expect(Tok::KwSynchronized,"'synchronized'");expect(Tok::LParen,"'('");auto s=std::make_unique<SynchronizedStmt>();s->monitor=parseExpr();expect(Tok::RParen,"')'");s->body=parseBlock();return s;}
StmtP Parser::parseTry(){expect(Tok::KwTry,"'try'");auto s=std::make_unique<TryStmt>();s->body=parseBlock();while(accept(Tok::KwCatch)){expect(Tok::LParen,"'('");CatchClause c; if(check(Tok::KwFinal))++i_; c.types.push_back(parseQualifiedName()); while(accept(Tok::BitOr)) c.types.push_back(parseQualifiedName()); for(size_t k=0;k<c.types.size();++k){ if(k) c.type+="|"; c.type+=c.types[k]; } c.variable=expect(Tok::Ident,"exception variable").text;expect(Tok::RParen,"')'");c.body=parseBlock();s->catches.push_back(std::move(c));}if(accept(Tok::KwFinally))s->finallyBlock=parseBlock();if(s->catches.empty()&&!s->finallyBlock)error("try requires catch or finally");return s;}
StmtP Parser::parseSwitch(){expect(Tok::KwSwitch,"'switch'");expect(Tok::LParen,"'('");auto s=std::make_unique<SwitchStmt>();s->selector=parseExpr();expect(Tok::RParen,"')'");expect(Tok::LBrace,"'{'");while(!check(Tok::RBrace)&&!check(Tok::Eof)){SwitchCase sc;if(accept(Tok::KwDefault)){sc.isDefault=true;expect(Tok::Colon,"':'");}else{expect(Tok::KwCase,"'case'");sc.labels.push_back(parseExpr());while(accept(Tok::Comma))sc.labels.push_back(parseExpr());expect(Tok::Colon,"':'");}while(!check(Tok::KwCase)&&!check(Tok::KwDefault)&&!check(Tok::RBrace)&&!check(Tok::Eof))sc.statements.push_back(parseStatement());s->cases.push_back(std::move(sc));}expect(Tok::RBrace,"'}'");return s;}
// Statements nest through their bodies and through `else` (an else-if chain is one level per link), also
// without braces, so the bracket check cannot see them. Each level costs several native stack frames.
static const int kMaxStatementDepth = 3000;
StmtP Parser::parseStatement(){
if(stmtDepth_>=kMaxStatementDepth) error("statements are nested too deeply (limit "+std::to_string(kMaxStatementDepth)+", counting each else-if)");
struct Level{ int& d; explicit Level(int& x):d(x){++d;} ~Level(){--d;} } level(stmtDepth_);
return parseStatementImpl();
}
StmtP Parser::parseStatementImpl(){
// A statement may carry leading annotations. The statement-level annotations
// are the loop-timing ones (@loopDelay / @loopBudget), which set a loop's
// per-iteration sleep, and @spill, which marks the loop entry as a timer-start
// checkpoint (a one-shot pause before iterating) and may name the judges and
// witnesses of the loop's performs. All must precede a for/while/do loop.
if(check(Tok::At)){
auto anns=parseAnnotations(annotation::UseSite::LocalVariable);
long ms=loopTimingMillis(anns);
LoopSpill spill=loopSpill(anns);
StmtP loop;
if(check(Tok::KwWhile)) loop=parseWhile();
else if(check(Tok::KwFor)) loop=parseFor();
else if(check(Tok::KwDo)) loop=parseDo();
else error("a loop annotation (@loopDelay / @loopBudget / @spill) must precede a 'for', 'while', or 'do' loop");
if(auto w=dynamic_cast<WhileStmt*>(loop.get())){ w->loopSleepMs=ms; w->spill=spill; }
else if(auto f=dynamic_cast<ForStmt*>(loop.get())){ f->loopSleepMs=ms; f->spill=spill; }
else if(auto d=dynamic_cast<DoStmt*>(loop.get())){ d->loopSleepMs=ms; d->spill=spill; }
else if(dynamic_cast<ForEachStmt*>(loop.get())) error("loop annotations (@loopDelay / @loopBudget / @spill) are not supported on an enhanced for");
return loop;
}
if(check(Tok::LBrace))return parseBlock();
if(check(Tok::KwIf))return parseIf();
if(check(Tok::KwWhile))return parseWhile();
if(check(Tok::KwDo))return parseDo();
if(check(Tok::KwFor))return parseFor();
if(check(Tok::KwSwitch))return parseSwitch();
if(check(Tok::KwSynchronized))return parseSynchronized();
if(check(Tok::KwTry))return parseTry();
if(check(Tok::KwBreak)){i_++;auto s=std::make_unique<BreakStmt>();if(check(Tok::Ident)){s->label=cur().text;i_++;uses31_.insert("labeled break");}expect(Tok::Semicolon,"';'");return s;}
if(check(Tok::KwContinue)){i_++;auto s=std::make_unique<ContinueStmt>();if(check(Tok::Ident)){s->label=cur().text;i_++;uses31_.insert("labeled continue");}expect(Tok::Semicolon,"';'");return s;}
// Syntax 3.1: `label: statement`.
if(check(Tok::Ident)&&peek(1).kind==Tok::Colon){
auto s=std::make_unique<LabeledStmt>();s->label=cur().text;i_+=2;uses31_.insert("labeled statement");
s->body=parseStatement();return s;
}
if(check(Tok::KwReturn)){i_++;auto s=std::make_unique<ReturnStmt>();if(!check(Tok::Semicolon))s->value=parseExpr();expect(Tok::Semicolon,"';'");return s;}
if(check(Tok::KwThrow)){i_++;auto s=std::make_unique<ThrowStmt>();s->value=parseExpr();expect(Tok::Semicolon,"';'");return s;}
if(check(Tok::KwAssert)){i_++;auto s=std::make_unique<AssertStmt>();s->cond=parseExpr();if(accept(Tok::Colon))s->message=parseExpr();expect(Tok::Semicolon,"';'");return s;}
if(check(Tok::KwYield)){i_++;auto s=std::make_unique<YieldStmt>();s->value=parseExpr();expect(Tok::Semicolon,"';'");return s;}
if(accept(Tok::KwPrint)){auto s=std::make_unique<PrintStmt>();expect(Tok::LParen,"'('");s->expr=parseExpr();expect(Tok::RParen,"')'");expect(Tok::Semicolon,"';'");return s;}
// Local declaration, assignment, or bare expression statement.
StmtP s=parseSimpleStatement();expect(Tok::Semicolon,"';'");return s;
}
} // namespace sleela