/******************************************************************************/ /* */ /* RVM.Machine.cls - The RVM: a small virtual machine that runs R-code */ /* =================================================================== */ /* */ /* The RVM of ooRexx: the machine itself, a stack, a program counter and a */ /* dispatch loop over the R-code instructions (RVM.Machine); the instruction */ /* set and its verifier (RVM.ISA); a loaded program and its tables */ /* (RVM.Program and its entries); the context of an activation (RVM.Context); */ /* the loading of the prelude; and the commands (IssueCommand and the */ /* redirectors that need objects). Its runtime is in the other packages: the */ /* values (RVM.Number), the built-in functions (RVM.BIFs), the streams */ /* (RVM.Stream), the host (RVM.Host, RVM.Commands), the execution state */ /* (RVM.BaseContext: variables, activations, settings, conditions, trace */ /* output), and the objects, activities and their scheduler (RVM.Objects). */ /* See doc/05-machine.md. */ /* */ /* Also here: R-code as TEXT (RVM.RCode~write / ~read). A program runs from */ /* its text form, never from the compiler's objects: what the compiler emits */ /* is what every RVM loads. */ /* */ /* 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) */ /* */ /******************************************************************************/ ::Requires "modules/rvm/RVM.Number.cls" ::Requires "modules/rvm/RVM.BaseContext.cls" ::Requires "modules/rvm/RVM.BIFs.cls" ::Requires "modules/rvm/RVM.Commands.cls" ::Requires "parser.cls" ::Requires "modules/rvm/RVM.Compiler.cls" ::Requires "modules/rvm/RVM.Objects.cls" ::Requires "modules/rvm/RVM.RexxUtil.cls" ::Requires "modules/rvm/RVM.RxMath.cls" ::Requires "modules/rvm/RVM.RxSock.cls" ::Requires "modules/rvm/RVM.HostEmu.cls" /******************************************************************************/ /* R-code as text (see doc/04-rcode.md) */ /* */ /* RCODE version (RVM.RCode~VERSION) */ /* COMPILER version isa frontier (RVM.Compiler~VERSION, RVM.ISA~VERSION, */ /* RVM.Compiler~frontier) */ /* SOURCE hash (SourceHash of the source file, or -) */ /* PROGRAM "name" */ /* PROLOG extent (where the prolog's source is: l.c-l.c, or -) */ /* OPTIONS d f form t numeric prolog conds explicit (the ::OPTIONS) */ /* CONSTANTS n then n lines: "value" */ /* NAMES n then n lines: "name" (slot 1, 2, ...) */ /* CLAUSES n then n lines: line "text" */ /* LABELS n then n lines: "label" address */ /* DESCRIPTORS n */ /* WITHS n then n lines: the redirections */ /* REQUIRES n then n lines: clause "name" [LIBRARY] */ /* [NAMESPACE "NS"] */ /* CLASSES n then n lines: clause "ID" "SUPER" "META" PUBLIC ... */ /* (a class qualified by a namespace is */ /* "NS:NAME"; one with a colon, ":NAME") */ /* METHODS n then n lines: class I|C|K "NAME" flags extent kind */ /* value [labels] (flags: P R K U A or -; */ /* K: the class's initializer of its */ /* calculated constants; kind CODE, GET, */ /* SET, DELEGATE, CONST, ABSTRACT, */ /* REXX: value is f of LIBRARY REXX f; */ /* LIBRARY: value is clause "spec" "NAME" */ /* prefix (- or GET, SET: an attribute), */ /* any other EXTERNAL; */ /* CCONST: a calculated constant) */ /* ROUTINES n then n lines: "NAME" PUBLIC|PRIVATE extent CODE a m */ /* labels (or: - EXTERNAL clause "spec") */ /* ANNOTATIONS n then n lines: P 0|C k|M k|R k "NAME" "VALUE" */ /* RESOURCES n then n times: "NAME" m, and m lines: "line" */ /* CODE n then n lines: OP operand... */ /* */ /* A string is written between double quotes (doubled inside) when all its */ /* characters are printable, else as X'hex'. Operands are numbers or bare */ /* words. */ /******************************************************************************/ ::Class RVM.RCode Public -- The version of the format: an RVM reads R-code of its own version only -- (see doc/04-rcode.md). ::Constant VERSION 1 -- The text of a compiled unit (RVM.Unit), as an Array of lines. 'hash' is -- the SourceHash of its source file (see CachedRCode), or "-". ::Method write Class Use Strict Arg unit, hash = "-" lines = .Array~new lines~append( "RCODE" .RVM.RCode~VERSION ) lines~append( "COMPILER" .RVM.Compiler~VERSION .RVM.ISA~VERSION - .RVM.Compiler~frontier ) lines~append( "SOURCE" hash ) lines~append( "PROGRAM" Quote( unit~name ) ) lines~append( "PROLOG" unit~prolog ) lines~append( "OPTIONS" OptionsLine( unit~options ) ) lines~append( "CONSTANTS" unit~consts~items ) Do c Over unit~consts lines~append( Quote( c ) ) End lines~append( "NAMES" unit~names~items ) Do n Over unit~names lines~append( Quote( n ) ) End lines~append( "CLAUSES" unit~clauses~items ) Do c Over unit~clauses lines~append( c[1] Quote( c[2] ) ) End lines~append( "LABELS" unit~labels~items ) Do With Index name Item address Over unit~labels lines~append( Quote( name ) address ) End lines~append( "DESCRIPTORS" unit~descriptors ) lines~append( "WITHS" unit~withs~items ) Do entries Over unit~withs line = entries~items Do e Over entries value = e[5] If e[4] \== "THUNK" Then value = Quote( value ) line = line e[1] e[2] e[3] e[4] value End lines~append( line ) End lines~append( "REQUIRES" unit~requires~items ) Do entry Over unit~requires lines~append( entry ) End lines~append( "CLASSES" unit~classes~items ) Do entry Over unit~classes lines~append( entry ) End lines~append( "METHODS" unit~methods~items ) Do m Over unit~methods line = m[1] m[2] Quote( m[3] ) m[7] m[8] m[4] Select Case m[4] When "CODE" Then Do line = line m[5] m[6]~items Do With Index label Item address Over m[6] line = line Quote( label ) address End End When "GET", "SET", "DELEGATE" Then line = line Quote( m[5] ) Otherwise line = line m[5] End lines~append( line ) End lines~append( "ROUTINES" unit~routines~items ) Do entry Over unit~routines lines~append( entry ) End lines~append( "ANNOTATIONS" unit~annotations~items ) Do a Over unit~annotations lines~append( a[1][1] a[1][2] Quote( a[2] ) Quote( a[3] ) ) End -- The resources (::RESOURCE): NAME and how many lines, then the lines. lines~append( "RESOURCES" unit~resources~items ) Do r Over unit~resources lines~append( Quote( r[1] ) r[2]~items ) Do l Over r[2] lines~append( Quote( l ) ) End End lines~append( "CODE" unit~code~items ) Do op Over unit~code line = op[1] Do i = 2 To op~items line = line op[i] End lines~append( line ) End Return lines -- Load R-code text (an Array of lines) into an RVM.Program. ::Method read Class Use Strict Arg lines p = .RVM.Program~new i = 1 Parse Value lines[i] With magic version If magic \== "RCODE" Then Raise Syntax 93.900 Additional( "RVM: not R-code" ) If version \== .RVM.RCode~VERSION Then Raise Syntax 93.900 Additional( "RVM: R-code" version - "is out of date (this RVM reads R-code" .RVM.RCode~VERSION"): compile the program again" ) i += 1 Parse Value lines[i] With . compiler isa . If isa \== .RVM.ISA~VERSION Then Raise Syntax 93.900 Additional( - "RVM: R-code for instruction set" isa "(this RVM runs" .RVM.ISA~VERSION"):" - "compile the program again" ) p~compiler = compiler i += 1 p~sourceHash = Word( lines[i], 2 ) i += 1 p~name = Unquote( SubWord( lines[i], 2 ) ); i += 1 p~prolog = Word( lines[i], 2 ); i += 1 If Word( lines[i], 1 ) \== "OPTIONS" Then Raise Syntax 93.900 Additional( "RVM: OPTIONS expected" ) p~options = SubWord( lines[i], 2 ); i += 1 n = Word( lines[i], 2 ); i += 1 Do k = 1 To n p~consts[k] = Unquote( lines[i] ); i += 1 End n = Word( lines[i], 2 ); i += 1 Do k = 1 To n p~names[k] = Unquote( lines[i] ); i += 1 End n = Word( lines[i], 2 ); i += 1 Do k = 1 To n Parse Value lines[i] With line text p~clauses[k] = .RVM.Clause~new( line, Unquote( text ) ); i += 1 End n = Word( lines[i], 2 ); i += 1 Do k = 1 To n line = lines[i]; i += 1 Parse Value ReverseWords( line ) With address label p~labels[ Unquote( label ) ] = address End p~descriptors = Word( lines[i], 2 ); i += 1 n = Word( lines[i], 2 ); i += 1 Do k = 1 To n t = Tokens( lines[i] ); i += 1 spec = .RVM.WithSpec~new( p ) Do e = 1 To t[1] b = 2 + ( e - 1 ) * 5 value = t[b+4] If t[b+3] \== "THUNK" Then value = Unquote( value ) spec~add( t[b], t[b+1], t[b+2], t[b+3], value ) End p~withs[k] = spec End n = Word( lines[i], 2 ); i += 1 Do k = 1 To n t = Tokens( lines[i] ); i += 1 e = .RVM.RequiresEntry~new e~clause = t[1] e~name = Unquote( t[2] ) Do j = 3 To t~items Select Case t[j] When "LIBRARY" Then e~library = .True When "NAMESPACE" Then Do j += 1 e~namespace = Unquote( t[j] ) End Otherwise Nop End End p~requires[k] = e End n = Word( lines[i], 2 ); i += 1 Do k = 1 To n t = Tokens( lines[i] ); i += 1 e = .RVM.ClassEntry~new e~clause = t[1] e~id = Unquote( t[2] ) Parse Value ClassRef( Unquote( t[3] ) ) With e~superNS "/" e~super Parse Value ClassRef( Unquote( t[4] ) ) With e~metaNS "/" e~meta e~public = ( t[5] == "PUBLIC" ) j = 6 If t[j] == "MIXIN" Then Do e~mixin = .True j += 1 End If t[j] == "ABSTRACT" Then Do e~abstract = .True j += 1 End If t[j] == "INHERIT" Then Do j = j + 1 To t~items Parse Value ClassRef( Unquote( t[j] ) ) With ns "/" name e~inherit~append( name ) e~inheritNS~append( ns ) End p~classes[k] = e End n = Word( lines[i], 2 ); i += 1 Do k = 1 To n t = Tokens( lines[i] ); i += 1 e = .RVM.MethodEntry~new e~cls = t[1] e~which = t[2] e~name = Unquote( t[3] ) e~flags = t[4] e~extent = t[5] t = t~section( 3 ) -- past flags and extent: kind at 4 Select Case t[4] When "CODE" Then Do e~key = "R" e~value = t[5] Do j = 1 To t[6] e~labels[ Unquote( t[5 + 2 * j] ) ] = t[6 + 2 * j] End End When "GET", "SET", "DELEGATE" Then Do e~key = "A."t[4] e~value = Unquote( t[5] ) End When "CONST" Then Do e~key = "A.CONST" e~value = t[5] End When "CCONST" Then Do -- calculated: no value until set e~key = "A.CONST" e~value = "-" End When "REXX" Then e~key = "X."t[5] -- EXTERNAL (not REXX): resolved when the package starts. When "LIBRARY" Then Do e~key = "L" e~value = t[5] e~library = .Array~of( Unquote( t[6] ), Unquote( t[7] ), t[8] ) End Otherwise e~key = t[4] End p~methods[k] = e End n = Word( lines[i], 2 ); i += 1 Do k = 1 To n t = Tokens( lines[i] ); i += 1 r = .RVM.Routine~new( Unquote( t[1] ), t[2] == "PUBLIC", p ) r~extent = t[3] t = t~section( 2 ) -- past the extent: CODE at 3 If t[3] == "CODE" Then Do r~address = t[4] Do j = 1 To t[5] label = Unquote( t[4 + 2 * j] ) If \ r~labels~hasIndex( label ) Then r~labels[ label ] = t[5 + 2 * j] End End Else If t[3] == "EXTERNAL" Then Do r~externalClause = t[4] r~external = Unquote( t[5] ) End p~routineList~append( r ) If \ p~routines~hasIndex( r~name ) Then p~routines[ r~name ] = r End -- The annotations of the package, its classes, methods and routines: each -- one keeps its pairs (name, value), in order. n = Word( lines[i], 2 ); i += 1 Do k = 1 To n t = Tokens( lines[i] ); i += 1 pair = .Array~of( Unquote( t[3] ), Unquote( t[4] ) ) Select Case t[1] When "P" Then p~annotations~append( pair ) When "C" Then p~classes[ t[2] ]~annotations~append( pair ) When "M" Then p~methods[ t[2] ]~annotations~append( pair ) When "R" Then p~routineList[ t[2] ]~annotations~append( pair ) End End -- The resources: .Array~of( NAME, lines ), in order. n = Word( lines[i], 2 ); i += 1 Do k = 1 To n t = Tokens( lines[i] ); i += 1 data = .Array~new Do j = 1 To t[2] data~append( Unquote( lines[i] ) ); i += 1 End p~resources~append( .Array~of( Unquote( t[1] ), data ) ) End n = Word( lines[i], 2 ); i += 1 Do k = 1 To n p~code[k] = lines[i]~makeArray(" "); i += 1 End -- The clause of the first instruction of each routine (its trace entry). Do r Over p~routineList If r~address \== .Nil Then r~firstClause = FirstClause( p, r~address ) End .RVM.ISA~verify( p ) Return p -- "label text" address -> address "label text" (the label may hold blanks). -- The tokens of a line: blank-separated words, a quoted string being one. ::Routine Tokens Use Strict Arg line t = .Array~new i = 1 n = Length( line ) Loop Do While i <= n, SubStr( line, i, 1 ) == " " i += 1 End If i > n Then Leave If SubStr( line, i, 1 ) == '"' Then Do j = i + 1 Loop q = Pos( '"', line, j ) If SubStr( line, q + 1, 1 ) == '"' Then j = q + 2 Else Leave End t~append( SubStr( line, i, q - i + 1 ) ) i = q + 1 End Else Do j = Pos( " ", line, i ) If j == 0 Then j = n + 1 t~append( SubStr( line, i, j - i ) ) i = j End End Return t ::Routine ReverseWords Use Strict Arg line n = Words( line ) Return Word( line, n ) SubWord( line, 1, n - 1 ) ::Routine Quote Use Strict Arg s If Verify( s, XRange( "20"x, "7E"x ) ) == 0 Then Return '"'ChangeStr( '"', s, '""' )'"' Return "X'"C2X( s )"'" ::Routine Unquote Use Strict Arg s s = Strip( s ) If Left( s, 2 ) == "X'" Then Return X2C( SubStr( s, 3, Length( s ) - 3 ) ) Return ChangeStr( '""', SubStr( s, 2, Length( s ) - 2 ), '"' ) /******************************************************************************/ /* RVM.ISA -- the instruction set, and the verifier of R-code */ /* */ /* Every instruction: its operands, how many values it pops and pushes, and */ /* its flow. Operand kinds: */ /* k a constant (1..) K a constant, or 0 (none) */ /* s a variable slot c a clause */ /* d a block descriptor a an address */ /* n a count (0..) l a source line (0..) */ /* i an integer (-1..) p a redirection (0: none) */ /* x an error code (m.n) w a word */ /* b a flag (0 or 1) D a block descriptor, or 0 (none) */ /* Pops and pushes are numbers, or "#j" (the value of operand j), "#j+m". */ /* Flow: "-" goes on to the next instruction; "E" never does (it ends the */ /* straight line: a return, an exit, a jump elsewhere, an error); "Bj" may */ /* also go to the address in operand j; "Z" must find the stack empty (the */ /* start of a clause); "Y" must find one value (the end of a thunk). */ /* */ /* The verifier checks every instruction and its operands, and follows the */ /* flow from the start, from every label and from every thunk (all at depth */ /* 0) to check that the stack never underflows and has the same depth */ /* wherever two paths meet. */ /******************************************************************************/ ::Class RVM.ISA Public -- The version of the instruction set: an RVM runs R-code of its own version -- only. It goes up whenever an instruction is added or changes its meaning -- (see doc/04-rcode.md). ::Constant VERSION 2 ::Method activate Class Expose table table = .Directory~new spec = .Array~of( - "PUSHC k 0 1 -", "PUSHQ k 0 1 -", "PUSHN k 0 1 -", "ENV k 0 1 -", - "PUSHNONE - 0 1 -", "POP - 1 0 -", "STR - 1 1 -", - "RES - 1 1 -", "RESA - 1 1 -", "TRARG - 1 1 -", "KEYW k 1 1 -", - "KEYWC - 1 1 -", "TRES k 0 0 -", "TRKEY kk 0 0 -", - "LOADV s 0 1 -", "STOREV s 1 0 -", "TAILV s 0 1 -", "TAILC s 0 1 -", - "LOADC snk #2 1 -", "STOREC snk #2+1 0 -", "LOADS s 0 1 -", "STORES s 1 0 -", - "ADD - 2 1 -", "SUB - 2 1 -", "MUL - 2 1 -", "DIV - 2 1 -", "IDIV - 2 1 -", - "REM - 2 1 -", "POW - 2 1 -", "CAT - 2 1 -", "ABUT - 2 1 -", "CATB - 2 1 -", - "AND - 2 1 -", "OR - 2 1 -", "XOR - 2 1 -", - "EQ k 2 1 -", "NE k 2 1 -", "LT k 2 1 -", "GT k 2 1 -", "LE k 2 1 -", - "GE k 2 1 -", "SEQ k 2 1 -", "SNE k 2 1 -", "SLT k 2 1 -", "SGT k 2 1 -", - "SLE k 2 1 -", "SGE k 2 1 -", - "PLUS - 1 1 -", "NEG - 1 1 -", "NOT - 1 1 -", - "JMP a 0 0 EB1", "JF aw 1 0 B1", "JT aw 1 0 B1", - "FUNCB kn #2 1 -", "CALLB kn #2 0 -", "FUNCX kn #2 1 -", "CALLX kn #2 0 -", - "FUNCI knl #2 1 -", "CALLI knl #2 0 -", "CALLN nl #1+1 0 -", - "RETURN - 0 0 E", "RETURNV - 1 0 E", "EXIT - 0 0 E", "EXITV - 1 0 E", - "SIGNAL kl 0 0 E", "SIGNALV l 1 0 E", - "SAY - 1 0 -", "PUSH - 1 0 -", "QUEUE - 1 0 -", - "CLAUSE cw 0 0 Z", "LABEL ck 0 0 Z", "TCLAUSE c 0 0 -", "BOUND - 0 0 -", - "INDENT - 0 0 -", "UNINDENT - 0 0 -", "UNIND2 - 0 0 -", - "BASE d 0 0 -", "SETIND d 0 0 -", "DOBODY d 0 0 -", "DOEXIT d 0 0 -", - "DOSTART d 1 0 -", "DOTO d 1 0 -", "DOBY d 1 0 -", "DOFOR d 1 0 -", - "DOREP d 1 0 -", "DOINIT ds 0 0 -", "DOSTEP ds 0 0 -", "DOTEST da 0 0 B2",- "CASE d 1 0 -", "CASEEQ d 1 1 -", - "PSRC ww 0 0 -", "PSRCV ww 1 0 -", "PTPL n 0 0 -", "PEND - 0 0 -", "PSRCH - 1 0 -", - "PABS - 1 0 -", "PFWD - 1 0 -", "PBWD - 1 0 -", "PFLEN - 1 0 -", - "PBLEN - 1 0 -", "PWORD s 0 0 -", "PREST s 0 0 -", "PDOTW - 0 0 -", - "PWORDC snk #2 0 -", "PRESTC snk #2 0 -", "PWORDS s 0 0 -", "PRESTS s 0 0 -", - "PDOTR - 0 0 -", - "NUMDIG - 1 0 -", "NUMFUZZ - 1 0 -", "NUMFORM w 1 0 -", - "DROPV s 0 0 -", "DROPS s 0 0 -", "DROPC sn #2 0 -", "DROPI s 0 0 -", - "ERR xK 0 0 E", "ERRJ xKi 0 0 E", - "TRACE k 0 0 -", "TRACEV - 1 0 -", "TRAPON kwk 0 0 -", "TRAPOFF k 0 0 -", - "RAISE Kwi #3+4 0 E", - "PROC - 0 0 -", "EXPV s 0 0 -", "EXPS s 0 0 -", "EXPC snk #2 0 -", - "EXPI s 0 0 -", - "ADDRT - 0 0 -", "ADDRS kp 0 0 -", "ADDRV p 1 0 -", "CMD - 1 0 -", - "CMDTO kp 1 0 -", "INTERP c 1 0 -", "IEND ac 0 0 E", "YIELD - 1 0 EY", - "PAUSE a 0 0 P", "BPAUSE anD 0 0 P", "DOPAUSE ad 0 0 P", "IPAUSE a 0 0 P", - "TPAUSE a 0 0 P", "CPAUSE a 0 0 P", "JPAUSE w 0 0 -", "JMARK caa 0 0 B2B3", - "TRACEN k 0 0 -", "DEND - 0 0 E", - "SEND knb #2+1+#3 1 -", "CASC knb #2+1+#3 1 -", - "SENDI knwb #2+1+#4 0 -", "SENDA knb #2+1+#3 0 -", "SCOPE - 2 2 -", - "EXPO s 0 0 -", "EXPOS s 0 0 -", "EXPOC snk #2 0 -", - "EXPOI s 0 0 -", "USEL k 0 0 -", - "USEARG isa 0 0 B3", "USESTRICT kn 0 0 -", "USEARGP ia 0 1 B2", - "USEOMIT i 0 0 E", - "DOOVER d 1 0 -", "DOOVERS ds 1 0 -", "DONEXT dsa 0 0 B3", "MKARR n #1 1 -", - "FWDOK - 0 0 -", "FWD ni #2+4 0 -", "DOWITH d 1 0 -", "DONEXTW da 0 0 B2", - "WITHSET dsw 0 0 -", - "GUARD w 0 0 -", "GWHEN ak 1 0 B1", "REPLY - 0 0 -", "REPLYV - 1 0 -", - "DOCTR dw 0 1 -", "TRCTR d 0 0 -", "DOINITP d 0 1 -", "DOSTEPP d 1 1 -", - "DOSKIP da 0 0 B2", "DOITEM d 0 1 -", "WITHGET dw 0 1 -", - "NSCLASS kk 0 1 -", "FUNCNS kkn #3 1 -", "CALLNS kkn #3 0 -", - "SETCONST k 1 0 -", "VREF s 0 1 -", "USEREF is 0 0 -", - "SWAP - 2 2 -", "PWORDM - 0 2 -", "PRESTM - 0 2 -", "PTRM - 1 0 -" - ) Do line Over spec Parse Var line op operands pops pushes flow If operands == "-" Then operands = "" table[ op ] = .Array~of( operands, pops, pushes, flow ) End ::Method spec Class Expose table Use Strict Arg op Return table[ op ] -- Check a program (see above). 'starts' are the addresses the flow starts -- at (depth 0); by default the start, the labels and the thunks. ::Method verify Class Use Strict Arg program, starts = .Nil, from = 1 code = program~code n = code~items If starts == .Nil Then Do starts = .Array~of( 1 ) Do address Over program~labels~allItems starts~append( address ) End Do spec Over program~withs Do address Over spec~thunks starts~append( address ) End End Do m Over program~methods If m~key == "R" Then Do starts~append( m~value ) Do address Over m~labels~allItems starts~append( address ) End End End Do r Over program~routineList If r~address \== .Nil Then Do starts~append( r~address ) Do address Over r~labels~allItems starts~append( address ) End End End End -- Every instruction and its operands. Do pc = from To n ins = code[ pc ] spec = self~spec( ins[1] ) If spec == .Nil Then Call Bad pc, "unknown instruction" ins[1] kinds = spec[1] If ins~items - 1 \== Length( kinds ) Then Call Bad pc, ins[1] "takes" Length( kinds ) "operands" Do j = 1 To Length( kinds ) If \ OperandOK( SubStr( kinds, j, 1 ), ins[j+1], program ) Then Call Bad pc, "operand" j "of" ins[1] "is not valid:" ins[j+1] End If ins[1] == "FUNCI" | ins[1] == "CALLI" Then If \ HasLabel( program, program~consts[ ins[2] ] ) Then Call Bad pc, "no label" program~consts[ ins[2] ] End -- The depth of the stack along every path. depth = .Array~new work = .Array~new Do address Over starts Call Reach address, 0 End Do While \ work~isEmpty pc = work[ work~last ] work~delete( work~last ) ins = code[ pc ] spec = self~spec( ins[1] ) d = depth[ pc ] flow = spec[4] If Pos( "Z", flow ) > 0, d \== 0 Then Call Bad pc, "a clause starts with" d "values on the stack" If Pos( "Y", flow ) > 0, d \== 1 Then Call Bad pc, "a thunk ends with" d "values on the stack" pops = Count( spec[2], ins ) If d < pops Then Call Bad pc, ins[1] "pops" pops "values; there are" d after = d - pops + spec[3] If Pos( "E", flow ) == 0 Then Do If pc == n Then Call Bad pc, "the code ends without an end" Call Reach pc + 1, after End b = Pos( "B", flow ) Do While b > 0 Call Reach ins[ SubStr( flow, b + 1, 1 ) + 1 ], after b = Pos( "B", flow, b + 1 ) End -- An interactive trace pause: "=" goes back to the clause (operand 1), -- without the values the clause had pushed so far. If Pos( "P", flow ) > 0 Then Call Reach ins[2], after - PauseDrop( ins ) End Return -- A path reaches address 'a' with 'd' values on the stack. Reach: Use Arg a, d If depth[ a ] == .Nil Then Do depth[ a ] = d work~append( a ) Return End If depth[ a ] \== d Then Call Bad a, "paths meet with" depth[ a ] "and" d "values on the stack" Return -- A routine of a library (lr: an entry of a library's table, as REXXUTIL's): -- the library that runs it. -- The arguments of a native routine (ooRexx's processArguments). REXXUTIL's -- routines are the REXX package's (ooRexx's image has them): an error in -- their arguments, raised with the native's frame on top, is reported there, -- with no line ("Error 88 running REXX:"; see Failed); RexxUtilNative turns -- the flag off once NativeArgs has converted them, so its own errors are -- the caller's line, as ooRexx raises them again there. The libraries' -- routines (rxmath, rxsock) have no package: the caller's line. ::Routine RoutineArgs Use Strict Arg lr, args, context context~nativeArgs = ( lr[5] \== "rxmath" & lr[5] \== "rxsock" ) Call CheckRoutineArgs lr, args ::Routine NativeRoutine Use Strict Arg lr, args, context If lr[5] == "rxmath" Then Return RxMathNative( lr, args, context ) If lr[5] == "rxsock" Then Return RxSockNative( lr, args, context ) Return RexxUtilNative( lr, args, context ) -- The EXTERNAL routines of a program that starts, resolved in the libraries -- of the RVM, as ooRexx does when it translates the package (each error at -- its directive): a routine becomes the library's routine (RVM.Routine~lib). -- Its EXTERNAL methods too, but only as far as the RVM knows: a wrong -- specification is 99.917, and a method a library of the RVM does not have -- is 90.998, as one of a library of ooRexx that has no methods (rxsock); a -- library that is not one of ooRexx's is 98.903; a method of one of -- ooRexx's that the RVM does not have fails only when it runs (98.903: see -- CallNative, "L"), so that a package that wraps it still loads. ::Routine CheckExternals Use Strict Arg program, context world = context~world Do r Over program~routineList If r~external == .Nil Then Iterate context~clause = program~clauses[ r~externalClause ] r~lib = ExternalRoutine( r~name, r~external, world, .True ) -- (Its Routine object now, as ooRexx makes it: the library's, of this -- package if it is the first; see RVM.World~libraryRoutineObject.) world~routineObject( r ) End Do m Over program~methods If m~key \== "L" Then Iterate context~clause = program~clauses[ m~value ] e = ExternalSpec( m~library[1], m~library[2] ) -- (The first to resolve an entry gives its code its package: see -- RVM.World~libraryHome.) If RVMLibrary( e[2] ) \== .Nil Then world~libraryHome( ExternalMethod( m~library[2], m~library[1], m~library[3], world, .True ), program ) Else Select Case OoRexxLibrary( e[2] ) When "NONE" Then Do entry = e[3] If m~library[3] \== "-" Then entry = m~library[3] || entry Raise Syntax 90.998 Array( entry ) End When "METHODS" Then Nop Otherwise Raise Syntax 98.903 Array( e[2] ) End End -- Is it a label of the prolog, of a method, or of a routine? ::Routine HasLabel Use Strict Arg program, name If program~labels~hasIndex( name ) Then Return .True Do m Over program~methods If m~key == "R", m~labels~hasIndex( name ) Then Return .True End Do r Over program~routineList If r~labels~hasIndex( name ) Then Return .True End Return .False -- How many values "=" drops at a pause. ::Routine PauseDrop Public Use Strict Arg ins If ins[1] == "BPAUSE" Then Return ins[3] If ins[1] == "IPAUSE" Then Return 1 Return 0 ::Routine Bad Use Strict Arg pc, reason Raise Syntax 93.900 Additional( "RVM: bad R-code at" pc":" reason ) -- A count of values: a number, or terms added ("#j": operand j). ::Routine Count Use Strict Arg expr, ins total = 0 Do term Over expr~makeArray( "+" ) If Left( term, 1 ) \== "#" Then v = term Else Do v = ins[ SubStr( term, 2 ) + 1 ] If v < 0 Then v = 0 -- RAISE: -1 items is no ARRAY End total += v End Return total ::Routine OperandOK Use Strict Arg kind, v, program Select Case kind When "w" Then Return v \== "" When "x" Then Return DataType( ChangeStr( ".", v, "" ), "W" ) Otherwise Nop End If \ DataType( v, "W" ) Then Return .False Select Case kind When "k" Then Return v >= 1 & v <= program~consts~items When "K" Then Return v >= 0 & v <= program~consts~items When "b" Then Return v == 0 | v == 1 When "s" Then Return v >= 1 & v <= program~names~items When "c" Then Return v >= 1 & v <= program~clauses~items When "d" Then Return v >= 1 & v <= program~descriptors When "D" Then Return v >= 0 & v <= program~descriptors When "a" Then Return v >= 1 & v <= program~code~items When "p" Then Return v >= 0 & v <= program~withs~items When "i" Then Return v >= -1 Otherwise Return v >= 0 -- n, l End /******************************************************************************/ /* A loaded program */ /******************************************************************************/ ::Class RVM.Program Public ::Attribute name ::Attribute consts ::Attribute names ::Attribute clauses ::Attribute labels ::Attribute descriptors ::Attribute code ::Attribute withs ::Attribute path -- the file it was loaded from (an external routine) ::Attribute source -- its source lines (SOURCELINE), or .Nil ::Attribute rcode -- its R-code lines (a macro's are saved: REXXUTIL) ::Attribute numCache -- PUSHN: (digits, form, value) per address ::Attribute icache -- INTERP: data -> address, per address ::Attribute envCache -- ENV: the class found, per name (see ENV) ::Attribute fragStart -- the first address of INTERPRET's code (none: 999999999) ::Attribute firstClause -- the clause of its first instruction (trace entry) ::Attribute compiler -- the version of the compiler that made it ::Attribute sourceHash -- the SourceHash of its source, or "-" ::Attribute classes -- its ::CLASS directives (RVM.ClassEntry) ::Attribute methods -- their methods (RVM.MethodEntry) ::Attribute classObjs -- its class objects (id -> class), once made ::Attribute requires -- its ::REQUIRES directives (RVM.RequiresEntry) ::Attribute routines -- its ::ROUTINEs: name -> RVM.Routine (the first one) ::Attribute routineList -- all of them, in order ::Attribute routinesObj -- .ROUTINES: their StringTable, once made ::Attribute methodsObj -- .METHODS: the floating methods', once made ::Attribute floating -- its floating methods (NAME -> RVM.Method), once made ::Attribute prolog -- where its prolog's source is (l.c-l.c), or - -- Its ::OPTIONS (see RVM.Compiler's OptionsLine): what its methods and -- routines start with. ::Attribute optDigits ::Attribute optFuzz ::Attribute optForm ::Attribute optTrace ::Attribute optInherit -- NUMERIC INHERIT: the caller's NUMERIC settings ::Attribute optProlog -- 0: NOPROLOG (its prolog does not run when required) ::Attribute syntaxConds -- the conditions that are SYNTAX (blank-separated) ::Attribute explicit -- the options its ::OPTIONS set (blank-separated; -- ooRexx's isExplicit...Option) ::Attribute initialLine -- its settings as it was made (Package~options "I", -- "RESET"), as settingsLine gives them -- Its ::OPTIONS, from the R-code's OPTIONS line (see RVM.Compiler's -- OptionsLine): its settings, the options set, and those as its initial ones. ::Method "options=" Use Strict Arg line self~settings = line explicit = Word( line, 8 ) If explicit == "" | explicit == "-" Then self~explicit = "" Else self~explicit = explicit~changeStr( ",", " " ) self~initialLine = self~settingsLine -- Its settings (the first seven words of an OPTIONS line): Package~options -- changes them. ::Method "settings=" Use Strict Arg line Parse Var line digits fuzz form trace inherit prolog conds . self~optDigits = digits self~optFuzz = fuzz self~optForm = form self~optTrace = trace self~optInherit = ( inherit == "INHERIT" ) self~optProlog = ( prolog \== 0 ) If conds == "-" Then self~syntaxConds = "" Else self~syntaxConds = conds~changeStr( ",", " " ) ::Method settingsLine conds = Space( self~syntaxConds )~changeStr( " ", "," ) If conds == "" Then conds = "-" Return self~optDigits self~optFuzz self~optForm self~optTrace - self~optInherit~?( "INHERIT", "NOINHERIT" ) self~optProlog~?( 1, 0 ) conds ::Attribute parent -- a program compiled at run time: the program it -- sees too (its classes and routines), or .Nil -- Its start (see StartPackage in the machine): NEW, LOADING (its requires -- being loaded, and their prologs run), READY (its classes made). ::Attribute state ::Attribute reqNext -- the next requires to load ::Attribute required -- the packages it requires (RVM.Program), loaded -- What it sees of the packages it requires (their public classes and -- routines, and those they see), and what it shows to those that require -- it (its own public ones, and those): name -> class / RVM.Routine. ::Attribute importedClasses ::Attribute publicClasses ::Attribute importedRoutines ::Attribute publicRoutines -- Its Package object (see RVM.World~packageObject), and what goes with it: -- its prolog as a Routine (PROLOG), its package-local directory (LOCAL), its -- annotations (a StringTable), its namespaces (NAME -> RVM.Program). ::Attribute pkgObj ::Attribute prologObj ::Attribute localObj ::Attribute annotationsObj ::Attribute annotations -- the pairs (name, value) of its ::ANNOTATE PACKAGE -- Its resources (::RESOURCE): .Array~of( NAME, lines ), in order, and their -- StringTable, once made (see RVM.World~resourcesTable). ::Attribute resources ::Attribute resourcesObj ::Attribute namespaces -- What it was compiled for at run time: METHOD (Method~new...), ROUTINE -- (Routine~new), or "" (a program, a package: it has a prolog). ::Attribute kind -- Its security manager (ooRexx's PackageClass::securityManager): an object, -- or .Nil. An activation of its code starts with it (RVM.BaseContext~secMgr); -- its environment symbols ask it (RVM.World~env). ::Attribute secMgr -- Write R-code caches next to the sources compiled (rvm -w). ::Attribute writeCache Class -- The programs loaded from files (path -> RVM.Program), and the texts they -- were loaded from (path -> the file's text): see LoadProgram. ::Attribute externals Class ::Attribute externalTexts Class ::Method init Expose consts names clauses labels code withs numCache icache envCache fragStart firstClause - classes methods classObjs requires routines routineList state reqNext - required importedClasses publicClasses importedRoutines publicRoutines - floating prolog parent routinesObj methodsObj pkgObj prologObj localObj - annotationsObj namespaces kind annotations resources resourcesObj secMgr secMgr = .Nil annotations = .Array~new resources = .Array~new self~options = "9 0 SCIENTIFIC N NOINHERIT 1 -" resourcesObj = .Nil pkgObj = .Nil prologObj = .Nil localObj = .Nil annotationsObj = .Nil namespaces = .Directory~new kind = "" routinesObj = .Nil methodsObj = .Nil prolog = "-" parent = .Nil requires = .Array~new routines = .Directory~new routineList = .Array~new state = "NEW" reqNext = 1 required = .Array~new importedClasses = .Directory~new publicClasses = .Directory~new importedRoutines = .Directory~new publicRoutines = .Directory~new classes = .Array~new methods = .Array~new classObjs = .Nil floating = .Directory~new numCache = .Array~new icache = .Array~new envCache = .Directory~new fragStart = 999999999 firstClause = 0 withs = .Array~new consts = .Array~new names = .Array~new clauses = .Array~new labels = .Table~new code = .Array~new -- A new program with the R-code of this one, read and verified already: a -- package of its own, not started (ooRexx makes one at each CALL of an -- external program: see LoadExternal). What a program changes is its own -- (its code, clauses and redirections grow with INTERPRET; its caches; the -- entries of its classes, at install; its routines, and its settings); what -- it only reads is shared (its methods, requires, annotations, resources). ::Method fresh p = .RVM.Program~new p~name = self~name p~consts = self~consts~copy p~names = self~names~copy p~clauses = self~clauses~copy p~labels = self~labels~copy p~descriptors = self~descriptors p~code = self~code~copy p~fragStart = self~fragStart Do w Over self~withs p~withs~append( w~copyFor( p ) ) End p~path = self~path p~source = self~source p~rcode = self~rcode p~firstClause = self~firstClause p~compiler = self~compiler p~sourceHash = self~sourceHash Do e Over self~classes c = e~copy c~constInit = .Nil p~classes~append( c ) End p~methods = self~methods p~requires = self~requires Do r Over self~routineList n = .RVM.Routine~new( r~name, r~public, p ) n~extent = r~extent n~address = r~address n~labels = r~labels n~firstClause = r~firstClause n~external = r~external n~externalClause = r~externalClause n~annotations = r~annotations p~routineList~append( n ) If \ p~routines~hasIndex( n~name ) Then p~routines[ n~name ] = n End p~prolog = self~prolog p~settings = self~initialLine p~explicit = self~explicit p~initialLine = self~initialLine p~annotations = self~annotations p~resources = self~resources p~kind = self~kind Return p -- A ::REQUIRES of a program: its clause, the name of the package, LIBRARY. ::Class RVM.RequiresEntry Public ::Attribute clause ::Attribute name ::Attribute library ::Attribute namespace -- NAMESPACE ns (upper case), or .Nil ::Method init Expose library namespace library = .False; namespace = .Nil -- A ::ROUTINE: its name, PUBLIC, its program, and its code (address, labels, -- the clause of its first instruction); an EXTERNAL one has no address, but -- its specification and clause, and once resolved (CheckExternals) the -- entry of the library routine it is (lib, as REXXUTIL's). ::Class RVM.Routine Public ::Attribute external ::Attribute externalClause ::Attribute lib ::Attribute name ::Attribute public ::Attribute program ::Attribute address ::Attribute labels ::Attribute firstClause ::Attribute extent -- where its source is (l.c-l.c), or - ::Attribute obj -- its Routine object, once made (routineObject) ::Attribute libHome -- a library's: its package (an RVM.Program, "REXX" or -- .Nil; see RVM.World~libraryRoutineObject) -- Its annotations: the pairs (name, value) of the R-code, and their -- StringTable, once made (see RVM.World~annotationsOf). ::Attribute annotations ::Attribute annotationsObj ::Method init Expose name public program address labels firstClause extent obj - annotations annotationsObj external externalClause lib Use Strict Arg name, public, program external = .Nil; externalClause = 0; lib = .Nil self~libHome = .Nil annotations = .Array~new annotationsObj = .Nil extent = "-" obj = .Nil address = .Nil labels = .Table~new firstClause = 0 -- A ::CLASS of a program: its clause, its id, the names of its superclass -- and metaclass ("": the default), PUBLIC, MIXIN, ABSTRACT, the classes it -- inherits, its annotations (pairs name, value). ::Class RVM.ClassEntry Public ::Attribute constInit -- the initializer of its calculated constants ::Attribute clause ::Attribute id ::Attribute super ::Attribute superNS -- the namespace that qualifies it, or "" ::Attribute meta ::Attribute metaNS ::Attribute public ::Attribute mixin ::Attribute abstract ::Attribute inherit ::Attribute inheritNS ::Attribute annotations ::Method init Expose mixin abstract inherit inheritNS public annotations constInit constInit = .Nil mixin = .False; public = .False; abstract = .False inherit = .Array~new inheritNS = .Array~new annotations = .Array~new -- A method of a ::CLASS: its class (index), I or C, its name, its key (R: -- code, A.GET, A.SET, A.CONST, ABSTRACT), its value (an address, a -- variable name, a constant index), its labels (R). ::Class RVM.MethodEntry Public ::Attribute cls ::Attribute which ::Attribute name ::Attribute key ::Attribute value ::Attribute labels ::Attribute flags -- P (private) R (protected) K (package) U (unguarded), or - ::Attribute extent -- where its source is (l.c-l.c), or - ::Attribute annotations -- pairs (name, value) ::Attribute library -- L (EXTERNAL): the specification, NAME, prefix ::Method init Expose labels flags extent annotations annotations = .Array~new labels = .Table~new flags = "-" extent = "-" -- The redirections of an ADDRESS ... WITH, as RVM.Commands wants them -- (redirectionType / redirectionTarget / redirectionOption). A target is -- .Array~of( kind, value ); a THUNK runs on the RVM when its value is needed. ::Class RVM.WithSpec Public ::Attribute program ::Method init Expose program entries Use Strict Arg program entries = .Directory~new -- The same redirections, for program p (see RVM.Program~fresh). ::Method copyFor Expose entries Use Strict Arg p spec = .RVM.WithSpec~new( p ) Do stream Over entries e = entries[ stream ] spec~add( stream, e[1], e[2], e[3], e[4] ) End Return spec ::Method add Expose entries Use Strict Arg stream, type, option, kind, value If option == "-" Then option = "" entries[ stream ] = .Array~of( type, option, kind, value ) -- The addresses of its thunks. ::Method thunks Expose entries list = .Array~new Do e Over entries~allItems If e[3] == "THUNK" Then list~append( e[4] ) End Return list ::Method redirectionType Expose entries Use Strict Arg stream e = entries[ Upper( stream ) ] If e == .Nil Then Return "" Return e[1] ::Method redirectionOption Expose entries Use Strict Arg stream e = entries[ Upper( stream ) ] If e == .Nil Then Return "" Return e[2] ::Method redirectionTarget Expose entries Use Strict Arg stream e = entries[ Upper( stream ) ] If e == .Nil Then Return .Nil If e[1] == "" | e[1] == "NORMAL" Then Return .Nil Return .Array~of( e[3], e[4] ) -- A label as the parser sees the labels of the body for INTERPRET data. ::Class RVM.LabelRef Public ::Attribute labelFor ::Method init Expose labelFor labelFor = .Nil -- A clause of the clause table: its line and its text (for error reports, -- SIGL, and the trace). /******************************************************************************/ /* RVM.PreludeLoader -- loads the prelude when the world needs it */ /* */ /* prelude.orx is next to this file (see makeprelude.rex), with its R-code */ /* (prelude.orx.rcode, the cache any source has: compiled again, and written */ /* with -w, when it is out of date). Its name is REXX, and it has no source. */ /******************************************************************************/ ::Class RVM.PreludeLoader Public ::Attribute context ::Method init Expose context Use Strict Arg context ::Method load Expose context Return self~loadFile( "prelude.orx" ) -- StreamClasses.orx, cut (prelude-streams.orx, and its cache): .Nil when it -- is not there. -- The prolog of program (the prelude's main code) runs now, to its end, in -- the activity running (see RVM.Machine~runSync), with 'arg' as its -- argument (ooRexx's image build: the REXX package). ::Method runProlog Expose context Use Strict Arg program, arg c = context~activityContext c~rvmProgram = program c~programName = program~path c~sourceLines = program~source c~invocation = "SUBROUTINE" c~args = .Array~of( arg ) Return .RVM.Machine~runSync( program, c ) -- A message sent now (see RVM.Machine~sendSync), in a context of its own -- (an activity's), the prelude's code at hand (the program may not have -- started). ::Method sendSync Expose context Use Strict Arg receiver, name, args c = context~activityContext world = context~world world~ensurePrelude Return .RVM.Machine~sendSync( receiver, name, args, world~prelude, c ) -- The same, and the names of the conditions raised to the sender (a RAISE -- ... RETURN in the method: ooRexx's RedirectionDispatcher sees them): -- .Array~of( result, names ). ::Method sendSyncWatch Expose context Use Strict Arg receiver, name, args c = context~activityContext c~conditionSink = .Array~new world = context~world world~ensurePrelude v = .RVM.Machine~sendSync( receiver, name, args, world~prelude, c ) Return .Array~of( v, c~conditionSink ) ::Method loadStreams here = .context~package~name If \ .RVM.FileSystem~isFile( Left( here, LastPos( .File~separator, here ) )"prelude-streams.orx" ) Then Return .Nil Return self~loadFile( "prelude-streams.orx" ) ::Method loadFile Private Expose context Use Strict Arg file here = .context~package~name path = Left( here, LastPos( .File~separator, here ) )file program = LoadProgram( path, context, .False ) program~path = "REXX" program~source = .Nil Return program /******************************************************************************/ /* RVM.SourceCompiler -- compiles a source at run time (world~sourceCompiler) */ /* */ /* A method (Method~new, DEFINE and SETMETHOD with a source) is the prolog of */ /* a package of its own (the parser's METHOD option: EXPOSE is allowed), that */ /* sees what its parent program sees. A source that does not parse raises */ /* its error with its line first in the report (among the natives' lines). */ /******************************************************************************/ ::Class RVM.SourceCompiler Public ::Method init Expose context Use Strict Arg context -- A routine of a library (lr: its entry), with no program -- (Routine~loadExternalRoutine). ::Method libraryRoutine Use Strict Arg name, lr r = .RVM.Routine~new( name, .True, .Nil ) r~lib = lr Return r ::Method method Expose context Use Strict Arg name, lines, parent program = CompileSource( name, lines, context, "METHOD" ) program~parent = parent program~kind = "METHOD" m = .RVM.Method~new( name, .Nil, "R", 0, -1 ) m~program = program m~address = 1 m~labels = program~labels m~firstClause = program~firstClause m~extent = program~prolog m~home = program Return m -- A routine (Routine~new): the prolog of a package of its own too, with no -- parser option (EXPOSE and USE LOCAL are errors when they run: 98.992, -- 98.993). ::Method routine Expose context Use Strict Arg name, lines, parent program = CompileSource( name, lines, context, "-" ) program~parent = parent program~kind = "ROUTINE" r = .RVM.Routine~new( name, .False, program ) r~address = 1 r~labels = program~labels r~firstClause = program~firstClause r~extent = program~prolog Return r -- A package from source lines (Package~new): no parser option either; its -- parent (.Nil: none) is the context it was given. ::Method package Expose context Use Strict Arg name, lines, parent program = CompileSource( name, lines, context, "-" ) program~parent = parent Return program -- A package from source lines with a name (loadPackage): loaded once per -- name, as a package in a file is once per file (see LoadProgram). ::Method named Expose context Use Strict Arg name, lines table = ExternalsTable() If table~hasIndex( name ) Then Return table[ name ] program = CompileSource( name, lines, context, "-" ) table[ name ] = program Return program -- A package in a file (loadPackage, Package~new): found as a ::REQUIRES is, -- from the directory of 'caller' ("": none; 43.901), and loaded once. ::Method file Expose context Use Strict Arg name, caller, running = ( context ) path = FindExternal( name, caller, .True ) If running~secMgr \== .Nil Then Return RequiresProgram( name, path, running ) If path == "" Then Raise Syntax 43.901 Array( name ) Return LoadProgram( path, context ) -- A package's prolog as a routine (PROLOG), made once: its code from the -- start, in the package. ::Method prolog Use Strict Arg program If program~prologObj \== .Nil Then Return program~prologObj r = .RVM.Routine~new( program~path, .False, program ) r~address = 1 r~labels = program~labels r~firstClause = program~firstClause r~extent = program~prolog program~prologObj = r Return r -- FINDPROGRAM: a program found as an external routine is, from the directory -- of the package, or else of the packages it sees (its parents); "" if none. ::Method findProgram Use Strict Arg name, program Do While program \== .Nil path = FindExternal( name, program~path ) If path \== "" Then Return path program = program~parent End Return "" ::Class RVM.Clause Public ::Attribute line ::Attribute text ::Method init Expose line text Use Strict Arg line, text /******************************************************************************/ /* RVM.Context -- the runtime's context, with the clauses of the clause table */ /******************************************************************************/ ::Class RVM.Context Public SubClass RVM.BaseContext -- An EXIT of a nested machine on its way to the machine below: -- .Array~of(its value), or .Nil (see ExitUnwind). ::Attribute nestedExit -- The condition of a nested machine on its way to the machine below, which -- goes on with its throw (see FailedUnwind). ::Attribute nestedHandoff -- What PARSE VERSION says (and .RexxInfo~name): "REXX-RVM--", -- the language level and the date. ::Constant VERSION "REXX-RVM-ooRexx-0.1 6.06 1 Oct 2026" -- The objects of the run (RVM.World), made when first needed. ::Method world Expose rvmWorld If rvmWorld == .Nil Then Do rvmWorld = .RVM.World~new rvmWorld~loader = .RVM.PreludeLoader~new( self ) rvmWorld~sourceCompiler = .RVM.SourceCompiler~new( self ) End Return rvmWorld -- The library that registered the ADDRESS environment 'name', or .Nil (a -- run with no objects yet has loaded no library). ::Method registeredEnvironment Expose rvmWorld Use Strict Arg name If rvmWorld == .Nil Then Return .Nil Return rvmWorld~addressEnvironment( name ) -- The "running" line of an untrapped error's report: .Nil (from its first -- line), "" (none: a RAISE PROPAGATE out of the main program) or an Array -- (line, program; line .Nil: none, "running REXX:"). ::Attribute errorHeader -- The method running (a traceback line of the prelude names it). ::Attribute currentMethod -- The arguments of the command line (.SYSCARGS: an Array), or .Nil. ::Attribute syscargs -- Where a standard stream (OUTPUT, INPUT, ERROR) goes: .Nil, the host -- straight; else the object of .LOCAL to send to (see RVM.World~localTarget). -- A run with no objects yet has no .LOCAL either. ::Method localTarget Expose rvmWorld Use Strict Arg name, forSay = .False If rvmWorld == .Nil Then Return .Nil Return rvmWorld~localTarget( name, forSay ) -- Where the queue instructions and functions go: .Nil, the queue straight; -- else the object to send to (see RVM.World~queueTarget). ::Method queueTarget Expose rvmWorld Use Strict Arg strict = .False If rvmWorld == .Nil Then Return .Nil Return rvmWorld~queueTarget( strict ) -- A line of trace output as a TraceObject (see RVM.World~traceObject). ::Method traceObject Expose rvmWorld Use Strict Arg line, info = .Nil If rvmWorld == .Nil Then Return .False Return rvmWorld~traceObject( line, self, info ) -- The traceback lines of the native methods running ("Compiled method"). ::Attribute nativeLines -- A context of sendSync: its first activation only sends the message (it is -- no frame of the stack). ::Attribute syncRoot ::Method init Expose rvmWorld nativeLines currentMethod errorHeader level levels activity - failedInfo syncRoot activity = .Nil failedInfo = .Nil syncRoot = .False rvmWorld = .Nil self~syscargs = .Nil errorHeader = .Nil currentMethod = .Nil nativeLines = .Array~new level = .RVM.Level~new( "PROGRAM" ) levels = .Array~new Forward Class ( super ) /*----------------------------------------------------------------------------*/ /* The activations as .CONTEXT and a StackFrame see them (RVM.Level): the */ /* current one, and those of the callers (levels, as savedActivations). A */ /* new activation is an internal routine's until the machine says otherwise */ /* (a program, a routine, a method: see the machine's EnterProgram and */ /* EnterMethod); it runs its caller's code and starts with its .RS. An */ /* INTERPRET has its own (its StackFrame) while it runs. */ /*----------------------------------------------------------------------------*/ ::Attribute level ::Attribute levels ::Method pushActivation Expose level levels Use Strict Arg newArgs, newFrame = .Nil levels~append( level ) caller = level level = .RVM.Level~new( "INTERNALCALL", newArgs ) level~runs( caller ) level~rs = caller~rs Forward Class ( super ) ::Method popActivation Expose level levels self~closeInterprets level~unlock -- its scope lock, if it has it level~close level = levels~lastItem levels~delete( levels~last ) Forward Class ( super ) Continue -- A HALT still pending for the caller. If level~haltPending Then self~clauseBoundary -- Message~halt (ooRexx's RexxActivation~halt): a HALT for the activation -- running, at its next clause boundary (RunTraps); .False when one is -- pending already. ::Method halt Expose level Use Strict Arg desc If level~haltPending Then Return .False level~haltPending = .True level~haltDesc = desc self~clauseBoundary Return .True -- hostemu TS / TE (ooRexx's RexxSetTrace, RexxResetTrace: externalTraceOn, -- externalTraceOff): TRACE ?R or TRACE O for the activation running, at its -- next clause boundary (RunTraps). ::Method externalTrace Expose level Use Strict Arg setting level~extTrace = setting self~clauseBoundary -- Ctrl-C: a HALT for every activity (RVM.Scheduler~haltAll). ::Method haltAll sched = self~world~scheduler If sched \== .Nil, self~activity \== .Nil Then sched~haltAll Else self~halt( .Nil ) ::Method enterInterpret Expose level self~enterInterpret:super( arg(1) ) lv = .RVM.Level~new( "INTERPRET" ) lv~parent = level lv~runs( level ) self~activeInterprets~lastItem[3] = lv ::Method leaveInterpret interprets = self~activeInterprets If interprets~items > 0 Then interprets~lastItem[3]~close Forward Class ( super ) ::Method clearInterprets self~closeInterprets Forward Class ( super ) ::Method closeInterprets Do entry Over self~activeInterprets entry[3]~close End -- What an activation has now: the context itself, or its saved state (a -- caller's): digits, fuzz, form, clause, frame, condition. ::Method levelState Expose level levels Use Strict Arg lv If lv == level Then Return self Return self~savedActivations[ levels~index( lv ) ] -- The StackFrames now, the innermost first (an Array; 'skipFirst': not that -- of the native asking for them). ::Method stackFrames Use Strict Arg skipFirst = .False world = self~world list = .Array~new Do line Over self~stackLines If skipFirst Then Do skipFirst = .False Iterate End list~append( world~stackFrameObject( line[5] ) ) End Return world~newArray( list ) /*----------------------------------------------------------------------------*/ /* Activities (see RVM.Activity): each has a context of its own. A new one */ /* shares the globals of the run (RVM.BaseContext~globals, the world) and */ /* has an activation of its own (activityContext: START); REPLY moves the */ /* current activation to it (replyContext): this context goes back to the */ /* caller as a RETURN does, and the level it ends then is a stand-in. */ /*----------------------------------------------------------------------------*/ ::Attribute activity -- its RVM.Activity ::Attribute failedInfo -- the condition of an error that ended it ::Method activityContext Expose rvmWorld rvmProgram If self~streams == .Nil Then self~streams = .RVM.StreamTable~new c = self~class~new( self~out ) c~shareGlobals( self~globals ) c~adoptWorld( rvmWorld ) c~rvmProgram = rvmProgram c~programName = self~programName c~sourceLines = self~sourceLines c~invocation = "METHOD" Return c ::Method replyContext Expose level currentMethod c = self~activityContext c~takeActivation( self~activationState ) c~level = level -- (It runs in another activity now: its THREAD, asked again.) level~thread = .Nil c~currentMethod = currentMethod level = .RVM.Level~new( "METHOD" ) Return c ::Method adoptWorld Expose rvmWorld Use Strict Arg rvmWorld -- The activity ends: the lock of its first activation, if it has it. ::Method endActivity Expose level level~unlock -- The machine side of the activations (the frames of the running machine): -- a traceback reads them (stackLines). ::Attribute frames -- The program running (RVM.Program): the package of what Method~new makes. ::Attribute rvmProgram -- The value of an environment symbol (VALUE('.NAME'): ooRexx's -- RexxDotVariable), as the ENV instruction finds it in the program running. ::Method dotValue Expose rvmProgram Use Strict Arg symbol v = self~world~env( symbol, rvmProgram, .True ) If v == .Nil Then v = DotSpecial( symbol, rvmProgram, self ) Return v -- The line number and the text of a clause; 'm' is the method running it (a -- clause of the prelude names it). ::Method clauseText Expose currentMethod Use Strict Arg clause, m = ( currentMethod ) If clause~isA( .RVM.Clause ) Then Do -- A clause of the prelude has no text: ooRexx says which method it is. If clause~text == .Nil Then Do text = "(no source available)." If m \== .Nil Then text = "Method" m~name 'with scope "'ScopeName( m )'" in package "REXX"' text Return .Array~of( clause~line, text ) End Return .Array~of( clause~line, clause~text ) End Return self~clauseText:super( clause ) -- The trace line of a clause (see RVM.BaseContext's), run by method 'm'. ::Method clauseTraceLine Use Strict Arg clause, indent = ( self~traceIndent ), m = ( self~currentMethod ) info = self~clauseText( clause, m ) Return Right( info[1], 6 ) "*-*" || - Copies( " ", 1 + 2 * Min( indent, 20 ) ) || info[2] -- A condition raised here knows where: the line and the program of the -- clause running (a NOTREADY comes from the stream objects of the REXX -- package: no line; its RESULT is ""). ::Method raiseCondition Use Strict Arg info If self~conditionSink \== .Nil Then self~conditionSink~append( info~condition ) -- Raised in the first activation of a sendSync (the message it sends: a -- NOMETHOD), it is the caller's: ooRexx's native has no activation, so the -- caller's traps see it (a SIGNAL ON there goes up out of this machine as -- the caller's throw: see Failed). If self~syncRoot, self~savedActivations~items == 0 Then Do outer = self~outerContext If outer \== .Nil Then Return outer~raiseCondition( info ) End self~locate( info ) -- Raised while this activation forwards (FORWARD without CONTINUE: a -- NOTREADY of the stream a Monitor forwards to, a HALT), it is a phantom: -- the caller's traps take it (ooRexx's RexxActivation::trap, isForwarded). If self~level~forwarded, self~callDepth > 0 Then Return self~callerRaise( info ) Forward Class ( super ) -- The names of the conditions raised here, when it is an Array (see -- RVM.PreludeLoader~sendSyncWatch). ::Attribute conditionSink ::Method locate Use Strict Arg info -- Its traceback is the stack now (a SYNTAX error: see Failed), after the -- lines of the ooRexx methods it comes from (a NOTREADY). If info~stack == .Nil Then Do natives = self~pendingNatives If info~nativeStack \== .Nil Then Do lines = .Array~new Do i = 1 To info~nativeStack~items l = info~nativeStack[ i ] fi = .RVM.FrameInfo~ofNative( l ) If info~nativeFrames \== .Nil Then Do spec = info~nativeFrames[ i ] -- (see RVM.ConditionInfo) fi~name = spec[2] fi~exec = .Array~of( spec[1], spec[2] ) fi~kind = "L" fi~target = spec[3] fi~args = spec[4] fi~line = spec[5] End lines~append( .Array~of( 0, l, "REXX", "NATIVE", fi ) ) End If natives \== .Nil Then lines~appendAll( natives ) natives = lines End info~stack = self~stackLines( natives ) End -- A source compiled at run time that does not parse: it is there. If info~program == .Nil, info~stack~items > 0, info~stack[1]~hasIndex( 5 ) Then Do fi = info~stack[1][5] If fi~type == "COMPILE" Then Do info~position = fi~line info~program = fi~name End End If info~program \== .Nil Then Return If info~condition == "NOTREADY" Then Do info~program = "REXX" If info~objResult == .Nil Then info~objResult = "" Return End -- In a compiled method (the RVM's part of the prelude) it has no place: -- it takes the one where it lands (see Failed). If self~hidden Then Return info~program = self~programName clause = self~clause If clause \== .Nil Then info~position = self~clauseText( clause )[1] -- Is the clause running one of a compiled method, or of a routine of the -- prelude (which only a compiled method calls)? Its lines are not shown. ::Method hidden Expose currentMethod Return self~hiddenAt( currentMethod, self~clause ) -- The same, for a clause run by method m (.Nil: none). ::Method hiddenAt Use Strict Arg m, clause If m \== .Nil Then Return m~compiled If clause == .Nil Then Return .False If \ clause~isA( .RVM.Clause ) Then Return .False Return clause~text == .Nil -- The traceback of a condition raised now (TRACEBACK): the lines an error -- report has when the error goes up to the top from here, innermost first -- (what Failed collects as it unwinds: see KeepErrorLines, KeepNativeLines -- and ErrorLines; nothing is taken here). 'natives': the lines of the natives -- running (NativeLines), when they were already taken. Each line is (line -- number, text, program, "NATIVE" or nothing, its StackFrame: an -- RVM.FrameInfo). ::Method stackLines Expose currentMethod frames level levels activity Use Strict Arg natives = ( self~pendingNatives ) lines = .Array~new If natives \== .Nil Then lines~appendAll( natives ) m = currentMethod prog = self~programName lv = level saved = self~savedActivations -- The first activation of a START's activity (or of a sendSync) only -- sends the message. If saved~items > 0 Then start = .False Else If self~syncRoot Then start = .True Else If activity == .Nil Then start = .False Else start = activity~message \== .Nil If \ start Then lines~appendAll( self~levelLines( self~clause, self~traceIndent, - self~activeInterprets, m, prog, self~interpretError, lv ) ) Do k = saved~items To 1 By -1 a = saved[ k ] inner = lv lv = levels[ k ] f = .Nil If frames \== .Nil, frames~hasIndex( k ) Then f = frames[ k ] leaving = m If f \== .Nil Then Do If f~program \== .Nil Then prog = f~progName If f~program \== .Nil | f~kind == "METHOD" Then m = f~method End clause = a~clause line = 0 If clause \== .Nil Then line = self~clauseText( clause, m )[1] -- A compiled method is one line, when it leads to one that is not. If leaving \== .Nil, leaving~compiled Then Do now = .False If m \== .Nil Then now = m~compiled If \ now Then Do -- (A native in ooRexx: no package, invocation nor context.) text = NativeLine( leaving ) fi = .RVM.FrameInfo~ofLevel( inner, text, .Nil ) fi~level = .Nil fi~package = .Nil lines~append( .Array~of( line, text, prog, , fi ) ) End End -- The natives that led to a method (NEW, SEND) or a routine (CALL). If f \== .Nil, f~natives \== .Nil Then Do j = f~natives~items To 1 By -1 nc = f~natives[ j ] lines~append( .Array~of( line, NativeText( nc ), prog, , .RVM.FrameInfo~ofNative( nc ) ) ) End -- The first activation of a START's activity (or of a sendSync) only -- sends the message. If k == 1, self~syncRoot Then Iterate If k == 1, activity \== .Nil, activity~message \== .Nil Then Iterate lines~appendAll( self~levelLines( clause, a~traceIndent, a~interprets, m, prog, .Nil, lv ) ) End -- A sendSync's stack goes on with the machine below's (as ooRexx's, through -- the native that sent the message). outer = self~outerContext If outer \== .Nil Then lines~appendAll( outer~stackLines ) Return lines -- The context of the machine below a sendSync's (where the native that sent -- the message runs), or .Nil. ::Method outerContext Expose activity syncRoot If \ syncRoot | activity == .Nil Then Return .Nil s = activity~syncs i = s~index( self ) If i == .Nil Then Return .Nil If i == 1 Then Return activity~context Return s[ i - 1 ] -- The traceback lines of one activation (lv; see ErrorLines): its clause -- (after the data of an INTERPRET that does not parse), then its INTERPRETs; -- the clause is the innermost INTERPRET's, and each INTERPRET instruction is -- the next one's (or the activation's). ::Method levelLines Use Strict Arg clause, indent, interprets, m, prog, iError, lv If clause == .Nil Then Return .Array~of( .Array~of( 0, "", , , .RVM.FrameInfo~ofLevel( lv, "", .Nil ) ) ) If self~hiddenAt( m, clause ) Then Return .Array~new lines = .Array~new -- Data that does not parse: ooRexx's COMPILE frame. If iError \== .Nil Then Do name = prog If iError~hasIndex( 3 ) Then name = iError[3] fi = .RVM.FrameInfo~new( "COMPILE", name, iError[2], iError[1] ) If \ iError~hasIndex( 3 ) Then fi~package = LevelPackage( lv ) t = iError~copy t[5] = fi lines~append( t ) End n = interprets~items here = lv If n > 0 Then here = interprets[ n ][3] line = self~clauseText( clause, m )[1] text = self~clauseTraceLine( clause, indent, m ) lines~append( .Array~of( line, text, prog, , .RVM.FrameInfo~ofLevel( here, text, line ) ) ) Do k = n To 1 By -1 entry = interprets[ k ] here = lv If k > 1 Then here = interprets[ k - 1 ][3] line = self~clauseText( entry[1], m )[1] text = self~clauseTraceLine( entry[1], entry[2], m ) lines~append( .Array~of( line, text, prog, , .RVM.FrameInfo~ofLevel( here, text, line ) ) ) End Return lines -- The traceback lines of the natives running (the innermost first), as -- lines of the current clause; .Nil if none. They are marked (a fourth item) -- so that the clause's own lines follow them (see KeepErrorLines). ::Method pendingNatives Expose nativeLines If nativeLines~isEmpty Then Return .Nil clause = self~clause line = 0 If clause \== .Nil Then line = self~clauseText( clause )[1] lines = .Array~new Do k = nativeLines~items To 1 By -1 nc = nativeLines[ k ] fi = .RVM.FrameInfo~ofNative( nc ) -- A source that does not parse: its line, in its program. If fi~type == "COMPILE" Then lines~append( .Array~of( fi~line, fi~traceLine, fi~name, "NATIVE", fi ) ) Else lines~append( .Array~of( line, fi~traceLine, self~programName, "NATIVE", fi ) ) End Return lines -- CONDITION('O'), and the argument of a CALL ON handler: the condition -- object, a new Directory each time (.NIL without a condition). What it -- holds is shared: its ADDITIONAL is always the same object. ::Method conditionObject Use Strict Arg info world = self~world If info == .Nil Then Return world~nil o = world~newDirectory d = o~native syntax = ( info~condition == "SYNTAX" ) d["CONDITION"] = info~condition d["DESCRIPTION"] = info~description d["PROPAGATED"] = info~propagated If info~rc \== .Nil Then d["RC"] = info~rc If syntax | info~additional \== .Nil Then d["ADDITIONAL"] = self~conditionAdditional( info ) If info~objResult \== .Nil Then d["RESULT"] = info~objResult If info~instruction \== "" Then d["INSTRUCTION"] = info~instruction If info~position \== .Nil Then d["POSITION"] = info~position If info~program \== .Nil Then d["PROGRAM"] = info~program Else d["PROGRAM"] = "" -- TRACEBACK: a List of its lines, made once (always the same object). If info~stack \== .Nil Then Do If info~stackObj == .Nil Then Do l = .List~new Do line Over info~stack l~append( line[2] ) End info~stackObj = world~newOf( world~listClass, l ) End d["TRACEBACK"] = info~stackObj -- STACKFRAMES: a List of its StackFrames, made once; PACKAGE: that of -- the innermost one that has one. If info~framesObj == .Nil Then Do l = .List~new Do line Over info~stack If line~hasIndex( 5 ) Then l~append( world~stackFrameObject( line[5] ) ) End info~framesObj = world~newOf( world~listClass, l ) End d["STACKFRAMES"] = info~framesObj -- (Raised in the REXX package: a NOTREADY, an argument of REXXUTIL.) If info~program == "REXX" Then d["PACKAGE"] = world~rexxPackage Else Do line Over info~stack If \ line~hasIndex( 5 ) Then Iterate If line[5]~package == .Nil Then Iterate d["PACKAGE"] = PackageOf( line[5]~package, world ) Leave End End If syntax Then Do code = info~code Parse Var code major "." minor d["CODE"] = code d["ERRORTEXT"] = ErrorText( major ) If minor == "" | minor == 0 Then d["MESSAGE"] = world~nil Else Do message = info~message If message == .Nil Then Do If info~additional == .Nil Then message = ErrorText( code ) Else message = ErrorText( code, info~additional ) End -- As in an error report, the message ends with a period. If message \== "", Right( message, 1 ) \== "." Then message = message"." d["MESSAGE"] = message End End Return o -- CONDITION('A'): the additional information (.NIL if none). An array of -- the machine becomes an Array once, and stays that one. ::Method conditionAdditional Use Strict Arg info world = self~world If info == .Nil Then Return world~nil a = info~additional If a == .Nil Then Return world~nil If a~isA( .RVM.Stream ) Then Return world~streamObject( a ) -- (NOTREADY) If \ a~isA( .Array ) Then Return a If info~additionalObj == .Nil Then info~additionalObj = world~newArray( a ) Return info~additionalObj /******************************************************************************/ /* The state of the machine that belongs to an activation: saved on CALL and */ /* restored on RETURN. */ /******************************************************************************/ ::Class RVM.Frame Public ::Attribute returnTo -- the address to go back to ::Attribute kind -- "SUB" (CALL) or "FUNC" (function call) ::Attribute name -- the routine's name (44.1, the trace of >F>) ::Attribute descs -- the caller's loop / SELECT descriptors ::Attribute parse -- the caller's parse state ::Attribute sp -- the caller's stack depth ::Attribute trap -- a CALL ON handler: its trap ::Attribute rest -- a CALL ON handler: the traps still to run ::Attribute iheld -- the caller's INTERPRETs (see the machine's iheld) -- An external routine: the caller's program, and what goes with it. ::Attribute program -- the caller's RVM.Program (.Nil: same program) ::Attribute progName -- the caller's program name ::Attribute progSource -- the caller's source lines ::Attribute invocation -- the caller's: COMMAND, SUBROUTINE or FUNCTION ::Attribute entryAllowed -- the caller's trace entry state (see TRACE) ::Attribute entryDone -- A method: where its result goes (see Deliver), and the caller's registers. ::Attribute mode ::Attribute receiver ::Attribute override -- a package's prolog run by a native: its result ::Attribute initAfter -- and INIT is sent to it then (Package~new) ::Attribute install -- a package only installed: the name of its method or routine ::Attribute pend -- a method: the delegates that sent it (see SendDone) ::Attribute natives ::Attribute labels ::Attribute method ::Attribute mframe ::Attribute entryClause ::Attribute entryText ::Attribute atStart -- the caller's clause started traced (see RESA) ::Attribute sender -- a method or a program: the caller's curSender -- A package's prolog run by a native (loadPackage): the package that loads -- it, and the package loaded (added to it when the prolog returns). ::Attribute addTo ::Attribute addTarget -- An external program called (a file's, a macro's): what is public in it -- goes to the caller's package when it returns (ooRexx's mergeRequired). ::Attribute mergeFrom ::Method init Expose returnTo kind name descs parse sp trap rest iheld program natives override - addTo addTarget mergeFrom returnTo = 0; kind = ""; name = ""; descs = .Nil; parse = .Nil; sp = 0 trap = .Nil; rest = .Array~new; iheld = .Nil; program = .Nil natives = .Nil; override = .Nil; self~atStart = .False; self~install = .Nil addTo = .Nil; addTarget = .Nil; mergeFrom = .Nil -- The descriptor of a block (DO, LOOP, SELECT): the trace level it started -- at, and for a loop its control value, TO limit, BY step and FOR count; for -- SELECT CASE, the case value. ::Class RVM.Block Public ::Attribute base ::Attribute first ::Attribute value ::Attribute limit ::Attribute step ::Attribute stepNeg ::Attribute forLeft ::Attribute case ::Attribute over -- DO ... OVER: the items (a host array) ::Attribute pos -- and the position of the current one ::Attribute count -- COUNTER: the rounds that entered the body ::Attribute msg -- DO WITH: a subclass of Supplier (asked by messages) ::Attribute nextSent -- its NEXT has been sent for this round ::Method init Expose base first value limit step stepNeg forLeft case over pos count msg nextSent base = 0; first = .True value = .Nil; limit = .Nil; step = .Nil; stepNeg = .False; forLeft = .Nil case = .Nil; over = .Nil; pos = 0; count = 0; msg = .False; nextSent = .False -- The state of a PARSE. ::Class RVM.Parse Public ::Attribute sources ::Attribute upper ::Attribute lower ::Attribute caseless ::Attribute target ::Method init Expose sources upper lower caseless target sources = .Array~new; upper = .False; lower = .False; caseless = .False target = .Nil /******************************************************************************/ /* RVM.Machine -- run a program */ /******************************************************************************/ ::Class RVM.Machine Public -- The deepest the activations of an activity go: then 11.1 (ooRexx: when its -- C stack is nearly full; about 22000 CALLs on Linux). ::Constant maxDepth 10000 /*----------------------------------------------------------------------------*/ /* Run a program: its main activity, and the activities REPLY and START make */ /* (see RVM.Activity). The one running goes on until it waits or ends; then */ /* the first one ready runs. The run is over when none is ready: the */ /* activities still waiting then wait for nothing that can come (ooRexx would */ /* wait for ever), and the run ends as the main program did. An error that */ /* ends an activity is reported then; the main program's is the run's (its */ /* exit code), and it is raised to the caller when no other activity lives. */ /* 'nested' is a machine run by the machine (a thunk: see YIELD). */ /*----------------------------------------------------------------------------*/ ::Method run Class Use Strict Arg program, context, start = 1, nested = .False Call On Halt Name HostHalt -- Ctrl-C between runs (haltAll) -- The context of the activity running raises NOSTRING (RVM.Obj~reporter: -- see RVM.Obj~stringValue); a nested machine runs in its caller's. If nested Then Do reporter = .RVM.Obj~reporter .RVM.Obj~reporter = context Signal On Syntax Name NestedFailed v = self~execute( program, context, start, .True ) .RVM.Obj~reporter = reporter Return v End world = context~world sched = .RVM.Scheduler~new sched~path = context~programName -- The slice: every so many clauses the activity running lets the others -- ready run (0: never; RVM_SLICE). n = Value( "RVM_SLICE", , "ENVIRONMENT" ) If DataType( n, "W" ) Then sched~slice = n -- The clock of the timers: the real one, or a virtual one (see -- RVM.Scheduler). If Upper( Value( "RVM_CLOCK", , "ENVIRONMENT" ) ) == "VIRTUAL" Then sched~virtual = .True world~scheduler = sched -- The main program starts with its ::OPTIONS. context~applyOptions( program ) act = sched~newActivity( context, .True ) act~state = "RUNNING" -- RVM_LOCAL=eager: .LOCAL is made now, as ooRexx makes it (see -- RVM.World~ensureLocal). If world~localEager Then Do sched~current = act world~ensureLocal End Loop Forever sched~current = act .RVM.Obj~reporter = act~context outcome = self~launch( act, program, start, sched ) If Value( "RVM_ACTTRACE", , "ENVIRONMENT" ) \== "" Then .error~say( "ACT" act~id outcome act~resumeAt ) If outcome \== "WAITING" Then Call EndActivity act, outcome, sched act = sched~next -- None is ready: the objects due their UNINIT get it, in an activity of -- their own (see uninitActivity). If act == .Nil Then act = self~uninitActivity( context, sched ) If act == .Nil Then Leave End sched~current = .Nil .RVM.Obj~reporter = .Nil Return NestedFailed: .RVM.Obj~reporter = reporter Raise Propagate HostHalt: context~haltAll Return -- Run a program's main code now, to its end, as a main program in a context -- of its own, in the activity running (a native needs its result now, as -- ooRexx's runProgram gives it): a wait runs the others in place (pump); an -- error goes up to the caller. The conversions of the instruction that asked (see -- NeedString) are kept for it. ::Method runSync Class Use Strict Arg program, context world = context~world act = .Nil If world~scheduler \== .Nil Then act = world~scheduler~current conversions = .RVM.Obj~conversions requests = .RVM.Obj~requests reporter = .RVM.Obj~reporter .RVM.Obj~reporter = context .RVM.Obj~conversions = .IdentityTable~new .RVM.Obj~requests = .IdentityTable~new If act \== .Nil Then Do context~activity = act act~syncs~append( context ) End Signal On Syntax Name SyncFailed v = self~execute( program, context, 1, .False, act, .True ) .RVM.Obj~conversions = conversions .RVM.Obj~requests = requests .RVM.Obj~reporter = reporter If act \== .Nil Then act~syncs~delete( act~syncs~last ) Return v SyncFailed: .RVM.Obj~conversions = conversions .RVM.Obj~requests = requests .RVM.Obj~reporter = reporter If act \== .Nil Then act~syncs~delete( act~syncs~last ) -- The condition goes on in the machine below, with its lines and frames -- (ooRexx's exception through the native: see Failed). .RVM.ConditionInfo~syncFailure = .Nil If context~failedInfo \== .Nil Then Do lines = context~errorLines If lines == .Nil Then lines = .Array~new sc = Condition( "O" ) .RVM.ConditionInfo~syncFailure = .Array~of( context~failedInfo, lines, sc~code, sc~description, .False ) End Raise Propagate -- Send a message now, to its end, in the activity running (a native needs -- its result now: ooRexx's sendMessage from C++), in context 'context' (see -- RVM.PreludeLoader~sendSync): as runSync, a wait runs the others in place -- (pump), and an error goes up to the caller. Returns the result (.Nil: none). ::Method sendSync Class Use Strict Arg receiver, name, args, program, context world = context~world act = .Nil If world~scheduler \== .Nil Then act = world~scheduler~current conversions = .RVM.Obj~conversions requests = .RVM.Obj~requests reporter = .RVM.Obj~reporter .RVM.Obj~reporter = context .RVM.Obj~conversions = .IdentityTable~new .RVM.Obj~requests = .IdentityTable~new If act \== .Nil Then Do context~activity = act act~syncs~append( context ) End context~syncRoot = .True Signal On Syntax Name SyncFailed v = self~execute( program, context, 1, .False, act, .True, - .Array~of( receiver, name, args ) ) .RVM.Obj~conversions = conversions .RVM.Obj~requests = requests .RVM.Obj~reporter = reporter If act \== .Nil Then act~syncs~delete( act~syncs~last ) Return v SyncFailed: .RVM.Obj~conversions = conversions .RVM.Obj~requests = requests .RVM.Obj~reporter = reporter chained = ( context~outerContext \== .Nil ) If act \== .Nil Then act~syncs~delete( act~syncs~last ) -- The condition goes on in the machine below, with its lines and frames -- (ooRexx's exception through the native: see Failed). .RVM.ConditionInfo~syncFailure = .Nil If context~failedInfo \== .Nil Then Do lines = context~errorLines If lines == .Nil Then lines = .Array~new sc = Condition( "O" ) .RVM.ConditionInfo~syncFailure = .Array~of( context~failedInfo, lines, sc~code, sc~description, chained ) End Raise Propagate -- A nested machine of activity 'act' waits: the other activities run until -- 'act' is ready again. 'act' is trapped (its host frames are below this -- one): the scheduler does not give it (nor the others trapped) while it -- is. None ready: 93.900. ::Method pump Class Use Strict Arg act, sched reporter = .RVM.Obj~reporter conversions = .RVM.Obj~conversions requests = .RVM.Obj~requests sched~trapped~push( act ) Call On Halt Name HostHalt -- Ctrl-C between runs (haltAll) Signal On Syntax Name PumpFailed Loop If act~state == "READY" Then Leave nxt = sched~next If nxt == .Nil Then Do If act~state == "READY" Then Leave -- Nothing can run: what it waits for comes from an activity trapped -- below it (nested waits that cross), or it cannot come at all. message = "RVM: an activity waits for something that cannot come" Do a Over sched~trapped If a \== act, a~state == "READY" Then message = "RVM: nested waits cross (an activity waits below this one)" End sched~trapped~pull Raise Syntax 93.900 Additional( message ) End sched~current = nxt .RVM.Obj~reporter = nxt~context .RVM.Obj~conversions = .IdentityTable~new .RVM.Obj~requests = .IdentityTable~new outcome = self~launch( nxt, .Nil, 1, sched ) If outcome \== "WAITING" Then Call EndActivity nxt, outcome, sched End sched~trapped~pull sched~unqueue( act ) act~state = "RUNNING" sched~current = act .RVM.Obj~reporter = reporter .RVM.Obj~conversions = conversions .RVM.Obj~requests = requests Return PumpFailed: .RVM.Obj~reporter = reporter .RVM.Obj~conversions = conversions .RVM.Obj~requests = requests Raise Propagate HostHalt: sched~haltAll Return -- When the run is over, the objects due their UNINIT (RVM.World~uninitsDue: -- ooRexx's lastChanceUninit) get it, one after another, in a new activity -- (execute: UninitNext); an error in an UNINIT is not reported, and the next -- one runs. .Nil when there is none (or it has run). ::Method uninitActivity Class Private Use Strict Arg context, sched due = context~world~uninitsDue If due~isEmpty Then Return .Nil act = sched~newActivity( context~activityContext ) act~uninits = due sched~ready( act ) Return sched~next -- Run activity 'act' until it waits or ends: WAITING, ENDED, or FAILED (an -- error ended it: its condition object is act~error). The main program's -- error goes up when no other activity lives (the runner reports it). ::Method launch Class Private Use Strict Arg act, program, start, sched Signal On Syntax Name Failed Return self~execute( program, act~context, start, .False, act ) Failed: -- (Not when UNINITs are due: they run after the report, as ooRexx's.) If act~isMain, \ sched~othersLive, \ act~context~world~hasUninits Then Raise Propagate act~error = Condition( "O" ) Return "FAILED" ::Method execute Class Private Use Strict Arg program, context, start = 1, nested = .False, act = .Nil, sync = .False, - syncSend = .Nil -- Ctrl-C (the host's HALT, SIGINT, SIGTERM, SIGHUP): a HALT for the -- program (see HostHalt). Call On Halt Name HostHalt -- An activity that waited goes on: its registers, where it stopped. If \ sync, act \== .Nil, act~regs \== .Nil Then Do rvmRegs = act~regs act~regs = .Nil Do rvmName Over rvmRegs~allIndexes If WordPos( rvmName, "SELF SUPER RVMREGS RVMNAME" ) > 0 Then Iterate Call Value rvmName, rvmRegs[ rvmName ] End Signal On Syntax Name Failed Signal Value act~resumeAt End code = program~code consts = program~consts names = program~names clauses = program~clauses labels = program~labels stack = .Array~new sp = 0 -- The machine side of the activations. A nested machine (a thunk) goes on -- with its caller's, from 'base' (the activation running the clause that -- asked): its frames are on the stack (the natives, the programs of the -- traceback), and an error or an EXIT that gets down to 'base' goes on in -- the machine below (NestedHandoff, ExitUnwind). If nested, context~frames \== .Nil Then frames = context~frames Else frames = .Array~new base = frames~items If \ nested Then context~frames = frames descs = .Array~new parse = .Nil numCache = program~numCache -- PUSHN: (digits, form, value) per address icache = program~icache -- INTERP: data -> address, per address envCache = program~envCache -- ENV: the class found, per name pc = start withs = program~withs again = 0 -- where to resume after CALL ON traps fromLabel = .Nil -- the label a SIGNAL or CALL went to callerFrame = .Nil -- PROCEDURE: the caller's frame and freshFrame = .Nil -- the new one (EXPV, EXPS, EXPC, TAILC) atStart = .False -- the clause started traced (TRACE A) -- Interactive trace (see PauseStart below). pauses = .Array~new -- the pauses open, innermost last jumpMark = .Nil -- JMARK: a LEAVE / ITERATE to pause for traceIgnored = .False -- a TRACE in debug: it pauses (TPAUSE) cmdTraced = .False -- the command was traced (CPAUSE) iheld = .Array~new -- per INTERPRET running: a flow change iflow = .Nil -- typed at its pause, for its end pendingFlow = .Nil -- a flow change for after CALL ON traps -- External routines (see CALLX): how this program was invoked, and the -- trace of the entry to a routine (ooRexx's traceEntry: shown when TRACE -- A, I, L or R starts in its first instruction). entryAllowed = .False entryDone = .False exitVal = .Nil -- EXIT's value (.Nil: none) entryClause = program~firstClause -- the first clause of the body entered entryText = .Nil -- its >I< line (.Nil: a routine's) -- Methods: the method running, its variables (RVM.MethodFrame), and its -- receiver (the sender of a message: a private method's is itself). curMethod = .Nil context~currentMethod = .Nil curFrame = .Nil curSender = .Nil If \ nested Then Do context~rvmProgram = program -- The main program's activation (.CONTEXT, a StackFrame). lv = context~level lv~name = context~programName lv~exec = program lv~kind = "P" lv~args = context~args End convPc = 0 -- the instruction conversions are for convSaved = .Array~new -- those of the instructions whose -- STRING runs (see NeedString) insPc = 0; insSp = 0 -- the instruction running, its stack -- The activity running (a nested machine runs in its caller's). If act == .Nil Then act = context~activity resumeAt = "RESUME" -- where it goes on after it waits heldHalt = .Nil -- a CALL ON HALT trap, one clause later uwReraise = .False -- an unwind that ran notifications replyTraced = .False -- REPLY: its entry traced again replyEntryDue = .False -- (when it starts: ReplyStart) yielding = .False -- it waits for nothing (its slice) sched = context~world~scheduler sliceLeft = 0 -- clauses left in its slice (0: none) If sched \== .Nil, \ sync Then sliceLeft = sched~slice -- The activity of the UNINITs (see uninitActivity). If act \== .Nil, \ sync Then If act~uninits \== .Nil Then Do Signal On Syntax Name Failed Signal UninitNext End -- A message sent now (sendSync): its result is what this returns (see -- Deliver, SYNC). If syncSend \== .Nil Then Do Signal On Syntax Name Failed sRecv = syncSend[1]; sName = syncSend[2]; sArgs = syncSend[3] sStart = .Nil; sMode = "SYNC" -- Its first activation runs as the caller's (ooRexx's native has no -- activation of its own): the sender and the package of the messages it -- sends (PRIVATE, PACKAGE) are the caller's. outer = context~outerContext If outer \== .Nil Then context~level~runs( outer~level ) curSender = context~level~sender Signal DoSend End Resume: Signal On Syntax Name Failed -- A program starts: the packages it requires, then its classes. If WordPos( program~state, "NEW LOADING" ) > 0, \ nested Then Signal StartPackage -- A package only installed (see EnterPackageRun): its requires and -- classes are done; it returns now, without running. If program~state == "READY", \ frames~isEmpty Then If frames~lastItem~install \== .Nil, frames~lastItem~addTarget == program Then Do retVal = .Nil Signal DoReturn End -- ::OPTIONS NOPROLOG: a package that a ::REQUIRES (or Package~new) loads -- does not run its prolog (its requires and its classes are done: it -- returns now). If pc == 1, \ program~optProlog, \ frames~isEmpty Then If frames~lastItem~kind == "REQ" | frames~lastItem~override \== .Nil Then Do retVal = .Nil Signal DoReturn End Loop Forever ins = code[ pc ] -- Conversions to string (see NeedString) last for one instruction. If convPc \== 0, pc \== convPc Then Do .RVM.Obj~conversions~empty .RVM.Obj~requests~empty convPc = 0 End insPc = pc insSp = sp pc += 1 Select Case ins[1] When "CLAUSE" Then Do -- Its slice is over: the activity lets the others ready run first. If sliceLeft > 0 Then Do sliceLeft -= 1 If sliceLeft == 0 Then Do sliceLeft = sched~slice If \ nested, sched~othersReady Then Do pc -= 1 resumeAt = "RESUME" yielding = .True Signal Suspend End End End -- The previous clause is over: the CALL ON traps it fired run now, -- and then this instruction again. If context~callTrapsPending Then Do again = pc - 1 Signal RunTraps End -- A CALL ON HALT trap held one clause (see RunTraps): it runs at the -- end of this one. If heldHalt \== .Nil Then Do context~restoreCallTraps( heldHalt ) heldHalt = .Nil End clause = clauses[ ins[2] ] context~clause = clause fromLabel = .Nil -- The entry is traced if TRACE starts in the first instruction (an -- EXPOSE before it does not count: CLAUSE c E). If entryAllowed, ins[2] \== entryClause, ins[3] \== "E" Then entryAllowed = .False atStart = context~traceA If context~tracing Then Do Select Case ins[3] When "N", "W", "E" Then If context~traceA Then context~traceClause( clause ) When "C" Then If context~traceC Then context~traceClause( clause ) Otherwise Nop End End End When "LABEL" Then Do If context~callTrapsPending Then Do again = pc - 1 Signal RunTraps End If context~traceL Then Do traced = .False If fromLabel == .Nil Then traced = .True Else If fromLabel == consts[ ins[3] ] Then Do fromLabel = .Nil traced = .True End If traced Then Do context~traceClause( clauses[ ins[2] ] ) -- Interactive trace pauses at every label it traces; "=" traces -- (and pauses at) that label again. If context~pauseL Then Do context~clause = clauses[ ins[2] ] pzKind = "N"; pzAgain = pc - 1; pzDrop = 0; pzBase = .Nil Signal PauseStart End End End End -- Interactive trace pauses (see PauseStart) ---------------------------- When "PAUSE" Then If context~pausing Then Do pzKind = "N"; pzAgain = ins[2]; pzDrop = 0; pzBase = .Nil Signal PauseStart End When "BPAUSE" Then If context~pausing Then Do pzKind = "N"; pzAgain = ins[2]; pzDrop = ins[3]; pzBase = .Nil If ins[4] > 0 Then pzBase = descs[ ins[4] ]~base Signal PauseStart End When "DOPAUSE" Then If context~pausing, descs[ ins[3] ]~first Then Do pzKind = "N"; pzAgain = ins[2]; pzDrop = 0 pzBase = descs[ ins[3] ]~base Signal PauseStart End When "IPAUSE" Then If context~pausing Then Do pzKind = "I"; pzAgain = ins[2]; pzDrop = 1; pzBase = .Nil Signal PauseStart End When "TPAUSE" Then If traceIgnored Then Do traceIgnored = .False If context~pausing Then Do pzKind = "N"; pzAgain = ins[2]; pzDrop = 0; pzBase = .Nil Signal PauseStart End End When "CPAUSE" Then If cmdTraced Then Do cmdTraced = .False If context~debug Then Do pzKind = "N"; pzAgain = ins[2]; pzDrop = 0; pzBase = .Nil Signal PauseStart End End When "JMARK" Then If context~pausing Then jumpMark = .Array~of( ins[2], ins[3], ins[4] ) When "JPAUSE" Then If jumpMark \== .Nil Then Do jm = jumpMark jumpMark = .Nil If context~pausing Then Do context~clause = clauses[ jm[1] ] pzKind = "N"; pzDrop = 0; pzBase = .Nil If ins[2] == "R" Then pzAgain = jm[2] Else pzAgain = jm[3] Signal PauseStart End End -- The end of a line typed at a pause: the next line. When "DEND" Then Do pz = pauses~lastItem Call DebugLineOver context, pz sp = pz~sp If context~debugBypass Then Do context~debugBypass = .False Signal PauseEnd End Signal DebugRead End When "TRACEN" Then Call DebugSkip consts[ ins[2] ], context When "TCLAUSE" Then If context~traceA Then context~traceClause( clauses[ ins[2] ] ) When "BOUND" Then If context~callTrapsPending Then Do again = pc - 1 Signal RunTraps End When "INDENT" Then context~indent When "UNINDENT" Then context~unindent When "UNIND2" Then context~unindentTwice When "BASE" Then Do b = .RVM.Block~new b~base = context~traceIndent descs[ ins[2] ] = b End When "SETIND" Then context~traceIndent = descs[ ins[2] ]~base When "DOBODY" Then descs[ ins[2] ]~first = .False When "DOEXIT" Then Do b = descs[ ins[2] ] context~traceIndent = b~base If \ b~first Then context~unindent End When "TRES" Then context~traceResult( consts[ ins[2] ] ) When "ERRJ" Then Do If ins[4] \== -1 Then context~traceIndent = context~activationIndent + ins[4] If ins[3] == 0 Then Raise Syntax ( ins[2] ) Raise Syntax ( ins[2] ) Additional( consts[ ins[3] ] ) End When "TRACE", "TRACEV" Then Do If ins[1] == "TRACE" Then setting = consts[ ins[2] ] Else Do setting = str( stack[sp] ); sp -= 1 n = WholeValue( setting, context~digits ) If n \== .Nil Then Do Call DebugSkip n, context Iterate End End -- In interactive debug the instruction changes nothing, and pauses -- (TPAUSE). If context~debug, \ context~debugPause Then traceIgnored = .True Else Do context~setTrace( setting ) -- An external routine whose first instruction starts tracing -- labels shows its entry (and then its exit). If entryAllowed, \ entryDone, context~traceL Then Do entryDone = .True Call TraceInvocation context, ">I>", entryText End End End When "LOADV" Then Do name = names[ ins[2] ] v = context~lookupVar( name ) If v == .Nil Then v = NoValue( context, name ) If context~traceI Then context~traceTagged( ">V>", name, " => ", v ) sp += 1; stack[sp] = v End When "PUSHC" Then Do v = consts[ ins[2] ] If context~traceI Then context~traceValue( ">L>", v ) sp += 1; stack[sp] = v End When "PUSHN" Then Do c = numCache[ pc ] If c \== .Nil, c[1] == context~digits, c[2] == context~form Then v = c[3] Else Do v = lit( consts[ ins[2] ], context ) numCache[ pc ] = .Array~of( context~digits, context~form, v ) End If context~traceI Then context~traceValue( ">L>", v ) sp += 1; stack[sp] = v End When "STOREV" Then Do name = names[ ins[2] ] v = stack[sp]; sp -= 1 context~setVar( name, v ) If context~traceI Then context~traceTagged( ">=>", name, " <= ", v ) End When "RES" Then context~traceResult( stack[sp] ) -- The result of an assignment: traced when the clause started traced. When "RESA" Then If atStart Then context~traceResult( stack[sp] ) When "PUSHQ" Then Do sp += 1; stack[sp] = consts[ ins[2] ] End When "JF" Then Do v = stack[sp]; sp -= 1 If \ LogicalCondition( str( v ), ins[3] ) Then pc = ins[2] End When "JT" Then Do v = stack[sp]; sp -= 1 If LogicalCondition( str( v ), ins[3] ) Then pc = ins[2] End When "JMP" Then pc = ins[2] When "ADD", "SUB", "MUL", "DIV", "IDIV", "REM" Then Do b = stack[sp]; sp -= 1 a = stack[sp] -- An object on the left: the operator is a message to it. If a~isA( .RVM.Obj ) Then Do op = OperatorName( ins[1] ) Signal SendOperator End If b~isA( .RVM.Obj ) Then b = str( b ) a = num( a, context ) b = num( b, context ) Select Case ins[1] When "ADD" Then Do; v = a~plus( b, context ); op = "+"; End When "SUB" Then Do; v = a~minus( b, context ); op = "-"; End When "MUL" Then Do; v = a~times( b, context ); op = "*"; End When "DIV" Then Do; v = a~divide( b, context ); op = "/"; End When "IDIV" Then Do; v = a~intDivide( b, context ); op = "%"; End When "REM" Then Do; v = a~remainder( b, context ); op = "//"; End End stack[sp] = v If context~traceI Then context~traceTagged( ">O>", '"'op'"', " => ", v ) End When "POW" Then Do b = stack[sp]; sp -= 1 If stack[sp]~isA( .RVM.Obj ) Then Do a = stack[sp]; op = "**" Signal SendOperator End If b~isA( .RVM.Obj ) Then b = str( b ) v = num( stack[sp], context )~power( b, context ) stack[sp] = v If context~traceI Then context~traceTagged( ">O>", '"**"', " => ", v ) End When "EQ", "NE", "LT", "GT", "LE", "GE" Then Do b = stack[sp]; sp -= 1 If stack[sp]~isA( .RVM.Obj ) Then Do a = stack[sp]; op = consts[ ins[2] ] Signal SendOperator End -- A string or a number is never equal to .nil, nor in order with -- it (ooRexx's String, NumberString and Integer): 1 for \= only. If b~isA( .RVM.Obj ) Then Do If b == context~world~nil Then Do v = ( ins[1] == "NE" )~?( "1", "0" ) stack[sp] = v If context~traceI Then context~traceTagged( ">O>", '"'consts[ ins[2] ]'"', " => ", v ) Iterate End b = str( b ) End cmp = CompareNormal( stack[sp], b, context ) Select Case ins[1] When "EQ" Then r = ( cmp == 0 ) When "NE" Then r = ( cmp \== 0 ) When "LT" Then r = ( cmp < 0 ) When "GT" Then r = ( cmp > 0 ) When "LE" Then r = ( cmp <= 0 ) When "GE" Then r = ( cmp >= 0 ) End v = r~?( "1", "0" ) stack[sp] = v If context~traceI Then context~traceTagged( ">O>", '"'consts[ ins[2] ]'"', " => ", v ) End When "SEQ", "SNE", "SLT", "SGT", "SLE", "SGE" Then Do If stack[sp-1]~isA( .RVM.Obj ) Then Do b = stack[sp]; sp -= 1 a = stack[sp]; op = consts[ ins[2] ] Signal SendOperator End b = stack[sp]; sp -= 1 -- .nil: as for EQ (1 for \== only). If b~isA( .RVM.Obj ) Then Do If b == context~world~nil Then Do v = ( ins[1] == "SNE" )~?( "1", "0" ) stack[sp] = v If context~traceI Then context~traceTagged( ">O>", '"'consts[ ins[2] ]'"', " => ", v ) Iterate End End b = str( b ) a = str( stack[sp] ) Select Case ins[1] When "SEQ" Then r = ( a == b ) When "SNE" Then r = \ ( a == b ) When "SLT" Then r = ( a << b ) When "SGT" Then r = ( a >> b ) When "SLE" Then r = ( a <<= b ) When "SGE" Then r = ( a >>= b ) End v = r~?( "1", "0" ) stack[sp] = v If context~traceI Then context~traceTagged( ">O>", '"'consts[ ins[2] ]'"', " => ", v ) End When "CAT", "ABUT", "CATB" Then Do If stack[sp-1]~isA( .RVM.Obj ) Then Do b = stack[sp]; sp -= 1 a = stack[sp]; op = OperatorName( ins[1] ) Signal SendOperator End b = str( stack[sp] ); sp -= 1 Select Case ins[1] When "CAT" Then Do; v = str( stack[sp] ) || b; op = "||"; End When "ABUT" Then Do; v = str( stack[sp] ) || b; op = ""; End When "CATB" Then Do; v = str( stack[sp] ) || " " || b; op = " "; End End stack[sp] = v If context~traceI Then context~traceTagged( ">O>", '"'op'"', " => ", v ) End When "AND", "OR", "XOR" Then Do If stack[sp-1]~isA( .RVM.Obj ) Then Do b = stack[sp]; sp -= 1 a = stack[sp]; op = OperatorName( ins[1] ) Signal SendOperator End -- The left operand is checked first (ooRexx's String~andOp). a = Boolean( str( stack[sp-1] ) ) b = Boolean( str( stack[sp] ) ); sp -= 1 Select Case ins[1] When "AND" Then Do; r = a & b; op = "&"; End When "OR" Then Do; r = a | b; op = "|"; End When "XOR" Then Do; r = a && b; op = "&&"; End End v = r~?( "1", "0" ) stack[sp] = v If context~traceI Then context~traceTagged( ">O>", '"'op'"', " => ", v ) End When "PLUS", "NEG", "NOT" Then Do v = stack[sp] If v~isA( .RVM.Obj ) Then Do a = v; b = .Nil; op = OperatorName( ins[1] ) Signal SendOperator End Select Case ins[1] When "PLUS" Then Do; v = num( v, context )~identity( context ); op = "+"; End When "NEG" Then Do; v = num( v, context )~negate( context ); op = "-"; End When "NOT" Then Do; v = ( \ Boolean( str( v ) ) )~?( "1", "0" ); op = "\"; End End stack[sp] = v If context~traceI Then context~traceTagged( ">P>", '"'op'"', " => ", v ) End -- SAY: to .OUTPUT (SAY), as ooRexx's sayOutput; straight to the -- output while .OUTPUT is the one .LOCAL started with (see -- RVM.World~localTarget). When "SAY" Then Do line = str( stack[sp] ); sp -= 1 context~traceResult( line ) target = context~localTarget( "OUTPUT", .True ) If target == .Nil Then context~out~lineOut( line ) Else Do sRecv = target; sName = "SAY"; sArgs = .Array~of( line ) sStart = .Nil; sMode = "SENDA" Signal DoSend End End When "TAILV" Then Do sp += 1; stack[sp] = str( context~getVar( names[ ins[2] ] ) ) End When "LOADC" Then Do n = ins[3] tail = "" Do k = sp - n + 1 To sp tail = tail || stack[k] End sp -= n stemKey = names[ ins[2] ] v = context~lookupCompound( stemKey, tail ) If v == .Nil Then v = NoValue( context, stemKey || tail, context~getCompound( stemKey, tail ) ) If context~traceI Then Do name = consts[ ins[4] ] context~traceTagged( ">C>", name, " => ", stemKey || tail ) context~traceTagged( ">V>", name, " => ", v ) End sp += 1; stack[sp] = v End When "STOREC" Then Do n = ins[3] tail = "" Do k = sp - n + 1 To sp tail = tail || stack[k] End sp -= n v = stack[sp]; sp -= 1 stemKey = names[ ins[2] ] context~setCompound( stemKey, tail, v ) If context~traceI Then Do name = consts[ ins[4] ] context~traceTagged( ">C>", name, " => ", stemKey || tail ) context~traceTagged( ">=>", name, " <= ", v ) End End When "LOADS" Then Do name = names[ ins[2] ] v = context~getStem( name ) If context~traceI Then context~traceTagged( ">V>", name, " => ", v ) sp += 1; stack[sp] = v End When "STORES" Then Do name = names[ ins[2] ] v = stack[sp]; sp -= 1 context~setStem( name, v ) If context~traceI Then context~traceTagged( ">=>", name, " <= ", v ) End -- An environment symbol that found a class of its package (its own, -- one it sees, one of the REXX package) keeps it, as ooRexx's -- RexxDotVariable does: one per name in a package (the parser's -- dotVariables), so here per name in the program; not in INTERPRET's -- code, parsed anew each time. When "ENV" Then Do name = consts[ ins[2] ] v = .Nil frag = ( insPc >= program~fragStart ) If \ frag Then v = envCache[ name ] If v == .Nil Then Do world = context~world v = world~env( name, program, .True ) If v == .Nil Then v = DotSpecial( name, program, context ) Else If world~envCached, \ frag Then envCache[ name ] = v End If context~traceI Then context~traceTagged( ">E>", name, " => ", v ) sp += 1; stack[sp] = v End -- Messages ------------------------------------------------------------ When "SEND", "CASC", "SENDI", "SENDA" Then Do n = ins[3] sArgs = PopArgs( stack, sp, n ); sp -= n -- ~name:scope: the scope is under the arguments. sStart = .Nil If ins[ ins~items ] == 1 Then Do sStart = stack[sp]; sp -= 1 End sRecv = stack[sp]; sp -= 1 sName = consts[ ins[2] ] sMode = ins[1] If sMode == "SENDI" Then sMode = "SENDI" ins[4] Signal DoSend End -- ~name:scope (ooRexx's RexxExpressionMessage~evaluate): the scope, on -- top of the receiver, must be a class (88.914) and one of the -- receiver's scopes (validateScopeOverride: 93.957). When "SCOPE" Then Do v = stack[sp] ok = v~isA( .RVM.Obj ) If ok Then ok = v~isClass If \ ok Then Raise Syntax 88.914 Array( "SCOPE", "Class" ) If \ context~world~behaviourOf( stack[sp - 1] )~hasScope( v ) Then Raise Syntax 93.957 Array( ObjectText( stack[sp - 1] ), ObjectText( v ) ) End -- USE ARG: argument i (present: to the variable, and on to a). When "USEARG" Then Do v = .Nil If ins[2] <= context~argCount Then v = context~argValue( ins[2] ) If v \== .Nil Then Do context~traceResult( v ) name = names[ ins[3] ] context~setVar( name, v ) If context~traceI Then context~traceTagged( ">=>", name, " <= ", v ) pc = ins[4] End End -- USE ARG to a stem or a compound: argument i on the stack (present: -- traced >>>, and the compiled store follows); absent, .Nil in its -- place, and on to a (its default, or the DROP). When "USEARGP" Then Do v = .Nil If ins[2] <= context~argCount Then v = context~argValue( ins[2] ) If v \== .Nil Then context~traceResult( v ) Else pc = ins[3] sp += 1; stack[sp] = v End -- USE ARG >v, >s.: argument i must be a VariableReference (to a -- simple variable, or to a stem); the local variable, which must have -- no value, becomes its variable (traced >R>). When "USEREF" Then Do v = .Nil If ins[2] <= context~argCount Then v = context~argValue( ins[2] ) Call UseRef context, ins[2], names[ ins[3] ], v End -- >x, >a. (and O>", '">"', " => ", name ) sp += 1; stack[sp] = v End -- USE STRICT ARG: the number of arguments against the flags (R -- required, O optional, S skipped, per position, then "."); ins[3] = 1 -- when "..." ends it. When "USESTRICT" Then Call UseStrict consts[ ins[2] ], ins[3], context, frames -- USE STRICT ARG: required argument i omitted (its turn has come). When "USEOMIT" Then Call UseOmit ins[2], context, frames -- EXPOSE in a method: the object's variables of the method's scope -- (98.992 elsewhere: the parser takes it first in a program or a -- routine, as ooRexx). When "EXPO" Then Do If curFrame == .Nil Then Raise Syntax 98.992 curFrame~share( names[ ins[2] ] ) End When "EXPOS" Then Do If curFrame == .Nil Then Raise Syntax 98.992 stemKey = names[ ins[2] ] curFrame~share( stemKey ) Call StemIn curFrame, stemKey End -- A compound (its tail worked out in the method's own variables): its -- tail of the method's stem is the object's variable (ExposeCompound). When "EXPOC" Then Do n = ins[3] tail = "" Do k = sp - n + 1 To sp tail = tail || stack[k] End sp -= n If curFrame == .Nil Then Raise Syntax 98.992 If context~traceI Then context~traceTagged( ">C>", consts[ ins[4] ], " => ", names[ ins[2] ] || tail ) Call ExposeCompound curFrame~pool, curFrame, names[ ins[2] ], tail End -- EXPOSE (x): x is exposed already (EXPO); now every name in its value -- (all checked first, as ooRexx), in order. When "EXPOI" Then Do If curFrame == .Nil Then Raise Syntax 98.992 name = names[ ins[2] ] value = curFrame[ name ]~value If value == .Nil Then value = NoValue( context, name ) If context~traceI Then context~traceTagged( ">V>", name, " => ", value ) Do up Over ExposeNames( str( value ) ) Call ExposeWord context, up, curFrame~pool, curFrame, curFrame, .True End End -- USE LOCAL in a method: the names in k (and RC, RESULT, SIGL, SELF, -- SUPER) are local; every other variable is the object's, of the -- method's scope, from its first reference on (98.993 elsewhere). When "USEL" Then Do If curFrame == .Nil Then Raise Syntax 98.993 curFrame~useLocal( consts[ ins[2] ] ) End When "PUSHNONE" Then Do sp += 1; stack[sp] = .Nil End When "POP" Then sp -= 1 When "TRARG" Then If context~traceI Then Do v = stack[sp] If v == .Nil Then v = "" context~traceValue( ">A>", v ) End When "KEYW" Then context~traceKeyword( consts[ ins[2] ], stack[sp] ) -- Calls --------------------------------------------------------------- When "FUNCB", "CALLB" Then Do name = consts[ ins[2] ] args = PopArgs( stack, sp, ins[3] ); sp -= ins[3] If \ IsBIF( name ) Then Raise Syntax 43.1 Additional( name ) -- LINEIN and CHARIN of standard input may make only their activity -- wait (see StdinWait). gated = .False If name == "LINEIN" | name == "CHARIN" Then gated = StdinGate( context, \ nested & \ sync, act, sched ) v = CallBIF( name, args, context ) If gated Then Do .RVM.StdinReader~gate = .Nil If v~isA( .RVM.StdinNeed ) Then Signal StdinWait End -- A stream function to .LOCAL's object: its message, sent from here -- (see Deliver, BIF). If v~isA( .RVM.BifSend ) Then Do sRecv = v~target; sName = v~message; sArgs = v~args; sStart = .Nil sMode = "BIF" ins[1] name v~post Signal DoSend End If ins[1] == "FUNCB" Then Do If context~traceI Then context~traceTagged( ">F>", name, " => ", v ) sp += 1; stack[sp] = v End Else Do -- (An object is RESULT as it is: VALUE's; converting it would be -- NOSTRING.) If \ v~isA( .RVM.Obj ) Then v = str( v ) context~setVar( "RESULT", v ) context~traceResult( v ) End End When "FUNCI", "CALLI", "CALLN" Then Do If ins[1] == "CALLN" Then Do n = ins[2] line = ins[3] args = PopArgs( stack, sp, n ); sp -= n name = str( stack[sp] ); sp -= 1 address = labels[ name ] If address == .Nil Then Do If \ IsBIF( name ) Then Do kind = "SUB" Signal CallRoutine End v = BifNow( CallBIF( name, args, context ), context ) If \ v~isA( .RVM.Obj ) Then v = str( v ) context~setVar( "RESULT", v ) context~traceResult( v ) Iterate End kind = "SUB" End Else Do name = consts[ ins[2] ] n = ins[3] line = ins[4] args = PopArgs( stack, sp, n ); sp -= n address = labels[ name ] If address == .Nil Then Raise Syntax 43.1 Additional( name ) If ins[1] == "FUNCI" Then kind = "FUNC" Else kind = "SUB" End f = .RVM.Frame~new f~returnTo = pc f~atStart = atStart f~kind = kind f~name = name f~descs = descs f~parse = parse f~sp = sp f~iheld = iheld If frames~items >= .RVM.Machine~maxDepth Then Raise Syntax 11.1 frames~append( f ) iheld = .Array~new context~pushActivation( args ) context~procValid = ProcedureFirst( code, address ) context~level~name = name context~setVar( "SIGL", line ) descs = .Array~new parse = .Nil fromLabel = name pc = address End When "RETURN", "RETURNV" Then Do context~endDebug If context~callTrapsPending Then Do again = pc - 1 Signal RunTraps End If ins[1] == "RETURNV" Then Do retVal = stack[sp]; sp -= 1 -- After REPLY nobody takes a result (98.936). If context~level~replied Then Raise Syntax 98.936 End Else retVal = .Nil If context~debugPause, \ pauses~isEmpty Then Do flow = .Array~of( "RETURN", retVal ) Signal DebugFlow End Signal DoReturn End -- A routine that is not internal nor built-in (see CallRoutine). -- ns:name, a class: a public class of the package tagged ns. When "NSCLASS" Then Do ns = consts[ ins[2] ] name = consts[ ins[3] ] v = context~world~namespaceClass( program, ns, name ) If context~traceI Then context~traceTagged( ">N>", ns":"name, " => ", v ) sp += 1; stack[sp] = v End -- ns:name(...), CALL ns:name: a public routine of the package tagged -- ns (43.902 when there is none). When "FUNCNS", "CALLNS" Then Do ns = consts[ ins[2] ] name = consts[ ins[3] ] n = ins[4] args = PopArgs( stack, sp, n ); sp -= n If ins[1] == "FUNCNS" Then kind = "FUNC" Else kind = "SUB" r = .RVM.World~findPublicRoutine( context~world~namespacePackage( program, ns ), name ) If r == .Nil Then Raise Syntax 43.902 Array( name, ns ) Signal CallFound End -- A calculated constant of the class whose initializer runs (the scope -- of the method): its value, for the constant's methods. When "SETCONST" Then Do v = stack[sp]; sp -= 1 name = consts[ ins[2] ] cls = curMethod~scope Do t Over .Array~of( cls~native~imethods, cls~native~cmethods ) If t[ name ] \== .Nil Then t[ name ]~value = v End End When "FUNCX", "CALLX" Then Do name = consts[ ins[2] ] n = ins[3] args = PopArgs( stack, sp, n ); sp -= n If ins[1] == "FUNCX" Then kind = "FUNC" Else kind = "SUB" Signal CallRoutine End -- PROCEDURE: a frame of its own; EXPOSE puts the caller's variables -- themselves in it (made in the caller's frame when they are not -- there yet). When "PROC" Then Do -- Valid only as the first instruction of an internal call (17.1). If context~procValid \== .True Then Raise Syntax 17.1 context~procValid = .False callerFrame = context~callerFrame freshFrame = .RVM.Vars~new context~installFrame( freshFrame ) End When "TAILC" Then Do name = names[ ins[2] ] v = ValueIn( callerFrame, name ) If v == .Nil Then v = name Else v = str( v ) sp += 1; stack[sp] = v End When "EXPV" Then Do name = names[ ins[2] ] freshFrame[ name ] = callerFrame~cell( name, .True ) End When "EXPS" Then Do stemKey = names[ ins[2] ] Call StemIn callerFrame, stemKey freshFrame[ stemKey ] = callerFrame~cell( stemKey ) End When "EXPC" Then Do n = ins[3] tail = "" Do k = sp - n + 1 To sp tail = tail || stack[k] End sp -= n If context~traceI Then context~traceTagged( ">C>", consts[ ins[4] ], " => ", names[ ins[2] ] || tail ) Call ExposeCompound callerFrame, freshFrame, names[ ins[2] ], tail End -- EXPOSE (x): x is exposed already (EXPV); now every name in its value. When "EXPI" Then Do name = names[ ins[2] ] value = ValueIn( callerFrame, name ) If value == .Nil Then Do trap = context~trapFor( "NOVALUE" ) If trap \== .Nil, trap~isSignal, trap~state == "ON" Then freshFrame~empty value = NoValue( context, name ) End If context~traceI Then context~traceTagged( ">V>", name, " => ", value ) Do up Over ExposeNames( str( value ) ) Call ExposeWord context, up, callerFrame, freshFrame, callerFrame, .False End End When "SIGNAL", "SIGNALV" Then Do If context~callTrapsPending Then Do again = pc - 1 Signal RunTraps End If ins[1] == "SIGNAL" Then Do name = consts[ ins[2] ] line = ins[3] End Else Do name = str( stack[sp] ); sp -= 1 line = ins[2] End address = labels[ name ] If address == .Nil Then Raise Syntax 16.001 Additional( name ) -- Typed at a pause: it keeps the indentation (see DebugFlow). If context~debugPause, \ pauses~isEmpty Then Do flow = .Array~of( "SIGNAL", name, line, context~traceIndent ) Signal DebugFlow End context~setVar( "SIGL", line ) -- A SIGNAL starts at level 0; in INTERPRET data it keeps its level. If context~interpretLines~isEmpty Then context~traceIndent = 0 context~clearInterprets iheld = .Array~new fromLabel = name pc = address End When "EXIT", "EXITV" Then Do context~endDebug If context~debugPause, \ pauses~isEmpty Then Do If ins[1] == "EXITV" Then Do v = stack[sp]; sp -= 1 End Else v = .Nil flow = .Array~of( "EXIT", v ) Signal DebugFlow End -- The CALL ON traps pending run first; in a routine, they are lost. If context~callTrapsPending Then Do If AtMain( frames ) Then Do again = pc - 1 Signal RunTraps End lost = context~takeCallTraps End -- The value, any object: a method or a routine returns it; the -- exit code of the program is its string (ExitUnwind). If ins[1] == "EXITV" Then Do exitVal = stack[sp]; sp -= 1 End Else exitVal = .Nil Signal ExitUnwind End -- ADDRESS and commands ----------------------------------------------- When "ADDRT" Then context~toggleAddress When "ADDRS", "ADDRV" Then Do If ins[1] == "ADDRS" Then Do name = consts[ ins[2] ]; spec = ins[3] End Else Do name = str( stack[sp] ); sp -= 1; spec = ins[2] End If spec == 0 Then spec = .Nil Else spec = withs[ spec ] If Length( name ) > 250 Then Raise Syntax 29.1 Array( 250, name ) context~setAddress( name, spec ) End When "CMD", "CMDTO" Then Do command = str( stack[sp] ); sp -= 1 If context~traceC Then context~traceValue( ">>>", command ) If ins[1] == "CMD" Then Do name = context~address; spec = .Nil End Else Do name = consts[ ins[2] ] If Length( name ) > 250 Then Raise Syntax 29.1 Array( 250, name ) If ins[3] == 0 Then spec = .Nil Else spec = withs[ ins[3] ] End -- With other activities alive (or a timer pending) a command that -- the host runs makes only its activity wait (RVM.CommandWait): the -- others go on, as natively (see doc/07-concurrency.md). canWait = .False If \ nested, \ sync, act \== .Nil, sched \== .Nil, \ context~debugPause Then canWait = sched~othersThan( act ) condition = IssueCommand( context, name, command, spec, canWait ) If condition~isA( .RVM.CommandWait ) Then Do condition~wait( act, sched ) resumeAt = "CMDRESUMED" Signal Suspend End Signal CmdDone End When "YIELD" Then Return stack[sp] -- INTERPRET ---------------------------------------------------------- When "INTERP" Then Do data = str( stack[sp] ); sp -= 1 held = iflow -- typed at its pause (IPAUSE) iflow = .Nil cache = icache[ pc ] If cache == .Nil Then Do cache = .Table~new icache[ pc ] = cache End address = cache[ data ] If address == .Nil Then Do address = Interpret( program, context, data, pc, ins[2], labels ) cache[ data ] = address End context~enterInterpret( context~clause ) If held == .Nil Then held = 0 iheld~append( held ) pc = address End When "IEND" Then Do context~leaveInterpret context~clause = clauses[ ins[3] ] pc = ins[2] held = iheld~lastItem iheld~delete( iheld~last ) If held \== 0 Then Do flow = held Signal DoFlow End End -- Conditions --------------------------------------------------------- When "TRAPON" Then Do name = consts[ ins[2] ] context~trapOn( name, - .RVM.Trap~new( name, ins[3] == "S", consts[ ins[4] ] ) ) End When "TRAPOFF" Then context~trapOff( consts[ ins[2] ] ) When "STR" Then stack[sp] = str( stack[sp] ) When "KEYWC" Then Do info = context~condition If info == .Nil Then Raise Syntax 98.918 context~traceKeyword( info~condition, stack[sp] ) End When "TRKEY" Then context~traceKeyword( consts[ ins[2] ], consts[ ins[3] ] ) When "RAISE" Then Do -- The operands (NONE when not given), from the top of the stack down. n = ins[4] resultValue = stack[sp]; sp -= 1 values = .Nil If n >= 0 Then Do values = PopArgs( stack, sp, n ); sp -= n End additional = stack[sp]; sp -= 1 description = stack[sp]; sp -= 1 rcValue = stack[sp]; sp -= 1 isReturn = ( ins[3] == "RETURN" ) propagate = ( ins[2] == 0 ) If propagate Then Do info = context~condition If info == .Nil Then Raise Syntax 98.918 name = info~condition info~propagated = "1" If resultValue \== .Nil Then info~objResult = resultValue -- A SYNTAX is raised again in the caller: it is there now (see -- Failed), and its message is made again. If name == "SYNTAX" Then Do info~program = .Nil info~position = .Nil info~message = .Nil End End Else Do name = consts[ ins[2] ] info = .RVM.ConditionInfo~new( name ) info~stack = context~stackLines If \ context~hidden Then Do info~program = context~programName info~position = context~clauseText( context~clause )[1] End If name == "SYNTAX" Then info~objResult = resultValue End If rcValue \== .Nil Then info~rc = rcValue If name == "SYNTAX", \ propagate Then Do Parse Value info~rc With major "." minor If \ DataType( major, "W" ) | ( minor \== "" & \ DataType( minor, "W" ) ) Then Raise Syntax 33.904 If minor == "" Then minor = 0 info~rc = major + 0 info~code = info~rc || "." || ( minor + 0 ) info~additional = .Array~new End If description \== .Nil Then info~description = description If additional \== .Nil Then Do info~additionalObj = .Nil If name \== "SYNTAX" Then info~additional = additional Else Do -- ooRexx's requestArray: an Array, a string's lines (MAKEARRAY), -- another object's REQUEST ARRAY; .NIL or more than one -- dimension is 98.939. If \ additional~isA( .RVM.Obj ) Then additional = context~world~newArray( str( additional )~makeArray ) Else If \ additional~native~isA( .Array ) Then additional = context~world~loader~sendSync( additional, "REQUEST", .Array~of( "ARRAY" ) ) If \ additional~isA( .RVM.Obj ) Then Raise Syntax 98.939 If \ additional~native~isA( .Array ) Then Raise Syntax 98.939 If additional~native~dimension > 1 Then Raise Syntax 98.939 info~additional = NumberInserts( additional~native ) info~additionalObj = additional End End If values \== .Nil Then info~additionalObj = .Nil If values \== .Nil Then info~additional = NumberInserts( values ) If resultValue \== .Nil Then info~result = resultValue -- RAISE ... RETURN acts in this activation; without it (EXIT), in -- the activation of the program, routine or method it runs in (the -- internal routines and handlers between end, as ooRexx's raiseExit). depth = frames~items top = TopLevel( frames ) -- RAISE HALT or NOMETHOD ... RETURN that the caller does not trap is -- an error here, where the RAISE is (ooRexx asks the caller first). If isReturn, depth > 0, WordPos( name, "HALT NOMETHOD" ) > 0 Then If \ context~callerTraps( name ) Then Call UntrappedRaise info If name == "SYNTAX" Then Do Select When propagate, isReturn Then target = depth - 1 When propagate Then target = top - 1 When isReturn Then target = depth Otherwise target = top End context~thrown = .RVM.Throw~new( info, .Nil, target ) Raise Syntax ( info~code ) Additional( info~additional ) - Description "RVM.Raise" End If \ isReturn, top > 0 Then Do Do While frames~items > top Call PopFrame End depth = top isReturn = .True End If isReturn, depth > 0 Then Do context~raising = info retVal = info~result Signal DoReturn End Call UntrappedRaise info If info~result == .Nil Then context~exitCode = "" Else context~exitCode = str( info~result ) Signal Finished End -- Concurrency ------------------------------------------------------- -- GUARD ON / GUARD OFF (ins[2]), in a method's activation only -- (99.911): ON takes the lock of the method's scope, when it has it -- not (it may wait for it: GRANTED); OFF lets it go. When "GUARD" Then Do lv = context~level If lv~type \== "METHOD" Then Raise Syntax 99.911 If ins[2] == "OFF" Then lv~unlock Else If \ lv~locked Then Do lv~locked = .True If \ lv~pool~reserve( act ) Then Do resumeAt = "GRANTED" Signal Suspend End End End -- GUARD ... WHEN: the value of the expression (34.902 unless 0 or 1). -- 0: the activity watches the variables k (names of the method's -- scope), lets the lock go while it waits for one of them to change, -- and then takes it again and evaluates the expression again (at a). When "GWHEN" Then Do v = stack[sp]; sp -= 1 context~traceKeyword( "WHEN", v ) If LogicalCondition( str( v ), "GUARD" ) Then act~unwatch Else Do lv = context~level act~watch( lv~pool, consts[ ins[3] ] ) act~relock = lv~locked lv~unlock act~guarding = .True pc = ins[2] resumeAt = "GUARDRESUME" Signal Suspend End End -- REPLY [v], in a method's activation only (99.919), once (98.935): -- the caller gets v as if the method returned, and the method goes on -- in a new activity (DoReply). When "REPLY", "REPLYV" Then Do If ins[1] == "REPLYV" Then Do retVal = stack[sp]; sp -= 1 End Else retVal = .Nil lv = context~level If lv~type \== "METHOD" Then Raise Syntax 99.919 If lv~replied Then Raise Syntax 98.935 lv~replied = .True Signal DoReply End -- FORWARD is for a method activation only (98.947). When "FWDOK" Then If context~level~type \== "METHOD" Then Raise Syntax 98.947 -- FORWARD: the message of this method activation sent on (see -- Forward); its result is this method's (FWD), or RESULT (CONTINUE). When "FWD" Then Do n = ins[3] values = .Nil If n >= 0 Then Do values = PopArgs( stack, sp, n ); sp -= n End fArgs = stack[sp]; sp -= 1 fClass = stack[sp]; sp -= 1 fMsg = stack[sp]; sp -= 1 fTo = stack[sp]; sp -= 1 world = context~world If fTo == .Nil Then sRecv = context~getVar( "SELF" ) Else sRecv = fTo If fMsg == .Nil Then sName = curMethod~name Else sName = Upper( str( fMsg ) ) Select When values \== .Nil Then sArgs = values When fArgs == .Nil Then sArgs = context~args~copy When fArgs~isA( .RVM.Obj ) Then Do If \ fArgs~native~isA( .Array ) Then Raise Syntax 98.946 If fArgs~native~dimension > 1 Then Raise Syntax 98.946 sArgs = fArgs~native~copy End Otherwise sArgs = str( fArgs )~makeArray End sStart = .Nil If fClass \== .Nil Then Do If \ fClass~isA( .RVM.Obj ) Then Raise Syntax 88.914 Array( "SCOPE", "Class" ) If \ fClass~isClass Then Raise Syntax 88.914 Array( "SCOPE", "Class" ) End -- Without CONTINUE, this activation is a phantom from here on: an -- error in the send (the scope's too) goes past its traps. If ins[2] \== 1 Then context~level~forwarded = .True If fClass \== .Nil Then Do sStart = fClass -- The receiver's scopes, as validateScopeOverride: a class -- object has those of its class methods (a mixin's too). If \ world~behaviourOf( sRecv )~hasScope( sStart ) Then Raise Syntax 93.957 Array( ObjectText( sRecv ), ObjectText( sStart ) ) End If ins[2] == 1 Then sMode = "FWDC" Else sMode = "FWD" Signal DoSend End -- Loops -------------------------------------------------------------- When "DOSTART" Then Do descs[ ins[2] ]~value = num( stack[sp], context )~identity( context ) sp -= 1 End When "DOTO" Then Do v = stack[sp]; sp -= 1 context~traceKeyword( "TO", v ) descs[ ins[2] ]~limit = num( v, context )~identity( context ) End When "DOBY" Then Do v = stack[sp]; sp -= 1 context~traceKeyword( "BY", v ) descs[ ins[2] ]~step = num( v, context )~identity( context ) End When "DOFOR", "DOREP" Then Do v = stack[sp]; sp -= 1 context~traceKeyword( "FOR", v ) If ins[1] == "DOFOR" Then kind = "FOR" Else kind = "REPEAT" descs[ ins[2] ]~forLeft = LoopCount( v, context, kind ) End When "DOINIT" Then Do l = descs[ ins[2] ] If l~step == .Nil Then l~step = lit( "1", context ) l~stepNeg = ( l~step~sign < 0 ) name = names[ ins[3] ] context~setVar( name, l~value ) If context~traceI Then context~traceTagged( ">=>", name, " <= ", l~value ) End -- A control variable that is a stem or a compound: DOINITP pushes its -- first value, DOSTEPP the next one (from the value it was loaded -- with); the compiled code stores them. When "DOINITP" Then Do l = descs[ ins[2] ] If l~step == .Nil Then l~step = lit( "1", context ) l~stepNeg = ( l~step~sign < 0 ) sp += 1; stack[sp] = l~value End When "DOSTEPP" Then Do l = descs[ ins[2] ] current = stack[sp] context~traceResult( current ) value = num( current, context )~plus( l~step, context ) context~traceResult( value ) l~value = value stack[sp] = value End -- COUNTER: 0 when the loop starts (Z), the next round (N), pushed for -- the compiled code to store; TRCTR traces it. When "DOCTR" Then Do b = descs[ ins[2] ] If ins[3] == "Z" Then b~count = 0 Else b~count += 1 sp += 1; stack[sp] = lit( b~count, context ) End When "TRCTR" Then context~traceKeyword( "COUNTER", lit( descs[ ins[2] ]~count, context ) ) When "DOSTEP" Then Do l = descs[ ins[2] ] name = names[ ins[3] ] current = context~lookupVar( name ) If current == .Nil Then current = NoValue( context, name ) If context~traceI Then context~traceTagged( ">V>", name, " => ", current ) context~traceResult( current ) value = num( current, context )~plus( l~step, context ) context~traceResult( value ) context~setVar( name, value ) If context~traceI Then context~traceTagged( ">=>", name, " <= ", value ) l~value = value End When "DOTEST" Then Do l = descs[ ins[2] ] go = .True If l~limit \== .Nil Then Do cmp = l~value~compare( l~limit, context ) If l~stepNeg Then go = ( cmp >= 0 ) Else go = ( cmp <= 0 ) End If go, l~forLeft \== .Nil Then Do If l~forLeft <= 0 Then go = .False Else l~forLeft -= 1 End If \ go Then pc = ins[3] End -- DO ... OVER: the items of the collection (DOOVER), or the tails of -- a stem (DOOVERS: its value was traced), taken now; DONEXT assigns -- the next one to the control variable, or goes to a. When "DOOVER", "DOOVERS" Then Do v = stack[sp]; sp -= 1 context~traceKeyword( "OVER", v ) b = descs[ ins[2] ] If ins[1] == "DOOVERS" Then b~over = StemTails( context, names[ ins[3] ] ) Else b~over = OverItems( v, context ) b~pos = 0 End When "DONEXT" Then Do b = descs[ ins[2] ] If b~pos >= b~over~items Then pc = ins[4] Else Do b~pos += 1 v = b~over[ b~pos ] name = names[ ins[3] ] context~setVar( name, v ) If context~traceI Then context~traceTagged( ">=>", name, " <= ", v ) End End -- DO ... OVER into a stem or a compound: DOSKIP moves to the next -- item (or goes to a), DOITEM pushes it. When "DOSKIP" Then Do b = descs[ ins[2] ] If b~pos >= b~over~items Then pc = ins[3] Else b~pos += 1 End When "DOITEM" Then Do b = descs[ ins[2] ] sp += 1; stack[sp] = b~over[ b~pos ] End -- DO WITH: the SUPPLIER of the collection (Deliver keeps it). When "DOWITH" Then Do sRecv = stack[sp]; sp -= 1 sName = "SUPPLIER"; sArgs = .Array~new; sStart = .Nil sMode = "WITH" ins[2] Signal DoSend End -- A round of DO WITH: the supplier's next (after the first round); -- none left, out. When "DONEXTW" Then Do b = descs[ ins[2] ] -- A subclass of Supplier: NEXT (after the first round; this -- instruction runs again when it returns), then AVAILABLE. If b~msg Then Do sRecv = b~over; sArgs = .Array~new; sStart = .Nil If b~pos > 0, \ b~nextSent Then Do b~nextSent = .True sName = "NEXT"; sMode = "SENDA" pc -= 1 Signal DoSend End b~nextSent = .False b~pos += 1 sName = "AVAILABLE"; sMode = "WAVAIL" ins[3] Signal DoSend End u = b~over If b~pos > 0 Then u~pos += 1 b~pos += 1 If \ u~available Then pc = ins[3] End -- DO WITH: the index (I) or the item (V) of the round, to a variable. When "WITHSET" Then Do If descs[ ins[2] ]~msg Then Do sRecv = descs[ ins[2] ]~over; sArgs = .Array~new; sStart = .Nil If ins[4] == "I" Then sName = "INDEX" Else sName = "ITEM" sMode = "WSET" ins[3] Signal DoSend End u = descs[ ins[2] ]~over If ins[4] == "I" Then v = u~indexes[ u~pos ] Else v = u~items[ u~pos ] If .Nil == v Then v = context~world~nil name = names[ ins[3] ] context~setVar( name, v ) If context~traceI Then context~traceTagged( ">=>", name, " <= ", v ) End -- DO WITH into a stem or a compound: the index (I) or the item (V) -- of the round, pushed. When "WITHGET" Then Do If descs[ ins[2] ]~msg Then Do sRecv = descs[ ins[2] ]~over; sArgs = .Array~new; sStart = .Nil If ins[3] == "I" Then sName = "INDEX" Else sName = "ITEM" sMode = "WPUSH" Signal DoSend End u = descs[ ins[2] ]~over If ins[3] == "I" Then v = u~indexes[ u~pos ] Else v = u~items[ u~pos ] If .Nil == v Then v = context~world~nil sp += 1; stack[sp] = v End -- An array term: its n items (NONE: none there). When "MKARR" Then Do n = ins[2] a = .Array~new( n ) Do k = 1 To n If stack[ sp - n + k ] \== .Nil Then a[k] = stack[ sp - n + k ] End sp -= n v = context~world~newArray( a ) context~traceResult( v ) sp += 1; stack[sp] = v End When "CASE" Then Do descs[ ins[2] ]~case = stack[sp]; sp -= 1 End -- WHEN of SELECT CASE: the CASE value's "==" (ooRexx's -- WhenCaseInstruction): an object's, a message; its result is traced -- (Deliver) and checked by the JT CASE that follows (34.905). A -- string's (or a number's): .nil is never equal; else the string -- value of the other (a conversion first: this instruction may run -- again, so nothing is traced before it). When "CASEEQ" Then Do c = descs[ ins[2] ]~case v = stack[sp] If c~isA( .RVM.Obj ) Then Do context~traceResult( v ) sArgs = .Array~of( v ); sMode = "CASEEQ" sRecv = c; sName = "=="; sStart = .Nil sp -= 1 Signal DoSend End If v~isA( .RVM.Obj ), v == context~world~nil Then r = .False Else r = ( str( c ) == str( v ) ) context~traceResult( v ) r = r~?( "1", "0" ) context~traceResult( r ) stack[sp] = r End -- Parsing ------------------------------------------------------------ When "PSRC", "PSRCV" Then Do parse = .RVM.Parse~new flags = ins[3] parse~upper = Pos( "U", flags ) > 0 parse~lower = Pos( "L", flags ) > 0 parse~caseless = Pos( "C", flags ) > 0 variant = ins[2] sources = .Array~new Select Case variant When "VAR", "VALUE" Then Do v = stack[sp]; sp -= 1 context~traceKeyword( variant, v ) sources~append( str( v ) ) End When "ARG" Then Do n = context~argCount Do k = 1 To n v = context~argValue( k ) If v == .Nil Then sources~append( "" ) Else sources~append( str( v ) ) End If n == 0 Then sources~append( "" ) End When "PULL" Then Do -- An empty queue: a line of STDIN, as PARSE LINEIN reads it -- (at its end, NOTREADY). .STDQUE's PULL (.nil: empty), when -- someone could tell (see RVM.World~queueTarget). target = context~queueTarget If target \== .Nil Then Do v = context~world~loader~sendSync( target, "PULL", .Array~new ) If v == .Nil | v == context~world~nil Then v = BifNow( CallBIF( "LINEIN", .Array~new, context ), context ) v = str( v ) End Else If context~queued > 0 Then v = context~pullLine Else Do gated = StdinGate( context, \ nested & \ sync, act, sched ) v = CallBIF( "LINEIN", .Array~new, context ) If gated Then Do .RVM.StdinReader~gate = .Nil If v~isA( .RVM.StdinNeed ) Then Signal StdinWait End v = BifNow( v, context ) End context~traceKeyword( "PULL", v ) sources~append( v ) End When "LINEIN" Then Do gated = StdinGate( context, \ nested & \ sync, act, sched ) v = CallBIF( "LINEIN", .Array~new, context ) If gated Then Do .RVM.StdinReader~gate = .Nil If v~isA( .RVM.StdinNeed ) Then Signal StdinWait End v = BifNow( v, context ) context~traceKeyword( "LINEIN", v ) sources~append( v ) End When "SOURCE" Then Do v = .RVM.SystemHost~systemName context~invocation context~programName context~traceKeyword( "SOURCE", v ) sources~append( v ) End When "VERSION" Then Do v = .RVM.Context~VERSION context~traceKeyword( "VERSION", v ) sources~append( v ) End Otherwise sources~append( "" ) End parse~sources = sources End When "PTPL" Then Do k = ins[2] If parse~sources~hasIndex( k ) Then src = parse~sources[ k ] Else src = "" If parse~upper Then src = Upper( src ) If parse~lower Then src = Lower( src ) context~traceResult( src ) parse~target = .RVM.ParseTarget~new( src ) End When "PEND" Then parse~target~moveToEnd When "PSRCH" Then Do pat = str( stack[sp] ); sp -= 1 If parse~caseless Then parse~target~caselessSearch( pat ) Else parse~target~search( pat ) End When "PABS", "PFWD", "PBWD", "PFLEN", "PBLEN" Then Do -- A whole number, not negative (ooRexx's requestUnsignedNumber). v = str( stack[sp] ); sp -= 1 n = unsignedWholeNumber( v, context~digits ) If n == .Nil Then Raise Syntax 26.4 Array( v ) Select Case ins[1] When "PABS" Then parse~target~absolute( n ) When "PFWD" Then parse~target~forward( n ) When "PBWD" Then parse~target~backward( n ) When "PFLEN" Then parse~target~forwardLength( n ) When "PBLEN" Then parse~target~backwardLength( n ) End End When "PWORD", "PREST" Then Do If ins[1] == "PWORD" Then piece = parse~target~getWord Else piece = parse~target~remainder name = names[ ins[2] ] context~setVar( name, piece ) If context~traceI Then context~traceTagged( ">=>", name, " <= ", piece ) Else If context~traceR Then context~traceResult( piece ) End -- A compound target: its tail is on the stack (worked out now). When "PWORDC", "PRESTC" Then Do n = ins[3] tail = "" Do k = sp - n + 1 To sp tail = tail || stack[k] End sp -= n If ins[1] == "PWORDC" Then piece = parse~target~getWord Else piece = parse~target~remainder stemKey = names[ ins[2] ] context~setCompound( stemKey, tail, piece ) If context~traceI Then Do name = consts[ ins[4] ] context~traceTagged( ">C>", name, " => ", stemKey || tail ) context~traceTagged( ">=>", name, " <= ", piece ) End Else If context~traceR Then context~traceResult( piece ) End -- A stem target: the whole stem. When "PWORDS", "PRESTS" Then Do If ins[1] == "PWORDS" Then piece = parse~target~getWord Else piece = parse~target~remainder name = names[ ins[2] ] context~setStem( name, piece ) If context~traceI Then context~traceTagged( ">=>", name, " <= ", piece ) Else If context~traceR Then context~traceResult( piece ) End -- A message term target: the piece, twice (one for the message, one -- for PTRM). When "PWORDM", "PRESTM" Then Do If ins[1] == "PWORDM" Then piece = parse~target~getWord Else piece = parse~target~remainder sp += 1; stack[sp] = piece sp += 1; stack[sp] = piece End -- The piece a message term got, traced after the assignment as -- ooRexx's ParseTrigger does (TRACE I shows nothing: the message's -- assignment trace has no value). When "PTRM" Then Do piece = stack[sp]; sp -= 1 If context~traceR, \ context~traceI Then context~traceResult( piece ) End When "SWAP" Then Do v = stack[sp]; stack[sp] = stack[sp - 1]; stack[sp - 1] = v End When "PDOTW", "PDOTR" Then Do If \ context~traceR Then Do If ins[1] == "PDOTW" Then parse~target~skipWord Else parse~target~skipRemainder End Else Do If ins[1] == "PDOTW" Then piece = parse~target~getWord Else piece = parse~target~remainder If context~traceI Then context~traceValue( ">.>", piece ) End End -- Other instructions ------------------------------------------------- When "PUSH", "QUEUE" Then Do line = str( stack[sp] ); sp -= 1 context~traceResult( line ) -- .STDQUE's PUSH or QUEUE, as ooRexx (see RVM.World~queueTarget); -- straight to the queue when no one could tell. target = context~queueTarget( .True ) If target == .Nil Then Do If ins[1] == "PUSH" Then context~pushLine( line ) Else context~queueLine( line ) End Else Do sRecv = target; sName = ins[1]; sArgs = .Array~of( line ) sStart = .Nil; sMode = "SENDA" Signal DoSend End End When "NUMDIG", "NUMFUZZ", "NUMFORM" Then Do v = stack[sp]; sp -= 1 If ins[1] == "NUMFORM" Then Call NumericForm context, ins[2], v, program Else Call Numeric context, ins[1], v, program End When "DROPV" Then context~dropVar( names[ ins[2] ] ) When "DROPS" Then context~dropStem( names[ ins[2] ] ) When "DROPC" Then Do n = ins[3] tail = "" Do k = sp - n + 1 To sp tail = tail || stack[k] End sp -= n context~dropCompound( names[ ins[2] ], tail ) End When "DROPI" Then Do -- (Unassigned: NOVALUE, as ooRexx's DropInstruction evaluates it.) value = context~lookupVar( names[ ins[2] ] ) If value == .Nil Then value = NoValue( context, names[ ins[2] ] ) If context~traceI Then context~traceTagged( ">V>", names[ ins[2] ], " => ", value ) value = str( value ) Do w = 1 To Words( value ) Call DropByName context, Word( value, w ) End End When "ERR" Then Do If ins[3] == 0 Then Raise Syntax ( ins[2] ) Raise Syntax ( ins[2] ) Additional( consts[ ins[3] ] ) End Otherwise Raise Syntax 93.900 Additional( "RVM: unknown instruction" ins[1] ) End End /*----------------------------------------------------------------------------*/ /* An operator with an object on its left (a, and b; .Nil for a prefix one): */ /* the message op to a. Its result goes where the operation's would, traced */ /* the same way (>O>, >P>). */ /*----------------------------------------------------------------------------*/ SendOperator: If b == .Nil Then Do sArgs = .Array~new sMode = "PREFIX" End Else Do sArgs = .Array~of( b ) sMode = "OP" End sRecv = a; sName = op; sStart = .Nil sp -= 1 Signal DoSend /*----------------------------------------------------------------------------*/ /* A message: sName to sRecv with sArgs (sStart: the class the search starts */ /* at, for ~name:scope). sMode says where its result goes (see Deliver). A */ /* native runs here (and may end by delegating: NEW sends INIT); a method in */ /* Rexx is a new activation (EnterMethod), and its result is delivered when */ /* it returns (DoReturn). */ /*----------------------------------------------------------------------------*/ DoSend: world = context~world sMsg = sName -- the message sent (91.999, >M>) sOrig = sRecv -- its receiver (a cascade) sPend = .Array~new -- the delegates to go back to sDepth = context~nativeLines~items sMethod = .Nil -- a delegate's own method sFirst = .True -- the message itself (not delegated) sUnknown = .False -- UNKNOWN runs instead -- What a native left (see RunNatives) runs first; then this message. If \ world~deferred~isEmpty Then Do dd = world~deferred[1] world~deferred~delete( 1 ) sPend~append( .RVM.Resend~new( sRecv, sName, sArgs, sStart ) ) Do e Over dd[2] sPend~append( e ) End v = dd[1] Signal Delegated End SendLoop: If sMethod \== .Nil Then m = sMethod Else m = Lookup( sRecv, sName, sStart, world ) sMethod = .Nil -- Not found: it may be a method of the prelude (see RVM.World). If m == .Nil, world~prelude == .Nil Then Do world~ensurePrelude m = Lookup( sRecv, sName, sStart, world ) End sStart = .Nil -- A private method: only its object sends it; from another, it is not -- there (UNKNOWN, NOMETHOD, and 97.2). sPrivate = .False If sFirst, m \== .Nil Then If m~flags \== "-", m~hasFlag( "P" ), \ PrivateOK( m, sRecv, curSender, world ) Then Do m = .Nil sPrivate = .True End -- A package method: only code of its package sends it; from another, it -- is not there (UNKNOWN, NOMETHOD, and 97.3; ooRexx's checkPackage). sPackage = .False If sFirst, m \== .Nil, \ sPrivate Then If m~flags \== "-", m~hasFlag( "K" ), \ m~hasFlag( "P" ), \ PackageOK( m, context ) Then Do m = .Nil sPackage = .True End sFirst = .False -- A protected method: the security manager of the activation is asked -- (METHOD, with the receiver, the name and the arguments: ooRexx's -- processProtectedMethod); when it handles it, its RESULT is the result. If m \== .Nil, context~secMgr \== .Nil Then If m~flags \== "-", m~hasFlag( "R" ) Then Do info = world~security( context~secMgr, "METHOD", .Array~of( "OBJECT", sRecv, - "NAME", sName, "ARGUMENTS", world~newArray( sArgs~copy ) ) ) If info \== .Nil Then Do v = info["RESULT"] Signal SendDone End End -- A VariableReference: a message it does not have goes to its variable's -- value, with no UNKNOWN run (ooRexx's processUnknown). If m == .Nil, \ sPrivate, \ sPackage, sRecv~isA( .RVM.Obj ) Then If sRecv~native~isA( .RVM.VarRef ) Then Do sRecv = sRecv~native~resolved( world ) sFirst = .True Signal SendLoop End If m == .Nil Then Do m = Lookup( sRecv, "UNKNOWN", .Nil, world ) -- Neither: NOMETHOD (described by the message, its ADDITIONAL the -- receiver); untrapped, 97.1 (97.2: private). If m == .Nil Then Do info = .RVM.ConditionInfo~new( "NOMETHOD", sName ) info~additional = sRecv context~raiseCondition( info ) -- a SIGNAL ON trap does not return If sPrivate Then Raise Syntax 97.2 Array( ObjectText( sRecv ), sName ) If sPackage Then Raise Syntax 97.3 Array( ObjectText( sRecv ), sName ) Raise Syntax 97.1 Array( ObjectText( sRecv ), sName ) End sUnknown = .True -- One written in Rexx gets the arguments as an Array. If m~isCode Then sArgs = .Array~of( sName, world~newArray( sArgs ) ) Else sArgs = .Array~of( sName, sArgs ) End If m~isCode Then Signal EnterMethod -- (Not for an attribute, nor for an ABSTRACT method: ooRexx shows no line.) If Left( m~key, 2 ) \== "A.", m~key \== "ABSTRACT" Then context~nativeLines~append( .RVM.NativeCall~new( NativeLine( m ), m, sRecv, sName, sArgs ) ) Call CheckMethodArgs m, sArgs -- RUN, SETMETHOD and UNSETMETHOD are restricted: they check who sends -- them (see CheckRestricted). If Left( m~key, 2 ) == "O.", WordPos( m~key, "O.RUN O.SETMETHOD O.UNSETMETHOD" ) > 0 Then .RVM.Obj~sender = curSender -- A Stream's LINEIN, CHARIN and ARRAYIN of standard input may make only -- their activity wait (see StdinWait; the method is sent again then). gated = .False If Left( m~key, 2 ) == "X." Then If WordPos( Upper( SubStr( m~key, 3 ) ), "STREAM_LINEIN STREAM_CHARIN STREAM_ARRAYIN" ) > 0 Then gated = StdinGate( context, \ nested & \ sync, act, sched ) v = CallNative( m, sRecv, sArgs, context, sName ) If gated Then .RVM.StdinReader~gate = .Nil -- The packages of the methods and routines it compiled are installed -- first (see PendingInstall). If .RVM.NativeCall~pending Then v = InstallsFirst( v, context ) If v~isA( .RVM.RoutineCall ) Then Signal EnterRoutineCall If v~isA( .RVM.PackageRun ) Then Signal EnterPackageRun If v~isA( .RVM.Delegate ) Then Signal Delegated If v~isA( .RVM.StartMessage ) Then Signal SpawnStart If v~isA( .RVM.Wait ) Then Signal WaitFor If v~isA( .RVM.Reraise ) Then Signal Reraise Signal SendDone -- The native must wait (v, an RVM.Wait): for a message to complete (a -- circular wait is 98.905), or for a lock (the native took its place in the -- queue); then it is sent again. WaitFor: natives = context~nativeLines Do While natives~items > sDepth natives~delete( natives~last ) End w = v~on If w~isA( .RVM.MessageState ) Then Do If w~startActivity \== .Nil Then w~startActivity~checkDeadLock( act ) w~waiting~append( act ) act~waitingOn = w End sMethod = m resumeAt = "SENDLOOP" If w~isA( .RVM.StdinWait ) Then resumeAt = "STDINSENT" Signal Suspend -- The error of a message raised again (v, an RVM.Reraise: its RESULT): here, -- with the lines it had (ooRexx's reraiseException). Reraise: info = v~info info~program = .Nil info~position = .Nil info~message = .Nil info~propagated = "1" throw = .RVM.Throw~new( info, .Nil, frames~items ) throw~reraise = .True context~thrown = throw Raise Syntax ( info~code ) Additional( info~additional ) Description "RVM.Raise" -- The message sent returned v: back to the delegates that sent it (their -- result, or what their THEN gives: maybe another message), and then v is -- the result of the first message. SendDone: natives = context~nativeLines Loop While \ sPend~isEmpty p = sPend~lastItem sPend~delete( sPend~last ) If p~result \== .Nil Then v = p~result If p~then \== .Nil Then Do Do While natives~items > sDepth natives~delete( natives~last ) End v = p~then~next( v, context ) If v~isA( .RVM.Delegate ) Then Signal Delegated End End Do While natives~items > sDepth natives~delete( natives~last ) End Signal Deliver -- A native ended by delegating (v): the message it sends. Delegated: If v~result \== .Nil | v~then \== .Nil Then sPend~append( v ) -- (A message that a native sends is checked as the message itself, with -- the sender and the package of the code that called the native: ooRexx's -- C++ methods have no activation, so messageSend sees the caller's. Not -- when the delegate runs a given method: ooRexx's method->run.) sFirst = ( v~method == .Nil ) sRecv = v~receiver sName = v~name sArgs = v~args sStart = v~scope sMethod = v~method sUnknown = .False Signal SendLoop -- The result v of the message sMsg to sOrig, where sMode says: SEND (the -- stack; 91.999 without one), CASC (the receiver, instead), SENDI N / SENDI -- C (RESULT), SENDA (nowhere), OP / PREFIX (an operator: the stack). Deliver: If WordPos( Word( sMode, 1 ), "WITH WAVAIL WSET" ) > 0 Then Parse Var sMode sMode sWith If Word( sMode, 1 ) == "BIF" Then Parse Var sMode sMode bifKind bifName bifPost Select Case sMode When "SEND", "OP", "PREFIX" Then Do If .Nil == v Then Raise Syntax 91.999 Array( sMsg ) If context~traceI Then Select Case sMode When "SEND" Then context~traceTagged( ">M>", '"'sMsg'"', " => ", v ) When "OP" Then context~traceTagged( ">O>", '"'sMsg'"', " => ", v ) Otherwise context~traceTagged( ">P>", '"'sMsg'"', " => ", v ) End sp += 1; stack[sp] = v End -- WHEN of SELECT CASE: the result of "==" (see CASEEQ), traced. When "CASEEQ" Then Do If .Nil == v Then Raise Syntax 91.999 Array( sMsg ) context~traceResult( v ) sp += 1; stack[sp] = v End When "CASC" Then Do If context~traceI Then context~traceTagged( ">M>", '"'sMsg'"', " => ", sOrig ) sp += 1; stack[sp] = sOrig End -- STRING, for a conversion: kept, and the instruction runs again. When "STRING" Then Do -- (None: its default string value, its OBJECTNAME; ooRexx's -- requestString falls back to stringValue, which sends OBJECTNAME -- when Rexx code makes the name: none again is 91.999, of STRING.) If .Nil == v Then Do If sOrig~isA( .RVM.Obj ), sOrig~nameInRexx Then Do v = context~world~loader~sendSync( sOrig, "OBJECTNAME", .Array~new ) If .Nil == v Then Raise Syntax 91.999 Array( "STRING" ) End Else v = sOrig~objectName End -- (ooRexx's requestString: primitiveMakeString of the result; with -- none, the value is .nil's.) If \ v~isA( .String ) Then Do v2 = PrimitiveString( v ) If v2 == .Nil Then v2 = context~world~nil~objectName v = v2 End Call RestoreConversions convSaved .RVM.Obj~conversions[ sOrig ] = v convPc = pc -- the instruction, again End -- MAKESTRING, for a conversion (REQUEST STRING): the same. When "REQUEST" Then Do -- (None: as .nil, no string: REQUEST gives .nil.) If .Nil == v Then v = context~world~nil -- (A result with no primitive string stays an object: the conversion -- is then the STRING's, with NOSTRING: see RVM.Obj~stringValue.) If \ v~isA( .String ) Then Do v2 = PrimitiveString( v ) If v2 \== .Nil Then v = v2 End Call RestoreConversions convSaved .RVM.Obj~requests[ sOrig ] = v convPc = pc End -- DO WITH: a Supplier (98.994 names the collection) for the loop. -- A subclass of Supplier is asked with messages (NEXT, AVAILABLE, INDEX, -- ITEM: ooRexx's loopNext...); a Supplier, directly. When "WITH" Then Do If \ v~isA( .RVM.Obj ) Then Raise Syntax 98.994 Array( ObjectText( sOrig ) ) world = context~world If \ IsSubclass( world~classOf( v ), world~supplierClass ) Then Raise Syntax 98.994 Array( ObjectText( sOrig ) ) b = descs[ sWith ] b~msg = ( world~classOf( v ) \== world~supplierClass ) If b~msg Then b~over = v Else Do If \ v~native~isA( .RVM.SupplierState ) Then Raise Syntax 98.994 Array( ObjectText( sOrig ) ) b~over = v~native End b~pos = 0 b~nextSent = .False End -- DO WITH a subclass of Supplier: its AVAILABLE ("0": out, to sWith). When "WAVAIL" Then Do If .Nil == v Then Raise Syntax 91.999 Array( sMsg ) s = str( v ) If s \== "0", s \== "1" Then Raise Syntax 34.906 Array( s ) If s == "0" Then pc = sWith End -- Its INDEX or ITEM: to a variable (WSET), or on the stack (WPUSH). When "WSET", "WPUSH" Then Do If .Nil == v Then v = context~world~nil If sMode == "WPUSH" Then Do sp += 1; stack[sp] = v End Else Do name = names[ sWith ] context~setVar( name, v ) If context~traceI Then context~traceTagged( ">=>", name, " <= ", v ) End End -- START: the message has completed; so has the activity, when those to -- notify have been (MESSAGECOMPLETE, sent here: the delegates of an -- RVM.Notifier, and then back here). When "START" Then Do ms = act~message If \ ms~complete Then Do ms~result = v ms~returned = .True ms~done v = ms~notifyAll( v ) If v~isA( .RVM.Delegate ) Then Signal Delegated End Signal Finished End -- The message of a START failed, and those to notify have been: the -- activity ends with its error (see Failed). When "FAILED" Then Return "FAILED" -- A message sent failed, and those to notify have been: the error goes -- on (see Failed). When "UNWIND" Then Do throw = uwState[1]; co = uwState[2]; isTrap = uwState[3] raised = uwState[4]; context~errorLines = uwState[5] uwState = .Nil uwReraise = .True -- (see PropagateCo) context~thrown = throw Signal On Syntax Name Failed Signal FailedUnwind End -- An UNINIT has run: the next one. When "UNINIT" Then Signal UninitNext -- A message sent now (sendSync): its result. When "SYNC" Then Return v -- A stream function's message to .LOCAL's object (FUNCB, CALLB): its -- result is the function's. When "BIF" Then Do v = .RVM.BifSend~finish( v, bifPost ) If bifKind == "FUNCB" Then Do If .Nil == v Then Raise Syntax 44.1 Array( bifName ) If context~traceI Then context~traceTagged( ">F>", bifName, " => ", v ) sp += 1; stack[sp] = v End Else Do If .Nil == v Then context~dropVar( "RESULT" ) Else Do context~setVar( "RESULT", v ) context~traceResult( v ) End End End -- FORWARD: the method returns the result; CONTINUE: it is RESULT. When "FWD" Then Do context~endDebug retVal = v Signal DoReturn End When "FWDC" Then Do If .Nil == v Then context~dropVar( "RESULT" ) Else Do context~traceResult( v ) context~setVar( "RESULT", v ) End End When "SENDI N", "SENDI C" Then Do If sMode == "SENDI C" Then v = sOrig If .Nil == v Then context~dropVar( "RESULT" ) Else Do If context~traceI Then context~traceTagged( ">M>", '"'sMsg'"', " => ", v ) context~setVar( "RESULT", v ) End End Otherwise Nop -- SENDA End Signal Resume -- An object whose STRING method is written in Rexx was converted to a -- string by the instruction at insPc (see doc/05-machine.md#needstring): the -- instruction is abandoned (it has changed nothing yet), its stack is as it -- was, STRING runs, and then the instruction runs again (see Deliver). NeedString: Signal On Syntax Name Failed context~nativeLines~empty sp = insSp pc = insPc -- The conversions of this instruction wait while STRING runs (its -- instructions would drop them), and come back with its result: an -- instruction may convert several objects, one after another. convSaved~append( .Array~of( .RVM.Obj~conversions, .RVM.Obj~requests ) ) .RVM.Obj~conversions = .IdentityTable~new .RVM.Obj~requests = .IdentityTable~new convPc = 0 sRecv = .RVM.Obj~pending .RVM.Obj~pending = .Nil sName = .RVM.Obj~pendingMessage; sArgs = .Array~new; sStart = .Nil; sMode = "STRING" If sName == "MAKESTRING" Then sMode = "REQUEST" Signal DoSend /*----------------------------------------------------------------------------*/ /* A routine that is not internal nor built-in: name, with args, kind SUB or */ /* FUNC. A ::ROUTINE of the program running (FindRoutine), a public routine */ /* of a package it requires, or else an external one (LoadExternal: another */ /* program, found as rexxref 7.2.1 says). It runs in an activation with its */ /* own variables and settings, and in its own program (EnterProgram). */ /*----------------------------------------------------------------------------*/ CallRoutine: r = FindRoutine( program, name ) rMacro = .Nil -- Not a ::ROUTINE: the security manager of the activation is asked (CALL, -- with the name and the arguments: ooRexx's callObjectFunctionExit); when -- it handles it, its RESULT is the routine's. If r == .Nil, context~secMgr \== .Nil Then Do info = context~world~security( context~secMgr, "CALL", .Array~of( "NAME", name, - "ARGUMENTS", context~world~newArray( args~copy ) ) ) If info \== .Nil Then Do v = info["RESULT"] Signal CallDone End End -- Not a ::ROUTINE: a macro of the macrospace to be found first (ooRexx's -- callMacroSpaceFunction, RXMACRO_SEARCH_BEFORE: REXXUTIL's), then a -- routine of REXXUTIL (always loaded: ooRexx's callNativeRoutine), -- before the programs in files. If r == .Nil Then rMacro = MacroProgram( name, "B" ) If r == .Nil, rMacro == .Nil Then Do lr = RexxUtilRoutine( name ) If lr \== .Nil Then Do lrName = lr[1] Signal CallRexxUtil End -- A routine of a library loaded (RVM.World~libraryRoutine). lr = context~world~libraryRoutine( name ) If lr \== .Nil Then Do lrName = lr[1] Signal CallRexxUtil End End CallFound: rMerge = .Nil If r == .Nil Then Do -- A new package at each call, as ooRexx's (callExternalRexx: -- createProgramFromFile; a macro's, getMacroCode): its classes are made -- again, and what is public in it goes to the caller when it returns. If rMacro \== .Nil Then target = FreshProgram( rMacro, context, .False ) Else target = LoadExternal( name, context ) rMerge = target address = 1 rLabels = target~labels rClause = target~firstClause rText = .Nil rExec = target; rKind = "P" End Else Do -- An EXTERNAL routine: a routine of a library (see CheckExternals). If r~address == .Nil Then Do lr = r~lib lrName = r~name -- (its traceback line has its name) Signal CallRexxUtil End target = r~program address = r~address rLabels = r~labels rClause = r~firstClause rText = 'Routine "'r~name'" in package "'target~path'".' rExec = r; rKind = "R" End rName = name If kind == "FUNC" Then invocation = "FUNCTION" Else invocation = "SUBROUTINE" Signal EnterProgram -- A routine of REXXUTIL (lr; see RVM.RexxUtil.cls), a native routine: its -- line in a traceback while it runs ('Compiled routine'), its arguments -- checked as a native routine's; when it must wait (an RVM.Wait), the -- activity waits, and its result is then the wait's (RexxUtilResumed). CallRexxUtil: nc = .RVM.NativeCall~new( ' *-* Compiled routine "'lrName'".', .Nil, .Nil, lrName, args ) nc~lib = lr context~nativeLines~append( nc ) Call RoutineArgs lr, args, context v = NativeRoutine( lr, args, context ) If v~isA( .RVM.Wait ) Then Do resumeAt = "REXXUTILRESUMED" Signal Suspend End RexxUtilDone: context~nativeLines~delete( context~nativeLines~last ) CallDone: If kind == "TRAP" Then Signal TrapDone If kind == "FUNC" Then Do If v == .Nil Then Raise Syntax 44.1 Additional( name ) If context~traceI Then context~traceTagged( ">F>", name, " => ", v ) sp += 1; stack[sp] = v End Else Do If v == .Nil Then context~dropVar( "RESULT" ) Else Do context~setVar( "RESULT", v ) context~traceResult( v ) End End Signal Resume RexxUtilResumed: v = act~waitResult act~waitResult = .Nil Signal RexxUtilDone RoutineCallResumed: v = act~waitResult act~waitResult = .Nil RoutineCallDone: context~nativeLines~delete( context~nativeLines~last ) Signal SendDone -- A Routine object's CALL (v, an RVM.RoutineCall): the routine runs as an -- external routine does (a SUBROUTINE, in its own program), in a frame of -- kind RCALL; the natives that led to it (CALL) are shown below it in a -- traceback, and its result is the message's (see DoReturn). EnterRoutineCall: r = v~routine -- An EXTERNAL routine (a library's): a native, run now, with its line -- ('Compiled routine', the routine's name); when it must wait, the -- activity waits (RoutineCallResumed). If r~address == .Nil Then Do nc = .RVM.NativeCall~new( ' *-* Compiled routine "'r~name'".', .Nil, .Nil, r~name, v~args ) nc~lib = r~lib context~nativeLines~append( nc ) rcArgs = v~args Call RoutineArgs r~lib, rcArgs, context v = NativeRoutine( r~lib, rcArgs, context ) If v~isA( .RVM.Wait ) Then Do resumeAt = "ROUTINECALLRESUMED" Signal Suspend End Signal RoutineCallDone End natives = context~nativeLines rNatives = natives~section( sDepth + 1 ) Do While natives~items > sDepth natives~delete( natives~last ) End kind = "RCALL" name = sMsg args = v~args target = r~program address = r~address rLabels = r~labels rClause = r~firstClause rText = 'Routine "'r~name'" in package "'target~path'".' rExec = r; rKind = "R"; rName = r~name invocation = "SUBROUTINE" rOverride = .Nil rInit = .False rAddTo = .Nil rInstall = .Nil Signal EnterProgram -- A package a native loads or makes (v, an RVM.PackageRun: loadPackage, -- Package~new): when it has not started, its prolog runs (its requires and -- classes first, see StartPackage), as a ::REQUIRES does, in a frame of kind -- RCALL whose result is the package; the package that loads it (if any) -- adds it when it returns. A package that has started is the result now. EnterPackageRun: If v~program~state \== "NEW" Then Do If v~addTo \== .Nil Then world~addPackage( v~addTo, v~program, context ) v = v~result -- (After an install: what the native gave, which may go on.) If v~isA( .RVM.PackageRun ) Then Signal EnterPackageRun If v~isA( .RVM.Delegate ) Then Signal Delegated Signal SendDone End natives = context~nativeLines rNatives = natives~section( sDepth + 1 ) Do While natives~items > sDepth natives~delete( natives~last ) End kind = "RCALL" name = sMsg args = .Array~new target = v~program address = 1 rLabels = target~labels rClause = target~firstClause rText = .Nil rExec = target; rKind = "P"; rName = target~path invocation = "REQUIRES" rOverride = v~result rInit = v~runInit rAddTo = v~addTo rInstall = v~install Signal EnterProgram -- Code of another program, or of a routine: a new activation (kind, name, -- args), in 'target' at 'address' with labels rLabels; its entry is traced -- as rText (.Nil: the program's), when TRACE starts in clause rClause. The -- caller's program comes back when it returns (LeaveProgram). EnterProgram: f = .RVM.Frame~new f~returnTo = pc f~atStart = atStart f~kind = kind f~name = name f~descs = descs f~parse = parse f~sp = sp f~iheld = iheld f~program = program f~progName = context~programName f~progSource = context~sourceLines f~invocation = context~invocation f~entryAllowed = entryAllowed f~entryDone = entryDone f~entryClause = entryClause f~entryText = entryText f~labels = labels f~method = curMethod f~mframe = curFrame f~sender = curSender If kind == "SUB" | kind == "FUNC" | kind == "TRAP" Then f~mergeFrom = rMerge If kind == "TRAP" Then Do -- a CALL ON handler (TrapRoutine) f~trap = rTrap f~rest = rRest End pkgRun = .False If kind == "RCALL" Then Do f~natives = rNatives f~mode = sMode f~receiver = sOrig f~override = rOverride f~initAfter = rInit f~addTo = rAddTo f~addTarget = target f~install = rInstall f~pend = sPend pkgRun = rOverride \== .Nil End curSender = .Nil If frames~items >= .RVM.Machine~maxDepth Then Raise Syntax 11.1 frames~append( f ) iheld = .Array~new context~pushActivation( args ) Call EnterLevel context, "ROUTINE", rName, rExec, rKind context~startProgram( target ) -- A routine, or a package's prolog, starts with the default ADDRESS (an -- external program has the caller's). If rText \== .Nil | kind == "REQ" | pkgRun Then context~defaultAddress context~programName = target~path context~sourceLines = target~source context~invocation = invocation program = target Call SwitchProgram labels = rLabels entryAllowed = .True entryDone = .False entryClause = rClause entryText = rText -- It starts tracing (its package's ::OPTIONS TRACE): its entry is shown -- (its clause is the first one: ooRexx's StackFrame line). Not when it is -- only installed (see InstallTrace). If context~traceL, \ ( kind == "RCALL" & rInstall \== .Nil ) Then Do entryDone = .True c = EntryClause( program, address ) If c \== .Nil Then context~clause = c Call TraceInvocation context, ">I>", entryText End curMethod = .Nil context~currentMethod = .Nil curFrame = .Nil descs = .Array~new parse = .Nil fromLabel = .Nil pc = address Signal Resume /*----------------------------------------------------------------------------*/ /* A program starts (the main one, an external routine, a package required): */ /* each package it requires, in order, is loaded (LoadPackage) and started */ /* in its turn (its own requires, its classes), and its prolog runs, in an */ /* activation of kind REQ; the program goes on with the next requires when */ /* it returns. Then its classes are made (RVM.World~install), and it runs. */ /*----------------------------------------------------------------------------*/ StartPackage: program~state = "LOADING" -- Its EXTERNAL routines and methods, first (ooRexx resolves them when it -- translates the package). If program~reqNext == 1 Then Call CheckExternals program, context Loop While program~reqNext <= program~requires~items req = program~requires[ program~reqNext ] program~reqNext += 1 context~clause = clauses[ req~clause ] -- A library: one of the RVM's (RVMLibrary), or 98.903. If req~library Then Do table = RVMLibrary( req~name ) If table == .Nil Then Raise Syntax 98.903 Array( req~name ) context~world~loadLibrary( req~name, table ) Iterate End target = LoadPackage( req~name, context ) If req~namespace \== .Nil Then program~namespaces[ req~namespace ] = target If \ program~required~hasItem( target ) Then program~required~append( target ) If target~state == "READY" | target~state == "CLASSES" Then Iterate If target~state == "LOADING" Then Raise Syntax 98.952 Array( target~path ) kind = "REQ" name = req~name args = .Array~new address = 1 rLabels = target~labels rClause = target~firstClause rText = .Nil rExec = target; rKind = "P"; rName = target~path invocation = "REQUIRES" Signal EnterProgram End -- The classes: made by messages (see RVM.Installer), whose result goes -- nowhere; the program is READY when they are made. program~state = "CLASSES" v = context~world~install( program, context, .True ) If v == .Nil Then Do program~state = "READY" Signal Resume End world = context~world sMode = "SENDA"; sMsg = ""; sOrig = .Nil sPend = .Array~new sDepth = context~nativeLines~items sFirst = .False Signal Delegated -- A method written in Rexx (m): a new activation, with its own variables -- (SELF, SUPER, and those EXPOSE shares with the object) and settings; the -- natives that led to it (NEW, SEND) are shown below it in a traceback. EnterMethod: f = .RVM.Frame~new f~returnTo = pc f~atStart = atStart f~kind = "METHOD" f~name = sMsg f~descs = descs f~parse = parse f~sp = sp f~iheld = iheld f~mode = sMode f~receiver = sOrig f~pend = sPend natives = context~nativeLines f~natives = natives~section( sDepth + 1 ) Do While natives~items > sDepth natives~delete( natives~last ) End f~labels = labels f~method = curMethod f~mframe = curFrame f~sender = curSender f~entryAllowed = entryAllowed f~entryDone = entryDone f~entryClause = entryClause f~entryText = entryText -- A method of a class of another package runs in its program. If m~program \== program Then Do f~program = program f~progName = context~programName f~progSource = context~sourceLines End f~invocation = context~invocation -- PARSE SOURCE says METHOD If frames~items >= .RVM.Machine~maxDepth Then Raise Syntax 11.1 frames~append( f ) iheld = .Array~new context~pushActivation( sArgs ) If sUnknown Then Call EnterLevel context, "METHOD", "UNKNOWN", m, "M", sRecv Else Call EnterLevel context, "METHOD", sName, m, "M", sRecv context~startProgram( m~program ) context~newStreamScope context~defaultAddress -- a method starts with the default ADDRESS If m~program \== program Then Do program = m~program Call SwitchProgram context~programName = program~path context~sourceLines = program~source End curFrame = .RVM.MethodFrame~new( sRecv~pool( m~scope ) ) context~installFrame( curFrame ) context~invocation = "METHOD" context~setVar( "SELF", sRecv ) curSender = sRecv -- SUPER: the scope before the method's in the receiver's behaviour -- (ooRexx's superScope; SETMETHOD's, with none: the receiver's class). superClass = world~behaviourOf( sRecv )~superScope( m~scope ) If superClass == .Nil Then superClass = world~nil context~setVar( "SUPER", superClass ) curMethod = m context~currentMethod = m labels = m~labels descs = .Array~new parse = .Nil fromLabel = .Nil entryAllowed = .True entryDone = .False entryClause = m~firstClause -- ooRexx traces the activation's message name (traceEntryOrExit), not -- the method's (RUN's is *UNNAMED*; SETMETHOD's, the name it was given). entryName = sName entryText = 'Method "'entryName'" with scope "'ScopeName( m )'" in package "'context~programName'".' -- It starts tracing (its package's ::OPTIONS TRACE): its entry is shown -- (its clause is the first one: ooRexx's StackFrame line). If context~traceL Then Do entryDone = .True c = EntryClause( m~program, m~address ) If c \== .Nil Then context~clause = c Call TraceInvocation context, ">I>", entryText End pc = m~address -- A guarded method takes the lock of its scope's variables (ooRexx: at -- its first instruction, where a deadlock, 98.905, is reported); it may -- have to wait for it. A compiled method (ooRexx's are C++) does not. lv = context~level lv~pool = curFrame~pool If \ m~hasFlag( "U" ), \ m~compiled Then Do lv~locked = .True If lv~pool~owningActivity \== .Nil, lv~pool~owningActivity \== act Then Do k = pc Do While k <= code~items, code[k][1] \== "CLAUSE" k += 1 End If k <= code~items Then context~clause = clauses[ code[k][2] ] End If \ lv~pool~reserve( act ) Then Do resumeAt = "GRANTED" Signal Suspend End End Signal Resume -- Back from a method (frame f): the registers of its caller. LeaveMethod: context~invocation = f~invocation labels = f~labels curSender = f~sender curMethod = f~method context~currentMethod = f~method curFrame = f~mframe entryAllowed = f~entryAllowed entryDone = f~entryDone entryClause = f~entryClause entryText = f~entryText Return /*----------------------------------------------------------------------------*/ /* Activities (see RVM.Machine~run, RVM.Activity). The activity running */ /* waits (Suspend): its registers are kept, and the machine returns; when it */ /* runs again, it goes on at resumeAt. In a nested machine the registers stay */ /* where they are: the others run in place (pump), and then resumeAt. REPLY */ /* (DoReply) and START (SpawnStart) make a new one, ready, with registers of */ /* its own. */ /*----------------------------------------------------------------------------*/ Suspend: If act == .Nil | sched == .Nil Then Raise Syntax 93.900 Additional( "RVM: an activity cannot wait here" ) -- A nested machine (sendSync, runSync, a thunk) waits where it is: the -- others run (Pump) until this one is ready, and it goes on at resumeAt, -- its registers as they were. If nested | sync Then Do act~state = "WAITING" yielding = .False self~pump( act, sched ) Signal Value resumeAt End act~resumeAt = resumeAt act~state = "WAITING" ready = yielding yielding = .False act~regs = .context~variables If ready Then sched~ready( act ) Return "WAITING" -- A read of standard input (a terminal or a pipe) would block, and -- something else may run (v, an RVM.StdinNeed: see RVM.Stream~inputNeed): -- the activity waits for what it needs (RVM.StdinWait), and then the -- instruction runs again, from its start (nothing it did shows). StdinWait: .RVM.StdinWait~start( v, context ) pc = insPc sp = insSp resumeAt = "STDINRESUMED" Signal Suspend -- A HALT (Ctrl-C) cut it short: the instruction gets it (RunTraps; a CALL ON -- HALT handler that returns runs it again). StdinResumed: If act~waitResult == "HALT" Then Do act~waitResult = .Nil again = pc Signal RunTraps End Signal Resume -- (The same for a Stream method, whose native was sent: see WaitFor.) StdinSent: If act~waitResult == "HALT" Then Do act~waitResult = .Nil pc = insPc; sp = insSp again = insPc Signal RunTraps End Signal SendLoop -- A command that made its activity wait (see CMD) has ended: it is -- finished here, in its activity (its redirections, RC), and goes on. CmdResumed: w = act~waitResult act~waitResult = .Nil condition = w~finish( context ) -- A command's end (CMD): .RS, its trace, its condition. CmdDone: -- .RS: 0, 1 (ERROR) or -1 (FAILURE); not at a pause. If \ context~debugPause Then Select Case condition When "ERROR" Then context~level~rs = 1 When "FAILURE" Then context~level~rs = -1 Otherwise context~level~rs = 0 End cmdTraced = CommandTrace( context, condition, command ) Call CommandCondition context, condition, command Signal Resume -- A lock it waited for is its now. Granted: act~granted = .Nil If replyEntryDue Then Signal ReplyStart Signal Resume -- The activity of a REPLY starts: ooRexx traces the method's entry again -- (the exit was traced at the REPLY, in the caller's). ReplyStart: replyEntryDue = .False Call TraceInvocation context, ">I>", entryText Signal Resume -- GUARD WHEN: a variable changed; the lock again (if it had it), and the -- expression again. GuardResume: If act~relock Then Do act~relock = .False lv = context~level lv~locked = .True If \ lv~pool~reserve( act ) Then Do resumeAt = "GRANTED" Signal Suspend End End Signal Resume -- REPLY retVal: the method's activation goes to a new activity (its context, -- level and lock, the registers of the method), ready; here, the caller gets -- retVal as a RETURN gives it. In a nested machine (sendSync, runSync, a -- thunk) too: the caller is then the native that asked, which gets retVal -- now, as native's; the new activity's machine is not nested (its frames -- are its own, from 0). DoReply: -- The exit is traced now, while the activation is still this one's (its -- invocation, its lock); DoReturn does not trace it again. replyExit = entryDone & context~traceL If replyExit Then Call TraceInvocation context, " 0 Then top = stack[ pz~sp ] next = NextAfter( code, consts, pz~cont, top ) last = ( next == "00"x ) If flow[1] \== "EXIT", last | ( flow[1] == "SIGNAL" & flow[2] == next ) Then Do pz~held = flow pz~last = last If context~debugBypass Then Do context~debugBypass = .False Signal PauseEnd End Signal DebugRead End pauses~delete( pauses~last ) Signal DoFlow -- An error in a line typed at a pause: it is shown, and the pause goes on. DebugFailed: pz = pauses~lastItem Call DebugError context, co, pz~clause context~thrown = .Nil context~errorLines = .Nil context~interpretError = .Nil Call DebugLineOver context, pz sp = pz~sp Signal DebugRead -- Carry out a flow change typed at a pause: after the CALL ON traps pending. DoFlow: If context~callTrapsPending Then Do If flow[1] == "EXIT", \ AtMain( frames ) Then lost = context~takeCallTraps Else Do pendingFlow = flow again = 0 Signal RunTraps End End Select Case flow[1] When "SIGNAL" Then Do context~setVar( "SIGL", flow[3] ) context~traceIndent = flow[4] context~clearInterprets iheld = .Array~new fromLabel = flow[2] pc = labels[ flow[2] ] Signal Resume End When "RETURN" Then Do retVal = flow[2] Signal DoReturn End Otherwise Do exitVal = flow[2] Signal ExitUnwind End End -- EXIT in a routine: the activations end, up to the main program, whose -- CALL ON traps still pending (a line typed at a pause keeps those of its -- clause aside) run before the program ends, as in ooRexx. In an external -- routine, the program that ends is the routine's: exitVal goes back to its -- caller, as a RETURN. ExitUnwind: Loop -- A nested machine (a thunk): down to the activation that asked, the -- EXIT goes on in the machine below. If nested, frames~items == base Then Do context~nestedExit = .Array~of( exitVal ) Signal Off Syntax -- (to the machine below, not Failed) Raise Syntax 98.900 Array( "exit" ) Description "RVM.Exit" End If AtMain( frames ) Then Do -- The main program's debug ends too (ooRexx's exitFrom: resetDebug at -- each level): its CALL ON traps pending run without pauses. context~endDebug -- After REPLY nobody takes a result (98.937). If exitVal \== .Nil, context~level~replied Then Raise Syntax 98.937 If context~callTrapsPending Then Do pendingFlow = .Array~of( "EXIT", exitVal ) again = 0 Signal RunTraps End If frames~isEmpty Then Do If exitVal == .Nil Then context~exitCode = "" Else context~exitCode = QuietString( exitVal ) Signal Finished End retVal = exitVal Signal DoReturn End Call PopFrame Do While \ pauses~isEmpty pz = pauses~lastItem If pz~level < frames~items Then Leave If pz~level == frames~items, context~debugPause Then Call DebugLineOver context, pz pauses~delete( pauses~last ) End If context~callTrapsPending, \ AtMain( frames ) Then lost = context~takeCallTraps End -- RETURN (retVal: the value, or .Nil). In the main program, it ends it as -- EXIT does. DoReturn: If frames~isEmpty Then Do If retVal \== .Nil Then context~exitCode = QuietString( retVal ) Signal Finished End f = frames~lastItem frames~delete( frames~last ) -- The end of an external routine that showed its entry. If f~program \== .Nil | f~kind == "METHOD", entryDone, context~traceL Then Call TraceInvocation context, "F>", f~name, " => ", retVal ) sp += 1; stack[sp] = retVal End Signal Resume -- The host's HALT (Ctrl-C: ooRexx's signalHandler, haltAllActivities): a -- HALT pending for every activity of the program, seen at its next clause -- (RunTraps). The machine goes on where it was. HostHalt: context~haltAll Return -- The CALL ON traps the clause fired: each handler is called in turn, and -- then the instruction at 'again' runs (again). RunTraps: pairs = context~takeCallTraps -- A HALT (Message~halt: ooRexx's processClauseBoundary), once the CALL ON -- traps pending have run (a trap's return makes this boundary again: see -- RVM.Context~popActivation). Not trapped, it is error 4.1; a CALL ON trap -- for it is queued, and runs at the next boundary, after one more clause -- (ooRexx's: SIGL is that clause's line); a SIGNAL ON trap goes now. If pairs~isEmpty, context~level~haltPending Then Do lv = context~level lv~haltPending = .False info = .RVM.ConditionInfo~new( "HALT" ) If lv~haltDesc \== .Nil Then info~description = lv~haltDesc lv~haltDesc = .Nil info~stack = context~stackLines info~program = context~programName info~position = context~clauseText( context~clause )[1] If \ context~raiseCondition( info ) Then Raise Syntax 4.1 Array( "HALT" ) Description "RVM.Halt" heldHalt = context~takeCallTraps If heldHalt~isEmpty Then heldHalt = .Nil End -- An external TRACE (hostemu TS, TE), after the HALT, as ooRexx's -- processClauseBoundary: TRACE ?R or TRACE O now. If pairs~isEmpty, context~level~extTrace \== .Nil Then Do setting = context~level~extTrace context~level~extTrace = .Nil context~setTrace( setting ) -- (As a TRACE instruction: on the first instruction of a method or a -- routine, its entry is traced, ooRexx's traceEntry.) If entryAllowed, \ entryDone, context~traceL Then Do entryDone = .True Call TraceInvocation context, ">I>", entryText End End If pairs~isEmpty Then Do pc = again If pc == 0 Then Do flow = pendingFlow pendingFlow = .Nil Signal DoFlow End Signal Resume End CallTrap: pair = pairs[1] pairs = pairs~section( 2 ) trap = pair[1] info = pair[2] info~instruction = "CALL" If info~rc \== .Nil Then context~setVar( "RC", info~rc ) trap~state = "DELAY" address = labels[ trap~target ] If address == .Nil Then Signal TrapRoutine context~setVar( "SIGL", context~clause~line ) f = .RVM.Frame~new f~returnTo = again f~atStart = atStart f~kind = "TRAP" f~name = trap~target f~descs = descs f~parse = parse f~sp = sp f~trap = trap f~rest = pairs f~iheld = iheld frames~append( f ) iheld = .Array~new context~pushActivation( .Array~of( context~conditionObject( info ) ) ) context~procValid = ProcedureFirst( code, address ) context~level~name = trap~target context~condition = info descs = .Array~new parse = .Nil fromLabel = trap~target pc = address Signal Resume -- A CALL ON handler that is not a label (ooRexx's -- RexxInstructionCallOn::trap): a built-in function, called with the -- condition object, or else a routine, called with it as an external routine -- is (CallRoutine), in a frame of kind TRAP. Its result is ignored. TrapRoutine: name = trap~target args = .Array~of( context~conditionObject( info ) ) rTrap = trap rRest = pairs pc = again If IsBIF( name ) Then Do v = BifNow( CallBIF( name, args, context ), context ) Signal TrapDone End kind = "TRAP" Signal CallRoutine -- A native routine as a CALL ON handler has returned: the next one, if any. TrapDone: rTrap~state = "ON" If \ rRest~isEmpty Then Do pairs = rRest Signal CallTrap End If pc == 0 Then Do flow = pendingFlow pendingFlow = .Nil Signal DoFlow End Signal Resume -- The activity of the UNINITs: UNINIT to the next object due it (from -- the run: a private one is never due), and back here (Deliver, UNINIT). UninitNext: If act~uninits~isEmpty Then Signal Finished sRecv = act~uninits[1] act~uninits~delete( 1 ) sName = "UNINIT"; sArgs = .Array~new; sStart = .Nil; sMode = "UNINIT" curSender = .Nil sp = 0 Signal DoSend -- The program (the activity) is over: end the activations still open. Finished: -- The activity of a REPLY ends: the method's exit again (see ReplyStart). If replyTraced, context~traceL Then Do replyTraced = .False Call TraceInvocation context, " base -- (a nested machine: its own) frames~delete( frames~last ) context~popActivation End Return "ENDED" -- The condition goes on in the caller (out of this machine). After the -- notifications of a failed message ran (UNWIND), the host's current -- condition may be one they trapped: co, the one unwinding, is raised again -- itself (as NestedHandoff does). PropagateCo: If \ uwReraise Then Raise Propagate uwReraise = .False Signal Off Syntax If co~additional == .Nil Then Raise Syntax ( co~code ) Description ( co~description ) Raise Syntax ( co~code ) Additional( co~additional ) Description ( co~description ) -- A condition was raised by a SIGNAL ON trap (RVM.Trap), by RAISE -- (RVM.Raise), or it is a Rexx error. It goes up the activations to the -- one that must take it: a SIGNAL ON trap -- resumes there at its label; an untrapped error goes on up, and ends the -- program at the top. Failed: co = Condition("O") .RVM.StdinReader~gate = .Nil -- (a read that failed before it took it) uwReraise = .False -- The host's HALT (Ctrl-C) in the machine's own code, out of HostHalt's -- reach (a helper: RVM.Number, a native...): the instruction it ran is -- abandoned, and the program gets its HALT now (RunTraps); a CALL ON HALT -- handler that returns runs that instruction again. (The RVM's own 4.1 is -- "RVM.Halt".) If co~code == 4.1, co~description \== "RVM.Halt", insPc > 0 Then Do context~haltAll pc = insPc; sp = insSp again = insPc Signal On Syntax Name Failed Signal RunTraps End If co~description == "RVM.NeedString" Then Signal NeedString -- An EXIT in a nested machine (a thunk) that got down to the activation -- running here: it goes on here. If co~description == "RVM.Exit", context~nestedExit \== .Nil Then Do exitVal = context~nestedExit[1] context~nestedExit = .Nil Signal On Syntax Name Failed Signal ExitUnwind End isTrap = WordPos( co~description, "RVM.Trap RVM.Raise" ) > 0 -- A trap of the machine below taken by a condition of a sendSync's first -- activation (see RVM.Context~raiseCondition): its throw is that machine's, -- where it goes on. If co~description == "RVM.Trap", context~thrown == .Nil, context~syncRoot, - context~outerContext \== .Nil Then Do If context~outerContext~thrown \== .Nil Then Do Signal Off Syntax Raise Propagate End End -- (The condition of a nested machine that got down to the activation -- running here, NestedHandoff: its throw goes on here.) handedOff = .False If context~nestedHandoff == .True Then Do context~nestedHandoff = .False isTrap = .True handedOff = .True End -- (A RAISE that came out of a machine run by a native, sendSync: its -- throw was that machine's; here it is an error with its code and -- ADDITIONAL, as ooRexx's exception going up through the native.) If isTrap, context~thrown == .Nil Then isTrap = .False If isTrap Then Do throw = context~thrown info = throw~info If info~condition == "SYNTAX", info~message == .Nil Then info~message = BifMessageOf( co ) End Else Do syncErr = .RVM.ConditionInfo~syncFailure .RVM.ConditionInfo~syncFailure = .Nil If syncErr \== .Nil Then If syncErr[3] \== co~code | syncErr[4] \== co~description Then syncErr = .Nil If context~thrown == .Nil Then context~errorLines = .Nil -- The natives that were running: their lines go first in the report. natives = NativeLines( context ) If context~errorLines == .Nil Then context~errorLines = natives If syncErr \== .Nil Then Do -- The error that ended a machine run by a native (sendSync) goes on -- here, as ooRexx's exception through the native: its condition (the -- clause and program where it was raised), its lines and frames, -- then the natives' and those of this machine. info = syncErr[1] -- (The natives at the bottom of that machine, REQUEST for MAKEARRAY, -- have no clause there: theirs is the one here. Its first activation, -- which only sent the message, has no line.) here = 0 If context~clause \== .Nil Then here = context~clauseText( context~clause )[1] context~errorLines = .Array~new Do e Over syncErr[2] If e[2] == "" Then Iterate -- (that machine's first activation) If e[1] == 0 Then Do e = e~copy e[1] = here End context~errorLines~append( e ) End -- (This activation's lines: below the natives', with KeepErrorLines; -- with none, now.) If natives \== .Nil, natives~items > 0 Then context~errorLines~appendAll( natives ) Else context~errorLines~appendAll( ErrorLines( context ) ) If info~stack == .Nil Then info~stack = .Array~new Else info~stack = info~stack~copy If \ syncErr[5] Then info~stack~appendAll( context~stackLines( natives ) ) -- (Raised again out of that machine, RAISE PROPAGATE: here.) If info~position == .Nil Then Do info~program = .Nil context~locate( info ) End info~stackObj = .Nil info~framesObj = .Nil info~traceback = .Nil info~propagated = "1" End Else Do info =.RVM.ConditionInfo~new( "SYNTAX", "", co~rc ) info~code = BifCodeOf( co ) info~additional = ErrorAdditional( co ) info~message = BifMessageOf( co ) info~stack = context~stackLines( natives ) -- In the arguments of a routine of REXXUTIL: the REXX package, no line. If context~nativeArgs Then Do context~nativeArgs = .False info~program = "REXX" End If context~interpretError \== .Nil Then Do info~position = context~interpretError[1] If context~interpretError~hasIndex( 3 ) Then info~program = context~interpretError[3] End context~locate( info ) End throw = .RVM.Throw~new( info, .Nil, frames~items ) context~thrown = throw End -- A RAISE SYNTAX goes up to its level at once (no trap on the way sees -- it), but, untrapped there, its report has the lines of every activation -- it went through, as an error's. -- A RAISE PROPAGATE of a SYNTAX a trap took shows the lines it had then -- (not the handler's), and those of the activations it goes up through. raised = isTrap & throw~trap == .Nil -- (Not one handed off: its lines so far are the ones.) If raised, \ handedOff, throw~info~traceback \== .Nil Then context~errorLines = throw~info~traceback~copy -- An error raised again (Message~result) keeps the lines it had. If throw~reraise Then raised = .False FailedUnwind: Loop level = frames~items -- A nested machine (a thunk): down to the activation that asked, the -- condition goes on in the machine below (its trap, its lines). If nested, level == base Then Do context~nestedHandoff = .True Signal Off Syntax -- (to the machine below, not Failed) If co~additional == .Nil Then Raise Syntax ( co~code ) Description ( co~description ) Raise Syntax ( co~code ) Additional( co~additional ) Description ( co~description ) End -- A message this activation sent (Message~send) has failed: it has the -- error, and those to notify are notified now (ooRexx's trap, with the -- activation's notifyObject: MessageClass~error), before the error goes -- on (Deliver, UNWIND). If context~level~notifyMsg \== .Nil, throw~info~condition == "SYNTAX" Then Do ms = context~level~notifyMsg context~level~notifyMsg = .Nil ms~failed = .True ms~info = throw~info ms~condObj = .Nil ms~done If \ ms~parties~isEmpty Then Do uwState = .Array~of( throw, co, isTrap, raised, context~errorLines ) context~thrown = .Nil sMode = "UNWIND" sPend = .Array~new sDepth = context~nativeLines~items v = ms~notifyAll( .Nil ) Signal On Syntax Name Failed Signal Delegated End End If level > throw~level, level > 0 Then Do If raised Then Call KeepErrorLines leaving = context~currentMethod Call PopFrame If raised Then Do Call KeepNativeLines context~errorLines~appendAll( ErrorLines( context ) ) End Iterate End If level < throw~level Then Do -- beyond the main program context~thrown = .Nil Signal PropagateCo End -- A RAISE PROPAGATE (EXIT) in the main program: its caller is nobody; -- the report has no "running" line. If throw~level < 0 Then Do Call KeepErrorLines Call TracebackCheck context, throw~info context~errorHeader = "" context~thrown = .Nil Signal PropagateCo End -- A SYNTAX raised again (RAISE PROPAGATE) is where it lands. If throw~info~program == .Nil Then context~locate( throw~info ) -- An error in a line typed at a pause is shown, and the pause goes on. If \ isTrap, \ pauses~isEmpty, context~debugPause, - level == pauses~lastItem~level Then Signal DebugFailed trap = throw~trap If trap == .Nil, \ context~level~forwarded Then Do trap = context~trapFor( "SYNTAX" ) If trap \== .Nil, trap~state \== "ON" Then trap = .Nil End If trap \== .Nil Then Leave -- Untrapped: the caller gets its chance; the lines are kept. If \ throw~reraise Then Call KeepErrorLines If level == 0 Then Do -- Propagated with its old lines: the "running" line says where it -- was raised again. If raised | throw~reraise, throw~info~traceback \== .Nil Then context~errorHeader = .Array~of( throw~info~position, throw~info~program ) -- In the arguments of a routine of REXXUTIL: "running REXX:", no line. Else If throw~info~program == "REXX", throw~info~position == .Nil Then context~errorHeader = .Array~of( .Nil, "REXX" ) -- (A sendSync's is checked in the machine below, with all its lines.) If \ throw~reraise, \ context~syncRoot Then Call TracebackCheck context, throw~info -- An activity that ends so: its condition (a message it ran has it). If throw~info~traceback == .Nil, context~errorLines \== .Nil Then throw~info~traceback = context~errorLines~copy context~failedInfo = throw~info context~thrown = .Nil -- An error in an UNINIT: not reported; the next one runs. If act \== .Nil Then If act~uninits \== .Nil Then Do context~errorLines = .Nil context~errorHeader = .Nil context~failedInfo = .Nil context~nativeLines~empty Signal On Syntax Name Failed Signal UninitNext End -- The message of a START: it has the error, and those to notify are -- notified now, in this activity (ooRexx's MessageClass~error), before -- it ends (Deliver, FAILED) and its error is reported. If act \== .Nil Then Do ms = act~message If ms \== .Nil, \ ms~complete, \ ms~parties~isEmpty Then Do ms~failed = .True ms~info = throw~info ms~done act~error = co sMode = "FAILED" sPend = .Array~new sDepth = context~nativeLines~items sp = 0 v = ms~notifyAll( .Nil ) Signal On Syntax Name Failed Signal Delegated End End Signal PropagateCo End throw~level = level - 1 throw~info~propagated = "1" leaving = context~currentMethod Call PopFrame If \ throw~reraise Then Do Call KeepNativeLines context~errorLines~appendAll( ErrorLines( context ) ) End End -- Trapped here: SIGNAL ON turns its trap off, records the condition, sets -- RC and SIGL, and resumes at the trap's label. The pauses of this -- activation (and of those left) are over. Do While \ pauses~isEmpty pz = pauses~lastItem If pz~level < frames~items Then Leave If context~debugPause Then Call DebugLineOver context, pz pauses~delete( pauses~last ) End jumpMark = .Nil iheld = .Array~new -- A SYNTAX keeps its report's lines (RAISE PROPAGATE shows them). If throw~info~condition == "SYNTAX" Then Do Call KeepErrorLines throw~info~traceback = context~errorLines End context~thrown = .Nil context~errorLines = .Nil context~nativeLines~empty context~clearInterprets context~interpretError = .Nil info = throw~info info~instruction = "SIGNAL" context~trapOff( trap~condition ) context~condition = info If info~rc \== .Nil Then context~setVar( "RC", info~rc ) line = 0 If context~clause \== .Nil Then line = context~clause~line context~setVar( "SIGL", line ) context~traceIndent = 0 If frames~isEmpty Then sp = 0 Else sp = frames~lastItem~sp Signal On Syntax Name Failed address = labels[ trap~target ] If address == .Nil Then Raise Syntax 16.001 Additional( trap~target ) fromLabel = trap~target pc = address Signal Resume -- End the current activation (unwinding). -- The traceback lines of an error going up, from the activation it leaves: -- its clause, unless they are already there (and after the natives' lines). KeepErrorLines: If context~errorLines == .Nil Then context~errorLines = ErrorLines( context ) Else If context~errorLines~items > 0, - context~errorLines~lastItem~hasIndex( 4 ) Then context~errorLines~appendAll( ErrorLines( context ) ) Return -- After PopFrame: the natives that led to a method (NEW, SEND) or to a -- routine (CALL) are shown below it, and they are the natives' lines of the -- caller's clause. KeepNativeLines: line = 0 If context~clause \== .Nil Then line = context~clauseText( context~clause )[1] -- A compiled method (the RVM's part of the prelude) is one line, when the -- error leaves it (its lines, and those of its routines, are not shown). If leaving \== .Nil, leaving~compiled Then Do now = context~currentMethod If now == .Nil Then now = .False Else now = now~compiled If \ now Then context~errorLines~append( .Array~of( line, NativeLine( leaving ), context~programName ) ) End If f~natives \== .Nil Then Do Do k = f~natives~items To 1 By -1 context~errorLines~append( .Array~of( line, NativeText( f~natives[k] ), context~programName ) ) End End Return PopFrame: f = frames~lastItem frames~delete( frames~last ) context~popActivation descs = f~descs parse = f~parse iheld = f~iheld If f~program \== .Nil Then Call LeaveProgram If f~kind == "METHOD" Then Call LeaveMethod Return -- The registers of the program that runs now (see CALLX). SwitchProgram: context~rvmProgram = program code = program~code consts = program~consts names = program~names clauses = program~clauses labels = program~labels withs = program~withs numCache = program~numCache icache = program~icache envCache = program~envCache Return -- Back from an external routine (frame f) to its caller's program. LeaveProgram: program = f~program Call SwitchProgram context~programName = f~progName context~sourceLines = f~progSource context~invocation = f~invocation entryAllowed = f~entryAllowed entryDone = f~entryDone entryClause = f~entryClause entryText = f~entryText labels = f~labels curMethod = f~method context~currentMethod = f~method curFrame = f~mframe curSender = f~sender Return /******************************************************************************/ /* Helpers */ /******************************************************************************/ /******************************************************************************/ /* External routines (rexxref 7.2.1, for Classic Rexx: no ::ROUTINE, no */ /* function packages or macrospace; Rexx programs in files) */ /******************************************************************************/ -- An activity is over (outcome ENDED or FAILED): an error is reported now, -- as ooRexx does when an activity ends with one (the main program's is the -- run's exit code); a message it ran has the error; its lock goes. ::Routine EndActivity Use Strict Arg act, outcome, sched ctx = act~context If outcome == "FAILED" Then Do co = act~error lines = ctx~errorLines If lines == .Nil Then lines = .Array~of( .Array~of( 0, "" ) ) code = ErrorReport( BifCodeOf( co ), BifMessageOf( co ), lines, - ctx~errorHeader, sched~path, ctx ) ctx~errorLines = .Nil ctx~errorHeader = .Nil If act~isMain Then ctx~exitCode = code ms = act~message If ms \== .Nil, \ ms~complete, ctx~failedInfo \== .Nil Then Do ms~failed = .True ms~info = ctx~failedInfo ms~done End End ctx~endActivity sched~ended( act ) -- The report of an error nobody trapped (on the standard error stream): the -- lines it went through, "Error n running file line m:" and its message. -- Returns the exit code: minus the error number. 'header' is the running -- line (see RVM.Context~errorHeader); 'path' the main program's. ::Routine ErrorReport Public Use Strict Arg code, message, lines, header, path, ctx = .Nil Parse Var code major "." minor -- No line at all (a START whose message has no method in Rexx): no -- "running" line either. If lines~isEmpty Then header = "" Do entry Over lines If entry[1] > 0, entry[2] \== "" Then Call ReportLine entry[2], ctx End -- The "running" line: the first line's, unless the header says (a RAISE -- PROPAGATE: where it was raised again, or nowhere). The error may be in -- an external routine: its file (see ErrorLines). If header == .Nil Then Do line = lines[ 1 ][ 1 ] name = path If lines[ 1 ]~hasIndex( 3 ) Then name = lines[ 1 ][ 3 ] End Else If header \== "" Then Do line = header[ 1 ] name = header[ 2 ] If name == .Nil Then name = path End If header == "" Then Call ReportLine "Error" major": "ErrorText( major ), ctx -- (No line: raised in the REXX package, in a native routine's arguments.) Else If line == .Nil Then Call ReportLine "Error" major "running" name": "ErrorText( major ), ctx Else Call ReportLine "Error" major "running" name "line" line": "ErrorText( major ), ctx -- (An error with no secondary message, as X.0: no second line.) If minor \== "", minor \== "0" Then Do If message \== "", Right( message, 1 ) \== "." Then message = message"." Call ReportLine "Error" code": "message, ctx End Return -major -- A line of the report: as trace output (ooRexx's displayUsingTraceOutput: -- to .TRACEOUTPUT) when there is a context; else straight, with the -- characters that do not display as "?", as traceRaw (ooRexx's stringTrace: -- a source that does not parse, 13.1). ::Routine ReportLine Use Strict Arg line, ctx If ctx \== .Nil Then ctx~traceRaw( line ) Else .Error~lineOut( Translate( line, "?????????????????????????????", - "000102030405060708"x"0B0C"x"0E0F101112131415161718191A1B1C1D1E1F"x ) ) -- Is the current activation the main one of its program (the main program, -- or an external routine)? ::Routine AtMain Use Strict Arg frames If frames~isEmpty Then Return .True If frames~lastItem~kind == "METHOD" Then Return .True Return frames~lastItem~program \== .Nil -- The clause of the first instruction at 'address' of a program (EXPOSE -- too; ooRexx's current instruction when it traces an entry), or .Nil. ::Routine EntryClause Use Strict Arg program, address If program == .Nil | \ DataType( address, "W" ) Then Return .Nil code = program~code Do a = address To Min( code~items, address + 3 ) ins = code[ a ] If ins == .Nil Then Leave If ins[1] == "CLAUSE" Then Return program~clauses[ ins[2] ] End Return .Nil -- The trace of the entry to (">I>") or the exit from (" 0 Then on = ( WordPos( c, program~syntaxConds ) > 0 ) Else on = ( WordPos( c, conds ) > 0 ) If on Then syntax = syntax c End program~syntaxConds = Strip( syntax ) world~overrideCount -= 1 -- The program made of these R-code lines (verified: see RVM.RCode~read). ::Routine ProgramOfRCode Public Use Strict Arg rcode, path, source program = .RVM.RCode~read( rcode ) program~path = path program~source = source program~rcode = rcode Do ins Over program~code If ins[1] == "CLAUSE" Then Do program~firstClause = ins[2] Leave End End Return program -- REXXUTIL's macrospace (RVM.RexxUtil.cls) compiles and reads programs. ::Class RVM.MacroLoader ::Method activate Class package = .context~package .RVM.RexxUtil~loader = package~findRoutine( "LoadProgram" ) .RVM.RexxUtil~reader = package~findRoutine( "ProgramOfRCode" ) -- The program of a package a ::REQUIRES names: found as an external routine -- is, .cls first (43.901 when it is not), and loaded once (LoadProgram). ::Routine LoadPackage Public Use Strict Arg name, context path = FindExternal( name, context~programName, .True ) If context~secMgr \== .Nil Then Return RequiresProgram( name, path, context ) If path == "" Then Raise Syntax 43.901 Array( name ) Return LoadProgram( path, context ) -- A package required (name, found at 'path'; "": not found) when the -- activation has a security manager (ooRexx's PackageManager::loadRequires): -- one loaded already is the same, with no questions; else the manager is -- asked (REQUIRES) about the name and then about the file, and it may -- change them (NAME; none: 43.901) and give the package a manager of its -- own (SECURITYMANAGER). ::Routine RequiresProgram Public Use Strict Arg name, path, context table = ExternalsTable() If path \== "", table~hasIndex( path ) Then Return table[ path ] world = context~world mgr = context~secMgr pkgMgr = .Nil info = world~security( mgr, "REQUIRES", .Array~of( "NAME", name ) ) If info \== .Nil Then Do If info["NAME"] == .Nil Then Raise Syntax 43.901 Array( name ) m = info["SECURITYMANAGER"] If m \== .Nil, m \== world~nil Then pkgMgr = m End If path == "" Then Raise Syntax 43.901 Array( name ) first = path info = world~security( mgr, "REQUIRES", .Array~of( "NAME", path ) ) If info \== .Nil Then Do If info["NAME"] == .Nil Then Raise Syntax 43.901 Array( name ) path = SyncString( info["NAME"], context ) m = info["SECURITYMANAGER"] If m \== .Nil, m \== world~nil Then pkgMgr = m End If table~hasIndex( path ) Then program = table[ path ] Else Do program = LoadProgram( path, context ) If pkgMgr \== .Nil Then program~secMgr = pkgMgr End table[ first ] = program Return program -- The programs loaded (path, or the name of a package made from source -> -- RVM.Program): each once. -- The programs loaded from files, by path (or, with "TEXTS", the texts -- they were loaded from). ::Routine ExternalsTable Use Strict Arg which = "" table = .RVM.Program~externals If \ table~isA( .Table ) Then Do -- unset: it holds its name table = .Table~new .RVM.Program~externals = table .RVM.Program~externalTexts = .Table~new End If which == "TEXTS" Then Return .RVM.Program~externalTexts Return table -- The program in file 'path', loaded once: from R-code (a .rcode file) or -- compiled from its source. With 'reread' (an external routine), the file -- is read again and, when its text is not the one loaded, loaded again. A -- source that does not parse raises its error here, with its line first in -- the report. ::Routine LoadProgram Public Use Strict Arg path, context, override = .True, reread = .False table = ExternalsTable() program = table[ path ] If program \== .Nil, \ reread Then Return program text = CharIn( path, 1, Chars( path ) ) Call Stream path, "C", "Close" texts = ExternalsTable( "TEXTS" ) If program \== .Nil, texts[ path ] == text Then Return program If path~caselessEndsWith( ".rcode" ) Then Do rcode = text~makeArray source = .Nil End Else Do source = SourceLines( text ) -- Its R-code, when it is next to it and up to date; else compiled. rcode = CachedRCode( path, text ) If rcode == .Nil Then Do Signal On User Rexx.Parser.Error Name NotParsed parser = .Rexx.Parser~new( path, source ) package = parser~package Signal Off User Rexx.Parser.Error unit = .RVM.Compiler~compile( package, source, path ) rcode = .RVM.RCode~write( unit, SourceHash( text ) ) If .RVM.Program~writeCache == 1 Then Call WriteCache path, rcode End End program = ProgramOfRCode( rcode, path, source ) table[ path ] = program texts[ path ] = text If override Then Call OverrideOptions program, context~world Return program NotParsed: error = Condition("O")~additional context~interpretError = .Array~of( error~line, - ParseErrorLine( source, error ), path ) Raise Syntax ( error~code ) Additional( error~substitutions~copy ) -- Where the file of an external routine is (ooRexx's -- InterpreterInstance::resolveProgramName and SysFileSystem, Unix): a name -- with an extension (a period after its last "/") only as it is; else with -- .cls first for a ::REQUIRES, then the caller's extension, .REX, .rex, and -- none. Each of them, as given and in lower case (the name; the extension as -- it is), in the directory of the caller, the current one, REXX_PATH and -- PATH; a name that starts with "/", "~", "./" or "../" only there. A name -- that is found but is not a file ends the search of that name. The file -- found is qualified. When no source is found, the same search for their -- R-code (a deployed program: see CachePath) gives it. "" when it is not -- found. ::Routine FindExternal Public Use Strict Arg name, caller, requires = .False dirs = .Array~new -- (Windows: "\" too in the caller's name, and ";" between directories.) windows = .File~separator == "\" slash = LastPos( "/", caller ) If windows Then slash = Max( slash, LastPos( "\", caller ) ) If slash > 1 Then dirs~append( Left( caller, slash ) ) dirs~append( Directory() ) If windows Then delimiter = ";" Else delimiter = ":" Do var Over .Array~of( "REXX_PATH", "PATH" ) Do d Over Value( var, , "ENVIRONMENT" )~makeArray( delimiter ) If d \== "" Then dirs~append( d ) End End exts = .Array~new If FileExtension( name ) \== "" Then exts~append( "" ) Else Do If requires Then exts~append( ".cls" ) exts~append( FileExtension( caller ) ) exts~append( ".REX" ) exts~append( ".rex" ) exts~append( "" ) End Do cached Over .Array~of( .False, .True ) Do i = 1 To exts~items ext = exts[i] If i < exts~items, ext == "" Then Iterate -- (the caller's, when none) file = SearchName( name, ext, dirs, cached ) If file \== "" Then Return file End End Return "" -- The extension of file 'name' (ooRexx's SysFileSystem::extractExtension): -- from its last period after its last "/" (not its first character); "" if -- none. ::Routine FileExtension Use Strict Arg name Do i = Length( name ) To 2 By -1 c = SubStr( name, i, 1 ) If c == "/" Then Return "" If c == "." Then Return SubStr( name, i ) End Return "" -- One search of FindExternal (ooRexx's SysFileSystem::primitiveSearchName): -- 'name' || 'ext', then its name in lower case; the source file, or its -- R-code (cached). -- Windows: a name with a drive ("C:..."), or that starts with "\", ".\" or -- "..\", is searched only as it is (as "/", "./" and "../" on Unix). ::Routine WindowsAbsolute Use Strict Arg file If .File~separator \== "\" Then Return .False If SubStr( file, 2, 1 ) == ":" Then Return .True Return file~startsWith( "\" ) | file~startsWith( ".\" ) | file~startsWith( "..\" ) ::Routine SearchName Use Strict Arg name, ext, dirs, cached names = .Array~of( name ) If Lower( name ) \== name Then names~append( Lower( name ) ) Do n Over names file = n || ext If file~startsWith( "/" ) | file~startsWith( "~" ) | file~startsWith( "./" ) | - file~startsWith( "../" ) | WindowsAbsolute( file ) Then Do full = Qualify( file ) If cached Then full = CachePath( full ) If SysIsFile( full ) Then Return full Iterate End Do d Over dirs full = Qualify( d"/"file ) If cached Then Do full = CachePath( full ) If SysIsFile( full ) Then Return full Iterate End If SysIsFile( full ) Then Return full If SysFileExists( full ) Then Leave -- (a directory) End End Return "" /******************************************************************************/ /* R-code caches: the R-code of a source file, next to it (CachePath). It is */ /* used instead of compiling the source when it was made from the same text */ /* (SourceHash) by the same compiler for the same instruction set. rvm -w */ /* writes them. */ /******************************************************************************/ -- The R-code file of a source: x.rex -> x.rcode; any other name + .rcode. ::Routine CachePath Public Use Strict Arg path If path~caselessEndsWith( ".rex" ) Then Return Left( path, Length( path ) - 4 )".rcode" Return path".rcode" -- A fingerprint of a text: two remainders (by primes near 2**31) of the text -- taken as a number in base 2**32, 4 bytes at a time, and its length. The -- JS RVM computes the same (sourceHash in rcode.mjs). ::Routine SourceHash Public Use Strict Arg text Numeric Digits 30 h1 = 0; h2 = 0 len = Length( text ) Do i = 1 To len By 4 c = C2D( SubStr( text, i, Min( 4, len - i + 1 ) ) ) h1 = ( h1 * 4294967296 + c ) // 2147483647 h2 = ( h2 * 4294967296 + c ) // 2147483629 End Return h1"."h2"."len -- The lines of source 'text', split as ooRexx splits a program -- (ProgramSource::buildDescriptors): the text ends at its first Ctrl-Z, and -- a line ends with CR, LF or CR LF (~makeArray knows LF and CR LF only: a -- lone CR stayed in the line, and the parser saw an incorrect character). ::Routine SourceLines Public Use Strict Arg text z = Pos( "1A"x, text ) If z > 0 Then text = Left( text, z - 1 ) text = text~changeStr( "0D0A"x, "0A"x )~changeStr( "0D"x, "0A"x ) Return text~makeArray( "0A"x ) -- The R-code of source 'path' (whose text is 'text') from its cache, when it -- is up to date; else .Nil. ::Routine CachedRCode Public Use Strict Arg path, text cache = CachePath( path ) If \ SysIsFile( cache ) Then Return .Nil lines = CharIn( cache, 1, Chars( cache ) )~makeArray Call Stream cache, "C", "Close" If lines~items < 3 Then Return .Nil If lines[1] \== "RCODE" .RVM.RCode~VERSION Then Return .Nil If lines[2] \== "COMPILER" .RVM.Compiler~VERSION .RVM.ISA~VERSION - .RVM.Compiler~frontier Then Return .Nil If lines[3] \== "SOURCE" SourceHash( text ) Then Return .Nil Return lines -- Write the cache of source 'path'; a file that cannot be written is left. ::Routine WriteCache Public Use Strict Arg path, lines cache = CachePath( path ) Signal On NotReady Name Done Signal On Syntax Name Done If Stream( cache, "C", "Open Write Replace" ) \= "READY:" Then Return Do l Over lines Call LineOut cache, l End Done: Call Stream cache, "C", "Close" Return /******************************************************************************/ /* Interactive trace */ /******************************************************************************/ -- Does the pause happen? Not while a line typed -- at a pause runs; not once after a TRACE typed there (bypass); not during -- TRACE n. The first one shows the prompt. ::Routine DebugStart Use Strict Arg context If context~debugPause Then Return 0 If context~debugBypass Then Do context~debugBypass = .False Return 0 End If context~traceSkip > 0 Then Do context~traceSkip = context~traceSkip - 1 If context~traceSkip == 0 Then context~traceSuppressed = .False Return 0 End If \ context~promptIssued Then Do context~traceRaw( '+++ Interactive trace. "Trace Off" to end debug,' - 'ENTER to continue. +++' ) context~promptIssued = .True End Return 1 -- The line typed at a pause (ooRexx's traceInput): from .DEBUGINPUT (LINEIN) -- when it is not the monitor .LOCAL started with; else from the standard -- input straight. .NIL is ""; an error of the LINEIN is the program's (a -- destination with no LINEIN: 97.1). ::Routine DebugLineIn Use Strict Arg context target = context~localTarget( "DEBUGINPUT" ) If target == .Nil Then Do If Lines() > 0 Then Return LineIn() Return "" End world = context~world If target == world~nil Then Return "" v = world~loader~sendSync( target, "LINEIN", .Array~new ) If v == .Nil | v == world~nil Then Return "" Return str( v ) -- TRACE n: only at a pause (else 24.901). The next n pauses are skipped; when -- n is negative, nothing is traced meanwhile either. ::Routine DebugSkip Use Strict Arg n, context If \ context~debugPause Then Raise Syntax 24.901 context~traceSkip = Abs( n ) context~traceSuppressed = n < 0 context~debugBypass = .True -- A line typed at a pause is over: the clause that paused is the current one -- again, and its CALL ON traps are back. ::Routine DebugLineOver Use Strict Arg context, pz context~debugPause = .False context~clause = pz~clause If pz~traps \== .Nil Then context~restoreCallTraps( pz~traps ) pz~traps = .Nil -- What comes after a pause: the name of the label that comes next, "00"x at -- the end of INTERPRET data, or "". ::Routine NextAfter Use Strict Arg code, consts, a, top = .Nil first = a Loop While a <= code~items op = code[ a ][ 1 ] Select Case op When "BOUND", "INDENT", "UNINDENT", "UNIND2" Then a += 1 When "JMP" Then a = code[ a ][ 2 ] -- The branch of the IF (or WHEN) that paused: its value is on the stack -- (ooRexx's pause comes after the branch is chosen). When "JF", "JT" Then Do If a \== first | top == .Nil Then Return "" If top~isA( .RVM.Obj ) Then Return "" v = str( top ) If ( op == "JF" & v == "0" ) | ( op == "JT" & v == "1" ) Then a = code[ a ][ 2 ] Else a += 1 End When "LABEL" Then Return consts[ code[ a ][ 3 ] ] When "IEND" Then Return "00"x Otherwise Return "" End End Return "" -- Compile a line typed at a pause, as INTERPRET data that ends with DEND. -- Returns its address, or 0 when it does not parse (the error is shown). ::Routine DebugCompile Use Strict Arg program, context, data, clause, bodyLabels source = .Array~of( data ) line = 0 If clause \== .Nil Then line = clause~line Signal On Syntax Name NotParsed Signal On User Rexx.Parser.Error Name NotParsed labels = .Table~new Do name Over bodyLabels~allIndexes labels[ name ] = .RVM.LabelRef~new End parser = .Rexx.Parser~new( context~programName, source, - .Array~of( .Array~of( "INTERPRET", labels ) ) ) .environment~Options.Interpret = 0 package = parser~package Signal Off Syntax Signal Off User Rexx.Parser.Error .RVM.Fragments~register( package, source, line ) Return LoadData( program, package, source, 0, 0 ) NotParsed: .environment~Options.Interpret = 0 Call DebugError context, Condition("O"), clause Return 0 -- An error in a line typed at a pause, as ooRexx shows it -- (Activity::displayDebug). ::Routine DebugError Use Strict Arg context, co, clause If co~condition == "USER REXX.PARSER.ERROR" Then Do code = co~additional~code -- it did not parse inserts = co~additional~substitutions~copy Parse Value LineInsert( code ) With n . If n \== "", inserts~hasIndex( n ) Then Do line = 0 If clause \== .Nil Then line = clause~line inserts[ n ] = line End message = ErrorText( code, inserts ) End Else Do code = BifCodeOf( co ) message = BifMessageOf( co ) End Parse Var code major "." minor context~traceRaw( "+++ Interactive trace. Error" major": "ErrorText( major ) ) -- (An error with no secondary message, as X.0: no second line.) If minor \== "", minor \== "0" Then Do If message \== "", Right( message, 1 ) \== "." Then message = message"." context~traceRaw( "+++ Interactive trace. Error" code": "message ) End -- A RAISE ... RETURN: raised in the caller once the routine has returned. -- HALT and NOMETHOD that nobody traps are errors. ::Routine RaiseInCaller Use Strict Arg context, info If context~raiseCondition( info ) Then Return Call UntrappedRaise info ::Routine UntrappedRaise Use Strict Arg info If info~condition == "HALT" Then Raise Syntax 4.1 Array( "HALT" ) Description "RVM.Halt" If info~condition == "NOMETHOD" Then Raise Syntax 97.5 /******************************************************************************/ /* Commands (see RVM.Commands: the same, with the RVM's */ /* redirections) */ /******************************************************************************/ ::Routine IssueCommand Use Strict Arg context, env, command, local, canWait = .False context~commandNoResult = .False host = context~commandHost global = context~ioConfigFor( env ) input = MakeInput( context, PickSpec( "INPUT", local, global ) ) output = MakeOutput( context, "OUTPUT", PickSpec( "OUTPUT", local, global ) ) error = MakeOutput( context, "ERROR", PickSpec( "ERROR", local, global ) ) merged = .False If output \== .Nil, error \== .Nil Then If output~sameTarget( error, context ) Then Do error = output merged = .True End -- The security manager of the activation is asked (COMMAND, with the -- command and the environment: ooRexx's callCommandExit); when it handles -- it, its RC (0 if none) is the command's, and FAILURE or ERROR raise -- their condition. If context~secMgr \== .Nil Then Do info = context~world~security( context~secMgr, "COMMAND", - .Array~of( "COMMAND", command, "ADDRESS", env ) ) If info \== .Nil Then Do rc = info["RC"] If rc == .Nil Then rc = 0 condition = "" If info["FAILURE"] \== .Nil Then condition = "FAILURE" Else If info["ERROR"] \== .Nil Then condition = "ERROR" If \ context~debugPause Then context~setVar( "RC", rc ) context~commandNoResult = .True Return condition End End -- An environment a library registered (hostemu): its handler runs the -- command (RVM.HostEmu.cls). It does not redirect: any WITH, the -- instruction's or the environment's, is 98.921 (ooRexx's -- CommandHandler::call, for a handler registered by name). lib = context~registeredEnvironment( env ) If lib \== .Nil Then Do If local \== .Nil | global \== .Nil Then Raise Syntax 98.921 Array( env ) res = EnvironmentCommand( lib, env, command, context ) If \ context~debugPause Then context~setVar( "RC", res[1] ) context~commandNoResult = .True Return res[2] End strategy = host~strategyFor( env ) If strategy == .Nil Then Do If \ context~debugPause Then context~setVar( "RC", host~NOT_REGISTERED ) context~commandNoResult = .True Return "FAILURE" End inputBytes = .Nil If input \== .Nil Then Do -- An InputStream that fails (an error in its LINEIN): the command runs -- with the lines it gave, and then the error goes on (ooRexx reads the -- input while the command runs). If input~isA( .RVM.StreamObjInput ) Then Signal On Syntax Name InputFailed inputBytes = input~bytes( context, host~lineEnd ) Signal Off Syntax End Return RunRedirected() InputFailed: inputBytes = input~partial canWait = .False Call RunRedirected Raise Propagate -- (IssueCommand's, with its variables.) RunRedirected: If output \== .Nil Then output~open( context ) If error \== .Nil, \ merged Then error~open( context ) res = .Nil If local == .Nil, global == .Nil Then res = host~runInternally( command ) If res == .Nil Then Do Select When merged Then errorMode = "MERGE" When error \== .Nil Then errorMode = "CAPTURE" Otherwise errorMode = "INHERIT" End -- (Its activity may wait for it: see CMD.) If canWait Then Do run = host~start( strategy, command, inputBytes, output \== .Nil, errorMode, - .RVM.CommandWait~sem ) If run~started Then Return .RVM.CommandWait~new( run, host, output, error, merged ) End Else run = host~run( strategy, command, inputBytes, output \== .Nil, errorMode ) Return CommandFinish( run, host, output, error, merged, context ) End rc = res~rc condition = res~condition If output \== .Nil Then output~close If error \== .Nil, \ merged Then error~close If \ context~debugPause Then context~setVar( "RC", rc ) Return condition -- What a command that the host ran (run) gives: what it wrote, to its -- targets (closed then), its RC (not at a pause) and its condition. ::Routine CommandFinish Use Strict Arg run, host, output, error, merged, context If output \== .Nil Then output~writeText( run~out, context ) If error \== .Nil, \ merged Then error~writeText( run~err, context ) rc = run~rc Select When \ run~started Then condition = "FAILURE" -- (On Windows a command cmd.exe does not know is rc 9009 and an ERROR, -- as in ooRexx; 127 is a return code like any other.) When rc == host~UNKNOWN_COMMAND, \ host~windows Then condition = "FAILURE" When rc \== 0 Then condition = "ERROR" Otherwise condition = "" End If output \== .Nil Then output~close If error \== .Nil, \ merged Then error~close If \ context~debugPause Then context~setVar( "RC", rc ) Return condition /******************************************************************************/ /* RVM.CommandWait -- a command that the host runs while the RVM goes on (see */ /* RVM.CommandHost~start): its activity waits for it among the scheduler's */ /* I/O waits (RVM.CommandPoller polls them) and, when it has ended, finishes */ /* it (see CmdResumed in the machine). One EventSemaphore, posted by every */ /* command that ends, wakes the poller. */ /******************************************************************************/ ::Class RVM.CommandWait Public ::Attribute sem Class ::Attribute run ::Method activate Class self~sem = .EventSemaphore~new ::Method init Expose run host output error merged Use Strict Arg run, host, output, error, merged ::Method wait Expose act sched Use Strict Arg act, sched act~waitingOn = self sched~addIO( self, .RVM.CommandPoller ) ::Method owningActivity Return .Nil ::Method ended Expose run Return run~job~done -- It has ended: its activity goes on (CmdResumed). ::Method retry Expose act sched sched~removeIO( self ) act~semDone( self ) -- Its activity ended while it waited (the command goes on by itself). ::Method cancel Expose sched sched~removeIO( self ) ::Method finish Expose run host output error merged Use Strict Arg context host~finish( run ) Return CommandFinish( run, host, output, error, merged, context ) /******************************************************************************/ /* The scheduler's poll of the commands that run (RVM.Scheduler~pollIO): the */ /* ones that have ended go on; for 'ms' milliseconds at most (-1: until one */ /* has), waiting on their semaphore in steps of 100 ms. The host's HALT */ /* (Ctrl-C) is the scheduler's (haltAll), and ends the poll. */ /******************************************************************************/ ::Class RVM.CommandPoller Public ::Method poll Class Use Strict Arg sched, ms Call On Halt Name HostHalt -- Ctrl-C while it waits (haltAll) halted = .False sem = .RVM.CommandWait~sem Numeric Digits 18 left = ms Loop sem~reset any = .False Do w Over sched~ios~copy If \ w~isA( .RVM.CommandWait ) Then Iterate If \ w~ended Then Iterate w~retry any = .True End If any | halted | left == 0 Then Return step = 100 If left > 0 Then step = Min( step, left ) t0 = Time( "F" ) sem~wait( step / 1000 ) If left > 0 Then left = Max( 0, left - ( Time( "F" ) - t0 ) % 1000 ) End HostHalt: sched~haltAll halted = .True Return ::Routine PickSpec Use Strict Arg stream, local, global If local \== .Nil Then Do type = local~redirectionType( stream ) If type == "NORMAL" Then Return .Nil If type \== "" Then Return local End If global == .Nil Then Return .Nil type = global~redirectionType( stream ) If type == "" | type == "NORMAL" Then Return .Nil Return global -- The redirections of a command (ooRexx's CommandIOConfiguration): INPUT, -- OUTPUT and ERROR, in that order, each target evaluated (and traced: its -- value, then >K> with the stream's name) when the command runs, and the -- redirector made for it (errors: 98.996, 98.997, 98.922, 98.924). ::Routine MakeInput Use Strict Arg context, spec If spec == .Nil Then Return .Nil type = spec~redirectionType( "INPUT" ) v = TargetValue( context, spec, "INPUT" ) world = context~world Select When type == "STEM" Then Return .RVM.StemObjInput~new( world~stemOf( v ) ) When type == "STREAM" Then Return .RVM.StreamInput~new( SyncString( v, context ) ) Otherwise Nop End -- USING: a string is a line; a stem, its lines; an InputStream (or a -- Monitor), what LINEIN reads; a File, its lines; else MAKEARRAY -- (REQUEST ARRAY), its items made strings. If \ v~isA( .RVM.Obj ) Then Return .RVM.LinesInput~new( .Array~of( str( v ) ) ) st = world~stemOf( v ) If st \== .Nil Then Return .RVM.StemObjInput~new( st ) world~ensurePrelude If InstanceOfNamed( v, "INPUTSTREAM", world ) | InstanceOfNamed( v, "MONITOR", world ) Then Return .RVM.StreamObjInput~new( v ) If InstanceOfNamed( v, "FILE", world ) Then Return .RVM.StreamInput~new( SyncString( SyncSend( context, v, "ABSOLUTEPATH" ), context ) ) If InstanceOfNamed( v, "ARRAY", world ) Then a = SyncSend( context, v, "MAKEARRAY" ) Else a = SyncSend( context, v, "REQUEST", "ARRAY" ) If \ InstanceOfNamed( a, "ARRAY", world ) Then Raise Syntax 98.924 Array( ObjectText( v ) ) If \ a~native~isA( .Array ) Then Raise Syntax 98.924 Array( ObjectText( v ) ) lines = .Array~new Do item Over a~native~allItems lines~append( SyncString( item, context ) ) End Return .RVM.LinesInput~new( lines ) ::Routine MakeOutput Use Strict Arg context, stream, spec If spec == .Nil Then Return .Nil type = spec~redirectionType( stream ) option = spec~redirectionOption( stream ) append = ( option == "APPEND" ) v = TargetValue( context, spec, stream ) world = context~world Select When type == "STEM" Then Return .RVM.StemObjOutput~new( world~stemOf( v ), append ) When type == "STREAM" Then Return .RVM.StreamOutput~new( SyncString( v, context ), append ) Otherwise Nop End -- USING: a stem; an OutputStream (or a Monitor): LINEOUT; a RexxQueue: -- QUEUE; a File: its path, as STREAM; an OrderedCollection: APPEND (EMPTY -- first, but with APPEND). Anything else (a string too): 98.996. If v~isA( .RVM.Obj ) Then Do st = world~stemOf( v ) If st \== .Nil Then Return .RVM.StemObjOutput~new( st, append ) world~ensurePrelude If InstanceOfNamed( v, "OUTPUTSTREAM", world ) | InstanceOfNamed( v, "MONITOR", world ) Then Do If option \== "" Then Raise Syntax 98.997 Return .RVM.ObjectOutput~new( v, "LINEOUT", .True ) End If InstanceOfNamed( v, "REXXQUEUE", world ) Then Do If option \== "" Then Raise Syntax 98.922 Return .RVM.ObjectOutput~new( v, "QUEUE", .True ) End If InstanceOfNamed( v, "FILE", world ) Then Return .RVM.StreamOutput~new( SyncString( SyncSend( context, v, "ABSOLUTEPATH" ), context ), append ) If InstanceOfNamed( v, "ORDEREDCOLLECTION", world ) Then Return .RVM.ObjectOutput~new( v, "APPEND", append ) End Raise Syntax 98.996 Array( ObjectText( v ) ) -- The value of a redirection target, traced as ooRexx traces it: a string -- (>L>), a stem (>V>), an expression (its own trace), and then >K> with -- the stream's name. ::Routine TargetValue Use Strict Arg context, spec, stream target = spec~redirectionTarget( stream ) Select Case target[1] When "STR" Then Do v = target[2] If context~traceI Then context~traceValue( ">L>", v ) End When "STEM", "USTEM" Then Do v = context~getStem( target[2] ) If context~traceI Then context~traceTagged( ">V>", Upper( target[2] ), " => ", v ) End -- ENV: the compiler never writes it (an expression is a THUNK). When "ENV" Then Raise Syntax 93.900 Additional( - "RVM: ADDRESS WITH USING an environment symbol" target[2] ) When "THUNK" Then v = .RVM.Machine~run( spec~program, context, target[2], .True ) End context~traceKeyword( stream, v ) Return v -- Whether v is an instance of the class named 'name' of the REXX package -- (.Nil there: it is not). ::Routine InstanceOfNamed Use Strict Arg v, name, world If \ v~isA( .RVM.Obj ) Then Return .False k = world~environment~native[ name ] If k == .Nil Then Return .False Return IsSubclass( world~classOf( v ), k ) -- A message sent now, to its end (see RVM.Machine~sendSync): its result. ::Routine SyncSend Use Strict Arg context, receiver, name, arg = .Nil args = .Array~new If arg \== .Nil Then args~append( arg ) Return context~world~loader~sendSync( receiver, name, args ) -- The string value of v (ooRexx's requestString): a STRING written in Rexx -- runs now (a command cannot run its instruction again, as the others do: -- see RVM.NeedString). ::Routine SyncString Public Use Strict Arg v, context If \ v~isA( .RVM.Obj ) Then Return str( v ) Signal On Syntax Name SyncStringNeeded Return str( v ) SyncStringNeeded: co = Condition( "O" ) If co~description \== "RVM.NeedString" Then Raise Propagate Return str( SyncSend( context, v, "STRING" ) ) -- The count in stem.0 (see RVM.Commands' StemCount): 26.904. ::Routine StemObjCount Use Strict Arg st, value w = unsignedWholeNumber( value, .RVM.Number~WholeDigits ) If w \== .Nil Then Return w Raise Syntax 26.904 Array( st~name, value ) -- INPUT STEM s. (or USING a stem): s.1 .. s.n with n = s.0 (98.998 when -- s.0 has no value); a tail with no value reads as the stem's default. ::Class RVM.StemObjInput Public ::Method init Expose st Use Strict Arg st ::Method bytes Expose st Use Strict Arg context, lineEnd If \ st~hasRealValue( "0" ) Then Raise Syntax 98.998 Array( st~name ) count = StemObjCount( st, SyncString( st~tailValue( "0" ), context ) ) text = "" Do i = 1 To count tail = i || "" If st~hasRealValue( tail ) Then v = st~tailValue( tail ) Else v = context~world~stemObjectOf( st ) text = text || SyncString( v, context ) || lineEnd End Return text -- INPUT USING an InputStream (or a Monitor): its lines, LINEIN until it -- raises NOTREADY (ooRexx's StreamObjectInputSource; any other condition -- ends it too, and an error goes up). ::Class RVM.StreamObjInput Public ::Attribute partial Get -- what it read (when LINEIN fails) ::Method init Expose obj partial Use Strict Arg obj partial = "" ::Method bytes Expose obj partial Use Strict Arg context, lineEnd loader = context~world~loader partial = "" Loop Forever r = loader~sendSyncWatch( obj, "LINEIN", .Array~new ) If \ r[2]~isEmpty | r[1] == .Nil Then Leave partial = partial || SyncString( r[1], context ) || lineEnd End Return partial -- OUTPUT/ERROR STEM s. (or USING a stem): REPLACE (the default) empties it -- first (keeping its default value); APPEND goes on after s.0 (when s.0 has -- a value). ::Class RVM.StemObjOutput Public ::Attribute st Get ::Method init Expose st append index Use Strict Arg st, append index = 1 ::Method open Expose st append index Use Strict Arg context If append, st~hasRealValue( "0" ) Then Do index = StemObjCount( st, SyncString( st~tailValue( "0" ), context ) ) + 1 Return End st~emptyTails st~setTail( "0", "0" ) index = 1 ::Method writeText Expose st index Use Strict Arg text, context Do line Over SplitOutput( text ) st~setTail( index || "", line ) st~setTail( "0", index || "" ) index = index + 1 End ::Method close Nop ::Method sameTarget Expose st Use Strict Arg other, context If \ other~isA( .RVM.StemObjOutput ) Then Return .False Return other~st == st -- OUTPUT/ERROR USING an object: each line is sent to it with 'message' -- (APPEND to an OrderedCollection, LINEOUT to an OutputStream, QUEUE to a -- RexxQueue); a collection is sent EMPTY first, unless 'keep' (APPEND). ::Class RVM.ObjectOutput Public ::Attribute obj Get ::Method init Expose obj message keep Use Strict Arg obj, message, keep ::Method open Expose obj keep Use Strict Arg context If \ keep Then context~world~loader~sendSync( obj, "EMPTY", .Array~new ) ::Method writeText Expose obj message Use Strict Arg text, context loader = context~world~loader Do line Over SplitOutput( text ) loader~sendSync( obj, message, .Array~of( line ) ) End ::Method close Nop ::Method sameTarget Expose obj Use Strict Arg other, context If \ other~isA( .RVM.ObjectOutput ) Then Return .False Return other~obj == obj ::Routine CommandTrace Use Strict Arg context, condition, command traced = context~traceC -- A condition that ::OPTIONS makes SYNTAX: its error or failure is not -- traced, nor its RC (ooRexx). If condition \== "", context~isSyntaxCond( condition ) Then Return traced~?( 1, 0 ) If ( condition == "ERROR" & context~traceE ) | - ( condition == "FAILURE" & context~traceF ) Then Do context~traceClause( context~clause ) context~traceValue( ">>>", command ) traced = .True End If \ traced Then Return 0 rc = context~getVar( "RC" ) If DataType( rc, "W" ), rc \= 0 Then context~traceValue( "+++", "RC("rc")" ) Return 1 -- A command ended with ERROR or FAILURE: the condition; an untrapped FAILURE -- is raised again as an ERROR. ::Routine CommandCondition Use Strict Arg context, condition, command If condition == "" Then Return If context~debugPause Then Return rc = context~getVar( "RC" ) -- ::OPTIONS FAILURE SYNTAX, ERROR SYNTAX (ooRexx's RexxActivation::command). If condition == "FAILURE", context~isSyntaxCond( "FAILURE" ) Then Raise Syntax 98.971 Array( command, rc ) If condition == "ERROR", context~isSyntaxCond( "ERROR" ) Then Raise Syntax 98.970 Array( command, rc ) -- Its RESULT is the RC when a command of the system raised it (ooRexx's -- SystemCommands: RaiseCondition with the RC as its result); none for an -- environment that is not there, a registered one, or the security -- manager's (createConditionObject with no result). info = .RVM.ConditionInfo~new( condition, command, rc ) If \ context~commandNoResult Then info~objResult = info~rc If context~raiseCondition( info ) Then Return If condition == "FAILURE" Then Do If context~isSyntaxCond( "ERROR" ) Then Raise Syntax 98.970 Array( command, rc ) info = .RVM.ConditionInfo~new( "ERROR", command, context~getVar( "RC" ) ) If \ context~commandNoResult Then info~objResult = info~rc trapped = context~raiseCondition( info ) End -- The lines of an error report for the current activation: the clause in -- error (after the data of an INTERPRET that does not parse), then the -- INTERPRETs it runs in, innermost first. ::Routine ErrorLines Use Strict Arg context clause = context~clause -- The first activation of a START's activity only sends the message. If context~callDepth == 0, context~activity \== .Nil, - context~activity~message \== .Nil Then Return .Array~new If clause == .Nil Then Return .Array~of( .Array~of( 0, "" ) ) -- The lines of a compiled method (and of the routines of the prelude, -- which only a compiled method calls) are not shown: see KeepNativeLines. If context~hidden Then Return .Array~new lines = .Array~new If context~interpretError \== .Nil Then Do lines~append( context~interpretError ) context~interpretError = .Nil End lines~append( .Array~of( context~clauseText( clause )[1], - context~clauseTraceLine( clause ), context~programName ) ) Do l Over context~interpretLines l[3] = context~programName lines~append( l ) End Return lines -- The traceback lines of the natives running when an error happened (the -- innermost first), as error lines of the current clause; .Nil if none. They -- are marked (a fourth item) so that the clause's own lines follow them. -- A check (with RVM_TBCHECK set): the report of an untrapped error is its -- traceback (TRACEBACK), which is made when it is raised. ::Routine TracebackCheck Use Strict Arg context, info If Value( "RVM_TBCHECK", , "ENVIRONMENT" ) == "" Then Return report = .Array~new Do l Over context~errorLines report~append( l[2] ) End stack = .Array~new If info~stack \== .Nil Then Do l Over info~stack stack~append( l[2] ) End If report~makeString == stack~makeString Then Return .Error~lineOut( "RVM_TBCHECK mismatch in" context~programName ) Do l Over report .Error~lineOut( " report: ["l"]" ) End Do l Over stack .Error~lineOut( " stack: ["l"]" ) End -- The depth of the activation of the program, routine or method that runs -- (0: the main program's); those above it are internal routines and CALL ON -- handlers. ::Routine TopLevel Use Strict Arg frames Do k = frames~items To 1 By -1 f = frames[ k ] If f~kind == "METHOD" | f~program \== .Nil Then Return k End Return 0 -- The activation just pushed is a program's, a routine's or a method's: how -- it was called (type, name, what runs, receiver). It has no .RS yet. ::Routine EnterLevel Use Strict Arg context, type, name, exec, kind, target = .Nil lv = context~level lv~type = type lv~name = name lv~exec = exec lv~kind = kind lv~target = target lv~sender = target lv~rs = .Nil Return -- An environment symbol that is not a class nor in .LOCAL or .ENVIRONMENT -- (see RVM.World's env): the special ones, as ooRexx's rexxVariable -- (.ROUTINES, .METHODS: the program's ::ROUTINEs and floating methods; -- .RESOURCES: its ::RESOURCEs; .LINE), or else its name. ::Routine DotSpecial Use Strict Arg symbol, program, context name = symbol If Left( name, 1 ) == "." Then name = SubStr( name, 2 ) Select Case Upper( name ) When "ROUTINES" Then Do t = context~world~routinesTable( program ) If t \== .Nil Then Return t End When "METHODS" Then Do t = context~world~methodsTable( program ) If t \== .Nil Then Return t End -- .RESOURCES: the package's resources, the same StringTable (none: the -- symbol's name, as ooRexx's package with no resources). When "RESOURCES" Then Do t = context~world~resourcesTable( program ) If t \== .Nil Then Return t End -- .LINE: the line of the clause (where it starts; in INTERPRET data, the -- INTERPRET's). When "LINE" Then If context~clause \== .Nil Then Return context~clause~line -- .CONTEXT: the activation's RexxContext (in an INTERPRET, its parent's); -- .RS: its last command's status (none yet: the symbol's name). When "CONTEXT" Then Do lv = context~level If lv~thread == .Nil Then Do If context~activity == .Nil Then lv~thread = 1 Else lv~thread = context~activity~id End Return context~world~contextObject( lv ) End When "RS" Then If context~level~rs \== .Nil Then Return context~level~rs Otherwise Nop End Return symbol -- May a read of standard input make its activity wait (see StdinWait)? -- Outside a nested machine ('may') and an interactive pause, when something -- else may run meanwhile (another activity, a timer); then the read may -- (RVM.StdinReader's gate: see RVM.Stream~inputNeed). ::Routine StdinGate Use Strict Arg context, may, act, sched If \ may | act == .Nil | sched == .Nil Then Return .False If context~debugPause Then Return .False If \ sched~othersThan( act ) Then Return .False .RVM.StdinReader~gate = context Return .True -- What a built-in function returns, now: a message to .LOCAL's object is -- sent now (see RVM.BifSend). ::Routine BifNow Use Strict Arg v, context If v~isA( .RVM.BifSend ) Then Return v~result( context ) Return v -- The conversions of the instruction whose STRING has run, back (see -- NeedString). ::Routine RestoreConversions Use Strict Arg convSaved If convSaved~isEmpty Then Return saved = convSaved~lastItem convSaved~delete( convSaved~last ) .RVM.Obj~conversions = saved[1] .RVM.Obj~requests = saved[2] ::Routine NativeLines Use Strict Arg context lines = context~pendingNatives context~nativeLines~empty Return lines -- The value of a condition: 0 or 1, else error 34 for its instruction (IF, -- WHEN, WHILE, UNTIL, an element of a LIST; "-": none). ::Routine LogicalCondition Use Strict Arg v, keyword If v == "0" Then Return .False If v == "1" Then Return .True Select Case keyword When "IF" Then Raise Syntax 34.1 Array( v ) When "WHEN" Then Raise Syntax 34.2 Array( v ) When "WHILE" Then Raise Syntax 34.3 Array( v ) When "UNTIL" Then Raise Syntax 34.4 Array( v ) When "LIST" Then Raise Syntax 34.6 Array( v ) When "GUARD" Then Raise Syntax 34.902 Array( v ) When "CASE" Then Raise Syntax 34.905 Array( v ) Otherwise Raise Syntax 34.901 Additional( v ) End -- USE STRICT ARG: too many arguments, too few, or a required one omitted -- (93.90x in a method, 40.x in a routine). ::Routine UseStrict Use Strict Arg flags, more, context, frames flags = Left( flags, Length( flags ) - 1 ) n = context~argCount max = Length( flags ) -- R: required; S: a skipped position (no variable), required too, but its -- argument may be omitted; O: optional (a default). min = Max( LastPos( "R", flags ), LastPos( "S", flags ) ) inMethod = ( context~level~type == "METHOD" ) name = "" If \ frames~isEmpty Then name = frames~lastItem~name If more == 0, n > max Then Do If inMethod Then Raise Syntax 93.902 Array( max ) Raise Syntax 40.4 Array( name, max ) End If n < min Then Do If inMethod Then Raise Syntax 93.901 Array( min ) Raise Syntax 40.3 Array( name, min ) End -- USE STRICT ARG: required argument i omitted. Raised when its variable's -- turn comes, so the ones before it are already assigned (ooRexx). ::Routine UseOmit Use Strict Arg i, context, frames If context~level~type == "METHOD" Then Raise Syntax 93.903 Array( i ) name = "" If \ frames~isEmpty Then name = frames~lastItem~name Raise Syntax 40.5 Array( name, i ) -- The name of the message an operator instruction sends. ::Routine OperatorName Use Strict Arg op Select Case op When "ADD" Then Return "+" When "SUB" Then Return "-" When "MUL" Then Return "*" When "DIV" Then Return "/" When "IDIV" Then Return "%" When "REM" Then Return "//" When "CAT" Then Return "||" When "ABUT" Then Return "" When "CATB" Then Return " " When "AND" Then Return "&" When "OR" Then Return "|" When "XOR" Then Return "&&" When "PLUS" Then Return "+" When "NEG" Then Return "-" When "NOT" Then Return "\" End /******************************************************************************/ /* INTERPRET: compile the data */ /******************************************************************************/ ::Routine Interpret Use Strict Arg program, context, data, returnTo, clauseNo, bodyLabels source = .Array~of( data ) line = context~clause~line Signal On User Rexx.Parser.Error Name NotParsed -- The parser wants the labels of the body running (the prolog, a method, -- a routine), as label clauses: only their names matter here. labels = .Table~new Do name Over bodyLabels~allIndexes labels[ name ] = .RVM.LabelRef~new End parser = .Rexx.Parser~new( context~programName, source, - .Array~of( .Array~of( "INTERPRET", labels ) ) ) Signal Off User Rexx.Parser.Error .environment~Options.Interpret = 0 package = parser~package .RVM.Fragments~register( package, source, line ) If program~fragStart > program~code~items Then program~fragStart = program~code~items + 1 Return LoadData( program, package, source, returnTo, clauseNo ) -- The data does not parse: the error is raised here, at the INTERPRET, after -- the line of the data. NotParsed: .environment~Options.Interpret = 0 error = Condition("O")~additional inserts = error~substitutions~copy Parse Value LineInsert( error~code ) With n . If n \== "", inserts~hasIndex( n ) Then inserts[ n ] = line -- The clause is the parser's; without it, the data (it has no lines). clause = error~clause If clause == "" Then clause = Strip( data, "L" ) context~interpretError = .Array~of( line, Right( line, 6 ) "*-*" clause ) Raise Syntax ( error~code ) Additional( inserts ) -- Compile parsed INTERPRET data (or a line typed at a pause: returnTo 0) at -- the end of the program, and check it. Returns the address it starts at. ::Routine LoadData Use Strict Arg program, package, source, returnTo, clauseNo clauses = program~clauses firstClause = clauses~items + 1 firstWith = program~withs~items + 1 start = .RVM.Compiler~extend( package, program, source, returnTo, clauseNo ) Do k = firstClause To clauses~items c = clauses[k] clauses[k] = .RVM.Clause~new( c[1], c[2] ) End Do k = firstWith To program~withs~items entries = program~withs[k] spec = .RVM.WithSpec~new( program ) Do e Over entries spec~add( e[1], e[2], e[3], e[4], e[5] ) End program~withs[k] = spec End -- The new code is checked like any other: from its start and its thunks. starts = .Array~of( start ) Do k = firstWith To program~withs~items starts~appendAll( program~withs[k]~thunks ) End .RVM.ISA~verify( program, starts, start ) Return start -- May 'sender' (the receiver of the method running, or .Nil) send private -- method m to 'receiver'? Itself, an instance of m's scope, or a class -- that is the scope or a subclass of it (ooRexx's checkPrivate). ::Routine PrivateOK Use Strict Arg m, receiver, sender, world If sender == .Nil Then Return .False If sender == receiver Then Return .True scope = m~scope If scope == .Nil Then Return .False If IsSubclass( world~classOf( sender ), scope ) Then Return .True If \ sender~isA( .RVM.Obj ) Then Return .False If \ sender~isClass Then Return .False Return IsSubclass( sender, scope ) -- May the code running send package method m? Only when it is of m's -- package, its home program (ooRexx's checkPackage: the package of the -- caller's activation). The RVM's own code in Rexx (the REXX package: the -- prelude) may: in ooRexx most of it is C++, which has no activation, so -- that the package seen is that of the code that called it. ::Routine PackageOK Use Strict Arg m, context lv = context~level If lv == .Nil Then Return .True caller = LevelPackage( lv ) If caller == .Nil | caller == "REXX" Then Return .True home = m~home If home == .Nil Then home = "REXX" Return caller == home -- A program compiled from source lines at run time (see -- RVM.SourceCompiler); 'option' is the parser's (METHOD), or "-" (none). ::Routine CompileSource Public Use Strict Arg name, lines, context, option Signal On User Rexx.Parser.Error Name NotParsed options = .Array~new If option \== "-" Then options~append( .Array~of( option, 1 ) ) parser = .Rexx.Parser~new( name, lines, options ) package = parser~package Signal Off User Rexx.Parser.Error unit = .RVM.Compiler~compile( package, lines, name ) program = .RVM.RCode~read( .RVM.RCode~write( unit ) ) program~path = name program~source = lines Do ins Over program~code If ins[1] == "CLAUSE" Then Do program~firstClause = ins[2] Leave End End Call OverrideOptions program, context~world Return program NotParsed: error = Condition("O")~additional inserts = error~substitutions~copy n = error~line -- Its line goes before the native that compiles it (the innermost first). nc = .RVM.NativeCall~new( ParseErrorLine( lines, error ), .Nil, .Nil, name ) nc~compileAt = n -- (The package of the condition: one with that name and the source, and -- nothing in it, as ooRexx's that did not translate.) stub = .RVM.Program~new stub~path = name stub~source = lines stub~state = "READY" nc~compilePackage = stub context~nativeLines~append( nc ) Raise Syntax ( error~code ) Additional( inserts ) -- The report line of a source that does not parse ('error' is the -- parser's Rexx.Parser.Error): the clause in error as ooRexx shows it -- after "*-*", which the parser gives (its clause, issue #8), or else the -- line of the error. -- Does the code at 'address' (an internal call's target) start with a -- PROCEDURE, past its labels? (ooRexx's RexxActivation::run looks ahead the -- same way to set procedureValid.) ::Routine ProcedureFirst Use Strict Arg code, address k = address Do While k <= code~items, code[k][1] == "LABEL" k += 1 End If k >= code~items Then Return .False Return code[k][1] == "CLAUSE" & code[k + 1][1] == "PROC" -- The "*-*" line of a syntax error (a Rexx.Parser.Error) in "source" ::Routine ParseErrorLine Public Use Strict Arg source, error n = error~line If n < 1 | n > source~items Then Return "" If error~clause \== "" Then Return Right( n, 6 ) "*-*" error~clause Return Right( n, 6 ) "*-*" Strip( source[ n ], "L" ) ::Routine LineInsert Use Strict Arg code Select Case code When "6.1", "7.1", "7.2", "14.1", "14.2", "14.3", "14.4", "14.5", - "14.901", "18.1", "18.2" Then Return 1 When "10.3", "10.7", "36.901", "36.902" Then Return 2 When "10.2", "10.4" Then Return 3 Otherwise Return "" End -- The n arguments on top of the stack, as an Array (an omitted one is a hole). ::Routine PopArgs Use Strict Arg stack, sp, n args = .Array~new Do k = 1 To n v = stack[ sp - n + k ] If v \== .Nil Then args[k] = v End Return args -- The items DO ... OVER goes over: an array's (holes left out), a stem's -- tails, a directory's indexes, a string's lines; another object's REQUEST -- ARRAY; else 98.913. ::Routine OverItems Use Strict Arg v, context If \ v~isA( .RVM.Obj ) Then Return str( v )~makeArray If v~native~isA( .Array ) Then Return v~native~allItems If v~native~isA( .RVM.Stem ) Then Return v~native~tailNames If v~native~isA( .Directory ) Then Do -- .ENVIRONMENT: with the prelude's classes (see RVM.World~ensurePrelude). world = context~world If world~prelude == .Nil Then If v == world~environment Then world~ensurePrelude Return v~native~allIndexes End If TableLike( v~native ) Then Return UnhashedArray( v~native~allIndexes ) If v~native~isA( .Queue ) Then Return v~native~allItems If v~beh~cls~native~kind == "LIST" Then Return ListNative( v )~allItems If HashKind( v ) Then Return UnhashedArray( HashNative( v )~allIndexes ) -- Any other object: REQUEST ARRAY (ooRexx's requestArray: its MAKEARRAY), -- which must give an Array. a = context~world~loader~sendSync( v, "REQUEST", .Array~of( "ARRAY" ) ) If a~isA( .RVM.Obj ), a~native~isA( .Array ) Then Return a~native~allItems Raise Syntax 98.913 Array( v ) -- The tails of a stem (DO ... OVER a.): those with a value. ::Routine StemTails Use Strict Arg context, stemKey st = context~stemObject( stemKey ) tails = .Array~new If st == .Nil Then Return tails Do tail Over st~tailNames tails~append( tail ) End Return tails -- The inserts of a SYNTAX raised by RAISE: a number (RVM.Number) is its -- string, as in the message of ooRexx (where it is a String). A copy only if -- there is one (the Array of ADDITIONAL is the program's own: see -- conditionAdditional). ::Routine NumberInserts Use Strict Arg a copy = .Nil If a~last == .Nil Then Return a -- (an empty array) Do i = 1 To a~last If \ a~hasIndex( i ) Then Iterate If \ a[i]~isA( .RVM.Number ) Then Iterate If copy == .Nil Then copy = a~copy copy[i] = str( a[i] ) End If copy == .Nil Then Return a Return copy -- A variable read while unset: NOVALUE, and its value is its name (of a -- compound: the name the stem composes, "B.5" after a. = b.). ::Routine NoValue Use Strict Arg context, name, value = .Nil -- ::OPTIONS NOVALUE SYNTAX (ooRexx's handleNovalueEvent: first of all). If context~isSyntaxCond( "NOVALUE" ) Then Raise Syntax 98.986 Array( name ) trapped = context~raiseCondition( .RVM.ConditionInfo~new( "NOVALUE", name ) ) If value == .Nil Then Return name Return value -- The count of DO n and of FOR n. ::Routine LoopCount Use Strict Arg value, context, kind count = .Nil If value~isA( .RVM.Integer ), context~digits >= 9 Then count = value~whole Else If isNum( value ) Then count = num( value, context )~identity( context )~numberValue( context~digits ) If count \== .Nil Then If count >= 0 Then Return count If kind == "FOR" Then Raise Syntax 26.3 Array( str( value ) ) Raise Syntax 26.2 Array( str( value ) ) -- NUMERIC DIGITS / FUZZ ('value' is .Nil without an expression: the -- default of the package of 'program', its ::OPTIONS, as ooRexx's package -- settings; else 9 and 0). ::Routine Numeric Use Strict Arg context, op, value, program = .Nil Numeric Digits 20 If op == "NUMDIG" Then Do If value == .Nil Then setting = PackageDefault( program, "DIGITS" ) Else Do setting = unsignedWholeNumber( value, context~digits ) If setting == .Nil Then Raise Syntax 26.5 Array( str( value ) ) If setting < 1 Then Raise Syntax 26.5 Array( str( value ) ) End If setting <= context~fuzz Then Raise Syntax 33.1 Array( setting, context~fuzz ) context~digits = setting Return End If value == .Nil Then setting = PackageDefault( program, "FUZZ" ) Else Do setting = unsignedWholeNumber( value, context~digits ) If setting == .Nil Then Raise Syntax 26.6 Array( str( value ) ) End If setting >= context~digits Then Raise Syntax 33.1 Array( context~digits, setting ) context~fuzz = setting ::Routine NumericForm Use Strict Arg context, kind, value, program = .Nil If kind \== "VALUE" Then Do context~form = kind Return End -- NUMERIC FORM alone (VALUE with no value): the package's default. If value == .Nil Then Do context~form = PackageDefault( program, "FORM" ) Return End form = str( value ) If form \== "SCIENTIFIC", form \== "ENGINEERING" Then Raise Syntax 25.11 Array( form ) context~form = form -- The default NUMERIC setting 'which' (DIGITS, FUZZ, FORM) of the package -- of 'program' (its ::OPTIONS), or the language's. ::Routine PackageDefault Use Strict Arg program, which Select Case which When "DIGITS" Then Do If program \== .Nil, program~optDigits \== .Nil Then Return program~optDigits Return 9 End When "FUZZ" Then Do If program \== .Nil, program~optFuzz \== .Nil Then Return program~optFuzz Return 0 End Otherwise If program \== .Nil, program~optForm \== .Nil Then Return program~optForm Return "SCIENTIFIC" End -- EXPOSE of one tail of a stem, as ooRexx's: the tail of the stem in -- 'frame' becomes the variable of that tail in the stem of 'source' (a -- node both stems share: see RVM.Stem~exposeTail). PROCEDURE -- EXPOSE: the caller's frame and the new one; EXPOSE in a method: the -- object's variables and the method's. ::Routine ExposeCompound Use Strict Arg source, frame, stemKey, tail node = StemIn( source, stemKey )~exposeTail( tail ) StemIn( frame, stemKey )~shareTail( tail, node ) -- The stem of a stem variable of 'frame' (an RVM.Vars): made when the -- variable, or its stem, does not exist yet. ::Routine StemIn Use Strict Arg frame, stemKey v = frame~cell( stemKey, .True ) If v~value == .Nil Then v~value = .RVM.Stem~new( stemKey ) Return v~value -- The value of a variable of 'frame' (an RVM.Vars), or .Nil. ::Routine ValueIn Use Strict Arg frame, name v = frame~cell( name ) If v == .Nil Then Return .Nil Return v~value -- The names of an EXPOSE (x) list, as ooRexx's RexxVariableReference~list: -- all of them are checked before any is exposed (31.3: it starts with a -- period; 31.2: with a digit; 20.928: it is not a symbol); what was exposed -- before (x itself too) stays. Uppercased. ::Routine ExposeNames Use Strict Arg value chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.!?_" list = .Array~new Do w = 1 To Words( value ) word = Word( value, w ) first = Left( word, 1 ) code = "" Select When first == "." Then code = 31.3 When Pos( first, "0123456789" ) > 0 Then code = 31.2 When Verify( word, chars ) > 0 Then code = 20.928 Otherwise list~append( Upper( word ) ) End If code \== "" Then Raise Syntax ( code ) Array( word ) End Return list -- A name of an EXPOSE (x) list (checked by ExposeNames), exposed from -- 'source' to 'frame': a simple variable, a stem, or a compound (its tail -- resolved in 'tails': the caller's frame for PROCEDURE, the method's own -- for EXPOSE). 'method': an EXPOSE in a method (frame is its MethodFrame). ::Routine ExposeWord Use Strict Arg context, up, source, frame, tails, method dot = Pos( ".", up ) If dot == 0 Then Do If method Then frame~share( up ) Else frame[ up ] = source~cell( up, .True ) Return End stemKey = Left( up, dot ) If dot == Length( up ) Then Do If method Then frame~share( stemKey ) Call StemIn source, stemKey If \ method Then frame[ stemKey ] = source~cell( stemKey ) Return End tail = "" rest = SubStr( up, dot + 1 ) Loop p = Pos( ".", rest ) If p == 0 Then component = rest Else Do component = Left( rest, p - 1 ) rest = SubStr( rest, p + 1 ) End If component \== "", Pos( Left( component, 1 ), "0123456789" ) == 0 Then Do v = ValueIn( tails, component ) If v \== .Nil Then component = str( v ) End tail = tail || component If p == 0 Then Leave tail = tail || "." End If context~traceI Then context~traceTagged( ">C>", up, " => ", stemKey || tail ) Call ExposeCompound source, frame, stemKey, tail -- USE ARG >v (or >s.): argument i (v: .Nil when omitted) to the local -- variable 'name', as ooRexx's handleReferenceArgument: required (88.931), -- a VariableReference (88.928), to a stem for a stem and to a simple -- variable for a simple one (88.929, 88.930: its name), and the local -- variable must be one it can alias (98.995). ::Routine UseRef Use Strict Arg context, i, name, v If v == .Nil Then Raise Syntax 88.931 Array( i ) ref = .Nil If v~isA( .RVM.Obj ) Then If v~native~isA( .RVM.VarRef ) Then ref = v~native If ref == .Nil Then Raise Syntax 88.928 Array( i, ObjectText( v ) ) If Right( name, 1 ) == "." Then Do If \ ref~isStem Then Raise Syntax 88.929 Array( i, ref~name ) End Else If ref~isStem Then Raise Syntax 88.930 Array( i, ref~name ) If \ context~isAliasable( name ) Then Raise Syntax 98.995 Array( name ) context~aliasVar( name, ref~var, ref~name ) If context~traceR Then context~traceTagged( ">R>", '"'ref~name'"', " => ", name ) -- DROP (x): drop each name in the value. ::Routine DropByName Use Strict Arg context, name ref = NameRef( name, context ) Select Case ref[1] When "SIMPLE" Then Do; context~dropVar( ref[2] ); Return; End When "STEM" Then Do; context~dropStem( ref[2] ); Return; End When "COMPOUND" Then Do; context~dropCompound( ref[2], ref[3] ); Return; End Otherwise Nop End up = Upper( name ) dot = Pos( ".", up ) If dot == 0 Then Do context~dropVar( up ) Return End If dot == Length( up ) Then Do context~dropStem( up ) Return End Parse Var up stemName "." tail context~dropCompound( stemName".", tail )