/******************************************************************************/ /* */ /* RVM.BaseContext.cls - Execution state (the RVM's runtime) */ /* ========================================================= */ /* */ /* The execution state that the machine works on. RVM.BaseContext is the */ /* context of an activation: its variables, its NUMERIC settings, ADDRESS and */ /* its redirections, the traps and the condition, the trace settings and the */ /* trace output, the streams and the clock; RVM.Context (in RVM.Machine.cls) */ /* extends it with what the machine needs. Also here: the activations */ /* (RVM.Activation), the variables (RVM.Var, RVM.Vars), the traps and */ /* conditions (RVM.Trap, RVM.Throw, RVM.ConditionInfo), the stems (RVM.Stem, */ /* with ooRexx's tail tree), PARSE (RVM.ParseTarget, as ooRexx's RexxTarget), */ /* the output of SAY (RVM.StandardOutput), the clock (RVM.Clock), INTERPRET */ /* data (RVM.Fragments) and the queues (RVM.Queues). See doc/05-machine.md. */ /* */ /* This file is part of the RVM, the Rexx Virtual Machine */ /* [See https://rexx.epbcn.com/rexx-parser/] */ /* */ /* This file is derived from the ooRexx interpreter: the stems */ /* (CompoundVariableTable.cpp) and PARSE (ParseTarget.cpp: RexxTarget), and */ /* much of the behaviour of the execution state. It is therefore distributed */ /* under the Common Public License v1.0, not under the Apache License 2.0 */ /* that covers the rest of the RVM (see NOTICE). */ /* */ /* Copyright (c) 1995, 2004 IBM Corporation. All rights reserved. */ /* Copyright (c) 2005-2026 Rexx Language Association. All rights reserved. */ /* Copyright (c) 2026 Josep Maria Blasco */ /* */ /* This program and the accompanying materials are made available under the */ /* terms of the Common Public License v1.0 which accompanies this */ /* distribution. A copy is also available at the following address: */ /* https://www.oorexx.org/license.html */ /* */ /******************************************************************************/ ::Class RVM.BaseContext Public -- The variables of the current activation (an RVM.Vars): uppercased name -- -> its variable (an RVM.Var). Deliberately NOT ooRexx's pool. ::Attribute frame Get ::Attribute frame Set -- The security manager of the current activation (an object, or .Nil): its -- package's when it started (ooRexx's ActivationSettings::securityManager). -- An internal routine and INTERPRET keep the caller's. ::Attribute secMgr -- The file streams its security manager was asked about (see the built-in -- functions' SecureStream): qualified name -> the stream object it gave, or -- "" (none: the RVM's stream). ooRexx asks when a name is not in the stream -- table of the activation, which is new for a program and for a method, and -- the caller's for a routine (RexxActivation::getStreams). .Nil: none yet. ::Attribute streamScope -- The stream table of the current activation (an RVM.StreamTable), or .Nil -- while it has none yet (see activeStreams). As in ooRexx -- (RexxActivation::getStreams), a program and a method have a table of -- their own; every other activation (an internal or external routine, a -- Routine object, a ::REQUIRES prolog) uses its caller's. streamsOwn is -- .True for a method activation. ::Attribute localStreams ::Attribute streamsOwn -- Is PROCEDURE valid now? As ooRexx's procedureValid: set when an internal -- call (or a CALL ON trap) lands on a PROCEDURE (past its labels), cleared -- by PROCEDURE; each activation has its own. ::Attribute procValid -- NUMERIC settings. Start at the Rexx defaults. ::Attribute digits Get -- NUMERIC DIGITS (default 9) ::Attribute digits Set ::Attribute fuzz Get -- NUMERIC FUZZ (default 0) ::Attribute fuzz Set ::Attribute form Get -- NUMERIC FORM (default "SCIENTIFIC") ::Attribute form Set -- Output sink for SAY: any object with ~lineOut. By default SAY is written -- straight to standard output, line by line, as the program runs (so output -- produced before an error still appears). A caller may inject a different -- sink -- e.g. a capturing one -- for testing. ::Attribute out Get ::Attribute out Set -- Where a standard stream (OUTPUT, INPUT, ERROR) goes: .Nil, the host -- straight (the RVM's context knows .LOCAL: RVM.Context~localTarget). ::Method localTarget Use Strict Arg name, forSay = .False Return .Nil -- Where the queue instructions and functions go: .Nil, the queue straight -- (RVM.Context~queueTarget: else .STDQUE, to send to). ::Method queueTarget Use Strict Arg strict = .False Return .Nil -- The exit code of the program: the value of EXIT or RETURN ("" when it had -- no operand). ::Attribute exitCode Get ::Attribute exitCode Set -- The activation stack. Every activation (the main program is the bottom one) -- has a variable frame and an argument array. 'args' is the CURRENT activation's -- arguments (what ARG() reads). 'callStack' holds the saved activations below. ::Attribute args Get ::Attribute args Set -- ADDRESS state. 'address' is the current environment (what ADDRESS() returns -- and where a command goes), 'alternateAddress' the previous one (ADDRESS with -- no operand swaps the two). 'ioConfigs' maps an UPPERCASED environment name to -- the ADDRESS instruction whose WITH clause was made that environment's default -- redirection (ADDRESS env WITH ...); its targets are re-evaluated for every -- command. All three belong to the current activation: an internal routine -- starts with a copy of the caller's and the caller's come back on RETURN. -- 'commandHost' launches commands (RVM.CommandHost); it is shared. ::Attribute address Get ::Attribute alternateAddress Get ::Attribute ioConfigs Get ::Attribute commandHost Get -- Condition state (SIGNAL ON / CALL ON / RAISE / CONDITION()). -- traps -- condition name ("ERROR", "USER FOO", "ANY"...) -> RVM.Trap. -- A called routine starts with the caller's table and gets its -- own copy the first time it changes it (trapsOwned tells). -- condition -- the RVM.ConditionInfo of the condition trapped in this -- activation (or inherited from the caller), or .Nil. -- callTraps -- CALL ON traps fired during the current clause, run when the -- clause ends: an Array of .Array~of( trap, conditionInfo ). -- clause -- the clause (instruction node) being executed; its line is -- what SIGL gets when a condition is trapped. -- thrown -- the condition a SIGNAL-type trap (or a RAISE) is carrying up -- while the interpreter unwinds, or .Nil. ::Attribute traps Get ::Attribute condition Get ::Attribute condition Set ::Attribute callTraps Get ::Attribute callTrapsPending Get -- is callTraps non-empty? (checked per clause) ::Attribute clause Get -- The program's source lines (an Array), for SOURCELINE; .Nil when the -- source is not available (SOURCELINE() is then 0). ::Attribute sourceLines -- A new clause: it becomes the current one, and it has no time stamp yet. ::Method "clause=" Expose clause clock Use Strict Arg clause clock~valid = .False ::Attribute thrown Get ::Attribute thrown Set -- A RAISE ... RETURN condition, waiting for the routine to return so that it -- can be raised in the caller (.Nil when none). ::Attribute raising Set -- The state of RANDOM's generator (a 64-bit number) of the current -- activation, or .Nil until RANDOM first runs in it. As in ooRexx -- (RexxActivation::getRandomSeed), a program, a method and an external -- routine (a ::ROUTINE, a Routine object, an external program) have one of -- their own, which starts unpredictable (startProgram); an internal routine -- and INTERPRET use, and advance, their caller's. ::Attribute randomSeed -- The program's stream table (an RVM.StreamTable), in the globals: the -- table of the activations that are not in a method, and the one whose -- standard streams every other table shares; .Nil until first needed. ::Attribute streams -- The TRACE setting of the current activation, as TRACE() returns it ("N", -- "?R"...). A called routine starts with the caller's; RETURN restores it. -- Change it with setTrace, which also sets the flags below. ::Attribute traceSetting Get -- What the setting traces (see setTraceFlags). 'tracing' is true when -- anything is traced at clause boundaries (clauses, labels or commands). ::Attribute tracing Get ::Attribute traceA Get -- every clause (A R I) ::Attribute traceR Get -- results (R I) ::Attribute traceI Get -- intermediate values (I) ::Attribute traceL Get -- labels (A R I L) ::Attribute traceC Get -- commands (A R I C) ::Attribute traceE Get -- commands that fail with ERROR (E) ::Attribute traceF Get -- ... and with FAILURE (E F N) -- The indentation of the trace lines of the current activation: one more -- than the caller's for a called routine, and it follows the blocks. ::Attribute traceIndent -- The program's fully qualified name (PARSE SOURCE), set by the runner. ::Attribute programName -- The lines an untrapped error has gone through, innermost first (the -- clause in error, then each caller's CALL), each an Array: its line number -- and its trace line (clauseTraceLine, at the indentation of the moment); -- .Nil when there is none. ::Attribute errorLines -- The clock of the current activation (RVM.Clock): the time of the -- current clause, the same for every DATE and TIME of it, and TIME's -- elapsed-time clock. ::Attribute clock -- Take (and clear) the pending RAISE ... RETURN condition. ::Method takeRaising Expose raising r = raising raising = .Nil Return r ::Method init Expose frame digits fuzz form out exitCode - args callStack queue - address alternateAddress ioConfigs commandHost - traps trapsOwned condition callTraps clause thrown raising - callTrapsPending randomSeed clock streams traceSetting programName errorLines - traceIndent clauseTexts interprets interpretError nativeArgs - debugPause debugBypass promptIssued sourceTraced traceSkip - traceSuppressed sourceLines - invocation secMgr streamScope localStreams streamsOwn commandNoResult Use Strict Arg out = .Nil commandNoResult = .False secMgr = .Nil streamScope = .Nil localStreams = .Nil streamsOwn = .False procValid = .False frame = .RVM.Vars~new -- uppercased name -> RVM.Var digits = 9 fuzz = 0 form = "SCIENTIFIC" exitCode = "" args = .Array~new -- the main program has no arguments here callStack = .Array~new -- saved activations (frame + args), grows on CALL queue = .Array~new -- the external data queue (PUSH/QUEUE/PULL) commandHost = .RVM.CommandHost~new address = commandHost~initialAddress alternateAddress = address ioConfigs = .Directory~new traps = .Directory~new trapsOwned = .True condition = .Nil callTraps = .Array~new callTrapsPending = .False clause = .Nil thrown = .Nil raising = .Nil randomSeed = .Nil streams = .Nil traceSetting = "N" self~syntaxConds = "" traceIndent = 0 interprets = .Array~new -- active INTERPRETs: (instruction, indentation) interpretError = .Nil -- the report line of data that did not parse nativeArgs = .False -- a REXXUTIL routine's arguments are being checked debugPause = .False -- a line typed at a pause is running debugBypass = .False -- skip the next pause promptIssued = .False -- the interactive trace prompt was shown sourceTraced = .False -- the source line was traced (debug start) traceSkip = 0 -- pauses to skip (TRACE n at a pause) traceSuppressed = .False -- and trace nothing meanwhile (TRACE -n) clauseTexts = .IdentityTable~new self~setTraceFlags programName = "" invocation = "COMMAND" -- how the program runs (PARSE SOURCE) sourceLines = .Nil errorLines = .Nil clock = .RVM.Clock~new If out == .Nil Then out = .RVM.StandardOutput~new /******************************************************************************/ /* TRACE setting */ /* */ /* A setting is read left to right: each "?" flips a debug request, and the */ /* first other character is the option (A C E F I L N O R, in any case; the */ /* rest is ignored); anything else is error 24.1. The null string is N. */ /* - only "?"s: an odd number flips interactive debug (not for OFF), an */ /* even number changes nothing; */ /* - O: tracing off, debug off; */ /* - any other option: that option, with debug when requested. */ /* Interactive debug is recorded (TRACE() shows the "?") but never pauses. */ /******************************************************************************/ ::Method setTrace Expose traceSetting traceSuppressed traceSkip promptIssued debugPause - debugBypass Use Strict Arg setting -- Any setting ends a TRACE n; leaving debug shows the prompt again when -- it comes back; a setting typed at a pause ends the pause. traceSuppressed = .False traceSkip = 0 wasDebug = Left( traceSetting, 1 ) == "?" If debugPause Then debugBypass = .True If setting == "" Then Do traceSetting = "N" self~setTraceFlags If wasDebug Then promptIssued = .False Return End debugRequest = .False option = "" Do i = 1 To Length( setting ) c = SubStr( setting, i, 1 ) If c == "?" Then Do debugRequest = \ debugRequest Iterate End If Pos( Upper( c ), "ACEFILNOR" ) == 0 Then Raise Syntax 24.1 Array( c ) option = Upper( c ) Leave End debug = Left( traceSetting, 1 ) == "?" current = Right( traceSetting, 1 ) Select When option == "" Then Do -- a debug toggle, or nothing If debugRequest, current \== "O" Then debug = \ debug option = current End When option == "O" Then debug = .False Otherwise debug = debugRequest End traceSetting = debug~?( "?", "" ) || option self~setTraceFlags If wasDebug, \ debug Then promptIssued = .False -- What the current setting traces. A traces every clause, and so labels and -- commands; R adds the results, I the intermediate values. L traces only -- labels, C only commands. E traces the commands that end with ERROR or -- FAILURE, F (and N, the default) only those that end with FAILURE. O -- traces nothing. ::Method setTraceFlags Private Expose traceSetting tracing traceA traceR traceI traceL traceC traceE traceF - debug pausing pauseL o = Right( traceSetting, 1 ) traceA = Pos( o, "ARI" ) > 0 traceR = Pos( o, "RI" ) > 0 traceI = o == "I" traceL = Pos( o, "ARIL" ) > 0 traceC = Pos( o, "ARIC" ) > 0 traceE = o == "E" traceF = Pos( o, "EFN" ) > 0 tracing = traceL | traceC -- Interactive debug pauses after the instructions it traces (A, R, I), at -- labels (A, R, I, L). A command pauses when it is traced (see -- the RVM's CPAUSE; ooRexx never calls its pauseCommand). debug = Left( traceSetting, 1 ) == "?" pausing = debug & traceA pauseL = debug & traceL /******************************************************************************/ /* TRACE output */ /* */ /* Trace lines go to the standard error stream. A clause is shown as its line */ /* number (six columns), "*-*" and the source of the clause, indented two */ /* blanks per level; a value as its prefix (">>>" a result, ">V>" a variable, */ /* ">L>" a literal, ">O>" an operation, ...) and the value in double quotes, */ /* indented the same way, sometimes with a tag ("A => ", '"TO" => '). */ /* */ /* The source of a clause runs from its first token to its end: a semicolon */ /* that ends it is included, and so are the blanks and comments before the */ /* end of the line; the lines of a clause that spans several are joined as */ /* they are, with nothing in between. */ /* */ /* The indentation grows one level for every called routine and follows the */ /* blocks: the instructions of a DO...END are one level in, those after THEN, */ /* ELSE, WHEN...THEN and OTHERWISE two levels in (see INDENT, UNINDENT and */ /* the rest in RVM.Compiler for the exact moves). */ /* */ /* Characters below blank (except tab, line feed and carriage return) are */ /* shown as "?". */ /******************************************************************************/ ::Method indent Expose traceIndent traceIndent += 1 ::Method unindent Expose traceIndent If traceIndent > 0 Then traceIndent -= 1 ::Method unindentTwice Expose traceIndent If traceIndent > 1 Then traceIndent -= 2 -- Trace a clause (any clause object of the parser: an instruction, a label, -- or a part of a block instruction such as THEN, WHEN or END). ::Method traceClause Expose debug debugPause sourceTraced traceSuppressed programName invocation Use Strict Arg clause -- The first clause traced in interactive debug comes after the source line. If debug, \ sourceTraced, \ debugPause, \ traceSuppressed Then Do sourceTraced = .True self~traceOut( " +++" '"'.RVM.SystemHost~systemName invocation - programName'"' ) End self~traceOut( self~clauseTraceLine( clause ) ) -- The trace line of a clause, at the current indentation (also used for the -- lines of an error report). At most twenty levels are shown. ::Method clauseTraceLine Expose traceIndent Use Strict Arg clause, indent = (traceIndent) info = self~clauseText( clause ) Return Right( info[1], 6 ) "*-*" || - Copies( " ", 1 + 2 * Min( indent, 20 ) ) || info[2] -- INTERPRET data that did not parse: (line number, report line). ::Attribute interpretError -- The arguments of a routine of REXXUTIL are being checked (RoutineArgs in -- RVM.Machine; RexxUtilNative turns it off): an error now is reported in -- the REXX package, with no line. ::Attribute nativeArgs -- Interactive trace (see the RVM's pause instructions). ::Attribute debug Get -- the setting starts with "?" ::Attribute pausing Get -- pause after instructions ::Attribute pauseL Get -- pause at labels ::Attribute debugPause -- a line typed at a pause is running ::Attribute debugBypass ::Attribute promptIssued ::Attribute sourceTraced -- COMMAND, or SUBROUTINE / FUNCTION for an external routine (the RVM). ::Attribute invocation -- The last command's condition has no RESULT (it did not come from a command -- of the system: ooRexx's createConditionObject with no result). ::Attribute commandNoResult ::Attribute traceSkip ::Attribute traceSuppressed -- The indentation of the current activation with no block open: where -- ooRexx reports a LEAVE or ITERATE that found no block (it has closed them -- all looking for one). In INTERPRET data, that of the INTERPRET. ::Method activationIndent Expose interprets callStack If interprets~items > 0 Then Return interprets~lastItem[2] If callStack~items > 0 Then Return callStack~lastItem~traceIndent + 1 Return 0 -- INTERPRET: the instruction starts running INTERPRET data (at the current -- indentation), or has finished it. ::Method enterInterpret Expose interprets traceIndent Use Strict Arg instruction interprets~append( .Array~of( instruction, traceIndent ) ) ::Method leaveInterpret Expose interprets interprets~delete( interprets~last ) -- A SIGNAL ON trap resumes at a label: every active INTERPRET of the -- activation is left. ::Method clearInterprets Expose interprets interprets = .Array~new -- The lines of an error report for the active INTERPRETs, innermost first: -- each is traced at the indentation it started with. ::Method interpretLines Expose interprets lines = .Array~new Do i = interprets~items To 1 By -1 entry = interprets[ i ] lines~append( .Array~of( self~clauseText( entry[1] )[1], - self~clauseTraceLine( entry[1], entry[2] ) ) ) End Return lines -- The line number and the source text of a clause, worked out once. ::Method clauseText Expose clauseTexts sourceLines Use Strict Arg clause info = clauseTexts[ clause ] If info \== .Nil Then Return info skip = .EL.END_OF_CLAUSE || .ALL.WHITESPACE_LIKE || .ALL.COMMENTS last = clause~end el = clause~begin Loop While el \== .Nil, el \== last, el < skip el = el~next End If el == .Nil Then el = clause~begin -- A label ends with its colon (whatever follows it on the line); any other -- clause, at the end of the clause (should 'end' be a token before it). If clause~isA( .Label.Clause ) Then Do last = el Loop While last \== clause~end, last~source \== ":" last = last~next End End Else Loop While last \< .EL.END_OF_CLAUSE, last~next \== .Nil last = last~next End Parse Value el~from With sLine sCol Parse Value last~to With eLine eCol -- A clause of INTERPRET data: the text is in its fragment, and its line is -- the line of the INTERPRET. lines = sourceLines line = sLine fragment = .RVM.Fragments~of( el ) If fragment \== .Nil Then Do lines = fragment~source line = fragment~line End If lines == .Nil | sLine > eLine | - ( sLine == eLine & sCol >= eCol ) Then text = "" Else If sLine == eLine Then text = SubStr( lines[ sLine ], sCol, eCol - sCol ) Else Do text = SubStr( lines[ sLine ], sCol ) Do n = sLine + 1 To eLine - 1 text ||= lines[ n ] End text ||= Left( lines[ eLine ], eCol - 1 ) End info = .Array~of( line, text ) clauseTexts[ clause ] = info Return info -- A value: prefix, then "value". ::Method traceValue Expose traceIndent Use Strict Arg prefix, value self~traceOut( " "prefix || Copies( " ", 3 + 2 * traceIndent ) || - '"'value~string'"' ) -- A tagged value: prefix, then tag marker "value" (the marker is " => ", or -- " <= " for an assignment). ::Method traceTagged Expose traceIndent Use Strict Arg prefix, tag, marker, value, info = .Nil -- A variable (>V>) or an assignment (>=>): its TraceObject says so. If info == .Nil, prefix == ">V>" | prefix == ">=>" Then info = .Array~of( prefix, tag, value ) self~traceOut( " "prefix || Copies( " ", 3 + 2 * traceIndent ) || - tag || marker || '"'value~string'"', info ) -- A result tagged with a keyword ('>K> "TO" => "10"'), when tracing results. ::Method traceKeyword Expose traceR Use Strict Arg keyword, value If traceR Then self~traceTagged( ">K>", '"'keyword'"', " => ", value, - .Array~of( ">K>", keyword, value ) ) -- A result, when tracing results. ::Method traceResult Expose traceR Use Strict Arg value If traceR Then self~traceValue( ">>>", value ) -- Write one trace line. ::Method traceOut Expose debugPause traceSuppressed Use Strict Arg line, info = .Nil -- Nothing is traced while a line typed at a pause runs, or during TRACE -n. If debugPause | traceSuppressed Then Return self~traceRaw( line, info ) -- A line of trace output, always (the interactive trace prompt and errors): -- to .TRACEOUTPUT when it has to be (see traceObject), else straight. ::Method traceRaw Use Strict Arg line, info = .Nil line = Translate( line, "????????????????????????????????", - "000102030405060708"x"0B0C"x"0E0F101112131415161718191A1B1C1D1E1F"x ) If self~traceObject( line, info ) Then Return Signal On NotReady Name Done .Error~lineOut( line ) Done: Return -- A line of trace output as a TraceObject sent to .TRACEOUTPUT (see -- RVM.World~traceObject): .True if it was; here, never (no objects). ::Method traceObject Return .False /******************************************************************************/ /* External data queue (PUSH / QUEUE / PULL) */ /* */ /* The current queue of RVM.Queues (SESSION, or the one RXQUEUE or .STDQUE's */ /* SET chose). QUEUE adds a line at the tail, PUSH at the head, PULL removes */ /* and returns the head line. When the queue is empty PULL reads a line from */ /* STDIN, matching the native fallback. */ /******************************************************************************/ -- Add a line at the tail (QUEUE). ::Method queueLine Use Strict Arg line .RVM.Queues~addOrFail( .RVM.Queues~current, line, .False ) -- Add a line at the head (PUSH). ::Method pushLine Use Strict Arg line .RVM.Queues~addOrFail( .RVM.Queues~current, line, .True ) -- Remove and return the head line; "" (after trying STDIN) if the queue is empty. ::Method pullLine line = .RVM.Queues~pull( .RVM.Queues~current ) If line == .Nil Then Do If Lines() > 0 Then Return LineIn() Return "" End Return line -- How many lines are queued (the QUEUED() BIF). ::Method queued Return .RVM.Queues~count( .RVM.Queues~current ) -- EXIT and RETURN switch interactive debug off (ooRexx: resetDebug in -- exitFrom and returnFrom): a CALL ON trap that still runs does not pause. -- The trace setting goes on without its "?"; a caller has its own. ::Method endDebug Expose traceSetting debugBypass If Left( traceSetting, 1 ) \== "?" Then Return traceSetting = SubStr( traceSetting, 2 ) debugBypass = .True self~setTraceFlags /******************************************************************************/ /* Activation stack (CALL / RETURN) */ /******************************************************************************/ -- Enter a called routine. 'newArgs' is its argument array. 'newFrame' is .Nil -- for a routine WITHOUT procedure (it shares the caller's frame, classic Rexx) -- or a fresh RVM.Vars for PROCEDURE. The caller's frame+args are saved so -- popActivation can restore them. ::Method pushActivation Expose frame args callStack - address alternateAddress ioConfigs digits fuzz form - traps trapsOwned condition callTraps clause callTrapsPending - clock traceSetting traceIndent interprets - debugPause debugBypass promptIssued sourceTraced traceSkip traceSuppressed - secMgr streamScope localStreams streamsOwn randomSeed procValid Use Strict Arg newArgs, newFrame = .Nil saved = .RVM.Activation~new( frame, args ) saved~secMgr = secMgr -- the callee starts with it too saved~localStreams = localStreams -- the callee uses the caller's table saved~streamsOwn = streamsOwn -- (a method gets its own: newStreamScope) streamsOwn = .False saved~randomSeed = randomSeed -- shared, unless the callee is a program saved~randomOwn = .False -- (startProgram) saved~procValid = procValid -- (the machine sets the callee's) procValid = .False -- (and with the streams asked about: a method has its own, see newStreamScope) If streamScope == .Nil Then streamScope = .StringTable~new saved~streamScope = streamScope saved~interprets = interprets -- the caller's active INTERPRETs interprets = .Array~new -- the callee has none yet saved~traceSetting = traceSetting -- the callee starts with it too saved~syntaxConds = self~syntaxConds -- (and with these) saved~debugState = .Array~of( debugPause, debugBypass, promptIssued, - sourceTraced, traceSkip, traceSuppressed ) debugPause = .False -- the callee is not a typed line saved~traceIndent = traceIndent -- the callee's trace is one level in traceIndent += 1 saved~saveSettings( digits, fuzz, form, address, alternateAddress, ioConfigs ) saved~saveConditionState( traps, trapsOwned, condition, callTraps, clause ) saved~clock = clock -- the caller's clause keeps its time clock = clock~copy -- the callee inherits the elapsed clock clock~valid = .False -- but its first clause is a new one callStack~append( saved ) -- push (LIFO) -- The callee starts with the caller's traps (shared until it changes one: -- then it takes its own copy, see ownTraps) and the caller's current -- condition; nothing is pending for it yet. trapsOwned = .False callTraps = .Array~new callTrapsPending = .False -- The callee starts with the caller's ADDRESS settings; its own changes must -- not leak back, so it gets its own copy of the WITH configuration table. ioConfigs = ioConfigs~copy args = newArgs If newFrame \== .Nil Then frame = newFrame -- The activation just pushed runs another program (an external routine, -- called by the RVM): its variables are its own, and so are its settings, -- which start as a program's do (NUMERIC, TRACE, traps, interactive debug, -- the elapsed-time clock). ADDRESS, the queue and the streams are the -- caller's. ::Method startProgram Expose frame digits fuzz form traps trapsOwned condition traceSetting - traceIndent debugPause debugBypass promptIssued sourceTraced - traceSkip traceSuppressed clock secMgr randomSeed callStack Use Strict Arg program = .Nil frame = .RVM.Vars~new secMgr = .Nil -- (its package's: applyOptions) -- RANDOM's state is its own, and the caller's comes back on return. If \ callStack~isEmpty Then callStack~lastItem~randomOwn = .True randomSeed = .Nil callerNumeric = .Array~of( digits, fuzz, form ) digits = 9 fuzz = 0 form = "SCIENTIFIC" traps = .Directory~new trapsOwned = .True condition = .Nil traceSetting = "N" traceIndent = 0 debugPause = .False debugBypass = .False promptIssued = .False sourceTraced = .False traceSkip = 0 traceSuppressed = .False self~syntaxConds = "" -- A new activation of ooRexx: its elapsed-time clock has not started (the -- clock is the activation's own copy: saveActivation). clock~elapsedStart = 0 clock~elapsedReset = .False If program \== .Nil Then self~applyOptions( program, callerNumeric ) self~setTraceFlags -- The ::OPTIONS of 'program' (its package), for an activation that starts: -- NUMERIC (with NUMERIC INHERIT, the caller's, when there is one), TRACE, -- and the conditions that are SYNTAX. ::Method applyOptions Expose digits fuzz form traceSetting secMgr Use Strict Arg program, callerNumeric = .Nil -- Its security manager: its package's, as it is now (ooRexx's -- RexxActivation copies it when it is made). If program~hasMethod( "SECMGR" ) Then secMgr = program~secMgr If program~optDigits == .Nil Then Return -- (not from R-code) If program~optInherit, callerNumeric \== .Nil Then Do digits = callerNumeric[1]; fuzz = callerNumeric[2]; form = callerNumeric[3] End Else Do digits = program~optDigits fuzz = program~optFuzz form = program~optForm End traceSetting = program~optTrace self~syntaxConds = program~syntaxConds self~setTraceFlags -- A method activation starts: its streams have not been asked about, and -- it has a stream table of its own. ::Method newStreamScope Expose streamScope localStreams streamsOwn streamScope = .Nil localStreams = .Nil streamsOwn = .True -- The stream table of the current activation, made when first needed: a -- method's own (sharing the program's standard streams); otherwise the -- caller's, looked for down the saved activations up to the first that has -- one or owns one (made then, and recorded in each activation in between so -- that they all share it), or the program's. 'tables' is the class of the -- tables (RVM.StreamTable, which this package cannot see). ::Method activeStreams Expose localStreams streamsOwn callStack Use Strict Arg tables If localStreams \== .Nil Then Return localStreams If streamsOwn Then Do localStreams = tables~new( self~rootStreams( tables ) ) Return localStreams End t = .Nil Do i = callStack~items To 1 By -1 rec = callStack[ i ] If rec~localStreams \== .Nil Then Do t = rec~localStreams Leave End If rec~streamsOwn == .True Then Do t = tables~new( self~rootStreams( tables ) ) Leave End End If t == .Nil Then t = self~rootStreams( tables ) Do j = callStack~items To Max( i, 1 ) By -1 callStack[ j ]~localStreams = t End localStreams = t Return t -- The program's stream table (see streams). ::Method rootStreams Expose streams Use Strict Arg tables If streams == .Nil Then streams = tables~new Return streams -- Leave a routine: the caller's frame and arguments come back (what the -- routine EXPOSEd is the caller's variables themselves: nothing to copy). ::Method popActivation Expose frame args callStack - address alternateAddress ioConfigs digits fuzz form - traps trapsOwned condition callTraps clause callTrapsPending - clock traceSetting traceIndent interprets - debugPause debugBypass promptIssued sourceTraced traceSkip traceSuppressed - secMgr streamScope localStreams streamsOwn randomSeed procValid saved = callStack~lastItem -- top of stack .. secMgr = saved~secMgr streamScope = saved~streamScope localStreams = saved~localStreams streamsOwn = saved~streamsOwn If saved~randomOwn == .True Then randomSeed = saved~randomSeed procValid = ( saved~procValid == .True ) callStack~delete( callStack~last ) -- .. then pop it frame = saved~frame args = saved~args digits = saved~digits fuzz = saved~fuzz form = saved~form address = saved~address alternateAddress = saved~alternateAddress ioConfigs = saved~ioConfigs traps = saved~traps trapsOwned = saved~trapsOwned condition = saved~condition callTraps = saved~callTraps callTrapsPending = \ callTraps~isEmpty clause = saved~clause clock = saved~clock traceSetting = saved~traceSetting self~syntaxConds = saved~syntaxConds traceIndent = saved~traceIndent interprets = saved~interprets Parse Value saved~debugState~makeString("L", " ") With - debugPause debugBypass promptIssued sourceTraced traceSkip traceSuppressed self~setTraceFlags -- The saved activations (the callers, outermost first), and the active -- INTERPRETs of the current one: the RVM reads them for a traceback. ::Method savedActivations Expose callStack Return callStack ::Method activeInterprets Expose interprets Return interprets -- Depth of the call stack (0 = in the main program). ::Method callDepth Expose callStack Return callStack~items -- The caller's variable frame (top of the saved stack). PROCEDURE uses it to -- read the values it EXPOSEs before installing the callee's fresh frame. ::Method callerFrame Expose callStack Return callStack~lastItem~frame -- Replace the current activation's frame (PROCEDURE installs a fresh one). ::Method installFrame Expose frame Use Strict Arg newFrame frame = newFrame -- Read argument n (1-based). 'args' is a sparse array: an omitted argument is a -- HOLE (no index), so a missing index -- omitted, or beyond the last supplied -- -- returns .Nil. The caller decides what that means for ARG(). ::Method argValue Expose args Use Strict Arg n If n < 1 Then Return .Nil If \ args~hasIndex(n) Then Return .Nil Return args[n] -- How many arguments the current activation received (ARG() with no operand). -- Rexx counts up to the LAST supplied argument (holes included), which is the -- sparse array's ~last (0 when empty). ::Method argCount Expose args If args~isEmpty Then Return 0 Return args~last /******************************************************************************/ /* Condition traps (SIGNAL ON / CALL ON) */ /* */ /* One trap per condition name: SIGNAL ON ERROR and CALL ON ERROR replace */ /* each other. A USER condition is keyed "USER name". ANY is its own key, */ /* consulted only when the specific condition has no trap -- and a CALL ON */ /* ANY does not catch the conditions CALL ON cannot trap (SYNTAX, NOVALUE, */ /* LOSTDIGITS, NOMETHOD, NOSTRING). */ /******************************************************************************/ -- Make sure the table this activation changes is its own (copy on first write). ::Method ownTraps Private Expose traps trapsOwned If \ trapsOwned Then Do traps = traps~copy trapsOwned = .True End ::Method trapOn Expose traps Use Strict Arg name, trap self~ownTraps traps[ name ] = trap self~dropSyntaxCond( name, trap~isSignal ) ::Method trapOff Expose traps Use Strict Arg name, signal = .True self~ownTraps traps~remove( name ) self~dropSyntaxCond( name, signal ) -- ::OPTIONS SYNTAX: the conditions (blank-separated) that are -- SYNTAX 98.97x / 98.986 when they are raised here. A trap set or removed -- for one of them (or ANY) turns it off for this activation (ooRexx's -- trapOn / trapOff: LOSTDIGITS, NOSTRING and NOVALUE by SIGNAL only). ::Attribute syntaxConds ::Method dropSyntaxCond Private Expose syntaxConds Use Strict Arg name, signal If syntaxConds == "" Then Return If name == "ANY" Then list = "ERROR FAILURE NOTREADY" signal~?( "LOSTDIGITS NOSTRING NOVALUE", "" ) Else Do If \ signal, WordPos( name, "LOSTDIGITS NOSTRING NOVALUE" ) > 0 Then Return list = name End Do w Over list~makeArray( " " ) k = WordPos( w, syntaxConds ) If k > 0 Then syntaxConds = DelWord( syntaxConds, k, 1 ) End -- Is condition 'name' SYNTAX here? ::Method isSyntaxCond Expose syntaxConds Use Strict Arg name Return WordPos( name, syntaxConds ) > 0 -- The trap that would handle condition 'name', or .Nil. ::Method trapFor Expose traps Use Strict Arg name Return TrapIn( traps, name ) -- Does the caller (the activation below this one) trap condition 'name'? -- (RAISE ... RETURN asks it first, as ooRexx's senderActivation~trap.) ::Method callerTraps Expose callStack Use Strict Arg name If callStack~items == 0 Then Return .False Return TrapIn( callStack~lastItem~traps, name ) \== .Nil -- Does this activation, or one below it, trap condition 'name'? (An error -- in the LINEOUT of a trace line goes to the program only then: see -- RVM.World~traceObject.) ::Method trapsBelow Expose traps callStack Use Strict Arg name If TrapIn( traps, name ) \== .Nil Then Return .True Do saved Over callStack If TrapIn( saved~traps, name ) \== .Nil Then Return .True End Return .False -- Raise condition 'info' (an RVM.ConditionInfo) in the current activation. -- Returns .True when a trap took it (a CALL ON trap is then queued for the end -- of the clause, or ignored while in DELAY), .False when nothing traps it. A -- SIGNAL ON trap does not return: the condition is thrown (as the interpreter's -- own Rexx error, marked "RVM.Trap") up to where the machine catches it, -- abandoning whatever was being done. ::Method raiseCondition Expose thrown Use Strict Arg info trap = self~trapFor( info~condition ) If trap == .Nil Then Return .False If trap~state == "DELAY" Then Return .True If trap~isSignal Then Do thrown = .RVM.Throw~new( info, trap, self~callDepth ) Raise Syntax 98.900 Array( "trap" ) Description "RVM.Trap" End self~queueCallTrap( trap, info ) Return .True -- A condition raised in an activation that is a phantom (it forwards: see -- RVM.Context~raiseCondition) is the caller's: a SIGNAL ON trap there -- unwinds to it, a CALL ON trap is queued for it (it runs at the caller's -- next clause boundary). .False: untrapped. ::Method callerRaise Expose callStack thrown Use Strict Arg info caller = callStack~lastItem trap = TrapIn( caller~traps, info~condition ) If trap == .Nil Then Return .False If trap~state == "DELAY" Then Return .True If trap~isSignal Then Do thrown = .RVM.Throw~new( info, trap, callStack~items - 1 ) Raise Syntax 98.900 Array( "trap" ) Description "RVM.Trap" End caller~callTraps~append( .Array~of( trap, info ) ) Return .True -- An arithmetic operand (an RVM.Number) had more digits than NUMERIC DIGITS: -- the LOSTDIGITS condition, described by the operand's value. Only a SIGNAL ON -- trap can take it; untrapped, it does nothing (the operand is then truncated). ::Method lostDigits Expose traps Use Strict Arg n -- ::OPTIONS LOSTDIGITS SYNTAX (ooRexx's Activity::raiseCondition). If self~isSyntaxCond( "LOSTDIGITS" ) Then Raise Syntax 98.972 Array( n~string ) If traps~isEmpty Then Return self~raiseCondition( .RVM.ConditionInfo~new( "LOSTDIGITS", n~string ) ) -- An object with no string value was converted to a string (its STRING -- gave 'v': see RVM.Obj~stringValue, ooRexx's requestString): the NOSTRING -- condition, described by 'v', with the object as ADDITIONAL. As LOSTDIGITS, -- only a SIGNAL ON trap can take it; untrapped, it does nothing. ::Method noString Expose traps Use Strict Arg v, obj -- ::OPTIONS NOSTRING SYNTAX (ooRexx's Activity::raiseCondition). If self~isSyntaxCond( "NOSTRING" ) Then Raise Syntax 98.973 Array( v ) If traps~isEmpty Then Return info = .RVM.ConditionInfo~new( "NOSTRING", v ) info~additional = obj self~raiseCondition( info ) -- CONDITION('O') and CONDITION('A'): objects (RVM.Context has them). ::Method conditionObject Raise Syntax 93.900 Additional( "RVM: CONDITION('O') returns an object" ) ::Method conditionAdditional Raise Syntax 93.900 Additional( "RVM: CONDITION('A') returns an object" ) -- ON, OFF or DELAY: the state of the trap for exactly this name (no ANY). ::Method trapState Expose traps Use Strict Arg name trap = traps[ name ] If trap == .Nil Then Return "OFF" Return trap~state -- Queue a fired CALL ON trap until the end of the current clause. ::Method queueCallTrap Expose callTraps callTrapsPending Use Strict Arg trap, info callTraps~append( .Array~of( trap, info ) ) callTrapsPending = .True -- Something is due at the next clause boundary (a HALT: RVM.Context~halt). ::Method clauseBoundary Expose callTrapsPending callTrapsPending = .True -- Take (and clear) the queued CALL ON traps. ::Method takeCallTraps Expose callTraps callTrapsPending taken = callTraps callTraps = .Array~new callTrapsPending = .False Return taken -- Queue again, first, the CALL ON traps 'held' (taken while a line typed at -- a pause ran: they belong to the clause that paused). ::Method restoreCallTraps Expose callTraps callTrapsPending Use Strict Arg held held~appendAll( callTraps ) callTraps = held callTrapsPending = \ callTraps~isEmpty /******************************************************************************/ /* ADDRESS environments */ /******************************************************************************/ -- ADDRESS env [WITH ...] / ADDRESS VALUE expr [WITH ...]: 'name' becomes the -- current environment and the old current one the alternate. 'spec' is the -- ADDRESS instruction when it had a WITH clause (it then REPLACES any default -- redirection that environment had), or .Nil. ::Method setAddress Expose address alternateAddress ioConfigs Use Strict Arg name, spec = .Nil alternateAddress = address address = name If spec \== .Nil Then ioConfigs[ Upper(name) ] = spec -- A routine called by the RVM (a ::ROUTINE, a Routine's CALL) and a method -- start with the default environment, as ooRexx's activations with no -- address given. ::Method defaultAddress Expose address alternateAddress ioConfigs commandHost address = commandHost~initialAddress alternateAddress = address ioConfigs = .Directory~new -- ADDRESS with no operand: swap the current and the alternate environment. ::Method toggleAddress Expose address alternateAddress temp = address address = alternateAddress alternateAddress = temp -- The default redirection (an ADDRESS instruction with WITH) of an environment, -- or .Nil. Environment names match caselessly. ::Method ioConfigFor Expose ioConfigs Use Strict Arg name Return ioConfigs[ Upper(name) ] /******************************************************************************/ /* Variable access */ /* */ /* The frame maps a name to its variable (an RVM.Var), made when the name is */ /* first given a value (or first referenced: EXPOSE, a stem); a variable with */ /* no value holds .Nil. Two frames that hold the same RVM.Var share that */ /* variable (EXPOSE, PROCEDURE EXPOSE). A method's frame after USE LOCAL */ /* makes the object's variable of a name not declared local the first time */ /* the name is referenced (RVM.Vars~cell: resolve). */ /******************************************************************************/ -- Assign a variable. 'name' is normalised to uppercase (Rexx symbol). ::Method setVar Expose frame Use Strict Arg name, value up = Upper(name) v = frame[ up ] If v == .Nil Then v = frame~cell( up, .True ) v~value = value -- Drop a variable (make it unset again), e.g. RETURN with no value drops RESULT. ::Method dropVar Expose frame Use Strict Arg name v = frame~cell( Upper(name) ) If v \== .Nil Then v~value = .Nil -- Read a variable. If it is NOT set, Rexx returns the variable NAME in -- uppercase (not an empty string, not an error). That is pure Rexx semantics. ::Method getVar Expose frame Use Strict Arg name upper = Upper(name) v = frame[ upper ] If v == .Nil Then v = frame~cell( upper ) If v == .Nil Then Return upper -- uninitialised variable -> its own name value = v~value If value == .Nil Then Return upper Return value -- The value of a variable, or .Nil when it is not set (NOVALUE checks this). ::Method lookupVar Expose frame Use Strict Arg name up = Upper(name) v = frame[ up ] If v == .Nil Then v = frame~cell( up ) If v == .Nil Then Return .Nil Return v~value -- Does the variable 'name' have a value? ::Method isSet Expose frame Use Strict Arg name v = frame~cell( Upper(name) ) If v == .Nil Then Return .False Return v~value \== .Nil -- The variable (an RVM.Var) of a name, made if it does not exist (the -- variable of a VariableReference: >x; a stem's, when 'name' ends in a -- period, with its stem). ::Method variable Expose frame Use Strict Arg name up = Upper(name) If Right( up, 1 ) == "." Then st = self~stemObject( up, 1 ) Return frame~cell( up, .True ) -- Can the variable of a name become another one (USE ARG >v, >s.)? Only a -- local one (not the object's) with no value, as ooRexx's isAliasable: a -- stem variable's stem must be empty, with its name as its default. ::Method isAliasable Expose frame Use Strict Arg name up = Upper(name) v = frame~cell( up ) If v == .Nil Then Return .True If \ frame~isLocal( up ) Then Return .False value = v~value If value == .Nil Then Return .True If Right( up, 1 ) \== "." Then Return .False If value~items \== 0 Then Return .False Return value~value == up -- Make 'var' (an RVM.Var), whose own name is 'varName', the variable of a -- name (USE ARG >v, >s.: the local variable becomes the caller's). ::Method aliasVar Expose frame Use Strict Arg name, var, varName frame~alias( Upper(name), var, varName ) /******************************************************************************/ /* Compound / stem variables */ /* */ /* A stem variable lives in the frame under its uppercased key WITH the dot, */ /* e.g. "A."; the simple "A" (no dot) is a wholly separate slot, so 'a' and */ /* 'a.1' coexist. Its variable holds an RVM.Stem, made when the variable is */ /* first referenced (read, written, dropped), named as the variable. */ /* Assigning the stem a Stem object puts that stem in the variable (a. = b.: */ /* both variables are the same stem); assigning it anything else, or dropping */ /* it, puts a new stem there, as ooRexx's RexxVariable~setStem and */ /* dropStemVariable. The 'tail' passed here is already DERIVED (each fragment */ /* resolved: a variable to its value verbatim, a number/literal to its text), */ /* so the context stores it as given -- it does NOT re-normalise numbers */ /* (a.007 and a.7 are different tails). */ /******************************************************************************/ -- The RVM.Stem stored under stemKey (made if asked). .Nil when absent and -- create is 0. ::Method stemObject Expose frame Use Strict Arg stemKey, create = 0 key = Upper( stemKey ) v = frame[ key ] If v == .Nil Then Do v = frame~cell( key, create ) If v == .Nil Then Return .Nil End st = v~value If st \== .Nil Then Return st If \ create Then Return .Nil st = .RVM.Stem~new( key ) v~value = st Return st -- Read a compound variable a.tail. 'stemKey' is "A.", 'tail' is the derived -- tail string. Falls back: this tail -> the stem default -> the compound -- name (the stem's own name: "B.5" after a. = b.). ::Method getCompound Use Strict Arg stemKey, tail Return self~stemObject( stemKey, 1 )~at( tail ) -- a reference creates the stem -- The value of a compound variable, or .Nil when neither the tail nor the stem -- default has one (NOVALUE checks this). ::Method lookupCompound Use Strict Arg stemKey, tail v = self~stemObject( stemKey, 1 )~tailValue( tail ) -- a reference creates it If v == .RVM.UseName Then Return .Nil Return v -- Assign a compound variable a.tail = value. ::Method setCompound Use Strict Arg stemKey, tail, value self~stemObject( stemKey, 1 )~setTail( tail, value ) -- The whole stem a.: its Stem object (its string value is its default, or -- its name). A stem read never raises NOVALUE. ::Method getStem Use Strict Arg stemKey st = self~stemObject( stemKey, 1 ) -- a reference creates the stem Return self~world~stemObjectOf( st ) -- Assign the whole stem a. = value: a Stem object is that stem; anything -- else is the default value of a new stem. ::Method setStem Expose frame Use Strict Arg stemKey, value key = Upper( stemKey ) st = self~world~stemOf( value ) If st == .Nil Then Do st = .RVM.Stem~new( key ) st~setValue( value ) End frame~cell( key, .True )~value = st -- DROP a.: a new stem, with no default and no tails (it reads as its name -- again; the stem still exists, as in ooRexx, where SYMBOL('A.') is VAR after -- DROP A.). ::Method dropStem Expose frame Use Strict Arg stemKey key = Upper( stemKey ) frame~cell( key, .True )~value = .RVM.Stem~new( key ) -- DROP a.tail -- that tail has no value (it reads as its name). ::Method dropCompound Use Strict Arg stemKey, tail self~stemObject( stemKey, 1 )~dropTail( tail ) /******************************************************************************/ /* Activities (the RVM's REPLY and START) */ /* */ /* Every activity has a context of its own: its activations. What the */ /* activities of a run share is the output, the data queue, the command host, */ /* the streams and the clause texts (globals); a new context takes them */ /* (shareGlobals). REPLY moves the current activation to the new activity: */ /* its variables and settings (activationState, takeActivation). */ /******************************************************************************/ ::Method globals Expose out queue commandHost streams clauseTexts Return .Array~of( out, queue, commandHost, streams, clauseTexts ) ::Method shareGlobals Expose out queue commandHost streams clauseTexts Use Strict Arg g out = g[1] queue = g[2] commandHost = g[3] streams = g[4] clauseTexts = g[5] ::Method activationState Expose frame digits fuzz form args address alternateAddress ioConfigs - traps trapsOwned condition callTraps callTrapsPending clause clock - traceSetting traceIndent debugPause debugBypass promptIssued - sourceTraced traceSkip traceSuppressed programName sourceLines invocation - secMgr streamScope localStreams streamsOwn s = .Directory~new s~secMgr = secMgr s~streamScope = streamScope s~localStreams = localStreams -- (The new activity has none of its callers: it gets the table now.) If \ streamsOwn, localStreams == .Nil, self~streams \== .Nil Then s~localStreams = self~activeStreams( self~streams~class ) s~streamsOwn = streamsOwn s~randomSeed = self~randomSeed s~frame = frame; s~digits = digits; s~fuzz = fuzz; s~form = form s~args = args; s~address = address; s~alternateAddress = alternateAddress s~ioConfigs = ioConfigs; s~traps = traps; s~trapsOwned = trapsOwned s~condition = condition; s~callTraps = callTraps s~callTrapsPending = callTrapsPending; s~clause = clause; s~clock = clock s~traceSetting = traceSetting; s~traceIndent = traceIndent s~debugState = .Array~of( debugPause, debugBypass, promptIssued, - sourceTraced, traceSkip, traceSuppressed ) s~programName = programName; s~sourceLines = sourceLines s~invocation = invocation Return s ::Method takeActivation Expose frame digits fuzz form args address alternateAddress ioConfigs - traps trapsOwned condition callTraps callTrapsPending clause clock - traceSetting traceIndent debugPause debugBypass promptIssued - sourceTraced traceSkip traceSuppressed programName sourceLines invocation - secMgr streamScope localStreams streamsOwn Use Strict Arg s secMgr = s~secMgr streamScope = s~streamScope localStreams = s~localStreams streamsOwn = s~streamsOwn self~randomSeed = s~randomSeed frame = s~frame; digits = s~digits; fuzz = s~fuzz; form = s~form args = s~args; address = s~address; alternateAddress = s~alternateAddress ioConfigs = s~ioConfigs; traps = s~traps; trapsOwned = s~trapsOwned condition = s~condition; callTraps = s~callTraps callTrapsPending = s~callTrapsPending; clause = s~clause clock = s~clock~copy traceSetting = s~traceSetting; traceIndent = s~traceIndent Parse Value s~debugState~makeString( "L", " " ) With - debugPause debugBypass promptIssued sourceTraced traceSkip traceSuppressed programName = s~programName; sourceLines = s~sourceLines invocation = s~invocation self~setTraceFlags /******************************************************************************/ /* Activation -- a saved caller state */ /* */ /* One is pushed on each CALL and popped on RETURN. It remembers what the */ /* callee may change but the caller must get back: the variable frame, the */ /* argument array, and the routine's settings -- NUMERIC DIGITS/FUZZ/FORM and */ /* the ADDRESS environments. The callee starts with the caller's settings; any */ /* change it makes (with or without PROCEDURE) is undone on RETURN. What is */ /* truly global (output sink, data queue, pending-jump flags) stays on the */ /* context and is not saved here. */ /******************************************************************************/ ::Class RVM.Activation Public ::Attribute frame Get ::Attribute args Get -- The caller's settings, restored on RETURN. ::Attribute digits Get ::Attribute fuzz Get ::Attribute form Get ::Attribute address Get ::Attribute alternateAddress Get ::Attribute ioConfigs Get ::Attribute traps Get ::Attribute trapsOwned Get ::Attribute condition Get ::Attribute callTraps Get ::Attribute clause Get ::Attribute clock -- the caller's clock (RVM.Clock) ::Attribute traceSetting -- the caller's TRACE setting ::Attribute traceIndent -- the caller's trace indentation ::Attribute interprets -- the caller's active INTERPRETs ::Attribute debugState -- the caller's interactive debug state ::Attribute syntaxConds -- the caller's ::OPTIONS ... SYNTAX ::Attribute secMgr -- the caller's security manager ::Attribute streamScope -- the caller's streams asked about ::Attribute localStreams -- the caller's stream table, or .Nil ::Attribute streamsOwn -- is the caller a method? ::Attribute randomSeed -- the caller's RANDOM state ::Attribute randomOwn -- does the callee have its own? ::Attribute procValid -- the caller's: may PROCEDURE run? ::Method init Expose frame args Use Strict Arg frame, args ::Method saveSettings Expose digits fuzz form address alternateAddress ioConfigs Use Strict Arg digits, fuzz, form, address, alternateAddress, ioConfigs ::Method saveConditionState Expose traps trapsOwned condition callTraps clause Use Strict Arg traps, trapsOwned, condition, callTraps, clause /******************************************************************************/ /* RVM.Var -- a variable, as ooRexx's RexxVariable: its value (.Nil when it */ /* has none). Frames hold them (RVM.Vars), and so do the variable pools of */ /* the objects (RVM.Pool) and VariableReferences; every frame that holds it */ /* shares it. A variable watched by GUARD WHEN tells its pool when it is set */ /* (watchBy: its own VALUE=, so that the others pay nothing). */ /* */ /* Made with ~new and then given its value (no INIT: it would cost a method */ /* run per variable). */ /******************************************************************************/ ::Class RVM.Var Public ::Attribute value -- GUARD WHEN: set (or dropped), it tells 'pool' that 'name' changed. ::Method watchBy Expose pool name Use Strict Arg pool, name self~setMethod( "VALUE=", "Use Arg v; self~store( v ); self~changed" ) ::Method store Expose value Use Arg value ::Method changed Expose pool name pool~changed( name ) /******************************************************************************/ /* RVM.Vars -- a variable frame: uppercased name -> RVM.Var. */ /******************************************************************************/ ::Class RVM.Vars Public SubClass Directory -- The variable of 'name' (uppercased): .Nil when there is none and 'create' -- is false. A method's frame after USE LOCAL resolves a name it does not -- have yet (RVM.MethodFrame~resolve). ::Method cell Use Strict Arg name, create = .False v = self[ name ] If v \== .Nil Then Return v v = self~resolve( name ) If v \== .Nil Then Return v If \ create Then Return .Nil v = .RVM.Var~new v~value = .Nil self[ name ] = v Return v ::Method resolve Return .Nil -- Is the variable of 'name' this activation's own (not an object's)? ::Method isLocal Return .True -- USE ARG >v: 'name' is now 'var', whose own name (what VARIABLES shows, -- as ooRexx's) is 'varName'; those names are kept under "" (no variable has -- that name). ::Method alias Use Strict Arg name, var, varName self[ name ] = var names = self[ "" ] If names == .Nil Then Do names = .Directory~new self[ "" ] = names End names[ name ] = varName -- The names of the variables that have a value. ::Method variableNames names = .Array~new s = self~supplier Do While s~available If s~index \== "" Then If s~item~value \== .Nil Then names~append( s~index ) s~next End Return names -- The name of the variable of 'name' (another after USE ARG >v). ::Method ownName Use Strict Arg name names = self[ "" ] If names == .Nil Then Return name own = names[ name ] If own == .Nil Then Return name Return own /******************************************************************************/ /* RVM.Trap -- one enabled condition trap. */ /* */ /* 'isSignal' tells SIGNAL ON from CALL ON; 'target' is the label key to go */ /* to (a symbol upper-cased, a string as written). A CALL ON trap is put in */ /* the DELAY state while its handler runs. */ /******************************************************************************/ ::Class RVM.Trap Public ::Attribute condition Get ::Attribute isSignal Get ::Attribute target Get ::Attribute state Get ::Attribute state Set ::Method init Expose condition isSignal target state Use Strict Arg condition, isSignal, target state = "ON" /******************************************************************************/ /* RVM.Throw -- a condition on its way to the activation that handles it. */ /* */ /* While the interpreter unwinds, the condition travels here: 'info' is the */ /* RVM.ConditionInfo, 'trap' the SIGNAL ON trap already chosen for it (or */ /* .Nil when the receiving activation still has to look for one -- a SYNTAX), */ /* and 'level' the call depth of the activation that receives it. Deeper */ /* activations are ended on the way up. */ /******************************************************************************/ ::Class RVM.Throw Public ::Attribute info Get ::Attribute trap Get ::Attribute level Get ::Attribute level Set -- The error of a message raised again (the RVM's Message~result): it keeps -- the lines it had, and goes up without taking more. ::Attribute reraise ::Method init Expose info trap level reraise Use Strict Arg info, trap, level reraise = .False /******************************************************************************/ /* RVM.ConditionInfo -- a raised condition (what CONDITION() reports). */ /* */ /* condition -- "SYNTAX", "ERROR", "USER FOO", ... */ /* description -- CONDITION('D'): "" unless one was given */ /* rc -- the value RC gets when trapped, or .Nil (NOVALUE, */ /* USER...) */ /* code -- SYNTAX only: the error code "major.minor" */ /* additional -- SYNTAX: the message substitutions (an Array), or .Nil */ /* instruction -- "SIGNAL" or "CALL" once trapped */ /* result -- a RAISE ... RETURN/EXIT value, or .Nil */ /* position -- the line where it was raised, or .Nil (the RVM) */ /* program -- the program where it was raised, or .Nil (the RVM) */ /* propagated -- "1" once it went up from an activation that did not trap */ /* it (or RAISE PROPAGATE), else "0" */ /* objResult -- the RESULT of the condition object, or .Nil (none) */ /* message -- SYNTAX: the secondary message, when known, or .Nil */ /* additionalObj -- the RVM's object for 'additional' (made once) */ /* traceback -- the lines of the error report when a trap took it, or */ /* .Nil (the RVM: a RAISE PROPAGATE shows them) */ /* stack -- the lines of the traceback when it was raised (every */ /* activation), or .Nil (the RVM: TRACEBACK) */ /* stackObj -- the RVM's List for 'stack' (made once) */ /* nativeStack -- the traceback lines (strings) of the ooRexx methods it */ /* was raised in (a NOTREADY), innermost first, or .Nil */ /* nativeFrames -- their frames, one per line: .Array~of(class, method, */ /* receiver, arguments, line), the receiver an RVM.Stream or */ /* .Array~of("LOCAL", name) (see RVM.World~frameTarget) */ /******************************************************************************/ ::Class RVM.ConditionInfo Public -- An error that ended a machine run by a native (sendSync, runSync), on its -- way up to the machine below (see SyncFailed and Failed in RVM.Machine): -- .Array~of(info, report lines, the host condition's code and description, -- whether its stack already goes on with that machine's: see -- RVM.Context~outerContext), or .Nil. ::Attribute syncFailure Class ::Method activate Class Expose syncFailure syncFailure = .Nil ::Attribute condition Get ::Attribute description Get ::Attribute description Set ::Attribute rc Get ::Attribute rc Set ::Attribute code Get ::Attribute code Set ::Attribute additional Get ::Attribute additional Set ::Attribute instruction Get ::Attribute instruction Set ::Attribute result Get ::Attribute result Set ::Attribute position ::Attribute program ::Attribute propagated ::Attribute objResult ::Attribute message ::Attribute additionalObj ::Attribute traceback ::Attribute stack ::Attribute stackObj ::Attribute framesObj -- STACKFRAMES (the RVM): a List, made once ::Attribute nativeStack ::Attribute nativeFrames ::Method init Expose condition description rc code additional instruction result - position program propagated objResult message additionalObj traceback - stack stackObj framesObj nativeStack nativeFrames Use Strict Arg condition, description = "", rc = .Nil code = .Nil additional = .Nil instruction = "" result = .Nil position = .Nil program = .Nil propagated = "0" objResult = .Nil message = .Nil additionalObj = .Nil traceback = .Nil stack = .Nil stackObj = .Nil framesObj = .Nil nativeStack = .Nil nativeFrames = .Nil -- The subcode of a SYNTAX condition (CONDITION('E')): what follows the dot. ::Method extra Expose code If code == .Nil Then Return "" Parse Var code . "." minor Return minor -- A CALL ON handler receives the condition object as its only argument. The -- interpreter has no objects of its own to hand over, so this stands in for -- it; its string value is what the native object's is. ::Method string Return "a Directory" /******************************************************************************/ /* RVM.Stem -- a stem, as ooRexx's StemClass: its name, its default value */ /* and its tails. A stem variable holds one; the Stem object that shows it */ /* (an RVM.Obj whose native value it is) is made when it is first needed: */ /* obj, see RVM.World~stemObjectOf. */ /* */ /* The tails are a port of ooRexx's CompoundVariableTable: a balanced binary */ /* tree (a tail is greater when longer; of the same length, by its bytes) */ /* walked in post-order, so that DO OVER, ALLINDEXES, SUPPLIER... go in the */ /* native's order. 'index' finds a node by its tail (the tree is only walked */ /* to insert one). */ /* */ /* A tail has three states (StemClass~evaluateCompoundVariableValue): */ /* a node with a value -> that value; */ /* a node with no value -> the name (a dropped tail beats the default); */ /* no node -> the default, if the stem has one; the name. */ /* The name is the stem's own ("B.5" when a. = b.), not the variable's. */ /* A node exposed to another (EXPOSE of a compound) reads, sets and drops */ /* that one (realVariable); its own value is none, so the stem does not */ /* count it among its tails. */ /******************************************************************************/ ::Class RVM.Stem Public ::Attribute name -- its name ("A.", or what .STEM~NEW was given) ::Attribute value -- the default value (the name while dropped) ::Attribute dropped -- it has no explicit default value ::Attribute obj -- its Stem object (an RVM.Obj), once made ::Method init Expose name value dropped obj root index Use Strict Arg name = "" value = name dropped = .True obj = .Nil root = .Nil index = .Directory~new -- The default value, or .Nil when there is none. ::Method default Expose value dropped If dropped Then Return .Nil Return value -- A new default value (StemClass~setValue): the tails stay. ::Method setValue Expose value dropped Use Strict Arg value dropped = .False -- The name of one of its compound variables: its name and the tail. ::Method compoundName Expose name Use Strict Arg tail Return name || tail -- The value of a tail: a real value, or .RVM.UseName (the name, the -- caller composes it: compoundName, or the variable's name for NOVALUE). ::Method tailValue Expose value dropped Use Strict Arg tail node = self~findEntry( tail ) If node == .Nil Then Do If dropped Then Return .RVM.UseName Return value End v = node~realVariable~value If v == .RVM.Dropped Then Return .RVM.UseName Return v -- The value of a tail as a Stem's [] gives it (no NOVALUE): the value, or -- the compound name. ::Method at Use Strict Arg tail v = self~tailValue( tail ) If v == .RVM.UseName Then Return self~compoundName( tail ) Return v -- The nodes, in the order of the native's traversal. ::Method nodes Expose root list = .Array~new If root == .Nil Then Return list node = FindLeaf( root ) Do While node \== .Nil list~append( node ) node = NextNode( node ) End Return list -- The tails that hold a value of their own (DO ... OVER a., ALLINDEXES, -- MAKEARRAY), in order. ::Method tailNames names = .Array~new Do node Over self~nodes If node~value \== .RVM.Dropped Then names~append( node~name ) End Return names -- Their values (ALLITEMS), in order. ::Method tailItems values = .Array~new Do node Over self~nodes If node~value \== .RVM.Dropped Then values~append( node~value ) End Return values -- How many tails hold a value of their own (ITEMS). ::Method items n = 0 Do node Over self~nodes If node~value \== .RVM.Dropped Then n += 1 End Return n -- Does this tail hold a real (assigned, non-dropped) value? ::Method hasRealValue Use Strict Arg tail node = self~findEntry( tail ) If node == .Nil Then Return .False Return node~realVariable~value \== .RVM.Dropped -- Remove every tail (the dropped and exposed ones too) but KEEP the default -- (StemClass~empty; what redirecting command output to a stem does before -- writing to it). ::Method emptyTails Expose root index root = .Nil index = .Directory~new -- Set one tail (an exposed one: the variable it shares). ::Method setTail Use Strict Arg tail, val self~findEntry( tail, .True )~realVariable~value = val -- DROP a.tail: the tail has no value (NOT the same as absent: a dropped tail -- reads as the name, overriding any default, until the stem is emptied). ::Method dropTail Use Strict Arg tail self~findEntry( tail, .True )~realVariable~value = .RVM.Dropped -- The RVM's EXPOSE of a compound (StemClass~exposeCompoundVariable): the -- variable of a tail. One that is there (a dropped one too) is kept; a new -- one takes the default, if any. ::Method exposeTail Expose value dropped Use Strict Arg tail node = self~findEntry( tail ) If node \== .Nil Then Return node~realVariable node = self~findEntry( tail, .True )~realVariable If node~value == .RVM.Dropped, \ dropped Then node~value = value Return node -- ... and its use from another stem (StemClass~expose): the tail is that -- variable from now on (until the stem is emptied or replaced). ::Method shareTail Use Strict Arg tail, node self~findEntry( tail, .True )~real = node -- A copy (StemClass~copy): the same name and default, and a node for each -- one of this stem's with its own value (in traversal order: the tree of -- the copy may be shaped otherwise, as the native's). ::Method copyStem Expose name value dropped copy = .RVM.Stem~new( name ) copy~value = value copy~dropped = dropped Do node Over self~nodes copy~findEntry( node~name, .True )~value = node~value End Return copy -- The node of a tail (CompoundVariableTable~findEntry), made if 'create'; -- .Nil when it is not there. The node itself, not its real variable. ::Method findEntry Expose root index Use Strict Arg tail, create = .False node = index[ tail ] If node \== .Nil Then Return node If \ create Then Return .Nil anchor = root previous = .Nil rc = 0 Do While anchor \== .Nil rc = TailCompare( tail, anchor~name ) previous = anchor If rc > 0 Then anchor = anchor~right Else anchor = anchor~left End node = .RVM.TailNode~new( tail ) index[ tail ] = node If previous == .Nil Then root = node Else Do node~parent = previous If rc > 0 Then previous~right = node Else previous~left = node self~balance( node ) End Return node -- Rebalance from an inserted node (CompoundVariableTable~balance). ::Method balance Private Expose root Use Strict Arg node If node == root Then Return parentNode = node~parent depth = 1 Do While parentNode \== .Nil If parentNode~right == node Then Do parentNode~rightDepth = depth workingDepth = parentNode~leftDepth + 1 If depth > workingDepth Then Do parentNode = self~moveNode( parentNode, .False ) depth = parentNode~rightDepth End Else If workingDepth < depth Then Return End Else Do parentNode~leftDepth = depth workingDepth = parentNode~rightDepth + 1 If depth > workingDepth Then Do parentNode = self~moveNode( parentNode, .True ) depth = parentNode~leftDepth End Else If workingDepth < depth Then Return End depth += 1 node = parentNode parentNode = parentNode~parent End -- A rotation (CompoundVariableTable~moveNode): the new anchor. ::Method moveNode Private Expose root Use Strict Arg temp, toRight If toRight Then Do work = temp~left work1 = work~right temp~left = work1 temp~leftDepth = work~rightDepth If work1 \== .Nil Then work1~parent = temp work~right = temp work~rightDepth = work~rightDepth + 1 End Else Do work = temp~right work1 = work~left temp~right = work1 temp~rightDepth = work~leftDepth If work1 \== .Nil Then work1~parent = temp work~left = temp work~leftDepth = work~leftDepth + 1 End work2 = temp~parent work~parent = work2 temp~parent = work If work2 == .Nil Then root = work Else If work2~left == temp Then work2~left = work Else work2~right = work Return work -- Tails compare by length first, then by their bytes. ::Routine TailCompare Use Strict Arg a, b la = Length( a ) lb = Length( b ) If la > lb Then Return 1 If la < lb Then Return -1 If a == b Then Return 0 If a >> b Then Return 1 Return -1 -- The first node of the traversal from a node (CompoundVariableTable~findLeaf). ::Routine FindLeaf Use Strict Arg node Loop Do While node~left \== .Nil node = node~left End If node~right == .Nil Then Return node node = node~right End -- The next node of the traversal (CompoundVariableTable~next). ::Routine NextNode Use Strict Arg node parentNode = node~parent If parentNode == .Nil Then Return .Nil If parentNode~right == node Then Return parentNode If parentNode~right \== .Nil Then Return FindLeaf( parentNode~right ) Return parentNode /******************************************************************************/ /* RVM.TailNode -- a compound variable: a node of the tree of its stem. */ /******************************************************************************/ ::Class RVM.TailNode Public ::Attribute name -- the tail ::Attribute value -- its value (.RVM.Dropped: none) ::Attribute real -- the node of another stem it is exposed to, or .Nil ::Attribute left ::Attribute right ::Attribute parent ::Attribute leftDepth ::Attribute rightDepth ::Method init Expose name value real left right parent leftDepth rightDepth Use Strict Arg name value = .RVM.Dropped real = .Nil left = .Nil right = .Nil parent = .Nil leftDepth = 0 rightDepth = 0 -- The variable it stands for: itself, or the one it is exposed to. ::Method realVariable Expose real If real == .Nil Then Return self Return real /******************************************************************************/ /* Sentinels for the three-state tail lookup: .RVM.Dropped is the value of a */ /* node that has none (a dropped tail); .RVM.UseName, what RVM.Stem~value */ /* gives for a tail that reads as its name. Unique objects, compared with ==. */ /******************************************************************************/ ::Class RVM.Dropped Public ::Class RVM.UseName Public -- The trap of 'traps' (a table: name -> RVM.Trap) for condition 'name': -- its own, or ANY (which a CALL ON does not give to SYNTAX, NOVALUE, -- LOSTDIGITS, NOMETHOD and NOSTRING), or .Nil. ::Routine TrapIn Use Strict Arg traps, name trap = traps[ name ] If trap \== .Nil Then Return trap trap = traps[ "ANY" ] If trap == .Nil Then Return .Nil If \ trap~isSignal, - WordPos( name, "SYNTAX NOVALUE LOSTDIGITS NOMETHOD NOSTRING" ) > 0 Then Return .Nil Return trap ::Requires "RVM.Host.cls" /******************************************************************************/ /* The output sink for SAY */ /******************************************************************************/ -- Write each line straight to standard output as it is said. ::Class RVM.StandardOutput Public ::Method lineOut Use Strict Arg string = "" .RVM.HostFile~said += 1 -- (a line of the STDOUT stream: see HostFile) Return .output~lineOut( string ) /******************************************************************************/ /* RVM.ParseTarget -- the PARSE cursor engine. */ /* */ /* A faithful, line-for-line port of ooRexx's RexxTarget */ /* (interpreter/execution/ParseTarget.cpp). It holds the parsing positions and */ /* exposes the exact primitive movements a trigger performs plus the word/ */ /* remainder extraction. ALL positions are 0-based, as in the C++, so the */ /* arithmetic matches character for character; the only translation is that */ /* SubStr is 1-based, so an extract of (offset, length) is SubStr(s, offset+1, */ /* length). */ /* */ /* start start of the substring being parsed into this section's vars */ /* end end of that substring (exclusive) */ /* patternStart start of the last matched position (base for + / - movement) */ /* patternEnd end of the last match (base for search / absolute); equals */ /* patternStart for numeric (zero-length) triggers */ /* subcurrent running cursor while breaking [start,end) into words */ /******************************************************************************/ ::Class RVM.ParseTarget Public ::Method init Expose string stringLength start end patternStart patternEnd subcurrent Use Strict Arg string stringLength = Length( string ) -- next() equivalent for a single source: reset all positions to 0. start = 0 end = 0 patternStart = 0 patternEnd = 0 subcurrent = 0 -- moveToEnd(): the section runs from the end of the last pattern to the string -- end (the synthetic END trigger for trailing variables). ::Method moveToEnd Expose stringLength start end patternStart patternEnd subcurrent start = patternEnd patternEnd = stringLength patternStart = stringLength end = stringLength subcurrent = start -- forward(+n): start at the last MATCH START, end at start+offset. If there was -- no forward movement (end <= start) the Rexx rule matches to the end and leaves -- patternStart at start; otherwise everything moves from end. ::Method forward Expose stringLength start end patternStart patternEnd subcurrent Use Strict Arg offset start = patternStart end = start + offset If end >= stringLength Then end = stringLength If end <= start Then Do end = stringLength patternStart = start End Else patternStart = end patternEnd = patternStart subcurrent = start -- forwardLength(>n): like forward, but without the "no movement -> to end" rule. ::Method forwardLength Expose stringLength start end patternStart patternEnd subcurrent Use Strict Arg offset start = patternStart end = start + offset If end >= stringLength Then end = stringLength patternStart = end patternEnd = patternStart subcurrent = start -- absolute(n): move to an absolute (1-based) column; origin-zero it. start is the -- end of the previous match. Moving backward (offset <= start) matches to the end -- and resets patternStart to the offset; forward caps at the string end. ::Method absolute Expose stringLength start end patternStart patternEnd subcurrent Use Strict Arg offset If offset > 0 Then offset = offset - 1 start = patternEnd If offset <= start Then Do end = stringLength patternStart = offset End Else Do end = offset If end >= stringLength Then end = stringLength patternStart = end End patternEnd = patternStart subcurrent = start -- backward(-n): the section starts at the last match and runs to the end; the new -- match position moves back by offset (never past the beginning). ::Method backward Expose stringLength start end patternStart patternEnd subcurrent Use Strict Arg offset start = patternStart end = stringLength If offset > patternStart Then patternStart = 0 Else patternStart = patternStart - offset patternEnd = patternStart subcurrent = start -- backwardLength( patternStart Then start = 0 Else start = patternStart - offset end = patternStart patternStart = start patternEnd = patternStart subcurrent = start -- search(needle): find needle from the end of the last match. Not found -> match -- to the end. Found at p -> patternStart = p, patternEnd = p + len(needle). ::Method search Expose string stringLength start end patternStart patternEnd subcurrent Use Strict Arg needle start = patternEnd -- ooRexx pos(needle, start) is 1-based over the whole string starting at -- character start+1 (0-based start). Pos with a start argument does just that. p = Pos( needle, string, start + 1 ) If p == 0 Then Do end = stringLength patternStart = stringLength patternEnd = stringLength End Else Do end = p - 1 -- origin-zero the found column patternStart = end patternEnd = patternStart + Length( needle ) End subcurrent = start -- caselessSearch(needle): as search, but case-insensitive. ::Method caselessSearch Expose string stringLength start end patternStart patternEnd subcurrent Use Strict Arg needle start = patternEnd p = Pos( Upper(needle), Upper(string), start + 1 ) If p == 0 Then Do end = stringLength patternStart = stringLength patternEnd = stringLength End Else Do end = p - 1 patternStart = end patternEnd = patternStart + Length( needle ) End subcurrent = start -- getWord(): next blank/tab-delimited word within [subcurrent, end); consumes the -- word and its single trailing whitespace. "" once the section is used up. ::Method getWord Expose string stringLength start end patternStart patternEnd subcurrent If subcurrent >= end Then Return "" -- skip leading whitespace (blanks and tabs) scan = subcurrent Do While scan < end c = Substr( string, scan + 1, 1 ) If c \== " ", c \== "09"x Then Leave scan = scan + 1 End subcurrent = scan If subcurrent >= end Then Return "" -- find the end of the word (next whitespace, bounded by 'end') wordStart = scan endPos = -1 Do While scan < end c = Substr( string, scan + 1, 1 ) If c == " " | c == "09"x Then Do endPos = scan Leave End scan = scan + 1 End If endPos == -1 Then Do length = end - subcurrent subcurrent = end End Else Do subcurrent = endPos + 1 -- consume the terminating blank too length = endPos - wordStart End Return Substr( string, wordStart + 1, length ) -- skipWord(): like getWord but discards the word (for a "." placeholder). ::Method skipWord Expose string end subcurrent If subcurrent >= end Then Return scan = subcurrent Do While scan < end c = Substr( string, scan + 1, 1 ) If c \== " ", c \== "09"x Then Leave scan = scan + 1 End subcurrent = scan If subcurrent >= end Then Return endPos = -1 Do While scan < end c = Substr( string, scan + 1, 1 ) If c == " " | c == "09"x Then Do endPos = scan Leave End scan = scan + 1 End If endPos == -1 Then subcurrent = end Else subcurrent = endPos + 1 -- remainder(): the rest of [subcurrent, end), consuming it. "" once used up. ::Method remainder Expose string end subcurrent If subcurrent >= end Then Return "" length = end - subcurrent offset = subcurrent subcurrent = end Return Substr( string, offset + 1, length ) -- skipRemainder(): discard the rest of the section (a trailing "." placeholder). ::Method skipRemainder Expose end subcurrent subcurrent = end /******************************************************************************/ /* RVM.Clock -- the time state of an activation, as ooRexx keeps it. */ /* */ /* stamp, offset the clause's time: microseconds since 0001-01-01, local, */ /* and the local offset from UTC in microseconds; */ /* valid whether stamp belongs to the current clause (a stale one */ /* is kept: a pending reset needs it, see elapsedReset); */ /* elapsedStart when the elapsed-time clock started (UTC microseconds), */ /* 0 while it has not; */ /* elapsedReset TIME('R') ran: the clock restarts at the time of THAT */ /* clause, but only once a later clause takes a new time */ /* (so, as in ooRexx, TIME('E') in the same clause as */ /* TIME('R') still reads the old clock). */ /******************************************************************************/ ::Class RVM.Clock Public ::Attribute stamp ::Attribute offset ::Attribute valid ::Attribute elapsedStart ::Attribute elapsedReset ::Method init Expose stamp offset valid elapsedStart elapsedReset stamp = 0; offset = 0; valid = .False elapsedStart = 0; elapsedReset = .False /* INTERPRET data: the fragment every element of a parsed INTERPRET belongs */ /* to (its source and the line of the INTERPRET). */ ::Class RVM.Fragments Public ::Attribute source Get ::Attribute line Get ::Method init Expose source line Use Strict Arg source, line ::Method activate Class Expose elements elements = .IdentityTable~new ::Method of Class Expose elements Use Strict Arg element Return elements[ element ] ::Method register Class Expose elements Use Strict Arg package, source, line fragment = self~new( source, line ) el = package~firstElement Do While el \== .Nil elements[ el ] = fragment el = el~next End /******************************************************************************/ /* RVM.Queues -- the external data queues: SESSION and the named ones, local */ /* to the process (ooRexx's are rxapi's, shared by the processes of the */ /* machine: a divergence). A queue is an Array of lines (index 1, the head). */ /* Names are 1 to 250 of A-Z a-z 0-9 . ! ? _, in upper case; SESSION is */ /* always there and cannot be created nor deleted. The return codes are */ /* rxapi's: 0; 5 RXQUEUE_BADQNAME; 9 RXQUEUE_NOTREG; 10 RXQUEUE_ACCESS (a */ /* LINEIN waits on it). The current queue is .STDQUE's NAMED_QUEUE (the RVM */ /* sets stdque and scope when .LOCAL is made); before, SESSION. */ /******************************************************************************/ ::Class RVM.Queues Public ::Attribute queues Class -- NAME -> Array of lines ::Attribute waits Class -- NAME -> what LINEIN waits on (post, reset) ::Attribute counter Class -- for the names CREATE makes ::Attribute stdque Class -- .STDQUE (an RVM object), or .Nil ::Attribute scope Class -- the RexxQueue class (NAMED_QUEUE's pool) ::Method activate Class Expose queues waits counter stdque scope queues = .Directory~new queues[ "SESSION" ] = .Array~new waits = .Directory~new counter = 0 stdque = .Nil scope = .Nil .RVM.CommandHost~queues = self -- the commands share the queues ::Method valid Class Use Strict Arg name If Length( name ) == 0 | Length( name ) > 250 Then Return .False Return Verify( name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.!?_" ) == 0 -- The name of the current queue. ::Method current Class Expose stdque scope If stdque == .Nil Then Return "SESSION" v = stdque~pool( scope )~valueOf( "NAMED_QUEUE" ) If v == .Nil Then Return "SESSION" Return Upper( v ) -- CREATE: a new queue; the name given (as given) when it is not there, else -- a unique one; "" when the name is not valid (or SESSION). ::Method create Class Expose queues counter Use Strict Arg name = .Nil If name \== .Nil Then Do If \ self~valid( name ) | Upper( name ) == "SESSION" Then Return "" If \ queues~hasIndex( Upper( name ) ) Then Do queues[ Upper( name ) ] = .Array~new Return name End End Loop counter += 1 n = "S000Q"Lower( Right( D2X( counter ), 12, "0" ) ) If \ queues~hasIndex( Upper( n ) ) Then Leave End queues[ Upper( n ) ] = .Array~new Return n ::Method open Class Expose queues Use Strict Arg name If \ self~valid( name ) Then Return 5 If \ queues~hasIndex( Upper( name ) ) Then queues[ Upper( name ) ] = .Array~new Return 0 ::Method exists Class Expose queues Use Strict Arg name If \ self~valid( name ) Then Return 0 Return queues~hasIndex( Upper( name ) )~?( 1, 0 ) ::Method delete Class Expose queues waits Use Strict Arg name If \ self~valid( name ) Then Return 5 name = Upper( name ) If name == "SESSION" Then Return 5 If \ queues~hasIndex( name ) Then Return 9 w = waits[ name ] If w \== .Nil Then If w~waiting~items > 0 Then Return 10 queues~remove( name ) waits~remove( name ) Return 0 -- Add a line (at the head: lifo); what LINEIN waits on is posted. ::Method add Class Expose queues waits Use Strict Arg name, line, lifo If \ self~valid( name ) Then Return 5 q = queues[ Upper( name ) ] If q == .Nil Then Return 9 If lifo Then q~insert( line, .Nil ) Else q~append( line ) w = waits[ Upper( name ) ] If w \== .Nil Then Do w~post w~reset End Return 0 -- The same; an error is 48.1 (ooRexx's RexxQueue's PUSH and QUEUE). ::Method addOrFail Class Use Strict Arg name, line, lifo rc = self~add( name, line, lifo ) If rc == 0 Then Return Select Case rc When 5 Then reason = "RXQUEUE_BADQNAME" When 9 Then reason = "RXQUEUE_NOTREG" Otherwise reason = "RXQUEUE_ACCESS" End Raise Syntax 48.1 Array( "SYSTEM QUEUE ("reason")" ) -- The head line, removed; .Nil when there is none (or no such queue). ::Method pull Class Expose queues Use Strict Arg name If \ self~valid( name ) Then Return .Nil q = queues[ Upper( name ) ] If q == .Nil Then Return .Nil If q~isEmpty Then Return .Nil line = q[1] q~delete( 1 ) Return line ::Method count Class Expose queues Use Strict Arg name If \ self~valid( name ) Then Return 0 q = queues[ Upper( name ) ] If q == .Nil Then Return 0 Return q~items ::Method clear Class Expose queues Use Strict Arg name If \ self~valid( name ) Then Return 5 q = queues[ Upper( name ) ] If q == .Nil Then Return 9 q~empty Return 0 -- What LINEIN waits on for a queue: made by 'maker' (an EventSemaphore's -- native value) the first time. ::Method waitFor Class Expose waits Use Strict Arg name, maker w = waits[ Upper( name ) ] If w == .Nil Then Do w = maker~new waits[ Upper( name ) ] = w End Return w -- The queues as text, for the programs a command starts (the queues are -- shared through a file: see RVM.CommandHost~run and rxqueue.rex): a line -- "RVMQUEUES 1 counter", then for each queue a line "NAME items" and, for -- each line of the queue, its length, a blank, the line and a newline. ::Method snapshot Class Expose queues counter nl = "0A"x out = .MutableBuffer~new( "RVMQUEUES 1" counter || nl ) -- SESSION first, then the others by name. names = .Array~of( "SESSION" ) Do name Over queues~allIndexes~sort If name \== "SESSION" Then names~append( name ) End Do name Over names q = queues[ name ] out~append( name q~items || nl ) Do line Over q out~append( Length( line ) line || nl ) End End Return out~string -- The queues from a snapshot (.False when it is not one): the queues it -- does not have are gone, and what LINEIN waits on is posted for the queues -- that have lines. ::Method restore Class Expose queues waits counter Use Strict Arg text nl = "0A"x e = Pos( nl, text ) If e == 0 Then Return .False head = Left( text, e - 1 ) If \ head~startsWith( "RVMQUEUES 1 " ) Then Return .False pos = Length( head ) + 2 new = .Directory~new Do While pos <= Length( text ) e = Pos( nl, text, pos ) If e == 0 Then Leave Parse Value SubStr( text, pos, e - pos ) With name n pos = e + 1 q = .Array~new Do n b = Pos( " ", text, pos ) len = SubStr( text, pos, b - pos ) q~append( SubStr( text, b + 1, len ) ) pos = b + 1 + len + 1 End new[ name ] = q End If \ new~hasIndex( "SESSION" ) Then new[ "SESSION" ] = .Array~new c = SubStr( head, 13 ) If c~dataType( "W" ) Then counter = Max( counter, c ) queues = new Do name Over waits~allIndexes If \ new~hasIndex( name ) Then waits~remove( name ) Else If new[ name ]~items > 0 Then Do w = waits[ name ] w~post w~reset End End Return .True