/******************************************************************************/ /* */ /* RVM.Compiler.cls - Compile a Rexx program (its AST) to R-code */ /* ============================================================= */ /* */ /* R-code is the instruction set of the RVM, a small virtual machine for */ /* Rexx, in the spirit of the P-code of Pascal-P4: the compiler lives here, */ /* on the Tree API AST, and emits R-code; any RVM loads it and runs it. */ /* See doc/03-compiler.md for the design. */ /* */ /* The compiler is a visitor: every AST class it handles gets a floating */ /* method "Class::rcompile", installed by Load.Parser.Module like the */ /* parser's own extension methods. Expressions leave their value */ /* on the stack; instructions leave the stack as they found it. */ /* */ /* The unit being built (RVM.Unit) holds the code, the constant pool, the */ /* variable names (one numbering for the whole program: a slot per name, */ /* stems included as "A."), the clause table, the labels of the program and */ /* the jump labels of the compiler, which are resolved when the unit is */ /* finished. */ /* */ /* This file is part of the RVM, the Rexx Virtual Machine */ /* [See https://rexx.epbcn.com/rexx-parser/] */ /* */ /* Copyright (c) 2026 Josep Maria Blasco */ /* */ /* License: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0) */ /* */ /******************************************************************************/ Call "modules/Load.Parser.Module.rex" -- LOOP is laid out as DO is (Loop.Instruction has the same parts). .Loop.Instruction~define( "RCOMPILE", .Do.Instruction~method( "RCOMPILE" ) ) ::Requires "parser.cls" ::Requires "modules/rvm/RVM.BaseContext.cls" /******************************************************************************/ /* Shared helpers */ /******************************************************************************/ -- Compile a node. A node the compiler does not know compiles to an error -- raised when (if) it runs. ::Routine Gen Public Use Strict Arg node, unit If node~hasMethod( "RCOMPILE" ) Then Do node~rcompile( unit ) Return End If node~isA( .Rexx.Clause ) Then unit~clause( node ) unit~emit( "ERR", "93.900", - unit~const( "RVM:" node~class~id "is not supported yet" ) ) -- Compile an expression that may be an Expression.List: an empty one is "", -- a single one is itself. ::Routine CompileExpr Public Use Strict Arg expression, unit If expression == .Nil Then Do unit~emit( "PUSHQ", unit~const( "" ) ) Return End If expression~isA( .Expression.List ) Then Do If expression~isEmpty Then Do unit~emit( "PUSHQ", unit~const( "" ) ) Return End If expression~arg() == 1 Then Do Call Gen expression~arg(1), unit Return End -- An array term: its items, traced as arguments are (MKARR). n = expression~arg() Do k = 1 To n If expression~arg( k, "E" ) Then Call Gen expression~arg(k), unit Else unit~emit( "PUSHNONE" ) unit~emit( "TRARG" ) End unit~emit( "MKARR", n ) Return End Call Gen expression, unit -- A condition (IF, WHEN): jump to 'falseRef' when it is false. Its value -- is traced as a result; a list is "1" when all its expressions are true (and -- stops at the first one that is not), each value traced as a result first. -- Interactive trace pauses once the value is known (BPAUSE: "=" goes back to -- 'again', the clause). ::Routine CompileCondition Public Use Strict Arg exprList, unit, falseRef, again, keyword If exprList~arg() == 1 Then Do Call Gen exprList~arg(1), unit unit~emit( "RES" ) unit~emit( "BPAUSE", again, 1, 0 ) unit~emit( "JF", falseRef, keyword ) Return End failRef = unit~newRef okRef = unit~newRef Loop k = 1 To exprList~arg() Call Gen exprList~arg(k), unit unit~emit( "RES" ) unit~emit( "JF", failRef, "LIST" ) End unit~emit( "TRES", unit~const( "1" ) ) unit~emit( "BPAUSE", again, 0, 0 ) unit~emit( "JMP", okRef ) unit~place( failRef ) unit~emit( "TRES", unit~const( "0" ) ) unit~emit( "BPAUSE", again, 0, 0 ) unit~emit( "JMP", falseRef ) unit~place( okRef ) -- The pieces of the tail of a compound variable, pushed on the stack: the -- value of each variable (untraced, no NOVALUE), and the constants, joined. -- Returns how many pieces were pushed. ::Routine CompileTail Public Use Strict Arg term, unit, tailOp = "TAILV" parts = term~parts n = 0 pending = .Nil -- constant text not pushed yet Do i = 2 To parts~items p = parts[i] Select When p < .EL.TAIL_SEPARATOR Then text = "." When p < .ALL.SIMPLE_VARIABLES Then text = .Nil Otherwise text = p~value -- number / literal End If text \== .Nil Then Do If pending == .Nil Then pending = text Else pending = pending || text Iterate End If pending \== .Nil Then Do unit~emit( "PUSHQ", unit~const( pending ) ) n += 1 pending = .Nil End unit~emit( tailOp, unit~slot( p~value ) ) n += 1 End If pending \== .Nil Then Do unit~emit( "PUSHQ", unit~const( pending ) ) n += 1 End Return n -- The name of a compound variable as traced: X.I, not X.1. ::Routine CompoundTraceName Public Use Strict Arg term parts = term~parts name = parts[1]~value Do i = 2 To parts~items If parts[i] < .EL.TAIL_SEPARATOR Then name ||= "." Else name ||= parts[i]~value End Return name -- Push the arguments of a call (a hole is PUSHNONE). Returns their count. ::Routine CompileArgs Public Use Strict Arg arguments, unit If arguments == .Nil Then Return 0 positional = arguments~positionalArguments If positional~isEmpty Then Return 0 Loop k = 1 To positional~last If positional~hasIndex(k) Then Call Gen positional[k], unit Else unit~emit( "PUSHNONE" ) unit~emit( "TRARG" ) End Return positional~last -- The source line of the first element with a given value in an instruction -- (the CALL or SIGNAL keyword), for SIGL. ::Routine KeywordLine Public Use Strict Arg instruction, keyword el = instruction~begin Loop While el \== .Nil If el~value == keyword Then Return ElementLine( el ) el = el~next End Return ElementLine( instruction~begin ) -- The source line of an element: the line of the INTERPRET for an element -- of INTERPRET data. ::Routine ElementLine Use Strict Arg el fragment = .RVM.Fragments~of( el ) If fragment \== .Nil Then Return fragment~line Return el~from~word( 1 ) -- The line SIGL gets for a function call: the first line of its clause. ::Routine TermLine Public Use Strict Arg term el = term~begin Loop While el~prev \== .Nil, el~prev \< .EL.END_OF_CLAUSE el = el~prev End skip = .EL.END_OF_CLAUSE || .ALL.WHITESPACE_LIKE || .ALL.COMMENTS Loop While el \== .Nil, el < skip el = el~next End If el == .Nil Then el = term~begin Return ElementLine( el ) /******************************************************************************/ /* EXPRESSIONS */ /******************************************************************************/ ::Method "SubExpression::rcompile" Use Strict Arg unit Call CompileExpr self~subexpression, unit -- (a, b, ...): an array term. ::Method "Array.Term::rcompile" Use Strict Arg unit Call CompileExpr self~expression_list, unit ::Method "Literal.String.Term::rcompile" Use Strict Arg unit unit~emit( "PUSHC", unit~const( self~theString~value ) ) ::Method "Symbol.Term::rcompile" Use Strict Arg unit element = self~value Select When element < .ALL.NUMBERS Then unit~emit( "PUSHN", unit~const( element~source ) ) When element < .ALL.SIMPLE_VARIABLES Then unit~emit( "LOADV", unit~slot( element~value ) ) When element < .EL.ENVIRONMENT_SYMBOL Then unit~emit( "ENV", unit~const( element~value ) ) When element < .EL.SYMBOL_LITERAL Then unit~emit( "PUSHC", unit~const( element~value ) ) -- A lone period: a constant symbol (ooRexx: SAY "a". says "a."). When element < .EL.PERIOD Then unit~emit( "PUSHC", unit~const( "." ) ) Otherwise unit~emit( "ERR", "93.900", - unit~const( "RVM: unsupported symbol category" element~category ) ) End -- A variable reference term, >x or and >< are all NE). -- (The not signs "AA"x and "AC"x are a backslash, also in the trace -- and as a message: \=, \==, \<...) op = Translate( args[i]~value, "\\", "AAAC"x ) Select Case op When "=" Then code = "EQ" When "\=", "<>", "><" Then code = "NE" When "<" Then code = "LT" When ">" Then code = "GT" When "<=", "\>" Then code = "LE" When ">=", "\<" Then code = "GE" When "==" Then code = "SEQ" When "\==" Then code = "SNE" When "<<" Then code = "SLT" When ">>" Then code = "SGT" When "<<=", "\>>" Then code = "SLE" When ">>=", "\<<" Then code = "SGE" Otherwise Raise Syntax 93.900 Additional( "RVM: comparison operator" C2X( op ) ) End unit~emit( code, unit~const( op ) ) End ::Method "Addition.Expression::rcompile" Use Strict Arg unit args = self~args Call Gen args[1], unit Loop i = 2 By 2 To args~items Call Gen args[i+1], unit If args[i]~value == "+" Then unit~emit( "ADD" ) Else unit~emit( "SUB" ) End ::Method "Multiplication.Expression::rcompile" Use Strict Arg unit args = self~args Call Gen args[1], unit Loop i = 2 By 2 To args~items Call Gen args[i+1], unit Select Case args[i]~value When "*" Then unit~emit( "MUL" ) When "/" Then unit~emit( "DIV" ) When "%" Then unit~emit( "IDIV" ) When "//" Then unit~emit( "REM" ) End End ::Method "Power.Expression::rcompile" Use Strict Arg unit args = self~args Call Gen args[1], unit Loop i = 2 By 2 To args~items Call Gen args[i+1], unit unit~emit( "POW" ) End ::Method "Prefix.Expression::rcompile" Use Strict Arg unit Call Gen self~term, unit prefixes = self~prefixes Loop i = prefixes~items To 1 By -1 Select Case prefixes[i]~source When "+" Then unit~emit( "PLUS" ) When "-" Then unit~emit( "NEG" ) When "\", "AA"x, "AC"x Then unit~emit( "NOT" ) End End ::Method "And.Expression::rcompile" Use Strict Arg unit args = self~args Call Gen args[1], unit Loop i = 2 By 2 To args~items Call Gen args[i+1], unit unit~emit( "AND" ) End ::Method "Or.Expression::rcompile" Use Strict Arg unit args = self~args Call Gen args[1], unit Loop i = 2 By 2 To args~items Call Gen args[i+1], unit If args[i]~value == "|" Then unit~emit( "OR" ) Else unit~emit( "XOR" ) End -- name(args): an internal function (FUNCI), a built-in one (FUNCB), or one -- we do not have (FUNCX: 43.1 once the arguments are evaluated). ::Method "Function.Call.Term::rcompile" Use Strict Arg unit name = self~name~value n = CompileArgs( self~argumentList, unit ) kind = self~name~subCategory Select When kind == .INTERNAL.FUNCTION.NAME Then unit~emit( "FUNCI", unit~const( name ), n, TermLine( self ) ) When kind == .BUILTIN.FUNCTION.NAME Then unit~emit( "FUNCB", unit~const( name ), n ) Otherwise unit~emit( "FUNCX", unit~const( name ), n ) End -- A namespace-qualified function call, ns:name(args): a public routine of -- the package tagged ns (FUNCNS). ::Method "NameSpace.Qualified.Function.Call::rcompile" Use Strict Arg unit If self~trailingBlock \== .Nil Then Do Call Unsupported unit, "trailing blocks" Return End n = CompileArgs( self~arguments, unit ) unit~emit( "FUNCNS", unit~const( Upper( self~nameSpace~value ) ), - unit~const( Upper( self~name~value ) ), n ) -- A namespace-qualified class name, ns:name: a public class of the package -- tagged ns (NSCLASS). ::Method "NameSpace.Qualified.ClassName::rcompile" Use Strict Arg unit unit~emit( "NSCLASS", unit~const( Upper( self~nameSpace~value ) ), - unit~const( Upper( self~className~value ) ) ) /******************************************************************************/ /* MESSAGES */ /******************************************************************************/ -- receiver~name(args), receiver~~name(args): SEND (CASC for a cascade). ::Method "Message.Term::rcompile" Use Strict Arg unit Call CompileMessage self, unit, "SEND", "CASC" -- receiver[args]: the message "[]". ::Method "Indexed.Or.Invoked.Term::rcompile" Use Strict Arg unit Call CompileMessage self, unit, "SEND", "SEND" -- A message term (Message.Term or Indexed.Or.Invoked.Term): the receiver, -- the arguments, and the instruction 'op' ('cascade' for "~~"), with 'extra' -- operands. Returns .False when it cannot be compiled (an error is emitted). ::Routine CompileMessage Public Use Strict Arg term, unit, op, cascade, extra = "" scope = 0 If term~isA( .Indexed.Or.Invoked.Term ) Then Do If term~bracket \< .EL.LEFT_BRACKET Then Return Unsupported( unit, "invoked terms (a routine or method object)" ) name = "[]" End Else Do If term~messageName == .Nil Then Return Unsupported( unit, "messages without a name" ) If term~scope \== .Nil Then scope = 1 -- Upper case, a string too (the parser has made it a TAKEN_CONSTANT). name = Upper( term~messageName~value ) If term~operator~value == "~~" Then op = cascade End If term~trailingBlock \== .Nil Then Return Unsupported( unit, "trailing blocks" ) Call Gen term~term, unit If scope Then Do Call CompileScope term~scope, unit unit~emit( "SCOPE" ) End n = CompileArgs( term~arguments, unit ) If extra == "" Then unit~emit( op, unit~const( name ), n, scope ) Else unit~emit( op, unit~const( name ), n, extra, scope ) Return .True -- The scope of ~name:scope, a variable or an environment symbol (ooRexx's -- addText): its value, evaluated after the receiver and before the -- arguments. SCOPE follows it, but in the target of PARSE or USE ARG. ::Routine CompileScope Use Strict Arg element, unit Select When element < .EL.ENVIRONMENT_SYMBOL Then unit~emit( "ENV", unit~const( element~value ) ) When element < .ALL.SIMPLE_VARIABLES Then unit~emit( "LOADV", unit~slot( element~value ) ) When element < .ALL.STEM_VARIABLES Then unit~emit( "LOADS", unit~slot( element~value ) ) Otherwise Do name = element~value Parse Var name stem "." tail n = ElementTail( tail, unit ) unit~emit( "LOADC", unit~slot( stem"." ), n, unit~const( name ) ) End End ::Routine Unsupported Use Strict Arg unit, what unit~emit( "ERR", "93.900", unit~const( "RVM:" what "are not supported yet" ) ) Return .False -- The single expression of an Expression.List, or the expression itself. ::Routine SingleExpression Use Strict Arg expression If expression~isA( .Expression.List ), expression~arg() == 1 Then Return expression~arg(1) Return expression -- A message as an instruction: RESULT gets its result (or the receiver, for -- a cascade), or is dropped when there is none. ::Method "Message.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) term = SingleExpression( self~expression ) If term~isA( .Message.Term ) | term~isA( .Indexed.Or.Invoked.Term ) Then Do If CompileMessage( term, unit, "SENDI", "SENDI", "N" ) Then Do ins = unit~code~lastItem If term~isA( .Message.Term ), term~operator~value == "~~" Then ins[4] = "C" End End Else Call Unsupported unit, "message instructions of this form" unit~emit( "PAUSE", a ) -- receiver~name(args) = value, receiver[args] = value: the message "NAME=" -- or "[]=", with the value as its first argument (evaluated after the -- receiver, before the other arguments, as ooRexx does). -- A compound one (receiver~name(args) op= e, ooRexx's -- messageAssignmentOpNew): the value is receiver~name(args) op e, on a copy -- of the message term, so its receiver and its arguments are evaluated -- twice, as ooRexx does. ::Method "Message.Assignment.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) term = SingleExpression( self~lhs ) op = self~operator~value target = MessageTarget( term, unit ) If target == .Nil Then Do unit~emit( "PAUSE", a ) Return End Parse Var target name scope Call Gen term~term, unit If scope Then Do Call CompileScope term~scope, unit unit~emit( "SCOPE" ) End If op \== "=" Then Call Gen term, unit Call CompileExpr self~rhs, unit If op \== "=" Then Call EmitAssignmentOp op, unit unit~emit( "TRARG" ) n = CompileArgs( term~arguments, unit ) unit~emit( "SENDA", unit~const( name"=" ), n + 1, scope ) unit~emit( "PAUSE", a ) -- A message term as the target of an assignment (receiver~name(args), -- receiver[args]): "name scope", its name and its scope operand (1 when it -- has one: ~name:scope); .Nil, with an error emitted, when it cannot be one. ::Routine MessageTarget Use Strict Arg term, unit scope = 0 Select When term~isA( .Indexed.Or.Invoked.Term ), term~bracket < .EL.LEFT_BRACKET, - term~trailingBlock == .Nil Then name = "[]" When term~isA( .Message.Term ), term~operator~value == "~", - term~messageName \== .Nil, term~trailingBlock == .Nil Then Do If term~scope \== .Nil Then scope = 1 name = Upper( term~messageName~value ) End Otherwise Do If term~trailingBlock \== .Nil Then Call Unsupported unit, "trailing blocks" Else Call Unsupported unit, "message assignments of this form" Return .Nil End End Return name scope -- Is it a message term (a target of PARSE or USE ARG)? ::Routine IsMessageTerm Use Strict Arg term Return term~isA( .Message.Term ) | term~isA( .Indexed.Or.Invoked.Term ) -- The value on the stack to a message term (ooRexx's -- RexxExpressionMessage~assign): the receiver is evaluated now, put under -- the value (SWAP), then the arguments; the message is "NAME=" or "[]=". ::Routine MessageTargetStore Use Strict Arg term, unit target = MessageTarget( term, unit ) If target == .Nil Then Return Parse Var target name scope Call Gen term~term, unit unit~emit( "SWAP" ) -- The scope is evaluated after the receiver, and goes under the value -- too; it is not checked (RexxExpressionMessage~assign): the send is. If scope Then Do Call CompileScope term~scope, unit unit~emit( "SWAP" ) End -- Its arguments are traced as results (>>>), an omitted one as "". n = 0 If term~arguments \== .Nil Then Do positional = term~arguments~positionalArguments If \ positional~isEmpty Then Do n = positional~last Loop k = 1 To n If positional~hasIndex(k) Then Do Call Gen positional[k], unit unit~emit( "RES" ) End Else Do unit~emit( "PUSHNONE" ) unit~emit( "TRES", unit~const( "" ) ) End End End End unit~emit( "SENDA", unit~const( name"=" ), n + 1, scope ) -- The operator of a compound assignment (op=). ::Routine EmitAssignmentOp Use Strict Arg op, unit Select Case Left( op, Length( op ) - 1 ) When "+" Then unit~emit( "ADD" ) When "-" Then unit~emit( "SUB" ) When "*" Then unit~emit( "MUL" ) When "/" Then unit~emit( "DIV" ) When "%" Then unit~emit( "IDIV" ) When "//" Then unit~emit( "REM" ) When "**" Then unit~emit( "POW" ) When "||" Then unit~emit( "CAT" ) When "&" Then unit~emit( "AND" ) When "|" Then unit~emit( "OR" ) When "&&" Then unit~emit( "XOR" ) End /******************************************************************************/ /* DIRECTIVES */ /* */ /* ::CLASS, ::METHOD, ::ATTRIBUTE and ::CONSTANT become the CLASSES and */ /* METHODS of the R-code: a method written in Rexx is a body of its own, */ /* compiled after the prolog, with labels of its own; an attribute (GET, SET) */ /* and a constant are native. A ::ROUTINE is a body of its own too */ /* (ROUTINES), and a ::REQUIRES an entry of REQUIRES: the RVM loads it when */ /* the program starts. */ /******************************************************************************/ -- The settings of the ::OPTIONS, in order (ooRexx's -- LanguageParser::optionsDirective: several directives add up). A condition -- is SYNTAX or CONDITION (NOVALUE ERROR is SYNTAX); ALL sets the six. FUZZ -- must stay below DIGITS: 33.1, which ooRexx raises while it translates -- (here, before the prolog runs, at the clause of the directive). ::Routine CompileOptions Use Strict Arg package, unit o = unit~options conditions = "ERROR FAILURE LOSTDIGITS NOSTRING NOTREADY NOVALUE" -- What the directives set (ooRexx's isExplicit...Option: Package~options -- "X", and what .Package~defaultOptions does not override). explicit = .Set~new Do d Over package~directives If \ d~isA( .Options.Directive ) Then Iterate Do s Over d~settings name = Upper( s[1] ); value = Upper( s[2] ) If value == "ERROR" Then value = "SYNTAX" Select When name == "ALL" Then Do c Over conditions~makeArray( " " ) o[ c ] = value explicit~put( c ) End When name == "DIGITS", value <= o~fuzz Then Signal Bad33 When name == "FUZZ", value >= o~digits Then Signal Bad33 Otherwise o[ name ] = value End Select When name == "ALL" Then Nop When name == "PROLOG", value == 0 Then Do explicit~remove( "PROLOG" ); explicit~put( "NOPROLOG" ) End When name == "PROLOG" Then Do explicit~remove( "NOPROLOG" ); explicit~put( "PROLOG" ) End Otherwise explicit~put( name ) End End End list = "" Do name Over ( "DIGITS FORM FUZZ NUMERIC" conditions "NOPROLOG PROLOG TRACE" )~makeArray( " " ) If explicit~hasIndex( name ) Then list = list","name End If list \== "" Then o~explicit = SubStr( list, 2 ) Return Bad33: If name == "DIGITS" Then Parse Value value o~fuzz With digits fuzz Else Parse Value o~digits value With digits fuzz unit~emit( "CLAUSE", unit~clauseNo( d ), "N" ) unit~emit( "PUSHC", unit~const( "33.1" ) ) unit~emit( "PUSHNONE" ) unit~emit( "PUSHNONE" ) unit~emit( "PUSHC", unit~const( digits ) ) unit~emit( "PUSHC", unit~const( fuzz ) ) unit~emit( "PUSHNONE" ) unit~emit( "RAISE", unit~const( "SYNTAX" ), "EXIT", 2 ) -- The OPTIONS line of the R-code: DIGITS FUZZ FORM TRACE NUMERIC PROLOG, -- the conditions that are SYNTAX (comma-separated, or "-") and the options -- the directives set (comma-separated, or "-"). ::Routine OptionsLine Public Use Strict Arg o conds = "" Do c Over .Array~of( "ERROR", "FAILURE", "LOSTDIGITS", "NOSTRING", "NOTREADY", "NOVALUE" ) If o[ c ] == "SYNTAX" Then conds = conds","c End If conds == "" Then conds = "-"; Else conds = SubStr( conds, 2 ) Return o~digits o~fuzz o~form o~trace o~numeric o~prolog conds o~explicit -- Is it EXTERNAL 'LIBRARY REXX f' (a method of the interpreter itself), f -- one of ooRexx's (its InternalPackage's INTERNAL_METHODs, in any case; f is -- the method's name when the specification leaves it out)? Any other f is -- compiled as a LIBRARY method: 90.998 when the program starts, as ooRexx -- says when it translates it. ::Routine IsRexxLibrary Use Strict Arg spec, name If spec == .Nil Then Return .False Parse Upper Value spec With w1 w2 f rest If w1 \== "LIBRARY" | w2 \== "REXX" | rest \== "" Then Return .False If f == "" Then f = name methods = "ALARM_STARTTIMER ALARM_STOPTIMER TICKER_CREATETIMER" - "TICKER_WAITTIMER TICKER_STOPTIMER STREAM_INIT STREAM_CHARS STREAM_LINES" - "STREAM_POSITION STREAM_STATE STREAM_DESCRIPTION STREAM_QUERY_POSITION" - "STREAM_CHAROUT STREAM_CHARIN STREAM_LINEIN STREAM_LINEOUT STREAM_ARRAYIN" - "QUALIFY QUERY_EXISTS QUERY_SIZE QUERY_TIME HANDLE_SET STD_SET" - "STREAM_FLUSH QUERY_HANDLE QUERY_STREAMTYPE STREAM_CLOSE STREAM_UNINIT" - "STREAM_OPEN REXX_CREATE_QUEUE REXX_OPEN_QUEUE REXX_QUEUE_EXISTS" - "REXX_DELETE_QUEUE REXX_QUERY_QUEUE REXX_PUSH_QUEUE REXX_QUEUE_QUEUE" - "REXX_PULL_QUEUE REXX_LINEIN_QUEUE REXX_CLEAR_QUEUE FILE_SEPARATOR" - "FILE_PATH_SEPARATOR FILE_CASE_SENSITIVE FILE_LIST_ROOTS FILE_QUALIFY" - "FILE_EXISTS FILE_DELETE_FILE FILE_DELETE_DIRECTORY FILE_ISDIRECTORY" - "FILE_ISFILE FILE_ISHIDDEN FILE_GET_LAST_MODIFIED FILE_SET_LAST_MODIFIED" - "FILE_SET_READ_ONLY FILE_LENGTH FILE_LIST FILE_MAKE_DIR FILE_CAN_READ" - "FILE_CAN_WRITE FILE_RENAME THIS_FILE_CASE_SENSITIVE" - "FILE_GET_LAST_ACCESSED FILE_SET_LAST_ACCESSED FILE_SET_WRITABLE" - "FILE_TEMPORARY_PATH FILE_SEARCH_PATH_IMPL" Return WordPos( f, methods ) > 0 ::Routine CompileDirectives Use Strict Arg package, unit cls = 0 calculated = .Array~new -- the active class's calculated constants Do d Over package~directives Select When d~isA( .Class.Directive ) Then Do Call ConstantInitializer cls, calculated, unit cls = unit~addClass( unit~clauseNo( d ) ClassEntry( d ) ) End -- A routine: a body of its own, with its own labels (or EXTERNAL). When d~isA( .Routine.Directive ) Then Do -- Its name is found in any case: kept in upper case. entry = Quote( Upper( d~name~value ) ) ( \ d~private )~?( "PUBLIC", "PRIVATE" ) -- EXTERNAL: its clause and its specification (the RVM resolves it -- when the package starts: see the machine's CheckExternals). If d~external \== .Nil Then entry = entry "- EXTERNAL" unit~clauseNo( d ) Quote( d~external~value ) Else Do entry = entry Extent( d~end~to, d~body ) address = unit~here labels = unit~startBody unit~body = d~body Do instruction Over d~body~instructions Call Gen instruction, unit End unit~flushRedos unit~endBody entry = entry "CODE" address labels~items Do With Index label Item a Over labels entry = entry Quote( label ) a End End unit~routines~append( entry ) End -- ::RESOURCE (ooRexx's LanguageParser~resourceDirective): its name, in -- uppercase, and its lines, those between the directive and the line -- that starts with the end marker (the parser's Resource.Data). When d~isA( .Resource.Directive ) Then unit~resources~append( .Array~of( Upper( d~name~value ), ResourceLines( d ) ) ) -- A package to load before the program runs: its clause, its name. When d~isA( .Requires.Directive ) Then Do entry = unit~clauseNo( d ) Quote( d~programName~value ) If d~library \== .Nil, d~library \== 0 Then entry = entry "LIBRARY" If d~nameSpace \== .Nil Then entry = entry "NAMESPACE" Quote( Upper( d~nameSpace~value ) ) unit~requires~append( entry ) End When d~isA( .Method.Directive ) Then Do which = d~isClassMethod~?( "C", "I" ) name = Upper( d~name~value ) flags = MethodFlags( d~isPrivate, d~isProtected, d~isPackage, d~isGuarded ) -- An attribute's methods are marked as such (A: Method~isAttribute). aflags = MethodFlags( d~isPrivate, d~isProtected, d~isPackage, d~isGuarded, 1 ) Select -- DELEGATE var (ooRexx's createDelegateMethod): the message goes to -- the object in the variable; with ATTRIBUTE, NAME= too (first). When d~delegateName \== .Nil Then Do var = Upper( d~delegateName~value ) If d~isAttribute Then Do unit~addMethod( cls, which, name"=", "DELEGATE", var, , aflags ) unit~addMethod( cls, which, name, "DELEGATE", var, , aflags ) End Else unit~addMethod( cls, which, name, "DELEGATE", var, , flags ) End -- ATTRIBUTE: EXTERNAL (GETname and SETname: ooRexx marks only the -- getter as an attribute), ABSTRACT, or the variable's. When d~isAttribute Then Select When d~external \== .Nil Then Do spec = unit~clauseNo( d ) Quote( d~external ) Quote( name ) unit~addMethod( cls, which, name, "LIBRARY", spec "GET", , aflags ) unit~addMethod( cls, which, name"=", "LIBRARY", spec "SET", , flags ) End When d~isAbstract Then Do unit~addMethod( cls, which, name, "ABSTRACT", "-", , aflags ) unit~addMethod( cls, which, name"=", "ABSTRACT", "-", , aflags ) End Otherwise Do unit~addMethod( cls, which, name, "GET", name, , aflags ) unit~addMethod( cls, which, name"=", "SET", name, , aflags ) End End When d~isAbstract Then unit~addMethod( cls, which, name, "ABSTRACT", "-", , flags ) -- EXTERNAL 'LIBRARY REXX f': a method of the REXX library (the -- RVM's natives X.f: the timers of Alarm and Ticker). When IsRexxLibrary( d~external, name ) Then Do Parse Upper Value d~external With . . f . If f == "" Then f = name -- (the method's own name) unit~addMethod( cls, which, name, "REXX", f, , flags ) End -- EXTERNAL 'LIBRARY lib [f]' (or anything else): the RVM resolves -- it when it runs (CallNative, L): its clause, the specification, -- the default name of the entry, no prefix. When d~external \== .Nil Then unit~addMethod( cls, which, name, "LIBRARY", - unit~clauseNo( d ) Quote( d~external ) Quote( name ) "-", , flags ) Otherwise Do address = unit~here labels = unit~startBody unit~body = d~method~body Do instruction Over d~method~body~instructions Call Gen instruction, unit End unit~flushRedos unit~endBody unit~addMethod( cls, which, name, "CODE", address, labels, flags, - Extent( d~end~to, d~method~body ) ) End End End When d~isA( .Attribute.Directive ) Then Do o. = d~options. which = ( o.class == 1 )~?( "C", "I" ) name = Upper( d~name~value ) -- (All of them are marked as attribute methods: A.) flags = MethodFlags( o.visibility == "PRIVATE", o.protected == 1, - o.visibility == "PACKAGE", o.guarded == 1, 1 ) If o.abstract == 1 Then Do If o.get == 1 Then unit~addMethod( cls, which, name, "ABSTRACT", "-", , flags ) If o.set == 1 Then unit~addMethod( cls, which, name"=", "ABSTRACT", "-", , flags ) End -- EXTERNAL: the methods are the library's entries GETname and SETname -- (or the entry given, after GET and SET), as ooRexx's -- attributeDirective; the RVM resolves them when they run. Else If o.external \== .Nil Then Do spec = unit~clauseNo( d ) Quote( o.external ) Quote( name ) getPrefix = "GET"; setPrefix = "SET" -- Only GET or only SET: an entry given (not the name) is taken as -- it is, with no prefix. If o.get \== o.set, Words( o.external ) == 3, Word( o.external, 3 ) \== name Then Do getPrefix = "-"; setPrefix = "-" End If o.get == 1 Then unit~addMethod( cls, which, name, "LIBRARY", spec getPrefix, , flags ) If o.set == 1 Then unit~addMethod( cls, which, name"=", "LIBRARY", spec setPrefix, , flags ) End -- DELEGATE var: the message goes to the object in the variable. Else If o.delegateName \== "" Then Do var = Upper( o.delegateName~value ) If o.get == 1 Then unit~addMethod( cls, which, name, "DELEGATE", var, , flags ) If o.set == 1 Then unit~addMethod( cls, which, name"=", "DELEGATE", var, , flags ) End -- With a body (GET or SET, one of them): a method written in Rexx. Else If d~body \== .Nil, \ d~body~isEmpty Then Do address = unit~here labels = unit~startBody unit~body = d~body Do instruction Over d~body~instructions Call Gen instruction, unit End unit~flushRedos unit~endBody If o.set == 1 Then name = name"=" unit~addMethod( cls, which, name, "CODE", address, labels, flags, - Extent( d~end~to, d~body ) ) End Else Do If o.get == 1 Then unit~addMethod( cls, which, name, "GET", name, , flags ) If o.set == 1 Then unit~addMethod( cls, which, name"=", "SET", name, , flags ) End End When d~isA( .Constant.Directive ) Then Do name = Upper( d~name~value ) value = d~value -- (expression): a calculated constant, given its value when the -- classes are made (see ConstantInitializer). If value \== .Nil, \ value~isA( .Element ), \ value~isA( .Array ) Then Do unit~addMethod( cls, "I", name, "CCONST", "-", , "U" ) unit~addMethod( cls, "C", name, "CCONST", "-", , "U" ) calculated~append( d ) Iterate End Select -- No value: the name as written ('NoValue', as ooRexx; a symbol's -- value is in uppercase). When value == .Nil Then value = d~name~value -- A signed number: the sign and the number, joined. When value~isA( .Array ) Then value = value[1]~value || value[2]~value Otherwise value = value~value End unit~addMethod( cls, "I", name, "CONST", unit~const( value ), , "U" ) unit~addMethod( cls, "C", name, "CONST", unit~const( value ), , "U" ) End Otherwise Nop End End Call ConstantInitializer cls, calculated, unit -- The lines of a ::RESOURCE: those of the Resource.Data element that the -- parser puts in the directive (from its first line to its last one; none, -- when the end marker follows the directive). ::Routine ResourceLines Use Strict Arg d lines = .Array~new e = d~begin Do While e \== .Nil, e \== d~end If e < .EL.RESOURCE_DATA Then Do Parse Value e~from With first . Parse Value e~to With last . Do k = first To last lines~append( e~source[k] ) End Leave End e = e~next End Return lines -- The calculated constants of a class (::CONSTANT name (expression)): a -- method of its own (ooRexx's ClassDirective~resolveConstants: the method -- "::CONSTANT", its instructions the ::CONSTANT directives), which the RVM -- runs on the class object once all the classes of the program are made, -- before ACTIVATE. It is a method K of the class in METHODS; each directive -- traces its clause and its value, and SETCONST gives it to the constant. ::Routine ConstantInitializer Use Strict Arg cls, calculated, unit If calculated~isEmpty Then Return address = unit~here labels = unit~startBody Do d Over calculated a = unit~clause( d ) Call CompileExpr d~value, unit unit~emit( "RES" ) unit~emit( "SETCONST", unit~const( Upper( d~name~value ) ) ) unit~emit( "PAUSE", a ) End unit~emit( "RETURN" ) unit~endBody unit~addMethod( cls, "K", "::CONSTANT", "CODE", address, labels, "U" ) calculated~empty -- ::ANNOTATE (ooRexx's LanguageParser~annotateDirective): the targets of -- each one, looked up as ooRexx does while it translates, among what the -- directives before it defined: a class (any ::CLASS before it), a routine, -- a method of the active class (an instance one first, then a class one; -- before the first ::CLASS, a floating one), an attribute (its methods made -- by ::ATTRIBUTE or ::METHOD ... ATTRIBUTE: the instance ones, or else the -- class ones), a constant, the package. Every pair (name, value) goes to -- each target, in order: the later one wins. A method is (class, I|C, NAME) -- until CompileDirectives has made the METHODS (RVM.Unit~resolveAnnotations); -- a constant is one method in ooRexx, and two in the RVM (I and C): both. -- A target that is not there is 99.945, a translation error in ooRexx: it is -- raised before the prolog runs, at the clause of the directive. ::Routine CompileAnnotations Use Strict Arg package, unit classes = .Directory~new -- NAME -> its number routines = .Directory~new -- NAME -> its number nClasses = 0; nRoutines = 0 imethods = .Directory~new -- the active class's: NAME -> targets cmethods = .Directory~new attrs = .Directory~new -- NAME -> "I" or "C" (an attribute's) consts = .Set~new Do d Over package~directives Select When d~isA( .Class.Directive ) Then Do nClasses += 1 name = Upper( d~name~value ) If \ classes~hasIndex( name ) Then classes[ name ] = nClasses imethods = .Directory~new; cmethods = .Directory~new attrs = .Directory~new; consts = .Set~new End When d~isA( .Routine.Directive ) Then Do nRoutines += 1 name = Upper( d~name~value ) If \ routines~hasIndex( name ) Then routines[ name ] = nRoutines End When d~isA( .Method.Directive ) Then Do which = d~isClassMethod~?( "C", "I" ) name = Upper( d~name~value ) If which == "I" Then t = imethods Else t = cmethods If d~isAttribute Then Do t[ name ] = .Array~of( .Array~of( "M", nClasses, which, name ) ) t[ name"=" ] = .Array~of( .Array~of( "M", nClasses, which, name"=" ) ) attrs[ which name ] = 1 attrs[ which name"=" ] = 1 End Else t[ name ] = .Array~of( .Array~of( "M", nClasses, which, name ) ) End When d~isA( .Attribute.Directive ) Then Do o. = d~options. which = ( o.class == 1 )~?( "C", "I" ) name = Upper( d~name~value ) If which == "I" Then t = imethods Else t = cmethods If o.get == 1 Then Do t[ name ] = .Array~of( .Array~of( "M", nClasses, which, name ) ) attrs[ which name ] = 1 End If o.set == 1 Then Do t[ name"=" ] = .Array~of( .Array~of( "M", nClasses, which, name"=" ) ) attrs[ which name"=" ] = 1 End End When d~isA( .Constant.Directive ) Then Do name = Upper( d~name~value ) targets = .Array~of( .Array~of( "M", nClasses, "I", name ), - .Array~of( "M", nClasses, "C", name ) ) imethods[ name ] = targets cmethods[ name ] = targets consts~put( name ) End When d~isA( .Annotate.Directive ) Then Do o. = d~options. type = o.["DIRECTIVE"] If type \== "PACKAGE" Then target = Upper( o.["NAME"]~value ) targets = .Nil Select Case type When "PACKAGE" Then targets = .Array~of( .Array~of( "P", 0 ) ) When "CLASS" Then If classes~hasIndex( target ) Then targets = .Array~of( .Array~of( "C", classes[ target ] ) ) When "ROUTINE" Then If routines~hasIndex( target ) Then targets = .Array~of( .Array~of( "R", routines[ target ] ) ) When "METHOD" Then Do targets = imethods[ target ] If targets == .Nil Then targets = cmethods[ target ] End When "CONSTANT" Then If consts~hasItem( target ) Then targets = imethods[ target ] When "ATTRIBUTE" Then Do Do which Over .Array~of( "I", "C" ) targets = .Array~new Do n Over .Array~of( target, target"=" ) If attrs~hasIndex( which n ) Then targets~append( .Array~of( "M", nClasses, which, n ) ) End If targets~items > 0 Then Leave End If targets~items == 0 Then targets = .Nil End End If targets == .Nil Then Do unit~emit( "CLAUSE", unit~clauseNo( d ), "N" ) unit~emit( "PUSHC", unit~const( "99.945" ) ) unit~emit( "PUSHNONE" ) unit~emit( "PUSHNONE" ) unit~emit( "PUSHC", unit~const( Lower( type ) ) ) unit~emit( "PUSHC", unit~const( target ) ) unit~emit( "PUSHNONE" ) unit~emit( "RAISE", unit~const( "SYNTAX" ), "EXIT", 2 ) Return End Do pair Over o.["PAIRS"] value = pair[3]~value If pair[2] \== .Nil Then value = pair[2]~value || value Do target Over targets unit~annotations~append( .Array~of( target, pair[1]~value, value ) ) End End End Otherwise Nop End End -- A ::CLASS as an entry of the CLASSES table (after its clause number): -- "ID" "SUPERCLASS" "METACLASS" -- PUBLIC|PRIVATE, then MIXIN if it is a mixin class, then INHERIT "C"... -- ("" is the default: Object, Class). A class reference qualified by a -- namespace is "NS:NAME"; an unqualified one with a colon, ":NAME". ::Routine ClassEntry Use Strict Arg d o. = d~options. super = "" mixin = .False If o.subclass \== .Nil Then super = ClassRef( o.subclass ) If o.mixinclass \== .Nil Then Do super = ClassRef( o.mixinclass ) mixin = .True End meta = "" If o.metaclass \== .Nil Then meta = ClassRef( o.metaclass ) entry = Quote( d~name~value ) Quote( super ) Quote( meta ) o.public~?( "PUBLIC", "PRIVATE" ) If mixin Then entry = entry "MIXIN" If o.abstract == 1 Then entry = entry "ABSTRACT" If o.inherit \== .Nil Then Do entry = entry "INHERIT" Do c Over o.inherit entry = entry Quote( ClassRef( c ) ) End End Return entry ::Routine ClassRef Use Strict Arg pair name = Upper( pair[2]~value ) If pair[1] \== .Nil Then Return Upper( pair[1]~value )":"name If Pos( ":", name ) > 0 Then Return ":"name Return name -- The options of a method, as a word: P (private), R (protected), K -- (package), U (unguarded), in that order; "-" for none (public, guarded). ::Routine MethodFlags Use Strict Arg private, protected, package, guarded, attribute = 0 flags = "" If private == 1 Then flags ||= "P" If protected == 1 Then flags ||= "R" If package == 1 Then flags ||= "K" If guarded \== 1 Then flags ||= "U" If attribute == 1 Then flags ||= "A" If flags == "" Then Return "-" Return flags -- Where the source of a body is, as a word "line.col-line.col": from 'start' -- (the end of its directive: "line col") to where its implicit EXIT is (see -- RVM.Machine's SourceOf: ooRexx's Method~source and Routine~source). ::Routine Extent Use Strict Arg start, body Parse Var start sl sc Parse Value body~instructions~lastItem~begin~from With el ec Return sl"."sc"-"el"."ec ::Routine Quote Use Strict Arg s If Verify( s, XRange( "20"x, "7E"x ) ) == 0 Then Return '"'ChangeStr( '"', s, '""' )'"' Return "X'"C2X( s )"'" -- EXPOSE (in a method): each variable shares the object's variable of the -- method's scope, in order. EXPO (simple), EXPOS (stem), EXPOC (compound: -- its tail worked out in the method's variables, TAILV; the name is for the -- trace), and for a list, (x), EXPO x and then EXPOI x (the names in its -- value). ::Method "Expose.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self, "E" ) Do term Over ExposeOrder( self~exposed ) Select When term~isA( .Array ) Then Do slot = unit~slot( term[1]~value~value ) unit~emit( "EXPO", slot ) unit~emit( "EXPOI", slot ) End When term~isA( .Stem.Variable.Term ) Then unit~emit( "EXPOS", unit~slot( Upper( term~symbol~value ) ) ) When term~isA( .Compound.Variable.Term ) Then Do n = CompileTail( term, unit ) unit~emit( "EXPOC", unit~slot( term~parts[1]~value ), n, - unit~const( CompoundTraceName( term ) ) ) End Otherwise unit~emit( "EXPO", unit~slot( term~value~value ) ) End End unit~emit( "PAUSE", a ) -- USE LOCAL (in a method): USEL k, k the names declared local (uppercased, -- blank-separated; a stem with its period). Out of a method, 98.993 when it -- runs (as ooRexx: the parser takes it there). ::Method "Use.Local.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) inMethod = .False If unit~body \== .Nil Then inMethod = ( unit~body~isAMethodBody == .True ) If \ inMethod Then Do unit~emit( "ERR", "98.993", 0 ) Return End names = "" Do name Over self~local names = names Upper( name~value ) End unit~emit( "USEL", unit~const( Strip( names ) ) ) unit~emit( "PAUSE", a ) -- USE [STRICT] ARG: each variable gets its argument (USEARG: the argument -- object itself, traced >>> and >=>), or its default (an expression, or a -- constant), or is dropped. STRICT checks the number of arguments first -- (USESTRICT: "R" / "O" / "S" per position, and whether "..." takes any -- more); a required one omitted is an error when its turn comes (USEOMIT), -- after the ones before it are assigned, as ooRexx (UseVariable:: -- handleArgument). ::Method "Use.Arg.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) If self~named Then Do Call Unsupported unit, "USE NAMED ARG" Return End args = self~arguments -- The positions, as ooRexx counts them ("USE ARG ," has one; "..." is -- not one). n = self~count flags = "" more = 0 If args~last \== .Nil Then If args[ args~last ][1]~isA( .Element ) Then more = 1 -- "..." -- A skipped position ("USE STRICT ARG , b") has no default, so it counts -- for the minimum, but its argument may be omitted (S). Do i = 1 To n If \ args~hasIndex( i ) Then Do flags ||= "S" Iterate End item = args[i] If item~items > 1 Then flags ||= "O" Else flags ||= "R" End If self~strict Then unit~emit( "USESTRICT", unit~const( flags"." ), more ) Do i = 1 To n If \ args~hasIndex( i ) Then Iterate item = args[i] term = item[1] -- >v, >s.: the argument's variable becomes the local one (USEREF). If term~isA( .Variable.Reference.Term ) Then Do unit~emit( "USEREF", i, unit~slot( term~variable~value ) ) Iterate End If term~isA( .Stem.Variable.Term ) | term~isA( .Compound.Variable.Term ) | - IsMessageTerm( term ) Then Do Call UseArgTarget term, item, i, self~strict, unit Iterate End If \ term~isA( .Symbol.Term ) Then Do Call Unsupported unit, "USE ARG to targets other than simple variables" Return End element = term~value If \ ( element < .ALL.SIMPLE_VARIABLES ) Then Do Call Unsupported unit, "USE ARG to targets other than simple variables" Return End slot = unit~slot( element~value ) doneRef = unit~newRef unit~emit( "USEARG", i, slot, doneRef ) If item~items > 1 Then Do default = item[2] Select When \ default~isA( .Element ) Then Call Gen default, unit When default < .ALL.NUMBERS Then unit~emit( "PUSHN", unit~const( default~source ) ) When default < .EL.ENVIRONMENT_SYMBOL Then unit~emit( "ENV", unit~const( default~value ) ) Otherwise unit~emit( "PUSHC", unit~const( default~value ) ) End unit~emit( "RES" ) unit~emit( "STOREV", slot ) End Else If self~strict Then unit~emit( "USEOMIT", i ) Else unit~emit( "DROPV", slot ) unit~place( doneRef ) End unit~emit( "PAUSE", a ) -- USE ARG to a stem or a compound (its tail resolved when it is assigned): -- USEARGP puts the argument on the stack, or .Nil and jumps to what the -- target gets when it is omitted: its default, a DROP, or (STRICT) the -- error. ::Routine UseArgTarget Use Strict Arg term, item, i, strict, unit elseRef = unit~newRef doneRef = unit~newRef unit~emit( "USEARGP", i, elseRef ) Call UseArgStore term, unit unit~emit( "JMP", doneRef ) unit~place( elseRef ) unit~emit( "POP" ) If item~items > 1 Then Do default = item[2] Select When \ default~isA( .Element ) Then Call Gen default, unit When default < .ALL.NUMBERS Then unit~emit( "PUSHN", unit~const( default~source ) ) When default < .EL.ENVIRONMENT_SYMBOL Then unit~emit( "ENV", unit~const( default~value ) ) Otherwise unit~emit( "PUSHC", unit~const( default~value ) ) End unit~emit( "RES" ) Call UseArgStore term, unit End Else Select When strict Then unit~emit( "USEOMIT", i ) When term~isA( .Compound.Variable.Term ) Then Do n = CompileTail( term, unit ) unit~emit( "DROPC", unit~slot( term~parts[1]~value ), n ) End When term~isA( .Stem.Variable.Term ) Then unit~emit( "DROPS", unit~slot( term~symbol~value ) ) -- A message term cannot be dropped: nothing happens (ooRexx's -- RexxVariableBase~drop). Otherwise Nop End unit~place( doneRef ) -- The value on the stack to a stem, a compound or a message term (as an -- assignment). ::Routine UseArgStore Use Strict Arg term, unit If IsMessageTerm( term ) Then Call MessageTargetStore term, unit Else If term~isA( .Compound.Variable.Term ) Then Do n = CompileTail( term, unit ) unit~emit( "STOREC", unit~slot( term~parts[1]~value ), n, - unit~const( CompoundTraceName( term ) ) ) End Else unit~emit( "STORES", unit~slot( term~symbol~value ) ) /******************************************************************************/ /* SIMPLE INSTRUCTIONS */ /******************************************************************************/ ::Method "Nop.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) unit~emit( "PAUSE", a ) ::Method "Say.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) Call CompileExpr self~expression, unit unit~emit( "SAY" ) unit~emit( "PAUSE", a ) ::Method "Assignment.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) lhs = self~symbol -- A compound assignment (x += e): the variable, e, the operator. op = self~operator~value If op \== "=" Then Do Select When lhs~isA( .Compound.Variable.Term ) | lhs~isA( .Symbol.Term ) Then Call Gen lhs, unit Otherwise Do Call Unsupported unit, "compound assignments to stems" Return End End End Call CompileExpr self~expression, unit If op \== "=" Then Call EmitAssignmentOp op, unit unit~emit( "RESA" ) Select When lhs~isA( .Compound.Variable.Term ) Then Do n = CompileTail( lhs, unit ) unit~emit( "STOREC", unit~slot( lhs~parts[1]~value ), n, - unit~const( CompoundTraceName( lhs ) ) ) End When lhs~isA( .Stem.Variable.Term ) Then unit~emit( "STORES", unit~slot( lhs~symbol~value ) ) Otherwise unit~emit( "STOREV", unit~slot( lhs~value~value ) ) End unit~emit( "PAUSE", a ) ::Method "Exit.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) If self~expression == .Nil Then unit~emit( "EXIT" ) Else Do Call CompileExpr self~expression, unit unit~emit( "RES" ) unit~emit( "EXITV" ) End ::Method "Implicit.Exit.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) unit~emit( "EXIT" ) ::Method "Return.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) If self~expression == .Nil Then unit~emit( "RETURN" ) Else Do Call CompileExpr self~expression, unit unit~emit( "RES" ) unit~emit( "RETURNV" ) End ::Method "Push.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) Call CompileExpr self~expression, unit unit~emit( "PUSH" ) unit~emit( "PAUSE", a ) ::Method "Queue.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) Call CompileExpr self~expression, unit unit~emit( "QUEUE" ) unit~emit( "PAUSE", a ) -- NUMERIC DIGITS|FUZZ [expr], NUMERIC FORM [SCIENTIFIC|ENGINEERING|VALUE expr] ::Method "Numeric.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) sub = "" el = self~begin Loop While el \== .Nil If el < .EL.SUBKEYWORD Then Do sub = el~value Leave End If el == self~end Then Leave el = el~next End If self~expression \== .Nil Then Do Call CompileExpr self~expression, unit unit~emit( "KEYW", unit~const( sub ) ) End Else unit~emit( "PUSHNONE" ) Select Case sub When "DIGITS" Then unit~emit( "NUMDIG" ) When "FUZZ" Then unit~emit( "NUMFUZZ" ) When "FORM" Then Do option = Upper( self~option ) Select When option == "FORM SCIENTIFIC" Then kind = "SCIENTIFIC" When option == "FORM ENGINEERING" Then kind = "ENGINEERING" -- NUMERIC FORM alone: VALUE with no value, the package's default. When self~expression == .Nil Then kind = "VALUE" Otherwise kind = "VALUE" End unit~emit( "NUMFORM", kind ) End End unit~emit( "PAUSE", a ) ::Method "Drop.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) Do item Over self~nameList Select When item~isA( .Array ) Then unit~emit( "DROPI", unit~slot( item[1]~value~value ) ) When item~isA( .Compound.Variable.Term ) Then Do n = CompileTail( item, unit ) unit~emit( "DROPC", unit~slot( item~parts[1]~value ), n ) End When item~isA( .Stem.Variable.Term ) Then unit~emit( "DROPS", unit~slot( item~symbol~value ) ) Otherwise unit~emit( "DROPV", unit~slot( item~value~value ) ) End End unit~emit( "PAUSE", a ) /******************************************************************************/ /* IF */ /* */ /* The indentation of the trace (and of error reports) changes as ooRexx */ /* changes it: INDENT, UNINDENT, UNIND2 (two levels, while there */ /* are two), BASE d (keep the level of a block in its descriptor), SETIND d */ /* (back to it). TCLAUSE c traces a clause that is not an instruction (THEN, */ /* ELSE, END, the DO clause of a new round) when TRACE A, R or I. BOUND ends */ /* a clause: the CALL ON traps it fired run. */ /******************************************************************************/ ::Method "If.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self~ifClause ) elseRef = unit~newRef endRef = unit~newRef Call CompileCondition self~ifClause~expressions, unit, elseRef, a, "IF" unit~emit( "BOUND" ) Call CompileBranch self~thenClause, self~thenInstruction, unit, self If self~elseInstruction \== .Nil Then Do unit~emit( "JMP", endRef ) unit~place( elseRef ) unit~emit( "BOUND" ) Call CompileBranch self~elseClause, self~elseInstruction, unit, self End Else Do unit~place( elseRef ) unit~emit( "BOUND" ) End unit~place( endRef ) -- THEN or ELSE (or the THEN of a WHEN) and its instruction. ::Routine CompileBranch Use Strict Arg clause, instruction, unit, block unit~emit( "INDENT" ) unit~emit( "TCLAUSE", unit~clauseNo( clause ) ) unit~emit( "INDENT" ) unit~enter( block ) Call Gen instruction, unit unit~leave -- The instruction is a clause of its own: the CALL ON traps it fired run -- at its indentation, before the branch ends. unit~emit( "BOUND" ) unit~emit( "UNIND2" ) /******************************************************************************/ /* DO and LOOP */ /* */ /* A loop is laid out as: */ /* CLAUSE do; BASE d */ /* (COUNTER: DOCTR d Z, TRCTR d; WITH: DOWITH d; OVER: DOOVER or */ /* DOOVERS d; a control variable: start, TO, BY and FOR in their */ /* order, DOINIT; a repetitor: DOREP d) */ /* INDENT; JMP first */ /* top: SETIND d; TCLAUSE do; INDENT <- ITERATE */ /* CLAUSE end Q (UNTIL: a true UNTIL goes to over; DOSTEP d) */ /* CLAUSE do Q */ /* first:(OVER: DONEXT d over; WITH: DONEXTW d over and WITHSET) */ /* DOTEST d over (TO, FOR, a repetitor) */ /* (WHILE: a false WHILE goes to over) */ /* (COUNTER: DOCTR d N, TRCTR d) */ /* DOPAUSE a d; JPAUSE R; DOBODY d; (body); */ /* CLAUSE end Q; SETIND d; TCLAUSE end; JMP top */ /* over: DOEXIT d; DOPAUSE a d; JPAUSE E; JMP done (the checks ended it) */ /* exit: SETIND d; JPAUSE E <- LEAVE */ /* done: */ /* The CLAUSE ... Q lines make an error in UNTIL or in the step be reported */ /* on the END clause, and one in the checks on the DO clause. The descriptor */ /* d keeps the level, the TO limit, the BY step and the FOR count of the loop */ /* (per activation). A simple DO ... END is BASE d, INDENT, BPAUSE a 0 d, the */ /* body, the END clause and, if it has a name, exit: SETIND d; JPAUSE E. */ /******************************************************************************/ ::Method "Do.Instruction::rcompile" Use Strict Arg unit dc = self~doClause a = unit~clause( dc ) topRef = unit~newRef exitRef = unit~newRef d = unit~descriptor unit~loops[ dc ] = .Array~of( topRef, exitRef, d ) unit~emit( "BASE", d ) -- A simple DO ... END runs once (a LEAVE with its label ends it). If \ dc~isA( .Loop.Clause ), - \ dc~forever, dc~control == .Nil, dc~exprr == .Nil, - dc~exprw == .Nil, dc~expru == .Nil, dc~supplier == .Nil, - dc~ctr == .Nil Then Do unit~emit( "INDENT" ) unit~emit( "BPAUSE", a, 0, d ) unit~enter( self ) Do instruction Over self~instructions Call Gen instruction, unit End unit~leave unit~clause( self~endClause, "Q" ) If dc~name == .Nil Then unit~emit( "UNINDENT" ) Else unit~emit( "SETIND", d ) unit~emit( "TCLAUSE", unit~clauseNo( self~endClause ) ) unit~place( exitRef ) If dc~name \== .Nil Then Do unit~emit( "SETIND", d ) unit~emit( "JPAUSE", "E" ) End Return End tested = .False control = .Nil over = 0 with = .Nil -- COUNTER c: 0 when the loop starts, before its expressions (ooRexx's -- DoBlock); the number of the round when a round enters the body. counter = .Nil If dc~ctr \== .Nil Then Do counter = LoopTarget( dc~ctr, unit ) unit~emit( "DOCTR", d, "Z" ) Call LoopStore counter, unit unit~emit( "TRCTR", d ) End -- DO WITH [INDEX i] [ITEM v] OVER collection [FOR n]: the collection's -- SUPPLIER, asked when the loop starts (DOWITH); DONEXTW moves to the -- next item (or ends the loop), WITHSET assigns its index or item. If dc~supplier \== .Nil Then Do with = .Array~of( .Nil, .Nil ) If dc~index \== .Nil Then with[1] = LoopTarget( dc~index, unit ) If dc~item \== .Nil Then with[2] = LoopTarget( dc~item, unit ) Call CompileExpr dc~supplier, unit unit~emit( "KEYW", unit~const( "WITH" ) ) unit~emit( "DOWITH", d ) If dc~exprf \== .Nil Then Do Call CompileExpr dc~exprf, unit unit~emit( "DOFOR", d ) tested = .True End End -- DO x OVER collection [FOR n]: the items (the tails of a stem) are taken -- when the loop starts (DOOVER, DOOVERS); DONEXT assigns the next one. If dc~collection \== .Nil Then Do over = LoopTarget( dc~control, unit ) term = SingleExpression( dc~collection ) Call CompileExpr dc~collection, unit If term~isA( .Stem.Variable.Term ) Then unit~emit( "DOOVERS", d, unit~slot( term~symbol~value ) ) Else unit~emit( "DOOVER", d ) If dc~exprf \== .Nil Then Do Call CompileExpr dc~exprf, unit unit~emit( "DOFOR", d ) tested = .True End End Else If dc~control \== .Nil Then Do control = LoopTarget( dc~control, unit ) Call CompileExpr dc~expri, unit unit~emit( "DOSTART", d ) Loop kw Over dc~order~makeArray(" ") Select When kw == "TO" Then Do Call CompileExpr dc~exprt, unit unit~emit( "DOTO", d ) tested = .True End When kw == "BY" Then Do Call CompileExpr dc~exprb, unit unit~emit( "DOBY", d ) End When kw == "FOR" Then Do Call CompileExpr dc~exprf, unit unit~emit( "DOFOR", d ) tested = .True End Otherwise Nop End End If control[1] == "V" Then unit~emit( "DOINIT", d, control[2] ) Else Do unit~emit( "DOINITP", d ) Call LoopStore control, unit End End Else If dc~exprr \== .Nil Then Do Call CompileExpr dc~exprr, unit unit~emit( "DOREP", d ) tested = .True End overRef = unit~newRef doneRef = unit~newRef firstRef = unit~newRef unit~emit( "INDENT" ) unit~emit( "JMP", firstRef ) unit~place( topRef ) unit~emit( "SETIND", d ) unit~emit( "TCLAUSE", unit~clauseNo( dc ) ) unit~emit( "INDENT" ) -- UNTIL and the step of the control variable belong to the END: an error -- there is reported on it (as ooRexx does), though the trace shows the DO. If dc~expru \== .Nil | control \== .Nil Then Do unit~emit( "CLAUSE", unit~clauseNo( self~endClause ), "Q" ) If dc~expru \== .Nil Then Call CompileLoopCondition dc~expru, "UNTIL", unit, overRef If control \== .Nil Then Do If control[1] == "V" Then unit~emit( "DOSTEP", d, control[2] ) Else Do Call LoopLoad control, unit unit~emit( "DOSTEPP", d ) Call LoopStore control, unit End End End unit~emit( "CLAUSE", unit~clauseNo( dc ), "Q" ) -- OVER and WITH take the next item before FOR is tested (ooRexx: after -- the last round, the variable has the item that was not used). unit~place( firstRef ) If over \== 0 Then Do If over[1] == "V" Then unit~emit( "DONEXT", d, over[2], overRef ) Else Do unit~emit( "DOSKIP", d, overRef ) unit~emit( "DOITEM", d ) Call LoopStore over, unit End End If with \== .Nil Then Do unit~emit( "DONEXTW", d, overRef ) Loop k = 1 To 2 t = with[k] If t == .Nil Then Iterate which = SubStr( "IV", k, 1 ) If t[1] == "V" Then unit~emit( "WITHSET", d, t[2], which ) Else Do unit~emit( "WITHGET", d, which ) Call LoopStore t, unit End End End If tested Then unit~emit( "DOTEST", d, overRef ) If dc~exprw \== .Nil Then Call CompileLoopCondition dc~exprw, "WHILE", unit, overRef If counter \== .Nil Then Do unit~emit( "DOCTR", d, "N" ) Call LoopStore counter, unit unit~emit( "TRCTR", d ) End -- Interactive trace pauses after the checks of the first round; an ITERATE -- after those of the round it started. unit~emit( "DOPAUSE", a, d ) unit~emit( "JPAUSE", "R" ) unit~emit( "DOBODY", d ) unit~enter( self ) Do instruction Over self~instructions Call Gen instruction, unit End unit~leave unit~clause( self~endClause, "Q" ) unit~emit( "SETIND", d ) unit~emit( "TCLAUSE", unit~clauseNo( self~endClause ) ) unit~emit( "JMP", topRef ) -- The loop ends: its indentation goes back first, then the pause (ooRexx -- terminates the block before the pause of a first round that fails: a -- SIGNAL typed there keeps that indentation). unit~place( overRef ) unit~emit( "DOEXIT", d ) unit~emit( "DOPAUSE", a, d ) unit~emit( "JPAUSE", "E" ) unit~emit( "JMP", doneRef ) unit~place( exitRef ) unit~emit( "SETIND", d ) unit~emit( "JPAUSE", "E" ) unit~place( doneRef ) -- WHILE (a false one goes to 'outRef') or UNTIL (a true one does). Its value -- is traced with the keyword: a list is "1" when all its expressions are -- true (and stops at the first one that is not), its values traced as -- results. ::Routine CompileLoopCondition Use Strict Arg exprList, keyword, unit, outRef kw = unit~const( keyword ) If exprList~arg() == 1 Then Do Call Gen exprList~arg(1), unit unit~emit( "KEYW", kw ) If keyword == "WHILE" Then unit~emit( "JF", outRef, keyword ) Else unit~emit( "JT", outRef, keyword ) Return End failRef = unit~newRef goRef = unit~newRef Loop k = 1 To exprList~arg() Call Gen exprList~arg(k), unit unit~emit( "RES" ) unit~emit( "JF", failRef, "LIST" ) End unit~emit( "TRKEY", kw, unit~const( "1" ) ) If keyword == "WHILE" Then unit~emit( "JMP", goRef ) Else unit~emit( "JMP", outRef ) unit~place( failRef ) unit~emit( "TRKEY", kw, unit~const( "0" ) ) If keyword == "WHILE" Then unit~emit( "JMP", outRef ) unit~place( goRef ) /******************************************************************************/ /* SELECT */ /******************************************************************************/ ::Method "Select.Instruction::rcompile" Use Strict Arg unit sc = self~selectClause a = unit~clause( sc ) endRef = unit~newRef d = unit~descriptor unit~loops[ sc ] = .Array~of( .Nil, endRef, d ) unit~emit( "BASE", d ) caseNode = sc~case If caseNode \== .Nil Then Do Call CompileExpr caseNode, unit unit~emit( "KEYW", unit~const( "CASE" ) ) unit~emit( "CASE", d ) End unit~emit( "INDENT" ) unit~emit( "BPAUSE", a, 0, d ) Do triple Over self~whenThenInstructions when = triple[1] nextRef = unit~newRef w = unit~clause( when, "W" ) If caseNode == .Nil Then Call CompileCondition when~expressions, unit, nextRef, w, "WHEN" Else Do matchRef = unit~newRef exprs = when~expressions Loop k = 1 To exprs~arg() Call Gen exprs~arg(k), unit unit~emit( "CASEEQ", d ) unit~emit( "JT", matchRef, "CASE" ) End unit~emit( "BPAUSE", w, 0, 0 ) unit~emit( "JMP", nextRef ) unit~place( matchRef ) unit~emit( "BPAUSE", w, 0, 0 ) End unit~emit( "BOUND" ) Call CompileBranch triple[2], triple[3], unit, self unit~emit( "SETIND", d ) unit~emit( "JMP", endRef ) unit~place( nextRef ) End If self~otherwiseClause \== .Nil Then Do unit~emit( "BOUND" ) unit~clause( self~otherwiseClause, "W" ) unit~emit( "INDENT" ) unit~enter( self ) Do instruction Over self~otherwiseSequence Call Gen instruction, unit End unit~leave unit~clause( self~endClause, "Q" ) unit~emit( "SETIND", d ) unit~emit( "TCLAUSE", unit~clauseNo( self~endClause ) ) End Else Do unit~emit( "BOUND" ) unit~emit( "UNINDENT" ) unit~clause( self~endClause, "W" ) unit~emit( "ERR", "7.3", 0 ) End unit~place( endRef ) unit~emit( "SETIND", d ) unit~emit( "JPAUSE", "E" ) /******************************************************************************/ /* LEAVE and ITERATE: jumps to the target the parser found. One that has no */ /* target is 28.x, reported at the indentation ooRexx reports it at */ /* (failedJumpOffset): the activation's plus an offset, or where it */ /* is (-1). */ /******************************************************************************/ ::Method "Leave.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) Call CompileJump self, "LEAVE", unit ::Method "Iterate.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) Call CompileJump self, "ITERATE", unit -- LEAVE or ITERATE. Interactive trace pauses where the jump lands (JPAUSE, at -- the end of the block for LEAVE; after the checks of the next round, or at -- the end of the loop, for ITERATE), and "=" there runs the instruction -- again from THERE, where its block may be gone. JMARK c r e records the -- jump (when pausing): r is where "=" goes when the loop goes on (JPAUSE R), -- e when it is over (JPAUSE E). Those "redo" pieces are compiled out of line -- (RVM.Unit~redo): each traces the clause again and jumps as the instruction -- would from outside the block it left (the next loop out, the block with -- that name, or 28.x). ::Routine CompileJump Use Strict Arg instruction, kind, unit c = unit~clauseNo( instruction ) If kind == "LEAVE" Then Do; code = "28.1"; named = "28.3"; End Else Do; code = "28.2"; named = "28.4"; End name = .Nil If instruction~name \== .Nil Then Do name = instruction~name~value code = named k = unit~const( name ) End Else k = 0 offset = unit~failedJumpOffset target = instruction~iteration If target \== .Nil Then refs = unit~loops[ target ] Else refs = .Nil If refs == .Nil Then Do unit~emit( "ERRJ", code, k, offset ) Return End blocks = unit~blocks -- ITERATE naming a SELECT or a simple DO: 28.5 when it runs. ooRexx ends -- the blocks inside the target first, so the indentation is the one the -- outermost of them started at (its descriptor's base), or where it is. If kind == "ITERATE", - ( target~isA( .Select.Clause ) | target~isA( .Simple.Do.Clause ) ) - Then Do inner = .Nil found = .False Do ins Over blocks If found, inner == .Nil, BlockClause( ins ) \== .Nil Then inner = unit~loops[ BlockClause( ins ) ][3] If BlockClause( ins ) == target Then found = .True End If inner \== .Nil Then unit~emit( "SETIND", inner ) unit~emit( "ERRJ", "28.5", k, -1 ) Return End -- The blocks outside the target. outer = .Array~new Do ins Over blocks If BlockClause( ins ) == target Then Leave outer~append( ins ) End e = unit~redo( kind, c, name, outer, code, k, offset ) If kind == "LEAVE" Then r = e Else r = unit~redoHere( kind, c, name, outer, code, k, offset, target ) unit~emit( "JMARK", c, r, e ) If kind == "LEAVE" Then unit~emit( "JMP", refs[2] ) Else unit~emit( "JMP", refs[1] ) -- The clause a block is known by in unit~loops. ::Routine BlockClause Public Use Strict Arg ins If ins~isA( .Iterative.Instruction ) Then Return ins~doClause If ins~isA( .Select.Instruction ) Then Return ins~selectClause Return .Nil -- Is a DO clause a loop (not a simple DO ... END)? ::Routine IsLoop Public Use Strict Arg dc If dc~isA( .Loop.Clause ) Then Return 1 If dc~forever Then Return 1 If dc~control \== .Nil | dc~exprr \== .Nil Then Return 1 If dc~exprw \== .Nil | dc~expru \== .Nil Then Return 1 Return 0 -- The block in 'blocks' (innermost first) that a LEAVE or ITERATE with no -- name ('name' .Nil) or with 'name' goes to: an -- unnamed one, the innermost loop; a named one, the block whose label (or, -- for a DO, control variable) it is. ITERATE only goes to loops. Returns its -- index, or 0. ::Routine JumpTarget Public Use Strict Arg blocks, kind, name Do i = blocks~items To 1 By -1 ins = blocks[i] If ins~isA( .Iterative.Instruction ) Then Do dc = ins~doClause loop = IsLoop( dc ) If kind == "ITERATE", \ loop Then Iterate If name == .Nil Then Do If loop Then Return i Iterate End n = dc~name If n == .Nil Then n = dc~control If n \== .Nil, n~value == name Then Return i End Else If ins~isA( .Select.Instruction ) Then Do If name == .Nil | kind == "ITERATE" Then Iterate n = ins~selectClause~name If n \== .Nil, n~value == name Then Return i End End Return 0 /******************************************************************************/ /* TRACE */ /******************************************************************************/ ::Method "Trace.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) If self~number \== .Nil Then Do -- TRACE n: the parser keeps the sign of TRACE -n apart. n = self~number~value If TheElementBefore( self~number ) < .EL.OP.MINUS Then n = -n unit~emit( "TRACEN", unit~const( n ) ) Return End Select When self~expression \== .Nil Then Do Call CompileExpr self~expression, unit unit~emit( "KEYW", unit~const( "VALUE" ) ) unit~emit( "TRACEV" ) unit~emit( "TPAUSE", a ) Return End When self~symbol \== .Nil Then setting = self~symbol~value When self~theString \== .Nil Then setting = self~theString~value Otherwise setting = "" End unit~emit( "TRACE", unit~const( setting ) ) unit~emit( "TPAUSE", a ) /******************************************************************************/ /* CALL, PROCEDURE, SIGNAL */ /******************************************************************************/ ::Method "Call.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) name = self~name n = CompileArgs( self~arguments, unit ) Select Case name~subCategory When .INTERNAL.SUBROUTINE.NAME Then unit~emit( "CALLI", unit~const( name~value ), n, KeywordLine( self, "CALL" ) ) When .BUILTIN.SUBROUTINE.NAME Then unit~emit( "CALLB", unit~const( name~value ), n ) Otherwise unit~emit( "CALLX", unit~const( name~value ), n ) End unit~emit( "PAUSE", a ) -- CALL ns:name args: a public routine of the package tagged ns (CALLNS). ::Method "NameSpace.Qualified.Call.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) n = CompileArgs( self~arguments, unit ) unit~emit( "CALLNS", unit~const( Upper( self~nameSpace~value ) ), - unit~const( Upper( self~name~value ) ), n ) unit~emit( "PAUSE", a ) -- CALL (expr): a label, matched verbatim, else a built-in function. ::Method "Call.Value.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) Call CompileExpr self~expression, unit unit~emit( "RES" ) n = CompileArgs( self~arguments, unit ) unit~emit( "CALLN", n, KeywordLine( self, "CALL" ) ) unit~emit( "PAUSE", a ) -- PROCEDURE [EXPOSE ...]: the tails of the exposed compounds are worked out -- first (in the caller's frame), then PROC installs the fresh frame and -- exposes, in order: S slot (simple), T slot (stem), C slot n (compound, the -- n pieces of its tail on the stack). ::Method "Procedure.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) -- In INTERPRET data, PROCEDURE is never the first instruction of a routine. If .RVM.Fragments~of( self~begin ) \== .Nil Then Do unit~emit( "ERR", "17.1", 0 ) Return End -- PROC installs the fresh frame; then each exposed variable, in order: -- EXPV (simple), EXPS (stem), EXPC (compound: its tail is worked out in -- the CALLER's frame, TAILC; the name is for the trace), and for an -- indirect list, (x), EXPV x and then EXPI x (the names in its value). unit~emit( "PROC" ) exposed = self~exposed If exposed \== .Nil Then Do term Over ExposeOrder( exposed ) Select When term~isA( .Array ) Then Do slot = unit~slot( term[1]~value~value ) unit~emit( "EXPV", slot ) unit~emit( "EXPI", slot ) End When term~isA( .Stem.Variable.Term ) Then unit~emit( "EXPS", unit~slot( Upper( term~symbol~value ) ) ) When term~isA( .Compound.Variable.Term ) Then Do n = CompileTail( term, unit, "TAILC" ) unit~emit( "EXPC", unit~slot( term~parts[1]~value ), n, - unit~const( CompoundTraceName( term ) ) ) End Otherwise unit~emit( "EXPV", unit~slot( term~value~value ) ) End End unit~emit( "PAUSE", a ) -- The order ooRexx exposes in (its parser pushes the variables and queues -- the lists, and the instruction takes them back from the end): the lists -- first, the last one first, and then the variables, in order. ::Routine ExposeOrder Use Strict Arg terms lists = .Array~new others = .Array~new Do term Over terms If term~isA( .Array ) Then lists~insert( term, .Nil ) Else others~append( term ) End Return lists~appendAll( others ) ::Method "Signal.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) unit~emit( "SIGNAL", unit~const( self~label~value ), ElementLine( self~label ) ) ::Method "Signal.Value.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) Call CompileExpr self~expression, unit unit~emit( "KEYW", unit~const( "VALUE" ) ) unit~emit( "SIGNALV", KeywordLine( self, "SIGNAL" ) ) /******************************************************************************/ /* PARSE, ARG, PULL */ /* */ /* PSRC sets the sources of the parse (the arguments, a line, a value). For */ /* each template, PTPL k takes the k-th source; then every trigger moves the */ /* cursor (PEND, PABS, PFWD, PBWD, PFLEN, PBLEN, PSRCH) and its variables get */ /* their pieces (PWORD, PREST; PDOTW, PDOTR for a "."). The grouping of the */ /* template into (trigger, variables) sections is done here, once. */ /******************************************************************************/ ::Method "Parse.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) variant = self~variant flags = self~upper~?( "U", "" )self~lower~?( "L", "" )self~caseless~?( "C", "" ) If flags == "" Then flags = "-" Select Case variant -- The variable: a simple one, a stem or a compound (its tail resolved -- now, as a loop variable's: LoopLoad). When "VAR" Then Do target = LoopTarget( self~varName, unit ) If target[1] == "V" Then unit~emit( "LOADV", target[2] ) Else Call LoopLoad target, unit End When "VALUE" Then Call CompileExpr self~expression, unit Otherwise Nop End -- PSRCV takes its source from the stack (VAR, VALUE); PSRC does not. If variant == "VAR" | variant == "VALUE" Then unit~emit( "PSRCV", variant, flags ) Else unit~emit( "PSRC", variant, flags ) Call CompileTemplates self~templates, unit unit~emit( "PAUSE", a ) ::Method "Arg.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) unit~emit( "PSRC", "ARG", "U" ) Call CompileTemplates self~templates, unit unit~emit( "PAUSE", a ) ::Method "Pull.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) unit~emit( "PSRC", "PULL", "U" ) Call CompileTemplates self~templates, unit unit~emit( "PAUSE", a ) ::Routine CompileTemplates Use Strict Arg templates, unit n = 1 If templates \== .Nil Then n = Max( 1, templates~items ) Do k = 1 To n unit~emit( "PTPL", k ) If templates == .Nil Then Iterate If \ templates~hasIndex( k ) Then Iterate If templates[ k ] \== .Nil Then Call CompileTemplate templates[ k ], unit End ::Routine CompileTemplate Use Strict Arg tpl, unit pending = .Array~new sections = .Array~new Do i = 1 To tpl~items item = tpl[i] If IsParseTrigger( item ) Then Do sections~append( .Array~of( item, pending ) ) pending = .Array~new End Else pending~append( item ) End If pending~items > 0 Then sections~append( .Array~of( .Nil, pending ) ) Do sec Over sections Call CompileTrigger sec[1], unit vars = sec[2] n = vars~items Do i = 1 To n v = vars[i] isLast = ( i == n ) Select When v == .Nil Then kind = "." When v~isA( .Symbol.Term ) Then kind = "V" When v~isA( .Compound.Variable.Term ) Then kind = "C" When v~isA( .Stem.Variable.Term ) Then kind = "S" When IsMessageTerm( v ) Then kind = "M" Otherwise kind = "." End op = isLast~?( "PREST", "PWORD" ) Select Case kind When "." Then unit~emit( isLast~?( "PDOTR", "PDOTW" ) ) When "V" Then unit~emit( op, unit~slot( v~value~value ) ) -- A compound: its tail is worked out now (after the variables before -- it in the template are assigned). When "C" Then Do m = CompileTail( v, unit ) unit~emit( op"C", unit~slot( v~parts[1]~value ), m, - unit~const( CompoundTraceName( v ) ) ) End -- A stem: the whole stem is assigned. When "S" Then unit~emit( op"S", unit~slot( Upper( v~symbol~value ) ) ) -- A message term: the piece (twice), sent to it (NAME=), and then -- traced as ooRexx's ParseTrigger does, after the assignment (PTRM). When "M" Then Do unit~emit( op"M" ) Call MessageTargetStore v, unit unit~emit( "PTRM" ) End End End End ::Routine IsParseTrigger Use Strict Arg item If item~isA( .Symbol.Term ) Then Return 0 If item~isA( .Compound.Variable.Term ) Then Return 0 If item~isA( .Stem.Variable.Term ) Then Return 0 If IsMessageTerm( item ) Then Return 0 If item~isA( .Element ), item < .EL.PARSE_PERIOD Then Return 0 Return 1 ::Routine CompileTrigger Use Strict Arg item, unit If item == .Nil Then Do unit~emit( "PEND" ) Return End If item~isA( .Prefixed.Template ) Then Do eos = item~elementOrSubExpression If eos~isA( .Element ) Then unit~emit( "PUSHC", unit~const( eos~value ) ) Else Call Gen eos, unit unit~emit( "RES" ) Select Case item~prefix~value When "=" Then unit~emit( "PABS" ) When "+" Then unit~emit( "PFWD" ) When "-" Then unit~emit( "PBWD" ) When ">" Then unit~emit( "PFLEN" ) When "<" Then unit~emit( "PBLEN" ) End Return End -- A number, or a constant symbol ("1y": ooRexx's isNumericSymbol; it is -- 26.4 when it runs). If item~isA( .Element ), item < ( .ALL.NUMBERS || .ALL.CONST_SYMBOLS ) Then Do unit~emit( "PUSHC", unit~const( item~value ) ) unit~emit( "RES" ) unit~emit( "PABS" ) Return End If item~isA( .Element ), item < .ALL.STRINGS Then unit~emit( "PUSHC", unit~const( item~value ) ) Else If item~isA( .Subexpression ) Then Call Gen item, unit Else unit~emit( "PUSHC", unit~const( "" ) ) unit~emit( "RES" ) unit~emit( "PSRCH" ) /******************************************************************************/ /* INTERPRET */ /* */ /* INTERP n runs the value on the stack as Rexx code: the RVM compiles it */ /* (RVM.Compiler~extend, once per INTERPRET and string), appended to the */ /* program, ending with IEND, which goes back after the INTERPRET. n is the */ /* clause of the INTERPRET. */ /******************************************************************************/ ::Method "Interpret.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) Call CompileExpr self~expression, unit unit~emit( "RES" ) unit~emit( "IPAUSE", a ) unit~emit( "INTERP", unit~clauseNo( self ) ) /******************************************************************************/ /* ADDRESS, commands, OPTIONS */ /* */ /* A WITH clause becomes an entry of the unit's table of redirections: for */ /* each stream given, (stream, type, option, kind, value), where kind is */ /* STEM (a stem name), STR (a string), USTEM (USING a stem) or THUNK: an */ /* expression (parenthesised, or an environment symbol), */ /* compiled apart (jumped over) and ending with YIELD, that the RVM runs */ /* each time a command needs the value. */ /******************************************************************************/ ::Routine CompileWith Use Strict Arg instruction, unit If \ instruction~with Then Return 0 entries = .Array~new Do stream Over .Array~of( "INPUT", "OUTPUT", "ERROR" ) type = instruction~redirectionType( stream ) If type == "" Then Iterate option = instruction~redirectionOption( stream ) If option == "" Then option = "-" target = instruction~redirectionTarget( stream ) kind = "-"; value = "" Select When type == "NORMAL" Then Nop When type == "STEM" Then Do; kind = "STEM"; value = target~value; End Otherwise Do node = target Loop While node~isA( .SubExpression ) node = node~subexpression End Select When type == "USING", node~isA( .Stem.Variable.Term ) Then Do kind = "USTEM"; value = node~symbol~value End -- An environment symbol (.local) is evaluated: a THUNK. When target~isA( .Element ), target < .EL.ENVIRONMENT_SYMBOL Then Nop When target~isA( .Element ) Then Do kind = "STR"; value = target~value End Otherwise Nop End If kind == "-" Then Do overRef = unit~newRef unit~emit( "JMP", overRef ) kind = "THUNK" value = unit~here If target~isA( .Element ) Then unit~emit( "ENV", unit~const( target~value ) ) Else Call Gen target, unit unit~emit( "YIELD" ) unit~place( overRef ) End End End entries~append( .Array~of( stream, type, option, kind, value ) ) End unit~withs~append( entries ) Return unit~withs~items ::Method "Address.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) If self~environment == .Nil, self~env_expression == .Nil Then Do unit~emit( "ADDRT" ) unit~emit( "PAUSE", a ) Return End spec = CompileWith( self, unit ) If self~environment == .Nil Then Do Call CompileExpr self~env_expression, unit unit~emit( "RES" ) unit~emit( "ADDRV", spec ) unit~emit( "PAUSE", a ) Return End name = unit~const( self~environment~value ) If self~expression \== .Nil Then Do Call CompileExpr self~expression, unit unit~emit( "CMDTO", name, spec ) unit~emit( "CPAUSE", a ) Return End unit~emit( "ADDRS", name, spec ) unit~emit( "PAUSE", a ) ::Method "Command.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) Call CompileExpr self~expression, unit unit~emit( "CMD" ) unit~emit( "CPAUSE", a ) ::Method "Options.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) If self~expression \== .Nil Then Do Call CompileExpr self~expression, unit unit~emit( "STR" ) unit~emit( "RES" ) unit~emit( "POP" ) End unit~emit( "PAUSE", a ) /******************************************************************************/ /* CONDITIONS: SIGNAL ON/OFF, CALL ON/OFF, RAISE */ /******************************************************************************/ -- The name a trap is filed under: the condition, or "USER name". ::Routine ConditionKey Use Strict Arg node name = node~condition~value If name == "USER" Then name = "USER" node~userCondition~value Return name -- The label a trap goes to without NAME: the condition's own name. ::Routine DefaultTrapTarget Use Strict Arg node If node~condition~value == "USER" Then Return node~userCondition~value Return node~condition~value ::Method "Signal.On.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) If self~label == .Nil Then target = DefaultTrapTarget( self ) Else target = self~label~value unit~emit( "TRAPON", unit~const( ConditionKey( self ) ), "S", unit~const( target ) ) ::Method "Call.On.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) If self~trapName == .Nil Then target = DefaultTrapTarget( self ) Else target = self~trapName~value unit~emit( "TRAPON", unit~const( ConditionKey( self ) ), "C", unit~const( target ) ) ::Method "Signal.Off.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) unit~emit( "TRAPOFF", unit~const( ConditionKey( self ) ) ) ::Method "Call.Off.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) unit~emit( "TRAPOFF", unit~const( ConditionKey( self ) ) ) -- RAISE name form n. The operands are always on the stack, in this order: -- the code, DESCRIPTION, ADDITIONAL, the n ARRAY items (n = -1: no ARRAY), -- the RETURN/EXIT value; an operand not given is NONE. Each one given is -- traced with its keyword as it is evaluated. name is 0 for PROPAGATE; form -- is RETURN or EXIT. ::Method "Raise.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) If self~propagate Then name = 0 Else Do key = self~condition~value If key == "USER" Then key = "USER" self~userCondition~value name = unit~const( key ) End If self~code \== .Nil Then Do Call RaiseOperand self~code, unit If self~propagate Then unit~emit( "KEYWC" ) Else unit~emit( "KEYW", name ) End Else unit~emit( "PUSHNONE" ) If self~description \== .Nil Then Do Call RaiseOperand self~description, unit, .True unit~emit( "KEYW", unit~const( "DESCRIPTION" ) ) End Else unit~emit( "PUSHNONE" ) If self~additional \== .Nil Then Do Call RaiseOperand self~additional, unit, .True unit~emit( "KEYW", unit~const( "ADDITIONAL" ) ) End Else unit~emit( "PUSHNONE" ) n = -1 If self~array \== .Nil Then n = ArrayItems( self~array, unit, .True ) If self~return \== .Nil Then Do form = "RETURN" resultNode = self~return End Else Do form = "EXIT" resultNode = self~exit End If resultNode \== .Nil, resultNode \== "" Then Do Call RaiseOperand resultNode, unit, .True unit~emit( "KEYW", unit~const( "RESULT" ) ) End Else unit~emit( "PUSHNONE" ) unit~emit( "RAISE", name, form, n ) -- The INDEX or ITEM variable of a DO WITH: its slot (a simple variable). /******************************************************************************/ /* The variables of a loop (its control variable, COUNTER, the INDEX and ITEM */ /* of DO WITH) are elements: a simple variable (V and its slot), a stem (S */ /* and its slot) or a compound (C, 0 and the element). A simple one has */ /* instructions of its own (DOINIT, DOSTEP, DONEXT, WITHSET); the others are */ /* stored as an assignment stores them (LoopStore: the value is on the */ /* stack; a compound's tail is resolved then). */ /******************************************************************************/ ::Routine LoopTarget Use Strict Arg element, unit If element < .ALL.SIMPLE_VARIABLES Then Return .Array~of( "V", unit~slot( element~value ), element ) If element < .ALL.STEM_VARIABLES Then Return .Array~of( "S", unit~slot( element~value ), element ) Return .Array~of( "C", 0, element ) ::Routine LoopStore Use Strict Arg target, unit Select Case target[1] When "V" Then unit~emit( "STOREV", target[2] ) When "S" Then unit~emit( "STORES", target[2] ) Otherwise Do name = target[3]~value Parse Var name stem "." tail n = ElementTail( tail, unit ) unit~emit( "STOREC", unit~slot( stem"." ), n, unit~const( name ) ) End End -- The value of a loop variable that is a stem or a compound (DOSTEPP). ::Routine LoopLoad Use Strict Arg target, unit If target[1] == "S" Then unit~emit( "LOADS", target[2] ) Else Do name = target[3]~value Parse Var name stem "." tail n = ElementTail( tail, unit ) unit~emit( "LOADC", unit~slot( stem"." ), n, unit~const( name ) ) End -- The pieces of the tail of a compound that is an element (the text after -- its first dot), pushed as CompileTail pushes them: the variables with -- TAILV, the constants and the dots joined. Returns how many. ::Routine ElementTail Use Strict Arg tail, unit n = 0 pending = "" Do While tail \== "" p = Pos( ".", tail ) If p == 0 Then Do fragment = tail tail = "" dot = "" End Else Do fragment = Left( tail, p - 1 ) tail = SubStr( tail, p + 1 ) dot = "." End If fragment \== "", DataType( fragment, "Variable" ) Then Do If pending \== "" Then Do unit~emit( "PUSHQ", unit~const( pending ) ) n += 1 pending = "" End unit~emit( "TAILV", unit~slot( fragment ) ) n += 1 pending = dot End Else pending ||= fragment || dot End If pending \== "" | n == 0 Then Do unit~emit( "PUSHQ", unit~const( pending ) ) n += 1 End Return n -- The items of an ARRAY (...) of RAISE or FORWARD, each traced as an -- argument (an omitted one is NONE), then the keyword; how many. RAISE -- traces each item twice (as ooRexx does). ::Routine ArrayItems Use Strict Arg node, unit, twice n = 0 If node \== "" Then Do If node~isA( .SubExpression ) Then node = node~subexpression If \ node~isA( .Expression.List ), \ node~isA( .Array.Term ), - \ node~isA( .Arguments ) Then Do Call Gen node, unit unit~emit( "TRARG" ) If twice Then unit~emit( "TRARG" ) n = 1 End Else Do n = node~arg() Loop k = 1 To n e = node~arg(k) If e \== .Nil Then Do Call Gen e, unit unit~emit( "TRARG" ) If twice Then unit~emit( "TRARG" ) End Else Do unit~emit( "PUSHNONE" ) unit~emit( "TRARG" ) End End End End unit~emit( "TRKEY", unit~const( "ARRAY" ), unit~const( "an Array" ) ) Return n /******************************************************************************/ /* CONCURRENCY */ /******************************************************************************/ -- GUARD ON | OFF [WHEN expression]: GUARD ON|OFF; with WHEN, the expression -- (a list is 1 when all its items are: each is traced as a result), and -- GWHEN top k: 0 waits for a change of the variables k and goes back to top. -- k are the variables of the expression the method exposes (ooRexx's -- captureGuardVariable: the simple variables, the tails' and the stems, of a -- compound too, that EXPOSE names, or that USE LOCAL does not); none is -- 99.913, which the parser raises when it translates, as ooRexx (the ERR -- here is a guard: it should not be reached). ::Method "Guard.Instruction::rcompile" Expose on expression Use Strict Arg unit a = unit~clause( self ) If expression \== .Nil Then Do code = unit~code start = code~items + 1 End unit~emit( "GUARD", on~?( "ON", "OFF" ) ) If expression \== .Nil Then Do top = unit~newRef unit~place( top ) first = code~items + 1 If expression~isA( .Expression.List ), expression~arg() > 1 Then Do failRef = unit~newRef okRef = unit~newRef Loop k = 1 To expression~arg() Call Gen expression~arg(k), unit unit~emit( "RES" ) unit~emit( "JF", failRef, "LIST" ) End unit~emit( "PUSHQ", unit~const( "1" ) ) unit~emit( "JMP", okRef ) unit~place( failRef ) unit~emit( "PUSHQ", unit~const( "0" ) ) unit~place( okRef ) End Else Call CompileExpr expression, unit names = GuardNames( unit, first, self ) If names == "" Then Do Do While code~items >= start code~delete( code~items ) End unit~emit( "ERR", "99.913", 0 ) Return End unit~emit( "GWHEN", top, unit~const( names ) ) End unit~emit( "PAUSE", a ) -- The variables GUARD WHEN watches (see above): those the code from -- 'first' on reads, that the method (the body) exposes before 'guard'. ::Routine GuardNames Use Strict Arg unit, first, guard exposed = .Nil locals = .Nil If unit~body \== .Nil Then Do instruction Over unit~body~instructions If instruction == guard Then Leave If instruction~isA( .Expose.Instruction ) Then Do If exposed == .Nil Then exposed = .Set~new Do term Over instruction~exposed Select When term~isA( .Array ) Then Nop When term~isA( .Stem.Variable.Term ) Then exposed~put( Upper( term~symbol~value ) ) When term~isA( .Compound.Variable.Term ) Then exposed~put( Upper( CompoundTraceName( term ) ) ) Otherwise exposed~put( Upper( term~value~value ) ) End End End If instruction~isA( .Use.Local.Instruction ) Then Do locals = .Set~of( "SELF", "SUPER", "RC", "RESULT", "SIGL" ) Do name Over instruction~local locals~put( Upper( name~value ) ) End End End names = "" code = unit~code Do k = first To code~items ins = code[ k ] If WordPos( ins[1], "LOADV LOADC LOADS TAILV" ) == 0 Then Iterate name = unit~names[ ins[2] ] Select When exposed \== .Nil Then ok = exposed~hasIndex( name ) When locals \== .Nil Then ok = \ locals~hasIndex( name ) Otherwise ok = .False End If ok, WordPos( name, names ) == 0 Then names = names name End Return Strip( names ) -- REPLY [expression]: REPLY, or REPLYV with its value. ::Method "Reply.Instruction::rcompile" Use Strict Arg unit a = unit~clause( self ) If self~expression == .Nil Then unit~emit( "REPLY" ) Else Do Call CompileExpr self~expression, unit unit~emit( "RES" ) unit~emit( "REPLYV" ) End unit~emit( "PAUSE", a ) -- FORWARD c n. The operands are on the stack in this order: TO, MESSAGE, -- CLASS, ARGUMENTS (each NONE when not given), then the n items of ARRAY -- (n = -1: no ARRAY). Each one given is traced with its keyword as it is -- evaluated. c is 1 for CONTINUE. ::Method "Forward.Instruction::rcompile" Use Strict Arg unit unit~clause( self ) unit~emit( "FWDOK" ) -- in a method? (before the operands) Call ForwardOperand self~to, "TO", unit Call ForwardOperand self~message, "MESSAGE", unit Call ForwardOperand self~theClass, "CLASS", unit Call ForwardOperand self~arguments, "ARGUMENTS", unit n = -1 If self~array \== .Nil Then n = ArrayItems( self~array, unit, .False ) continue = 0 If self~continue \== .Nil Then continue = 1 unit~emit( "FWD", continue, n ) ::Routine ForwardOperand Use Strict Arg operand, keyword, unit If operand == .Nil Then Do unit~emit( "PUSHNONE" ) Return End Call RaiseOperand operand, unit, .True unit~emit( "KEYW", unit~const( keyword ) ) -- A RAISE operand: a constant as written, or an expression (its string; as -- it is -- an object stays one -- when 'keep': all but the code). ::Routine RaiseOperand Use Strict Arg operand, unit, keep = .False If operand~isA( .Element ) Then Do unit~emit( "PUSHC", unit~const( operand~value ) ) Return End Call Gen operand, unit If \ keep Then unit~emit( "STR" ) /******************************************************************************/ /* RVM.Compiler -- the entry point */ /******************************************************************************/ ::Class RVM.Compiler Public -- The version of the compiler, written in the R-code it makes (see -- RVM.RCode~write): an R-code cache made by another version is not used. -- It goes up whenever what the compiler writes changes (see -- doc/04-rcode.md). ::Constant VERSION "0.3" -- The parser's frontier stamp: the first line of bin/resources/frontier (an -- integer the Rexx Parser raises whenever something the compiler consumes -- changes: the AST, the BIF table, the error texts, the parser options, the -- error directory), or 0 if there is no such file. Written next to VERSION -- in the R-code, so that a cache made against another parser is not used. ::Method frontier Class Expose frontier If Var( "frontier" ) Then Return frontier frontier = 0 loc = FileSpec( "Location", .context~package~name ) sep = Right( loc, 1 ) tail = "modules"sep"rvm"sep If Right( loc, Length( tail ) ) == tail Then loc = Left( loc, Length( loc ) - Length( tail ) ) file = loc"resources"sep"frontier" If Stream( file, "C", "Query Exists" ) == "" Then Return frontier line = LineIn( file )~strip Call Stream file, "C", "Close" If line \== "" Then frontier = line Return frontier -- Compile a parsed package (a Rexx.Parser's ~package) to an RVM.Unit. -- 'source' is the array of source lines (for the clause texts), 'name' the -- program's name. ::Method compile Class Use Strict Arg package, source, name unit = .RVM.Unit~new( source, name ) Call CompileOptions package, unit Call CompileAnnotations package, unit body = package~prolog~body unit~body = body unit~prolog = Extent( "1 1", body ) Do instruction Over body~instructions Call Gen instruction, unit End unit~flushRedos Call CompileDirectives package, unit unit~resolveAnnotations unit~finish Return unit -- Compile INTERPRET data (a parsed package) at the end of a loaded program: -- the unit shares the program's code, constants, names, clauses and -- redirections, and appends to them. The data ends with IEND returnTo -- clause. Returns the address it starts at. New clauses are appended as -- .Array~of( line, text ), new redirections as their entries: the RVM turns -- them into its own objects. -- A line typed at an interactive trace pause is compiled the same way -- (returnTo 0), and ends with DEND, back to the pause. ::Method extend Class Use Strict Arg package, program, source, returnTo, clause unit = .RVM.Unit~new( source, program~name ) unit~share( program ) start = unit~here body = package~prolog~body unit~body = body Do instruction Over body~instructions If instruction~isA( .Implicit.Exit.Instruction ) Then Leave Call Gen instruction, unit End If returnTo == 0 Then unit~emit( "DEND" ) Else unit~emit( "IEND", returnTo, clause ) unit~flushRedos unit~finish( start ) program~descriptors = unit~descriptors Return start -- Compile INTERPRET data (or a line typed at a pause: kind "D") as a -- fragment of its own, for an RVM that cannot compile (the JS RVM, through -- "rvm -f"): its own constants, names, clauses, descriptors and -- redirections, numbered from 1, and its code from address 1, ending with -- IEND 0 0 (the RVM puts the address to go back to and the clause) or DEND. -- The RVM relocates it when it appends it to the program (see rcode.mjs). ::Method fragment Class Use Strict Arg package, source, name, kind unit = .RVM.Unit~new( source, name ) unit~markExtended body = package~prolog~body unit~body = body Do instruction Over body~instructions If instruction~isA( .Implicit.Exit.Instruction ) Then Leave Call Gen instruction, unit End If kind == "D" Then unit~emit( "DEND" ) Else unit~emit( "IEND", 0, 0 ) unit~flushRedos unit~finish Return unit /******************************************************************************/ /* RVM.Unit -- a compiled program, and the state of the compiler */ /******************************************************************************/ ::Class RVM.Unit Public ::Attribute code -- Array of instructions: .Array~of( op, operands... ) ::Attribute consts -- the constant pool (strings) ::Attribute names -- slot -> name (a stem is "A.") ::Attribute clauses -- clause -> .Array~of( line, text ) ::Attribute labels -- label name -> address (the first one wins) ::Attribute name -- the program's name ::Attribute descriptors -- how many loop / SELECT descriptors are used ::Attribute withs -- the redirections of ADDRESS ... WITH (see CompileWith) ::Attribute classes -- the CLASSES entries (text) ::Attribute methods -- the METHODS entries: .Array~of( class, which, name, kind, value, labels ) ::Attribute routines -- the ROUTINES entries (text) ::Attribute requires -- the REQUIRES entries (text) ::Attribute annotations -- the ANNOTATIONS: .Array~of( target, name, value ), -- a target .Array~of( P|C|R|M, number ) ::Attribute resources -- the RESOURCES: .Array~of( NAME, lines ), in order ::Attribute prolog -- where the prolog's source is (see Extent) ::Attribute body -- the body being compiled (a Code.Body), or .Nil ::Attribute options -- the package's ::OPTIONS (see ApplyOptions) ::Method init Expose code consts names clauses labels name descriptors - constIndex nameIndex clauseIndex refs loops helper withs blocks extended - redos Use Strict Arg source, name self~prolog = "-" self~body = .Nil self~options = .Directory~new Do k Over .Array~of( "DIGITS 9", "FUZZ 0", "FORM SCIENTIFIC", "TRACE N", - "NUMERIC NOINHERIT", "PROLOG 1", "EXPLICIT -" ) Parse Var k key value self~options[ key ] = value End self~classes = .Array~new self~methods = .Array~new self~routines = .Array~new self~requires = .Array~new self~annotations = .Array~new self~resources = .Array~new redos = .Array~new blocks = .Array~new extended = .False code = .Array~new consts = .Array~new names = .Array~new clauses = .Array~new labels = .Table~new descriptors = 0 withs = .Array~new constIndex = .Table~new nameIndex = .Table~new clauseIndex = .IdentityTable~new refs = .Array~new loops = .IdentityTable~new -- A context only to compute the clause texts (line, text), as the runtime -- does. helper = .RVM.BaseContext~new helper~sourceLines = source -- Emit an instruction. Returns its address. ::Method emit Expose code op = .Array~new Do i = 1 To Arg() op[i] = Arg(i) End code~append( op ) Return code~items ::Method here Expose code Return code~items + 1 -- The index of a constant in the pool (each value once). ::Method const Expose consts constIndex Use Strict Arg value value = value~string k = constIndex[ value ] If k \== .Nil Then Return k consts~append( value ) constIndex[ value ] = consts~items Return consts~items -- The slot of a variable name (a stem is "A."). ::Method slot Expose names nameIndex Use Strict Arg name k = nameIndex[ name ] If k \== .Nil Then Return k names~append( name ) nameIndex[ name ] = names~items Return names~items -- A new loop / SELECT descriptor. ::Method descriptor Expose descriptors descriptors += 1 Return descriptors -- A new jump label of the compiler (an RVM.Ref, resolved by finish). ::Method newRef Expose refs ref = .RVM.Ref~new refs~append( ref ) Return ref ::Method place Use Strict Arg ref ref~address = self~here -- The clause table index of an AST clause (entered once). ::Method clauseNo Expose clauses clauseIndex helper Use Strict Arg clause k = clauseIndex[ clause ] If k \== .Nil Then Return k info = helper~clauseText( clause ) clauses~append( .Array~of( info[1], info[2] ) ) clauseIndex[ clause ] = clauses~items Return clauses~items -- A clause starts: its labels (defined here, and traced), then CLAUSE n k. -- k says how it is traced: N (TRACE A, R, I), C (a command: TRACE C too), -- W (a part of a block: no labels), X (never), Q (not traced, not even a -- boundary of its own: an END). ::Method clause Expose labels Use Strict Arg clause, kind = "" If kind == "" Then Do Select When clause~isA( .Command.Instruction ) Then kind = "C" When clause~isA( .Address.Instruction ), - clause~environment \== .Nil, clause~expression \== .Nil Then kind = "C" When clause~isA( .Implicit.Exit.Instruction ) Then kind = "X" Otherwise kind = "N" End End If kind \== "W", kind \== "Q", clause~labels \== .Nil Then Do lab Over clause~labels key = lab~label~value If \ labels~hasIndex( key ) Then labels[ key ] = self~here self~emit( "LABEL", self~clauseNo( lab ), self~const( key ) ) End Return self~emit( "CLAUSE", self~clauseNo( clause ), kind ) -- A class (its CLASSES entry); returns its number. ::Method addClass Use Strict Arg entry self~classes~append( entry ) Return self~classes~items -- A method of class 'cls' ("I" instance, "C" class): its kind (CODE, GET, -- SET, CONST, ABSTRACT), its value (an address, a variable name, a -- constant) and, for CODE, its labels; its options (see MethodFlags) and -- where its source is (see Extent). ::Method addMethod Use Strict Arg cls, which, name, kind, value, labels = .Nil, flags = "-", extent = "-" self~methods~append( .Array~of( cls, which, name, kind, value, labels, flags, extent ) ) -- The targets of the annotations of methods, (class, I|C, NAME), become -- "M k" (k: the method's number in METHODS). ::Method resolveAnnotations index = .Directory~new Do k = 1 To self~methods~items m = self~methods[k] index[ m[1] m[2] m[3] ] = k End Do a Over self~annotations t = a[1] If t[1] == "M" Then a[1] = .Array~of( "M", index[ t[2] t[3] t[4] ] ) End -- A method body starts: it has labels of its own (returned); endBody goes -- back to those of the prolog. ::Method startBody Expose labels prologLabels prologLabels = labels labels = .Table~new Return labels ::Method endBody Expose labels prologLabels labels = prologLabels -- The instructions being compiled around the current one (for 28.x). ::Method enter Expose blocks Use Strict Arg instruction blocks~append( instruction ) ::Method leave Expose blocks blocks~delete( blocks~last ) -- A LEAVE or ITERATE with no target: the offset of the indentation ooRexx -- reports it at from the activation's, or -1. ::Method failedJumpOffset Expose blocks extended If extended Then Return -1 offset = 0 Do ins Over blocks If ins~isA( .If.Instruction ) Then offset += 2 Else If ins~isA( .Iterative.Instruction ) Then Do dc = ins~doClause If \ dc~isA( .Simple.Do.Clause ) | dc~name \== .Nil Then Return offset offset += 1 End Else If ins~isA( .Select.Instruction ) Then Return offset End Return -1 -- The blocks being compiled around the current instruction, outermost first. ::Method blocks Expose blocks Return blocks -- A LEAVE or ITERATE run again ("=" at the pause where it landed) from -- outside the blocks it has left: 'outer' are the blocks still around it, -- outermost first. Returns the Ref of a piece of code, compiled at the end -- (flushRedos): TCLAUSE c, and the jump to the block it finds (with its own -- JMARK) or its error. ::Method redo Use Strict Arg kind, c, name, outer, code, k, offset ref = self~newRef j = JumpTarget( outer, kind, name ) If j == 0 Then Do self~addRedo( ref, .Array~of( .Array~of( "TCLAUSE", c ), - .Array~of( "ERRJ", code, k, offset ) ) ) Return ref End target = BlockClause( outer[j] ) refs = self~loops[ target ] rest = outer~section( 1, j - 1 ) e = self~redo( kind, c, name, rest, code, k, offset ) If kind == "LEAVE" Then Do self~addRedo( ref, .Array~of( .Array~of( "TCLAUSE", c ), - .Array~of( "JMARK", c, e, e ), .Array~of( "JMP", refs[2] ) ) ) Return ref End self~addRedo( ref, .Array~of( .Array~of( "TCLAUSE", c ), - .Array~of( "JMARK", c, ref, e ), .Array~of( "JMP", refs[1] ) ) ) Return ref -- An ITERATE run again at the pause after the checks of the next round of -- its loop (still going): another round of the same loop. ::Method redoHere Use Strict Arg kind, c, name, outer, code, k, offset, target ref = self~newRef e = self~redo( kind, c, name, outer, code, k, offset ) refs = self~loops[ target ] self~addRedo( ref, .Array~of( .Array~of( "TCLAUSE", c ), - .Array~of( "JMARK", c, ref, e ), .Array~of( "JMP", refs[1] ) ) ) Return ref ::Method addRedo Private Expose redos Use Strict Arg ref, ops redos~append( .Array~of( ref, ops ) ) -- Compile the redo pieces (see redo) where the code is now. ::Method flushRedos Expose redos code Do piece Over redos self~place( piece[1] ) Do op Over piece[2] code~append( op~copy ) End End redos = .Array~new -- The loops (and labelled SELECTs), for LEAVE and ITERATE: clause -> -- .Array~of( iterateRef, leaveRef ). ::Method loops Expose loops Return loops -- Resolve the jump labels: every RVM.Ref operand becomes its address. ::Method finish Expose code Use Strict Arg start = 1 Do k = start To code~items op = code[k] Do i = 2 To op~items If op[i]~isA( .RVM.Ref ) Then op[i] = op[i]~address End End -- INTERPRET data compiled apart (see RVM.Compiler~fragment). ::Method markExtended Expose extended extended = .True -- Share the tables of a loaded program (see RVM.Compiler~extend). ::Method share Expose code consts names clauses labels withs constIndex nameIndex descriptors - extended Use Strict Arg program extended = .True code = program~code consts = program~consts names = program~names clauses = program~clauses labels = program~labels withs = program~withs descriptors = program~descriptors Do k = 1 To consts~items If \ constIndex~hasIndex( consts[k] ) Then constIndex[ consts[k] ] = k End Do k = 1 To names~items If \ nameIndex~hasIndex( names[k] ) Then nameIndex[ names[k] ] = k End ::Class RVM.Ref Public ::Attribute address