/******************************************************************************/ /* */ /* RVM.Objects.cls - The object model of the RVM */ /* ============================================ */ /* */ /* Three layers (see doc/08-objects.md): */ /* */ /* 0. The target's leaves: strings and numbers (the Classic values, never */ /* boxed), and whatever native value an object wraps (a Directory). */ /* 1. The RVM: an object (RVM.Obj) is its behaviour (RVM.Behaviour: a */ /* table of methods, name -> RVM.Method), its variable pools, and its */ /* native value. A method is native (here) or R-code. */ /* 2. The ooRexx model on top: a class is an object whose native value is */ /* its RVM.ClassData (id, superclass, its own instance and class */ /* methods, its metaclass); the behaviour of its instances is the */ /* flattened table of the instance methods of its superclass chain, and */ /* its own behaviour is that of its metaclass's instances plus the */ /* class methods of its chain. */ /* */ /* A string or a number has the behaviour of the String class, by type. */ /* */ /* Natives never call user code: a native can only END by delegating (an */ /* RVM.Delegate: "send this message, and the result is ..."): NEW sends INIT, */ /* SEND sends its message. */ /* */ /* 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 behaviours of */ /* objects and classes (RexxBehaviour, MethodDictionary, ClassClass.cpp), and */ /* the behaviour of the classes of ooRexx, method by method. 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 */ /* */ /******************************************************************************/ ::Requires "modules/rvm/RVM.Number.cls" ::Requires "modules/rvm/RVM.BIFs.cls" /******************************************************************************/ /* RVM.Obj -- an object */ /******************************************************************************/ ::Class RVM.Obj Public ::Attribute beh -- its behaviour (RVM.Behaviour) ::Attribute native -- its native value (a class: its RVM.ClassData) ::Attribute objName -- its OBJECTNAME, or .Nil (the default name) ::Attribute pools -- its variable pools, per scope ::Attribute oid -- its identity number (IDENTITYHASH) ::Attribute dirMethods -- a Directory's SETMETHOD entries (RVM.DirMethods) ::Attribute count Class -- the objects created so far ::Method activate Class self~count = 0 self~conversions = .IdentityTable~new self~requests = .IdentityTable~new self~pending = .Nil self~pendingMessage = "STRING" self~reporter = .Nil self~sender = .Nil ::Method init Expose beh native objName pools oid dirMethods Use Strict Arg beh, native = .Nil objName = .Nil pools = .Nil dirMethods = .Nil .RVM.Obj~count += 1 oid = .RVM.Obj~count -- The variable pool of a scope (a class): created when first needed. ::Method pool Expose pools Use Strict Arg scope If pools == .Nil Then pools = .IdentityTable~new p = pools[ scope ] If p == .Nil Then Do p = .RVM.Pool~new pools[ scope ] = p End Return p -- Is it a class object? ::Method isClass Expose native Return native~isA( .RVM.ClassData ) -- Its class (a class object). ::Method rvmClass Expose beh Return beh~cls -- DEFAULTNAME: "The X class" for a class, "enhanced X" for an object made -- by ENHANCED, "a X" or "an X" otherwise. ::Method defaultName Expose native beh If native~isA( .RVM.ClassData ) Then Return "The" native~id "class" If beh~enhanced Then Return "enhanced" beh~cls~native~id Return Article( beh~cls~native~id ) -- OBJECTNAME. ::Method objectName Expose objName If objName \== .Nil Then Return objName Return self~defaultName -- Is its name made by Rexx code? ooRexx's stringValue sends OBJECTNAME, and -- Object's OBJECTNAME, with no name set, sends DEFAULTNAME: either may be a -- method written in Rexx. ::Method nameInRexx Expose beh m = beh~lookup( "OBJECTNAME" ) If m \== .Nil Then If m~isCode Then Return .True Return self~defaultNameInRexx -- Does Object's OBJECTNAME send a DEFAULTNAME written in Rexx (no name set)? ::Method defaultNameInRexx Expose beh objName If objName \== .Nil Then Return .False m = beh~lookup( "DEFAULTNAME" ) If m == .Nil Then Return .False Return m~isCode -- Its name as ooRexx's stringValue gives it (RexxObject::stringValue: the -- OBJECTNAME message). A name made in Rexx is asked for now (sendSync, as -- ooRexx's sendMessage), where no instruction can be run again: the trace, -- an error message, the items of an Array's toString. -- With 'safe' (an error message's substitution, ooRexx's -- messageSubstitution: requestingString and its try): asked for once at a -- time, and an error there gives the default name. ::Method stringName Use Strict Arg safe = .False If \ self~nameInRexx Then Return self~objectName r = .RVM.Obj~reporter If r == .Nil Then Return self~objectName If safe Then Do If .RVM.Obj~naming == .True Then Return self~objectName .RVM.Obj~naming = .True Signal On Syntax Name NameFailed End v = r~world~loader~sendSync( self, "OBJECTNAME", .Array~new ) If safe Then .RVM.Obj~naming = .False If v == .Nil Then Return self~objectName If v~isA( .RVM.Obj ) Then Return v~objectName Return str( v ) NameFailed: .RVM.Obj~naming = .False Return self~objectName -- (A name made in Rexx for an error message is being asked for.) ::Attribute naming Class -- What the trace shows (as ooRexx: its object name, never its STRING; a -- stem's is its default's; a StackFrame's, its traceback line, as ooRexx's -- StackFrameClass~stringValue; an instance of a subclass of String, its -- string, as RexxString~stringValue). ::Method string Expose native Use Strict Arg safe = .False -- (see stringName) If native~isA( .String ) Then Return native If native~isA( .RVM.Stem ) Then Return StemString( native ) If native~isA( .RVM.VarRef ) Then Return native~string If native~isA( .RVM.MBuffer ) Then Return native~text If native~isA( .RVM.FrameInfo ) Then Return native~traceLine Return self~stringName( safe ) -- Its string value, when the RVM needs one (a concatenation, SAY, a -- built-in function...): its STRING method. A native one runs here; one -- written in Rexx needs the machine: this raises the condition the machine -- catches (RVM.NeedString), runs the method, keeps its result for the -- instruction (conversions) and runs the instruction again. -- This is ooRexx's requestString: what converts without STRING (a -- MutableBuffer's text, an array's MAKESTRING, a MAKESTRING written in Rexx: -- REQUEST STRING) gives no condition; anything else is its STRING, and the -- NOSTRING condition is raised (see RVM.BaseContext~noString). -- (raise = .False: no condition, as when a program's result becomes its exit -- code: that is not converted in the activation.) ::Method stringValue Expose beh native Use Strict Arg raise = .True -- A MutableBuffer: its text (ooRexx's MutableBuffer~primitiveMakeString). If native~isA( .RVM.MBuffer ) Then Return native~text -- An instance of a subclass of String: its string (unless the subclass -- makes one in Rexx: see below). If native~isA( .String ) Then Do m = beh~lookup( "MAKESTRING" ) If m == .Nil Then Return native If \ m~isCode Then Return native End -- An array: its MAKESTRING (ooRexx asks for a string with REQUEST, and an -- array makes one: its items, a line each). One written in Rexx (a class -- of the program, or of the prelude: DateTime, File...): its result. If \ native~isA( .RVM.Stem ), \ native~isA( .RVM.VarRef ) Then Do m = beh~lookup( "MAKESTRING" ) If m \== .Nil Then Do If m~key == "V.MAKESTRING", native~isA( .Array ) Then Return ArrayString( self, "L" ) If m~isCode Then Do v = self~requestString If v~isA( .String ) Then Return v If v~isA( .RVM.Number ) Then Return v~string End End End -- A VariableReference: its value's (VariableReference~stringValue); a -- stem: its default's. If native~isA( .RVM.VarRef ) Then v = native~string Else v = self~stringOnly r = .RVM.Obj~reporter If r \== .Nil, raise Then r~noString( v, self ) Return v -- Its STRING (what ooRexx's stringValue gives: an array's items are made -- strings with it). ::Method stringOnly Expose beh native v = .RVM.Obj~conversions[ self ] If v \== .Nil Then Return v If native~isA( .RVM.Stem ) Then Return StemString( native ) If native~isA( .RVM.MBuffer ) Then Return native~text If native~isA( .String ) Then Do m = beh~lookup( "STRING" ) If m == .Nil Then Return native If \ m~isCode Then Return native End If native~isA( .RVM.VarRef ) Then Return native~string m = beh~lookup( "STRING" ) If m == .Nil Then Return self~objectName -- A StackFrame: its traceback line (ooRexx's StackFrameClass~stringValue). If native~isA( .RVM.FrameInfo ) Then Return native~traceLine -- Object's STRING: its name, which may be made in Rexx (OBJECTNAME or -- DEFAULTNAME): then STRING is sent, as one written in Rexx (below). If \ m~isCode, \ self~nameInRexx Then Return self~objectName .RVM.Obj~pending = self .RVM.Obj~pendingMessage = "STRING" Raise Syntax 93.900 Additional( "RVM: STRING" ) Description( "RVM.NeedString" ) -- Its REQUEST STRING: what its MAKESTRING gives, or .Nil when it has none. -- One written in Rexx runs as a STRING in Rexx does (see stringValue: -- RVM.NeedString, the machine sends MAKESTRING and runs the instruction -- again; the result is in 'requests'). ::Method requestString Expose beh native -- A VariableReference: its value's (a primitive class: its stringValue). If native~isA( .RVM.VarRef ) Then Return native~string -- A stem: its default's (ooRexx's StemClass~request). If native~isA( .RVM.Stem ) Then Do v = native~value If v~isA( .RVM.Obj ) Then Return v~requestString Return str( v ) End m = beh~lookup( "MAKESTRING" ) If m == .Nil Then Return .Nil If \ m~isCode Then Return self~stringValue v = .RVM.Obj~requests[ self ] If v \== .Nil Then Return v .RVM.Obj~pending = self .RVM.Obj~pendingMessage = "MAKESTRING" Raise Syntax 93.900 Additional( "RVM: MAKESTRING" ) Description( "RVM.NeedString" ) -- Conversions done for the instruction running (object -> string): STRING -- (conversions) and MAKESTRING (requests); the message the machine must -- send (pendingMessage) to the object that needs it (pending). ::Attribute conversions Class ::Attribute requests Class -- The context of the activity running (the machine sets it: see -- RVM.Machine~run), which raises NOSTRING (see stringValue). ::Attribute reporter Class -- Who sends RUN, SETMETHOD or UNSETMETHOD (the machine sets it: see -- CheckRestricted). ::Attribute sender Class ::Attribute pending Class ::Attribute pendingMessage Class ::Routine Article Public Use Strict Arg id If Pos( Upper( Left( id, 1 ) ), "AEIOU" ) > 0 Then Return "an" id Return "a" id /******************************************************************************/ /* RVM.Behaviour -- the methods of its objects, and their class */ /* */ /* A port of ooRexx's RexxBehaviour and MethodDictionary: every method of a */ /* name, the first found first (a message finds the first one; a method */ /* hidden by DEFINE or SETMETHOD with no method is the 'hidden' marker), and */ /* the scopes (classes) in the order they were added, each with the scopes */ /* before it when it was added: ~name:scope finds the first method whose */ /* scope is that one or one before it (findSuperMethod), and a method's */ /* SUPER is the last scope before its own (resolveSuperScope). */ /******************************************************************************/ ::Class RVM.Behaviour Public ::Attribute cls -- the class of the objects with this behaviour ::Attribute contents -- NAME -> Array of RVM.Method (or 'hidden') ::Attribute scopeList -- its scopes, in the order they were added ::Attribute scopeOrders -- scope -> the scopes before it (an Array) ::Attribute instMethods -- the methods SETMETHOD added (NAME -> method), or .Nil ::Attribute enhanced -- an object's made by ENHANCED (its default name) ::Attribute hidden Class -- a method hidden (ooRexx's .nil in the table) ::Method activate Class self~hidden = .Object~new ::Method init Expose cls instMethods Use Strict Arg cls self~clear instMethods = .Nil self~enhanced = .False -- No methods and no scopes (clearMethodDictionary). ::Method clear Expose contents scopeList scopeOrders contents = .Table~new scopeList = .Array~new scopeOrders = .IdentityTable~new -- A copy that changes apart from this one (RexxBehaviour~copy). ::Method copyBehaviour Expose cls contents scopeList scopeOrders instMethods b = .RVM.Behaviour~new( cls ) t = .Table~new Do With Index name Item list Over contents t[ name ] = list~copy End b~contents = t b~scopeList = scopeList~copy b~scopeOrders = scopeOrders~copy If instMethods \== .Nil Then b~instMethods = instMethods~copy b~enhanced = self~enhanced Return b -- The method a message finds (methodLookup): .Nil when none, or hidden. ::Method lookup Expose contents Use Strict Arg name list = contents[ name ] If list == .Nil Then Return .Nil m = list[1] If m == .RVM.Behaviour~hidden Then Return .Nil Return m -- Add a method (addMethod): one with the same scope is replaced; else it -- goes first. A hidden one (.Nil) always goes first. ::Method addMethod Expose contents Use Strict Arg name, m hidden = .RVM.Behaviour~hidden If m == .Nil Then m = hidden list = contents[ name ] If list == .Nil Then Do contents[ name ] = .Array~of( m ) Return End If m \== hidden Then Do i = 1 To list~items x = list[i] If x == hidden Then Iterate If x~scope == m~scope Then Do list[i] = m Return End End list~insert( m, .Nil ) -- Remove the first method of a name (remove); was there one? ::Method removeMethod Expose contents Use Strict Arg name list = contents[ name ] If list == .Nil Then Return .False list~delete( 1 ) If list~isEmpty Then contents~remove( name ) Return .True -- The methods of a table (a class's own: NAME -> RVM.Method, or .Nil). ::Method mergeTable Use Strict Arg t Do With Index name Item m Over t self~addMethod( name, m ) End -- The methods and scopes of another behaviour (merge): its methods keep -- their order, on top of these; its scopes not here go last. ::Method mergeBehaviour Expose contents Use Strict Arg b Do With Index name Item list Over b~contents Do i = list~items To 1 By -1 m = list[i] If m == .RVM.Behaviour~hidden Then Do mine = contents[ name ] If mine == .Nil Then contents[ name ] = .Array~of( m ) Else mine~insert( m, .Nil ) End Else self~addMethod( name, m ) End End Do s Over b~scopeList self~addScope( s ) End -- A scope, last (once), with the scopes before it. ::Method addScope Expose scopeList scopeOrders Use Strict Arg scope If scopeOrders~hasIndex( scope ) Then Return scopeOrders[ scope ] = scopeList~copy scopeList~append( scope ) ::Method hasScope Expose scopeOrders Use Strict Arg scope Return scopeOrders~hasIndex( scope ) -- ~name:start (findSuperMethod): the first method whose scope is 'start' or -- one of the scopes before it. ::Method superMethod Expose contents scopeOrders Use Strict Arg name, start scopes = scopeOrders[ start ] If scopes == .Nil Then Return .Nil list = contents[ name ] If list == .Nil Then Return .Nil Do m Over list If m == .RVM.Behaviour~hidden Then Iterate If m~scope == start Then Return m If m~scope \== .Nil, scopes~hasItem( m~scope ) Then Return m End Return .Nil -- The SUPER of a method of scope 'scope' (superScope): the scope before it; -- the class of the objects for a method with no scope (SETMETHOD's). ::Method superScope Expose cls scopeOrders Use Strict Arg scope If scope == .Nil Then Return cls scopes = scopeOrders[ scope ] If scopes == .Nil Then Return .Nil If scopes~isEmpty Then Return .Nil Return scopes~lastItem -- SETMETHOD (addInstanceMethod): first, replacing one SETMETHOD added. ::Method addInstanceMethod Expose contents instMethods Use Strict Arg name, m If instMethods == .Nil Then instMethods = .Table~new Else If instMethods~hasIndex( name ) Then self~removeMethod( name ) If m == .Nil Then m = .RVM.Behaviour~hidden list = contents[ name ] If list == .Nil Then contents[ name ] = .Array~of( m ) Else list~insert( m, .Nil ) instMethods[ name ] = m -- UNSETMETHOD (removeInstanceMethod): only one SETMETHOD added. ::Method removeInstanceMethod Expose instMethods Use Strict Arg name If instMethods == .Nil Then Return If \ instMethods~hasIndex( name ) Then Return instMethods~remove( name ) self~removeMethod( name ) -- Every method (with those a nearer one hides), or those of one scope -- (getMethods): two arrays, the names and the methods. ::Method allMethods Expose contents Use Strict Arg scope = .Nil names = .Array~new items = .Array~new Do With Index name Item list Over contents Do m Over list If m == .RVM.Behaviour~hidden Then Iterate If scope \== .Nil, m~scope \== scope Then Iterate names~append( name ) items~append( m ) End End Return .Array~of( names, items ) /******************************************************************************/ /* RVM.MethodFrame -- the variables of a method's activation */ /* */ /* A frame (RVM.Vars), as those of the context are, where EXPOSE puts the */ /* object's variables (of the pool of the method's scope) themselves: every */ /* activation that exposes them shares them. After USE LOCAL, every name not */ /* declared local is the object's variable, from its first reference on */ /* (resolve: ooRexx's autoExpose). */ /******************************************************************************/ ::Class RVM.MethodFrame Public SubClass RVM.Vars ::Method init Expose pool locals Use Strict Arg pool locals = .Nil self~init:super -- The object's variables it shares (of the method's scope). ::Method pool Expose pool Return pool -- EXPOSE name (a simple variable, or a stem "A."). ::Method share Expose pool Use Strict Arg name self[ name ] = pool~cell( name, .True ) -- USE LOCAL: the names (blank-separated) are local, and so are RC, RESULT, -- SIGL, SELF and SUPER; every other variable is the object's from its first -- reference on (ooRexx's autoExpose). A stem declared local is made now. ::Method useLocal Expose locals Use Strict Arg names locals = .Set~of( "SELF", "SUPER", "RC", "RESULT", "SIGL" ) Do w = 1 To Words( names ) name = Word( names, w ) locals~put( name ) If Right( name, 1 ) == "." Then Do v = self~cell( name, .True ) If v~value == .Nil Then v~value = .RVM.Stem~new( name ) End End -- A name it does not have: after USE LOCAL, one not declared local is the -- object's variable (from now on). ::Method resolve Expose pool locals Use Strict Arg name If locals == .Nil Then Return .Nil If locals~hasIndex( name ) Then Return .Nil v = pool~cell( name, .True ) self[ name ] = v Return v -- Is the variable of 'name' its own (not the object's)? ::Method isLocal Expose pool Use Strict Arg name Return pool[ name ] \== self[ name ] /******************************************************************************/ /* RVM.Level -- an activation, as ooRexx's RexxContext and StackFrame see it: */ /* what runs (a method, a routine, a program: its prolog), how it was called, */ /* its .RS, and its RexxContext object (made once, when asked; it is over */ /* when the activation ends). The machine makes one per activation (see */ /* RVM.Context); an INTERPRET has one too (a StackFrame), but .CONTEXT in it */ /* is its parent's. */ /******************************************************************************/ ::Class RVM.Level Public ::Attribute type -- PROGRAM, ROUTINE, METHOD, INTERNALCALL, INTERPRET ::Attribute name -- the name it was called by (a program: its path) ::Attribute exec -- what runs: an RVM.Method (kind M), an RVM.Routine ::Attribute kind -- (R), or a program (P: its prolog) ::Attribute target -- a method's receiver (.Nil) ::Attribute sender -- the receiver of the method whose code runs (.Nil: a -- program's, a routine's): who sends its messages -- (PRIVATE; ooRexx's getReceiver) ::Attribute args -- its arguments (an Array of the host) ::Attribute rs -- .RS: 0, 1, -1 (.Nil: no command yet) ::Attribute ctx -- its RexxContext object, once made ::Attribute active -- .False when it is over ::Attribute parent -- an INTERPRET: the activation it runs in ::Attribute id -- its invocation number (0: not given yet) -- A method's activation: the variable pool of its scope (an RVM.Pool), and -- whether it has its lock (ooRexx's objectScope: SCOPE_RESERVED); REPLY was -- issued. ::Attribute pool ::Attribute locked ::Attribute replied -- Message~halt: a HALT is pending for it (ooRexx's haltCondition), with its -- description (.Nil: none). ::Attribute haltPending ::Attribute haltDesc -- An external TRACE (hostemu TS, TE: ooRexx's externalTraceOn/Off) for its -- next clause boundary: "?R", "O", or .Nil. ::Attribute extTrace -- The activity it runs in (its number: RexxContext~thread), noted when its -- RexxContext is made (.CONTEXT, in it); .Nil until then. ::Attribute thread -- Message~send: the message it sent, to mark with an error that goes up -- through it (ooRexx's notifyObject), until it completes. ::Attribute notifyMsg -- FORWARD without CONTINUE: it has become a phantom (ooRexx's setForwarded -- and stopExecution); no trap of its own takes an error from then on. ::Attribute forwarded -- The invocation numbers are given when first asked for, as ooRexx's. ::Attribute counter Class ::Method init Expose type name exec kind target args rs ctx active parent id pool locked - replied haltPending haltDesc notifyMsg forwarded Use Strict Arg type, args = ( .Array~new ) name = ""; exec = .Nil; kind = ""; target = .Nil; rs = .Nil; ctx = .Nil self~sender = .Nil active = .True; parent = .Nil; id = 0 pool = .Nil; locked = .False; replied = .False haltPending = .False; haltDesc = .Nil; notifyMsg = .Nil self~extTrace = .Nil self~thread = .Nil forwarded = .False -- It lets its lock go (GUARD OFF, the end of the activation). ::Method unlock Expose pool locked If \ locked Then Return locked = .False pool~release -- It runs the code of another (an internal routine, an INTERPRET, the first -- activation of a sendSync). ::Method runs Expose exec kind Use Strict Arg other exec = other~exec kind = other~kind self~sender = other~sender -- Its invocation number. ::Method invocation Expose id If id == 0 Then Do n = .RVM.Level~counter If \ DataType( n, "W" ) Then n = 0 id = n + 1 .RVM.Level~counter = id End Return id -- It is over: its RexxContext is no longer active. ::Method close Expose active active = .False /******************************************************************************/ /* RVM.NativeCall -- a native running (a line of a traceback: "Compiled */ /* method"): its method, receiver, message and arguments (a StackFrame). Or */ /* a source compiled at run time that does not parse (compileAt: the line; */ /* its name is the source's): ooRexx's COMPILE frame. */ /******************************************************************************/ ::Class RVM.NativeCall Public ::Attribute text -- its traceback line ::Attribute method -- its RVM.Method ::Attribute target -- its receiver ::Attribute name -- the message ::Attribute args -- its arguments (an Array of the host) ::Attribute compileAt ::Attribute lib -- a routine of a library: its entry (lr; .Nil: none) ::Attribute compilePackage -- a source that does not translate: its package -- The packages of the methods and routines it compiled that must be -- installed before its result is (see PendingInstall): (program, name) -- pairs, or .Nil. ::Attribute installs -- Some native has installs pending (the machine looks after each one). ::Attribute pending Class ::Method activate Class self~pending = .False ::Method init Expose text method target name args compileAt lib compilePackage installs Use Strict Arg text, method = .Nil, target = .Nil, name = "", args = ( .Array~new ) compileAt = .Nil lib = .Nil compilePackage = .Nil installs = .Nil ::Method string Expose text Return text /******************************************************************************/ /* RVM.FrameInfo -- a StackFrame (ooRexx's StackFrameClass): its type (those */ /* of RVM.Level, or COMPILE), name, what ran (exec, of kind M, R or P, as a */ /* level's), receiver, arguments, traceback line and line number (.Nil: */ /* none); the activation (level: its invocation and RexxContext; .Nil for a */ /* native or a source that does not parse); and its package (an RVM.Program; */ /* .Nil: none; "REXX": the REXX package). */ /******************************************************************************/ ::Class RVM.FrameInfo Public ::Attribute type ::Attribute name ::Attribute exec ::Attribute kind ::Attribute target ::Attribute args ::Attribute traceLine ::Attribute line ::Attribute level ::Attribute package ::Method init Expose type name exec kind target args traceLine line level package Use Strict Arg type, name, traceLine, line = .Nil exec = .Nil; kind = ""; target = .Nil; args = .Nil; level = .Nil package = .Nil -- The frame of an activation. ::Method ofLevel Class Use Strict Arg lv, traceLine, line f = self~new( lv~type, lv~name, traceLine, line ) f~exec = lv~exec f~kind = lv~kind f~target = lv~target f~args = lv~args f~level = lv f~package = LevelPackage( lv ) Return f -- The frame of a native (an RVM.NativeCall, or only its line: a method of -- the stream objects of the REXX package). ::Method ofNative Class Use Strict Arg nc If nc~isA( .RVM.NativeCall ) Then Do If nc~compileAt \== .Nil Then Do f = self~new( "COMPILE", nc~name, nc~text, nc~compileAt ) f~package = nc~compilePackage Return f End -- (A native routine, REXXUTIL's: 'Compiled routine', a ROUTINE.) type = "METHOD" If nc~method == .Nil, nc~text~pos( '*-* Compiled routine "' ) > 0 Then type = "ROUTINE" f = self~new( type, nc~name, nc~text ) f~exec = nc~method f~kind = "M" -- (A routine of a library: its Routine object. The frame has no package: -- an error its code raises is the caller's.) If nc~lib \== .Nil Then Do f~exec = nc~lib f~kind = "LR" End f~target = nc~target f~args = nc~args If nc~method \== .Nil Then f~package = nc~method~home Return f End Parse Var nc . 'Compiled method "' name '"' f = self~new( "METHOD", name, nc ) f~package = "REXX" Return f -- The traceback line of a native running (a line, or an RVM.NativeCall). ::Routine NativeText Public Use Strict Arg nc If nc~isA( .RVM.NativeCall ) Then Return nc~text Return nc -- The package an activation runs in: its method's, its routine's, its -- program's ("REXX": a method of the REXX package; .Nil: none). ::Routine LevelPackage Public Use Strict Arg lv Select Case lv~kind When "M" Then Do If lv~exec~home == .Nil Then Return "REXX" Return lv~exec~home End When "R" Then Return lv~exec~program When "P" Then Return lv~exec Otherwise Return .Nil End /******************************************************************************/ /* RVM.Method -- a method: native (key) or R-code */ /******************************************************************************/ ::Class RVM.Method Public ::Attribute name ::Attribute scope -- the class that defines it ::Attribute scoped -- it was given a scope (NewScope), .NIL too ::Attribute key -- a native: its key in CallNative ::Attribute min -- the arguments it requires ::Attribute max -- the arguments it takes (-1: any) ::Attribute argName -- a missing argument is 88.901 with this name -- A method written in Rexx (key "R"): its program, its code, its labels and -- the clause of its first instruction. ::Attribute program ::Attribute address ::Attribute labels ::Attribute firstClause ::Attribute var -- an attribute (keys A.GET, A.SET): its variable ::Attribute value -- a constant (A.CONST): its value -- Written in Rexx but compiled in ooRexx (the RVM's part of the prelude): a -- traceback shows it as a "Compiled method" line (see RVM.Machine's Failed). ::Attribute compiled -- Its options: P (private), R (protected), K (package), U (unguarded), A -- (an attribute's), or "-" (see RVM.Compiler's MethodFlags); where its source is in its home -- program (l.c-l.c, or "-"); its Method object, once made (see methodObject). ::Attribute flags ::Attribute extent ::Attribute home ::Attribute obj -- Its annotations (::ANNOTATE METHOD...): the pairs (name, value), and their -- StringTable, once made (see RVM.World~annotationsOf). ::Attribute annotations ::Attribute annotationsObj ::Method init Expose name scope key min max argName compiled flags extent home obj - annotations annotationsObj Use Strict Arg name, scope, key, min, max, argName = "" annotations = .Array~new annotationsObj = .Nil compiled = .False flags = "-" extent = "-" home = .Nil obj = .Nil ::Method hasFlag Expose flags Use Strict Arg f Return flags~pos( f ) > 0 ::Method isCode Expose key Return key == "R" /******************************************************************************/ /* RVM.ClassData -- the native value of a class object */ /******************************************************************************/ ::Class RVM.ClassData Public ::Attribute id ::Attribute superclass -- a class object, or .Nil (Object) ::Attribute superclasses -- its superclass, then the classes it inherits ::Attribute subclasses -- the classes made from it or inheriting it, the last first ::Attribute imethods -- its own instance methods: NAME -> RVM.Method (.Nil: hidden) ::Attribute cmethods -- its own class methods ::Attribute metaclass -- a class object ::Attribute isMeta -- is it a metaclass (Class, or a subclass of one)? -- What its instances wrap: OBJECT, CLASS, DIRECTORY, ARRAY, LIST, QUEUE, -- TABLE, IDTABLE, SET, BAG, RELATION, SUPPLIER or STEM. ::Attribute kind ::Attribute instBeh -- the behaviour of its instances (.Nil: not built) ::Attribute mixin -- is it a MIXINCLASS? ::Attribute baseClass -- its own; a mixin's is its superclass's ::Attribute primitive -- a class of the RVM (not made by SUBCLASS or NEW) ::Attribute bare -- made by Class's NEW, not by SUBCLASS: its behaviours -- are copies, never made again ::Attribute rexx -- a class of the REXX package (DEFINE: 98.985) ::Attribute home -- the program of its ::CLASS (PACKAGE), or .Nil ::Attribute abstract -- ::CLASS ... ABSTRACT: NEW is 98.989 -- Its annotations (::ANNOTATE CLASS): the pairs (name, value), and their -- StringTable, once made (see RVM.World~annotationsOf). A class made by -- SUBCLASS or NEW has none, and is not abstract. ::Attribute annotations ::Attribute annotationsObj ::Method init Expose id superclass superclasses subclasses imethods cmethods metaclass - isMeta kind instBeh mixin baseClass primitive rexx home bare - abstract annotations annotationsObj Use Strict Arg id, superclass, metaclass, kind superclasses = .Array~new If superclass \== .Nil Then superclasses~append( superclass ) subclasses = .Array~new imethods = .Table~new cmethods = .Table~new isMeta = .False instBeh = .Nil mixin = .False baseClass = .Nil primitive = .False bare = .False rexx = .False home = .Nil abstract = .False annotations = .Array~new annotationsObj = .Nil /******************************************************************************/ /* RVM.SupplierState -- the native value of a Supplier: its items and indexes */ /* (host arrays, as they were when it was made) and the position of the */ /* current one. It is available while the position is within the items' size, */ /* and until ALLITEMS or ALLINDEXES drain it (they give what is left from the */ /* position, and they do each time: the position does not move; ooRexx). */ /******************************************************************************/ ::Class RVM.SupplierState Public ::Attribute items ::Attribute indexes ::Attribute pos ::Attribute drained ::Method init Expose items indexes pos drained Use Strict Arg items, indexes pos = 1 drained = .False ::Method available Expose items pos drained Return \ drained & pos <= items~size /******************************************************************************/ /* RVM.Delegate -- a native ends by sending a message */ /* */ /* The machine sends 'name' to 'receiver' with 'args'; the result of the */ /* first native is 'result' when it is not .Nil (NEW: the new object). */ /******************************************************************************/ ::Class RVM.Delegate Public ::Attribute receiver ::Attribute name ::Attribute args ::Attribute result ::Attribute scope -- where the search starts (.Nil: the receiver's) ::Attribute method -- the method to run (.Nil: the one the message finds) -- What runs when the message returns (.Nil: nothing): an object whose NEXT -- (result, context) gives the result, or another RVM.Delegate. Natives that -- send more than one message (SUBCLASS: NEW, then INIT) go on so. ::Attribute then -- The message a native's deferred messages held back, sent again (see -- RVM.Resend): it is the message itself, not a delegation (its private -- check applies). ::Attribute resend ::Method init Expose receiver name args result scope method then resend Use Strict Arg receiver, name, args, result = .Nil scope = .Nil method = .Nil then = .Nil resend = .False -- What runs when a delegated message returns: its result, or .NIL when it -- returned none (ooRexx's resultOrNil). ::Class RVM.OrNil Public ::Method init Expose nil Use Strict Arg nil ::Method next Expose nil Use Strict Arg v, context If .Nil == v Then Return nil Return v -- A native ends by calling a routine (Routine's CALL): the machine calls it -- as an external routine, and its result is the message's. ::Class RVM.RoutineCall Public ::Attribute routine ::Attribute args ::Method init Expose routine args Use Strict Arg routine, args -- A native ends by loading a package (loadPackage, Package~new): the machine -- runs its prolog if it has not started (see EnterPackageRun), and 'result' -- (its Package object) is the message's; 'addTo' (a program, or .Nil) adds -- it then. With 'install' (the name of a method or routine compiled at run -- time; .Nil: none) the package is only installed (its requires started, -- its classes made: no prolog), and 'result' is what the native gave (a -- value, .Nil, or a delegate or another PackageRun to go on with). ::Class RVM.PackageRun Public ::Attribute program ::Attribute result ::Attribute addTo ::Attribute runInit -- INIT is sent to the result after the prolog (Package~new) ::Attribute install ::Method init Expose program result addTo runInit install Use Strict Arg program, result, addTo = .Nil runInit = .False install = .Nil -- The scope of the last message name made by MessageName (see there). ::Class RVM.MessageScope Public ::Attribute scope Class /******************************************************************************/ /* RVM.MakeClass -- the steps of a new class (see RVM.World~subclass): NEW */ /* has made it (v); then INIT; then 'then' goes on with it. */ /******************************************************************************/ ::Class RVM.MakeClass Public ::Method init Expose world receiver meta methods home mixin after state Use Strict Arg world, receiver, meta, methods, home, mixin, after state = "NEW" ::Method next Expose world receiver meta methods home mixin after state c Use Strict Arg v, context If state == "NEW" Then Do ok = v~isA( .RVM.Obj ) If ok Then ok = v~isClass If \ ok Then Raise Syntax 93.900 Additional( "RVM: the NEW of a metaclass gave no class" ) c = v world~finishSubclass( receiver, c, meta, methods, home ) state = "INIT" d = .RVM.Delegate~new( c, "INIT", .Array~new ) d~then = self Return d End -- A mixin (mixinClass): after INIT; its base class is its superclass's. If mixin Then Do c~native~mixin = .True c~native~baseClass = receiver~native~baseClass End If after \== .Nil Then Return after~next( c, context ) Return c /******************************************************************************/ /* RVM.Enhance -- the steps of ENHANCED: the subclass is made (v); it gets */ /* the methods (scope .NIL), NEW is sent to it, and the object's class is */ /* the one that got ENHANCED. */ /******************************************************************************/ ::Class RVM.Enhance Public ::Method init Expose world cls methods rest state Use Strict Arg world, cls, methods, rest state = "MADE" ::Method next Expose world cls methods rest state Use Strict Arg v, context If state == "MADE" Then Do data = v~native Do With Index name Item m Over methods If m \== .Nil Then m~scope = .Nil data~imethods[ name ] = m End world~rebuildInstanceBehaviour( v ) state = "NEW" d = .RVM.Delegate~new( v, "NEW", rest ) d~then = self Return d End v~beh~cls = cls v~beh~enhanced = .True Return v /******************************************************************************/ /* RVM.Resend -- a message sent again: when what was deferred has run (see */ /* RunNatives), the message the machine was about to send. */ /******************************************************************************/ ::Class RVM.Resend Public ::Method init Expose receiver name args scope Use Strict Arg receiver, name, args, scope ::Method result Return .Nil ::Method then Return self ::Method next Expose receiver name args scope Use Strict Arg v, context d = .RVM.Delegate~new( receiver, name, args ) d~scope = scope d~resend = .True Return d /******************************************************************************/ /* RVM.Installer -- the classes of a program made, as ooRexx's */ /* PackageClass~processInstall and ClassDirective~install do: in order, each */ /* one made by its superclass (SUBCLASS or MIXINCLASS, with its metaclass */ /* and its class methods: INIT runs), then INHERIT sent to it for each mixin, */ /* then its instance methods; when all are made, ACTIVATE is sent to each. */ /* Errors are the ::CLASS directive's. */ /******************************************************************************/ ::Class RVM.Installer Public ::Attribute ready -- the program is READY when it ends ::Method init Expose world program order imethods cmethods pos state made ready byK Use Strict Arg world, program, order, imethods, cmethods pos = 0 state = "" made = .Array~new byK = .Array~new -- the class of each entry ready = .False -- The next class: its metaclass and superclass; SUBCLASS (or MIXINCLASS). ::Method nextClass Expose world program order pos state cmethods Use Strict Arg context pos += 1 If pos > order~items Then Do state = "CONSTANTS" pos = 0 Return self~next( .Nil, context ) End k = order[ pos ] e = program~classes[ k ] context~clause = program~clauses[ e~clause ] meta = .Nil If e~metaNS \== "" Then meta = world~namespaceClass( program, e~metaNS, e~meta ) Else If e~meta \== "" Then Do meta = self~find( e~meta ) If meta == .Nil Then Raise Syntax 98.908 Array( e~meta ) End If e~superNS \== "" Then super = world~namespaceClass( program, e~superNS, e~super ) Else If e~super == "" Then super = world~objectClass Else Do super = self~find( e~super ) If super == .Nil Then Raise Syntax 98.909 Array( e~super ) End state = "MADE" Return world~subclass( super, e~id, meta, cmethods[ k ], program, e~mixin, self ) -- A class by name, as the program sees it (.Nil: none); something that is -- not a class is 99.949 (ooRexx's ClassResolver~lookup). ::Method find Private Expose world program Use Strict Arg name c = program~classObjs[ name ] If c == .Nil Then c = world~env( name, program, .True ) If c == .Nil Then Return .Nil ok = c~isA( .RVM.Obj ) If ok Then ok = c~isClass If \ ok Then Raise Syntax 99.949 Array( name ) Return c ::Method next Expose world program order pos state cls ipos imethods made ready byK Use Strict Arg v, context If state == "MADE" Then Do e = program~classes[ order[ pos ] ] cls = v byK[ order[ pos ] ] = cls program~classObjs[ Upper( e~id ) ] = cls If e~public Then program~publicClasses[ Upper( e~id ) ] = cls made~append( cls ) state = "INHERIT" ipos = 0 End If state == "INHERIT" Then Do k = order[ pos ] e = program~classes[ k ] ipos += 1 If ipos <= e~inherit~items Then Do context~clause = program~clauses[ e~clause ] name = e~inherit[ ipos ] If e~inheritNS[ ipos ] \== "" Then m = world~namespaceClass( program, e~inheritNS[ ipos ], name ) Else Do m = self~find( name ) If m == .Nil Then Raise Syntax 98.909 Array( name ) End d = .RVM.Delegate~new( cls, "INHERIT", .Array~of( m ) ) d~then = self Return d End -- Its instance methods (defineMethods). Do With Index name Item m Over imethods[ k ] m~scope = cls cls~native~imethods[ name ] = m End world~rebuildInstanceBehaviour( cls ) -- Its annotations; ABSTRACT (a metaclass cannot be: 98.990). cls~native~annotations = e~annotations If e~abstract Then Do context~clause = program~clauses[ e~clause ] If cls~native~isMeta Then Raise Syntax 98.990 Array( cls~native~id ) cls~native~abstract = .True End Return self~nextClass( context ) End -- The calculated constants of each class, in the order of the -- directives (ooRexx's resolveConstants): its initializer, a method -- "::CONSTANT" run on the class object. If state == "CONSTANTS" Then Do Loop pos += 1 If pos > program~classes~items Then Leave m = program~classes[ pos ]~constInit If m == .Nil Then Iterate m~scope = byK[ pos ] d = .RVM.Delegate~new( byK[ pos ], "::CONSTANT", .Array~new ) d~method = m d~then = self Return d End state = "ACTIVATE" pos = 0 End -- ACTIVATE, to each class. pos += 1 If pos > made~items Then Do If ready Then program~state = "READY" Return .Nil End d = .RVM.Delegate~new( made[ pos ], "ACTIVATE", .Array~new ) d~then = self Return d /******************************************************************************/ /* Concurrency (ooRexx's Activity, VariableDictionary's reserve, Message) */ /* */ /* An activity (RVM.Activity) is a thread of activations: the main program's, */ /* and one more for every REPLY (the method goes on there) and every START */ /* (the message runs there). The RVM runs one at a time: the one running goes */ /* on until it waits (for a lock, a change of a variable of GUARD WHEN, a */ /* message) or ends; then the scheduler (RVM.Scheduler) takes the first one */ /* ready, in the order they became ready. An activity has a context of its */ /* own, and the registers of the machine while it does not run. */ /* */ /* The variables of an object for a scope (RVM.Pool) have a lock, as those */ /* of ooRexx (VariableDictionary's reserve, release, transfer): a guarded */ /* method takes it; the activity that has it may take it again (the count); */ /* another one waits, in order. The variables GUARD WHEN watches wake the */ /* activities waiting for them when they are set or dropped. */ /******************************************************************************/ ::Class RVM.Activity Public ::Attribute id ::Attribute context -- its RVM.Context ::Attribute isMain -- the main program's ::Attribute state -- NEW, READY, RUNNING, WAITING, ENDED ::Attribute regs -- the machine's registers while it waits (a Directory) ::Attribute resumeAt -- the label the machine goes on at with it ::Attribute waitingOn -- what it waits for: an RVM.Pool, an RVM.MessageState ::Attribute granted -- a lock it was given while it waited (see RVM.Pool) ::Attribute guarding -- GUARD WHEN: it waits for a variable to change ::Attribute relock -- GUARD WHEN: it had the lock before it waited ::Attribute watches -- GUARD WHEN: the variables it watches (pool, name) ::Attribute message -- START: the message it runs (an RVM.MessageState) ::Attribute error -- the condition object of the error that ended it ::Attribute scheduler ::Attribute uninits -- the last one: the objects it sends UNINIT to -- A semaphore it waits for (EventSemaphore, MutexSemaphore, the timers of -- Alarm and Ticker): what the wait gave (1, 0; .Nil: it has not ended), and -- its timer (an RVM.Timer: a wait with a timeout). ::Attribute waitResult ::Attribute timer ::Attribute mutexes -- the MutexSemaphores it holds (ooRexx's addMutex) ::Attribute spawnerInfo -- who started it, for TraceObjects (World~spawnerInfo) ::Attribute syncs -- the contexts of its runSync / sendSync running, innermost last ::Method init Expose id context isMain state regs resumeAt waitingOn granted guarding - relock watches message error scheduler uninits waitResult timer mutexes - syncs Use Strict Arg scheduler, context, isMain = .False id = scheduler~nextId state = "NEW"; regs = .Nil; resumeAt = "RESUME"; waitingOn = .Nil granted = .Nil; guarding = .False; relock = .False; watches = .Nil message = .Nil; error = .Nil; uninits = .Nil waitResult = .Nil; timer = .Nil; mutexes = .Nil syncs = .Array~new -- The context of the code it runs now: that of its innermost runSync / -- sendSync, or its own. ::Method topContext Expose context syncs If syncs~isEmpty Then Return context Return syncs~lastItem -- A semaphore it waited for has given 'r' (1: posted, acquired; 0: the -- timeout): it is ready again. ::Method semDone Expose waitResult timer scheduler Use Strict Arg r waitResult = r If timer \== .Nil Then scheduler~cancelTimer( self ) self~wake -- A circular wait (ooRexx's checkDeadLock): 'target' waits for what this -- one has; if this one waits, directly or not, for what 'target' has, it is -- 98.905. ::Method checkDeadLock Expose waitingOn Use Strict Arg target If waitingOn == .Nil Then Return owner = waitingOn~owningActivity If owner == target Then Raise Syntax 98.905 If owner \== .Nil Then owner~checkDeadLock( target ) -- What it waited for has come: it is ready again. ::Method wake Expose scheduler waitingOn waitingOn = .Nil scheduler~ready( self ) -- GUARD WHEN: a variable it watches has changed (ooRexx's guardPost). ::Method guardPost Expose guarding If \ guarding Then Return guarding = .False self~wake -- GUARD WHEN: it watches the variables 'names' (blank-separated) of 'pool'. ::Method watch Expose watches Use Strict Arg pool, names If watches \== .Nil Then Return watches = .Array~new Do w = 1 To Words( names ) name = Word( names, w ) pool~watch( name, self ) watches~append( .Array~of( pool, name ) ) End ::Method unwatch Expose watches If watches == .Nil Then Return Do w Over watches w[1]~unwatch( w[2], self ) End watches = .Nil -- The activities of a run: those ready (queue, in order), and those that -- have not ended (live). The timers of the waits with a timeout (timers, by -- deadline) run on a clock: the real one (milliseconds), or, with -- RVM_CLOCK=virtual, one that moves only when no activity is ready, to the -- next deadline, at once (the same run every time, and no waiting). ::Class RVM.Scheduler Public ::Attribute queue ::Attribute live ::Attribute current ::Attribute path -- the main program (an error report names it) ::Attribute slice -- clauses an activity runs before the others (0: all) ::Attribute virtual -- the virtual clock (RVM_CLOCK=virtual) ::Attribute timers -- The waits for I/O (the sockets of rxsock: RVM.SockWait; the commands -- that run: RVM.CommandWait), and what polls each -- (RVM.SockPoller~poll(scheduler, ms): -1, until one is ready). ::Attribute ios ::Attribute ioPollers -- The activities whose nested machine waits (RVM.Machine~pump), innermost -- on top: they are not given while they are (their frames are below). ::Attribute trapped ::Method init Expose queue live current count path slice virtual vnow timers start ios ioPollers trapped trapped = .Queue~new ios = .Array~new ioPollers = .IdentityTable~new slice = 10000 queue = .Array~new live = .Array~new current = .Nil count = 0 path = "" virtual = .False vnow = 0 timers = .Array~new start = .Nil -- The clock: milliseconds (since the first time it is asked, for the real -- one). ::Method now Expose virtual vnow start If virtual Then Return vnow Numeric Digits 18 t = Time( "F" ) % 1000 If start == .Nil Then start = t Return t - start -- The time the virtual clock has skipped, in microseconds (0 with the real -- one): TIME and DATE add it to the host's, so that a program that waits -- sees the time pass (SysSleep 1 moves TIME('E') by 1 second). ::Method skipped Expose virtual vnow If \ virtual Then Return 0 Numeric Digits 18 Return Trunc( vnow * 1000 ) -- Activity 'act' waits for 'on' (a semaphore) for 'ms' milliseconds at most: -- then on~timeout(act). Timers of the same deadline go in the order made. ::Method addTimer Expose timers Use Strict Arg act, ms, on t = .RVM.Timer~new( self~now + ms, act, on ) act~timer = t pos = timers~items + 1 Do i = timers~items To 1 By -1 While timers[i]~deadline > t~deadline pos = i End If pos == 1 Then timers~insert( t, .Nil ) -- (first) Else timers~insert( t, pos - 1 ) -- Ctrl-C (ooRexx's Interpreter::haltAllActivities): a HALT, without a -- description, for every activity that has started and not ended, in the -- activation it runs (that of its innermost runSync / sendSync: native's -- top Rexx frame). One in SysSleep wakes now (native's -- sleep is cut short by the signal); other waits go on. ::Method haltAll Expose live Do a Over live If WordPos( a~state, "NEW ENDED" ) > 0 Then Iterate If a~context == .Nil Then Iterate a~topContext~halt( .Nil ) w = a~waitingOn If w~isA( .RVM.EventSem ) Then If w~sleep Then Do self~cancelTimer( a ) w~timeout( a ) End -- A read of standard input is cut short, as natively. If w~isA( .RVM.StdinWait ) Then w~halted End ::Method cancelTimer Expose timers Use Strict Arg act If act~timer == .Nil Then Return timers~removeItem( act~timer ) act~timer = .Nil -- The timers due (now, or, virtual, when none is ready: the next ones) end -- their waits. ::Method fireTimers Expose timers virtual vnow queue If timers~isEmpty Then Return If virtual, self~idle Then vnow = Max( vnow, timers[1]~deadline ) now = self~now Loop While \ timers~isEmpty t = timers[1] If t~deadline > now Then Leave timers~delete( 1 ) t~act~timer = .Nil t~on~timeout( t~act ) End -- Is another activity ready (the slice)? The real clock's timers due are, -- and the I/O that is ready. ::Method othersReady Expose queue timers virtual ios If \ ios~isEmpty Then self~pollIO( 0 ) If \ virtual, \ timers~isEmpty Then self~fireTimers Return \ self~idle -- An activity waits for I/O ('w'; 'poller' polls it). ::Method addIO Expose ios ioPollers Use Strict Arg w, poller ioPollers[ w ] = poller ios~append( w ) ::Method removeIO Expose ios ioPollers Use Strict Arg w ios~removeItem( w ) ioPollers~remove( w ) -- The I/O waits whose I/O is ready go on (for 'ms' milliseconds at most; -- -1: until one is). Waits of one kind: their poller waits; of several -- (sockets and commands), each poller in turn without waiting, in steps of -- 10 ms. ::Method pollIO Expose ios ioPollers Use Strict Arg ms If ios~isEmpty Then Return kinds = .Array~new Do w Over ios p = ioPollers[ w ] If \ kinds~hasItem( p ) Then kinds~append( p ) End If kinds~items == 1 Then Do kinds[1]~poll( self, ms ) Return End Numeric Digits 18 left = ms Loop before = ios~items Do p Over kinds p~poll( self, 0 ) End If ios~items < before | left == 0 Then Return If left > 0 Then left = Max( 0, left - 10 ) Call SysSleep 0.01 End -- No activity can be given (the queue holds only trapped ones, or none). ::Method idle Expose queue trapped If trapped~isEmpty Then Return queue~isEmpty Do a Over queue If \ trapped~hasItem( a ) Then Return .False End Return .True -- A trapped activity ready again goes on where it waits (not through next). ::Method unqueue Expose queue Use Strict Arg act queue~removeItem( act ) ::Method nextId Expose count count += 1 Return count ::Method newActivity Expose live Use Strict Arg context, isMain = .False act = .RVM.Activity~new( self, context, isMain ) live~append( act ) context~activity = act Return act ::Method ready Expose queue Use Strict Arg act If act~state == "READY" | act~state == "ENDED" Then Return act~state = "READY" queue~append( act ) -- The next activity to run (.Nil: none is ready, and no timer nor I/O can -- make one). With none ready, the real clock waits for the next deadline. -- With I/O to wait for, the wait is for it too, and real (also with the -- virtual clock: the other end of a socket is not the RVM's), up to the -- next deadline, or until it is ready. ::Method next Expose queue timers virtual ios trapped Call On Halt Name HostHalt -- Ctrl-C while it waits (haltAll) Loop If \ ios~isEmpty Then self~pollIO( 0 ) If \ timers~isEmpty Then Do If self~idle, \ ios~isEmpty Then Do wait = timers[1]~deadline - self~now If wait > 0 Then self~pollIO( wait ) End self~fireTimers If self~idle, \ virtual, ios~isEmpty Then Do wait = timers[1]~deadline - self~now If wait > 0 Then Call SysSleep wait / 1000 self~fireTimers End End Else If self~idle, \ ios~isEmpty Then self~pollIO( -1 ) If \ self~idle Then Leave -- A trapped one ready: the pump that waits for it goes back to it. If \ trapped~isEmpty, trapped~peek~state == "READY" Then Return .Nil If timers~isEmpty, ios~isEmpty Then Leave End If self~idle Then Return .Nil Do i = 1 To queue~items act = queue[i] If \ trapped~hasItem( act ) Then Leave End queue~delete( i ) act~state = "RUNNING" Return act HostHalt: self~haltAll Return ::Method ended Expose live Use Strict Arg act act~state = "ENDED" act~unwatch self~cancelTimer( act ) -- An I/O wait (RVM.SockWait) is the scheduler's no more. If act~waitingOn \== .Nil, act~waitingOn~hasMethod( "CANCEL" ) Then act~waitingOn~cancel -- The MutexSemaphores it holds are released (ooRexx's forceLockRelease). If act~mutexes \== .Nil Then Do mx Over act~mutexes~copy mx~forceRelease( act ) End live~removeItem( act ) -- Is there something that may run while activity 'act' waits for a -- command: another activity that has not ended, or a timer? ::Method othersThan Expose live timers Use Strict Arg act If \ timers~isEmpty Then Return .True Do a Over live If a \== act, a~state \== "ENDED" Then Return .True End Return .False -- Is there an activity that has not ended, other than the main one? ::Method othersLive Expose live Do a Over live If \ a~isMain Then Return .True End Return .False -- A wait with a timeout: when (the clock's), who, and what for. ::Class RVM.Timer Public ::Attribute deadline ::Attribute act ::Attribute on ::Method init Expose deadline act on Use Strict Arg deadline, act, on -- An EventSemaphore's native value (ooRexx's SysSemaphore): posted or not, -- and the activities that wait for it. ::Class RVM.EventSem Public ::Attribute posted ::Attribute waiting ::Attribute sleep -- SysSleep's: Ctrl-C ends it (Scheduler~haltAll) ::Attribute closed ::Method init Expose posted waiting sleep closed posted = .False waiting = .Array~new sleep = .False closed = .False ::Method owningActivity Return .Nil -- Windows: UNINIT closes its handle (CloseHandle), and then POST and RESET -- do nothing, it is never posted, a wait for ever ends at once (1) and any -- other gives 0 (WaitForSingleObject fails). Unix: it goes on working. ::Method close Expose closed If .RVM.FileSystem~windows Then closed = .True -- Posted: all those waiting go on (their wait gives 1). ::Method post Expose posted waiting closed If closed Then Return posted = .True list = waiting waiting = .Array~new Do act Over list act~semDone( "1" ) End ::Method reset Expose posted closed If \ closed Then posted = .False -- The wait of 'act' for 'ms' milliseconds (-1: for ever; 0: none): "1" or -- "0" now, or .Nil when it must wait (an RVM.Wait for the machine). ::Method wait Expose posted waiting closed Use Strict Arg act, ms, sched If closed Then Return ( ms < 0 )~?( "1", "0" ) If posted Then Return "1" If ms == 0 Then Return "0" waiting~append( act ) act~waitingOn = self If ms > 0 Then sched~addTimer( act, ms, self ) Return .Nil ::Method timeout Expose waiting Use Strict Arg act waiting~removeItem( act ) act~semDone( "0" ) -- A MutexSemaphore's native value (ooRexx's SysMutex, a recursive pthread -- mutex, and MutexSemaphoreClass's nestCount): who has it and how many -- times (depth); how many acquires the object counts (nest); closed (SysMutex -- created is false: ACQUIRE with no timeout or a timeout says 0); destroyed -- (closed when nobody held it: pthread_mutex_destroy; else EBUSY and the -- mutex lives on: ACQUIRE(0) and RELEASE, that do not look at created, go on -- working); those waiting. ::Class RVM.MutexSem Public ::Attribute owner ::Attribute depth ::Attribute nest ::Attribute closed ::Attribute destroyed ::Attribute waiting ::Method init Expose owner depth nest closed destroyed waiting owner = .Nil; depth = 0; nest = 0; closed = .False; destroyed = .False waiting = .Array~new ::Method owningActivity Return .Nil -- ACQUIRE: "1" or "0" now, or .Nil when it must wait. ::Method acquire Expose owner depth closed destroyed waiting Use Strict Arg act, ms, sched -- Windows, after UNINIT (CloseHandle): requestImmediate succeeds (its -- WaitForSingleObject fails, which is not WAIT_TIMEOUT: nestCount goes -- up), any other request fails, and so does each release. If closed, .RVM.FileSystem~windows Then Do If ms \= 0 Then Return "0" self~nested( act ) Return "1" End If ms == 0 Then Do -- requestImmediate: pthread_mutex_trylock If destroyed Then Return "0" End Else If closed Then Return "0" If owner == .Nil | owner == act Then Do owner = act depth += 1 self~nested( act ) Return "1" End If ms == 0 Then Return "0" waiting~append( act ) act~waitingOn = self If ms > 0 Then sched~addTimer( act, ms, self ) Return .Nil -- One more acquire (ooRexx's handleNesting): the first time, the activity -- holds it (it is released if the activity ends). ::Method nested Expose nest Use Strict Arg act nest += 1 If nest == 1 Then Do If act~mutexes == .Nil Then act~mutexes = .Array~new act~mutexes~append( self ) End -- RELEASE: 0 when the object counts none, or the mutex cannot be unlocked -- ('act' does not hold it: EPERM; destroyed: EINVAL). ::Method release Expose owner nest destroyed closed Use Strict Arg act If nest == 0 Then Return "0" If closed, .RVM.FileSystem~windows Then Return "0" If destroyed | owner \== act Then Return "0" self~unlock nest -= 1 If nest == 0 Then self~unheld( act ) Return "1" ::Method unheld Use Strict Arg act If act~mutexes \== .Nil Then act~mutexes~removeItem( self ) -- The lock (pthread_mutex_unlock): once less; the last time, the first -- waiting has it. ::Method unlock Expose owner depth waiting depth -= 1 If depth > 0 Then Return owner = .Nil If waiting~isEmpty Then Return next = waiting[1] waiting~delete( 1 ) owner = next depth = 1 self~nested( next ) next~semDone( "1" ) ::Method timeout Expose waiting Use Strict Arg act waiting~removeItem( act ) act~semDone( "0" ) -- UNINIT (MutexSemaphoreClass~close): closed; destroyed unless held; the -- object counts no acquires any more (the current activity's removeMutex). ::Method close Expose depth nest closed destroyed Use Strict Arg act If \ closed, depth == 0 Then destroyed = .True closed = .True If nest > 0 Then self~unheld( act ) nest = 0 -- The activity 'act' ends holding it (ooRexx's forceLockRelease). ::Method forceRelease Expose owner nest Use Strict Arg act Do While nest > 0 If owner == act Then self~unlock nest -= 1 End self~unheld( act ) -- The variables of an object for a scope, with their lock. ::Class RVM.Pool Public SubClass RVM.Vars -- Its number (a TraceObject's ATTRIBUTEPOOL: ooRexx's variable dictionary -- identifier), given when first asked for. ::Attribute counter Class ::Method id Expose id If Var( "ID" ) Then Return id n = .RVM.Pool~counter If \ DataType( n, "W" ) Then n = 0 id = n + 1 .RVM.Pool~counter = id Return id -- How many times its lock is held (SCOPELOCKCOUNT). ::Method reserveCount Expose count Return count ::Method init Expose owner count waiting watchers owner = .Nil count = 0 waiting = .Nil watchers = .Nil self~init:super -- The value of a variable (.Nil: it has none). ::Method valueOf Use Strict Arg name v = self[ name ] If v == .Nil Then Return .Nil Return v~value -- Give a variable a value (those that watch it are told: RVM.Var~watchBy). ::Method setValue Use Strict Arg name, value v = self[ name ] If v == .Nil Then v = self~cell( name, .True ) v~value = value ::Method owningActivity Expose owner Return owner -- Take the lock for 'act': .True when it has it; .False when it must wait -- (it is in the queue: when its turn comes, it has it, and it is ready). ::Method reserve Expose owner count waiting Use Strict Arg act If owner == .Nil Then Do owner = act count = 1 Return .True End If owner == act Then Do count += 1 Return .True End owner~checkDeadLock( act ) If waiting == .Nil Then waiting = .Array~new waiting~append( act ) act~waitingOn = self Return .False -- Let it go once; the last time, the first activity waiting has it. ::Method release Expose owner count waiting count -= 1 If count > 0 Then Return owner = .Nil If waiting == .Nil Then Return If waiting~isEmpty Then Return owner = waiting[1] waiting~delete( 1 ) count = 1 owner~granted = self owner~wake -- REPLY: the lock goes to the new activity 'act' when it has it once; -- when more (another activation of the activity has it too), it lets it go -- once, and the new activity must take it again (.False). ::Method transfer Expose owner count Use Strict Arg act If count == 1 Then Do owner = act Return .True End self~release Return .False -- GUARD WHEN: the activities that watch a variable. ::Attribute watchers ::Method watch Expose watchers Use Strict Arg name, act If watchers == .Nil Then watchers = .Directory~new list = watchers[ name ] If list == .Nil Then Do list = .Array~new watchers[ name ] = list -- The variable tells when it is set (or dropped). self~cell( name, .True )~watchBy( self, name ) End If \ list~hasItem( act ) Then list~append( act ) ::Method unwatch Expose watchers Use Strict Arg name, act If watchers == .Nil Then Return list = watchers[ name ] If list == .Nil Then Return list~removeItem( act ) -- A variable was set or dropped: those that watch it are told. ::Method changed Expose watchers Use Strict Arg name list = watchers[ name ] If list == .Nil Then Return Do act Over list~copy act~guardPost End -- A Message object's native value (ooRexx's MessageClass): the message -- (receiver, name, scope, arguments), how it went (result, returned, an -- error: failed, info, its condition object), whether START was sent, the -- activity it runs in (a deadlock check), those waiting for it, its Message -- object, and those to notify when it completes (NOTIFY: parties; notified -- when they have been). ::Class RVM.MessageState Public ::Attribute receiver ::Attribute name ::Attribute scope ::Attribute args ::Attribute result ::Attribute returned ::Attribute failed ::Attribute info ::Attribute condObj ::Attribute activated ::Attribute startActivity ::Attribute waiting ::Attribute obj ::Attribute parties ::Attribute notified ::Method init Expose receiver name scope args result returned failed info condObj - activated startActivity waiting obj parties notified Use Strict Arg receiver, name, scope, args result = .Nil; returned = .False; failed = .False; info = .Nil condObj = .Nil; activated = .False; startActivity = .Nil waiting = .Array~new; obj = .Nil; parties = .Array~new; notified = .False ::Method complete Expose returned failed Return returned | failed ::Method owningActivity Expose startActivity Return startActivity ::Method clearCompletion Expose result returned failed info condObj notified result = .Nil; returned = .False; failed = .False; info = .Nil condObj = .Nil; notified = .False -- It has completed: the activities waiting for it go on. ::Method done Expose waiting Do act Over waiting act~wake End waiting = .Array~new -- A copy (REPLY): the same message, not sent yet, with a copy of the -- parties to notify. ::Method copyMessage Expose receiver name scope args parties copy = .RVM.MessageState~new( receiver, name, scope, args~copy ) copy~parties = parties~copy Return copy -- It has completed: the parties are notified (ooRexx's sendNotification), -- by the delegates of an RVM.Notifier, and then 'res' is the result. ::Method notifyAll Expose parties notified Use Strict Arg res If parties~isEmpty Then Do notified = .True Return res End Return .RVM.Notifier~new( self, res )~next( .Nil, .Nil ) -- What a native gives the machine: wait for 'on' (a message) and send the -- message again (RVM.Wait); start the message 'message' in a new activity, -- and 'result' is the native's (RVM.StartMessage); raise the error of a -- message again (RVM.Reraise). ::Class RVM.Wait Public ::Attribute on ::Method init Expose on Use Strict Arg on ::Class RVM.StartMessage Public ::Attribute message ::Attribute result ::Method init Expose message result Use Strict Arg message, res = .Nil result = res ::Class RVM.Reraise Public ::Attribute info ::Method init Expose info Use Strict Arg info -- A message sent (Message~send): its result is kept, and those to notify -- are (see RVM.MessageState~notifyAll); then it is the result, unless the -- send was MESSAGECOMPLETE or TRIGGERED ('quiet': no result). ::Class RVM.MessageSent Public ::Method init Expose ms quiet Use Strict Arg ms, quiet = .False ::Method next Expose ms quiet Use Strict Arg v, context context~level~notifyMsg = .Nil -- (ooRexx's sendNotification) ms~result = v ms~returned = .True ms~done If quiet Then Return ms~notifyAll( .Nil ) Return ms~notifyAll( v ) -- The notifications of a message that has completed: MESSAGECOMPLETE (the -- Message object) to each party it had then, in order; then 'res'. ::Class RVM.Notifier Public ::Method init Expose ms res pos count Use Strict Arg ms, res pos = 0 count = ms~parties~items ::Method next Expose ms res pos count Use Strict Arg v, context pos += 1 If pos > count Then Do ms~notified = .True Return res End d = .RVM.Delegate~new( ms~parties[ pos ], "MESSAGECOMPLETE", .Array~of( ms~obj ) ) d~then = self Return d -- What a native gives when its result is none (a notification sent to one -- party: MESSAGECOMPLETE's result goes nowhere). ::Class RVM.NoResult Public ::Method next Return .Nil /******************************************************************************/ /* RVM.World -- the objects of a run: the classes, .NIL, .LOCAL, .ENVIRONMENT */ /******************************************************************************/ ::Class RVM.World Public ::Attribute objectClass ::Attribute classClass ::Attribute stringClass ::Attribute directoryClass ::Attribute arrayClass ::Attribute supplierClass ::Attribute tableClass ::Attribute stringTableClass ::Attribute listClass ::Attribute queueClass ::Attribute setClass ::Attribute bagClass ::Attribute relationClass ::Attribute methodClass ::Attribute routineClass ::Attribute packageClass ::Attribute contextClass ::Attribute stackFrameClass ::Attribute stemClass ::Attribute messageClass ::Attribute eventSemClass ::Attribute mutexSemClass ::Attribute mbufferClass ::Attribute scheduler -- the activities of the run (RVM.Scheduler) ::Attribute nil ::Attribute local ::Attribute environment ::Attribute builtins -- NAME -> value: found before .LOCAL (classes, NIL...) ::Attribute classes -- every class made, in order (see refresh) ::Attribute prelude -- the prelude (the REXX package), once loaded ::Attribute loader -- what loads it (the machine's RVM.PreludeLoader) ::Attribute sortMethods -- SORT, STABLESORT -> the prelude's, for objects -- .Package~defaultOptions: the default settings (as an RVM.Program's -- settingsLine) and how many packages still take them (ooRexx's -- psOverridePackageSettings, overrideCount; see the machine's -- OverrideOptions). ::Attribute overrideLine ::Attribute overrideCount -- What compiles a source at run time (Method~new, DEFINE...): the machine's -- RVM.SourceCompiler (its method: name, lines, parent program -> a program). ::Attribute sourceCompiler -- What RunNatives left for the machine: (delegate, the delegates waiting). ::Attribute deferred ::Attribute varRefClass -- VariableReference -- .LOCAL as ooRexx's LocalServer makes it (see ensureLocal): "" (not yet), -- MAKING, MADE; made at the start with RVM_LOCAL=eager (and then SAY and -- the rest always go through its objects); the monitors it started with, -- and their destinations. ::Attribute localState ::Attribute envCached -- what env found may be kept (see env) ::Attribute localEager ::Attribute localOrig ::Attribute localDest -- The libraries loaded (see RVMLibrary): name -> the Directory of its -- routines, and the names in the order they were loaded. As ooRexx's -- PackageManager, their routines are found by any program once loaded. ::Attribute libraries ::Attribute libraryOrder -- The ADDRESS environments the libraries loaded registered: NAME (upper -- case) -> the library (see RVM.HostEmu.cls). ::Attribute addressEnvs ::Method init Expose objectClass classClass stringClass directoryClass arrayClass supplierClass - tableClass stringTableClass listClass queueClass setClass bagClass - relationClass methodClass routineClass packageClass nil local - environment builtins classes prelude loader sortMethods sourceCompiler - contextClass stackFrameClass stemClass deferred messageClass scheduler - uninits tracked eventSemClass mutexSemClass mbufferClass building - varRefClass localState localEager localOrig localDest rexxInfoClass - libraries libraryOrder addressEnvs overrideLine overrideCount traceBusy - libRoutineObjs libHomes libRoutineObjs = .IdentityTable~new libHomes = .IdentityTable~new overrideLine = "9 0 SCIENTIFIC N NOINHERIT 1 -" traceBusy = .False overrideCount = 0 addressEnvs = .Directory~new libraries = .Directory~new libraryOrder = .Array~new localState = "" self~envCached = .False localEager = ( Upper( Value( "RVM_LOCAL", , "ENVIRONMENT" ) ) == "EAGER" ) localOrig = .Directory~new localDest = .Directory~new building = .False sourceCompiler = .Nil scheduler = .Nil deferred = .Array~new uninits = .Array~new tracked = .IdentityTable~new classes = .Array~new sortMethods = .Directory~new prelude = .Nil loader = .Nil -- Object and Class: each is an instance of Class. objectClass = self~bareClass( "Object", .Nil, "OBJECT" ) classClass = self~bareClass( "Class", objectClass, "CLASS" ) objectClass~native~metaclass = classClass classClass~native~metaclass = classClass stringClass = self~bareClass( "String", objectClass, "OBJECT" ) directoryClass = self~bareClass( "Directory", objectClass, "DIRECTORY" ) stringClass~native~metaclass = classClass directoryClass~native~metaclass = classClass arrayClass = self~bareClass( "Array", objectClass, "ARRAY" ) arrayClass~native~metaclass = classClass supplierClass = self~bareClass( "Supplier", objectClass, "SUPPLIER" ) supplierClass~native~metaclass = classClass tableClass = self~bareClass( "Table", objectClass, "TABLE" ) tableClass~native~metaclass = classClass -- IdentityTable: a Table whose indexes are the same object (a host -- IdentityTable). identityTableClass = self~bareClass( "IdentityTable", objectClass, "IDTABLE" ) identityTableClass~native~metaclass = classClass stringTableClass = self~bareClass( "StringTable", objectClass, "DIRECTORY" ) stringTableClass~native~metaclass = classClass listClass = self~bareClass( "List", objectClass, "LIST" ) listClass~native~metaclass = classClass queueClass = self~bareClass( "Queue", objectClass, "QUEUE" ) queueClass~native~metaclass = classClass setClass = self~bareClass( "Set", objectClass, "SET" ) setClass~native~metaclass = classClass bagClass = self~bareClass( "Bag", objectClass, "BAG" ) bagClass~native~metaclass = classClass relationClass = self~bareClass( "Relation", objectClass, "RELATION" ) relationClass~native~metaclass = classClass methodClass = self~bareClass( "Method", objectClass, "OBJECT" ) methodClass~native~metaclass = classClass routineClass = self~bareClass( "Routine", objectClass, "OBJECT" ) routineClass~native~metaclass = classClass packageClass = self~bareClass( "Package", objectClass, "OBJECT" ) packageClass~native~metaclass = classClass contextClass = self~bareClass( "RexxContext", objectClass, "OBJECT" ) contextClass~native~metaclass = classClass stackFrameClass = self~bareClass( "StackFrame", objectClass, "OBJECT" ) stackFrameClass~native~metaclass = classClass -- Buffer and Pointer (ooRexx's BufferClass and PointerClass): the classes -- of what the native APIs make; there are none here (NEW: 93.967). bufferClass = self~bareClass( "Buffer", objectClass, "OBJECT" ) bufferClass~native~metaclass = classClass pointerClass = self~bareClass( "Pointer", objectClass, "OBJECT" ) pointerClass~native~metaclass = classClass stemClass = self~bareClass( "Stem", objectClass, "STEM" ) stemClass~native~metaclass = classClass messageClass = self~bareClass( "Message", objectClass, "OBJECT" ) messageClass~native~metaclass = classClass eventSemClass = self~bareClass( "EventSemaphore", objectClass, "OBJECT" ) eventSemClass~native~metaclass = classClass mutexSemClass = self~bareClass( "MutexSemaphore", objectClass, "OBJECT" ) mutexSemClass~native~metaclass = classClass mbufferClass = self~bareClass( "MutableBuffer", objectClass, "OBJECT" ) mbufferClass~native~metaclass = classClass varRefClass = self~bareClass( "VariableReference", objectClass, "OBJECT" ) varRefClass~native~metaclass = classClass rexxInfoClass = self~bareClass( "RexxInfo", objectClass, "OBJECT" ) rexxInfoClass~native~metaclass = classClass Call Methods objectClass, "I", - "= 1 1 O.EQ;" "== 1 1 O.EQ;" "\= 1 1 O.NE;" - "\== 1 1 O.NE;" "<> 1 1 O.NE;" ">< 1 1 O.NE;" - "|| 1 1 O.CAT;" "' ' 1 1 O.CATB;" "'' 1 1 O.CAT;" - "CLASS 0 0 O.CLASS;" "COPY 0 0 O.COPY;" "DEFAULTNAME 0 0 O.DEFAULTNAME;" - "HASMETHOD 1 1 O.HASMETHOD;" "IDENTITYHASH 0 0 O.IDENTITYHASH;" - "HASHCODE 0 0 O.HASHCODE;" - "INIT 0 0 O.INIT;" "ISA 1 1 O.ISA class;" - "ISINSTANCEOF 1 1 O.ISA class;" "ISNIL 0 0 O.ISNIL;" - "OBJECTNAME 0 0 O.OBJECTNAME;" "OBJECTNAME= 1 1 O.SETNAME;" - "SEND 1 -1 O.SEND message name;" "STRING 0 0 O.STRING;" - "SENDWITH 2 2 O.SENDWITH message name/message arguments;" - "REQUEST 1 1 O.REQUEST;" - "START 1 -1 O.START message name;" - "STARTWITH 2 2 O.STARTWITH message name/;" - "INSTANCEMETHOD 1 1 O.INSTANCEMETHOD method name;" - "INSTANCEMETHODS 0 1 O.INSTANCEMETHODS;" - "SETMETHOD 1 3 O.SETMETHOD method name;" - "UNSETMETHOD 1 1 O.UNSETMETHOD method name;" - "RUN 0 -1 O.RUN" Call Methods objectClass, "C", "NEW 0 -1 O.NEW" Call Methods classClass, "I", - "= 1 1 O.EQ;" "== 1 1 O.EQ;" "\= 1 1 O.NE;" - "\== 1 1 O.NE;" "<> 1 1 O.NE;" ">< 1 1 O.NE;" - "COPY 0 0 C.COPY;" "DEFAULTNAME 0 0 C.DEFAULTNAME;" - "HASHCODE 0 0 C.HASHCODE;" - "ID 0 0 C.ID;" "SUPERCLASS 0 0 C.SUPERCLASS;" - "SUBCLASS 0 3 C.SUBCLASS;" "ISSUBCLASSOF 1 1 C.ISSUBCLASSOF class;" - "MIXINCLASS 0 3 C.MIXINCLASS;" "QUERYMIXINCLASS 0 0 C.QUERYMIXINCLASS;" - "BASECLASS 0 0 C.BASECLASS;" "METACLASS 0 0 C.METACLASS;" - "SUPERCLASSES 0 0 C.SUPERCLASSES;" "SUBCLASSES 0 0 C.SUBCLASSES;" - "ISMETACLASS 0 0 C.ISMETACLASS;" "ISABSTRACT 0 0 C.ISABSTRACT;" - "INHERIT 0 2 C.INHERIT;" "UNINHERIT 0 1 C.UNINHERIT;" - "ENHANCED 0 -1 C.ENHANCED;" "ACTIVATE 0 0 O.INIT;" - "METHOD 1 1 C.METHOD method name;" "METHODS 0 1 C.METHODS;" - "DEFINE 1 2 C.DEFINE method name;" "DELETE 1 1 C.DELETE method name;" - "DEFINEMETHODS 0 1 C.DEFINEMETHODS;" "PACKAGE 0 0 C.PACKAGE;" - "ANNOTATIONS 0 0 C.ANNOTATIONS;" "ANNOTATION 1 1 C.ANNOTATION name;" - "DEFINECLASSMETHOD 2 2 C.DEFINECLASSMETHOD;" - "INHERITINSTANCEMETHODS 1 1 C.INHERITINSTANCEMETHODS" -- Its own NEW (ooRexx's RexxClass~newRexx): a new class, an instance of -- the metaclass that receives it. Call Methods classClass, "C", "NEW 0 -1 C.NEW" Call Methods stringClass, "C", "NEW 1 -1 S.NEW" Call StringMethods stringClass dirSpec = - "[] 1 1 D.AT;" "[]= 0 2 D.PUT;" "AT 1 1 D.AT;" - "PUT 0 2 D.PUT;" "ENTRY 1 1 D.ENTRY;" "SETENTRY 1 2 D.SETENTRY;" - "HASENTRY 1 1 D.HASENTRY;" "HASINDEX 1 1 D.HASINDEX;" - "REMOVE 1 1 D.REMOVE;" "ITEMS 0 0 D.ITEMS;" "ISEMPTY 0 0 D.ISEMPTY;" - "EMPTY 0 0 D.EMPTY;" "UNKNOWN 0 2 D.UNKNOWN;" - "ALLINDEXES 0 0 D.ALLINDEXES;" "ALLITEMS 0 0 D.ALLITEMS;" - "MAKEARRAY 0 0 D.ALLINDEXES;" "SUPPLIER 0 0 D.SUPPLIER;" - "HASITEM 1 1 D.HASITEM;" "INDEX 1 1 D.INDEX;" "REMOVEITEM 1 1 D.REMOVEITEM;" - "REMOVEENTRY 1 1 D.REMOVEENTRY" Call Methods directoryClass, "I", dirSpec";" "INIT 0 1 D.INIT" -- A Directory's own SETMETHOD and UNSETMETHOD (ooRexx's DirectoryClass:: -- setMethodRexx), protected: entries that are methods (see DirMethods). Call Methods directoryClass, "I", "SETMETHOD 1 2 D.SETMETHOD index;" - "UNSETMETHOD 1 1 D.UNSETMETHOD index" directoryClass~native~imethods["SETMETHOD"]~flags = "R" directoryClass~native~imethods["UNSETMETHOD"]~flags = "R" Call Methods directoryClass, "C", "NEW 0 -1 O.NEW" Call Methods stringTableClass, "C", "NEW 0 -1 O.NEW" Call Methods tableClass, "C", "NEW 0 -1 O.NEW" Call Methods identityTableClass, "C", "NEW 0 -1 O.NEW" -- StringTable: a Directory without SETMETHOD; Table: any object as an -- index (the same object), no entries. Call Methods stringTableClass, "I", dirSpec";" "INIT 0 1 D.INIT" Call Methods tableClass, "I", - "[] 1 1 D.AT;" "[]= 0 2 D.PUT;" "AT 1 1 D.AT;" - "PUT 0 2 D.PUT;" "HASINDEX 1 1 D.HASINDEX;" - "REMOVE 1 1 D.REMOVE;" "ITEMS 0 0 D.ITEMS;" "ISEMPTY 0 0 D.ISEMPTY;" - "EMPTY 0 0 D.EMPTY;" "ALLINDEXES 0 0 D.ALLINDEXES;" - "ALLITEMS 0 0 D.ALLITEMS;" "MAKEARRAY 0 0 D.ALLINDEXES;" - "SUPPLIER 0 0 D.SUPPLIER;" "HASITEM 1 1 D.HASITEM;" - "INDEX 1 1 D.INDEX;" "REMOVEITEM 1 1 D.REMOVEITEM;" "INIT 0 1 D.INIT" Call Methods identityTableClass, "I", - "[] 1 1 D.AT;" "[]= 0 2 D.PUT;" "AT 1 1 D.AT;" - "PUT 0 2 D.PUT;" "HASINDEX 1 1 D.HASINDEX;" - "REMOVE 1 1 D.REMOVE;" "ITEMS 0 0 D.ITEMS;" "ISEMPTY 0 0 D.ISEMPTY;" - "EMPTY 0 0 D.EMPTY;" "ALLINDEXES 0 0 D.ALLINDEXES;" - "ALLITEMS 0 0 D.ALLITEMS;" "MAKEARRAY 0 0 D.ALLINDEXES;" - "SUPPLIER 0 0 D.SUPPLIER;" "HASITEM 1 1 D.HASITEM;" - "INDEX 1 1 D.INDEX;" "REMOVEITEM 1 1 D.REMOVEITEM;" "INIT 0 1 D.INIT" -- Array: most of its methods are those of the host's arrays (V.HOST: the -- same name, the same checks and errors); the others compare items or -- make strings as the RVM does. Call Methods arrayClass, "C", "NEW 0 -1 V.NEW;" "OF 0 -1 V.OF" spec = "" Do name Over .Array~of( "[]", "[]=", "AT", "PUT", "APPEND", "INSERT", - "DELETE", "REMOVE", "ITEMS", "SIZE", "DIMENSION", "DIMENSIONS", "FIRST", - "LAST", "NEXT", "PREVIOUS", "FIRSTITEM", "LASTITEM", "HASINDEX", - "ISEMPTY", "EMPTY", "FILL", "ALLITEMS", "ALLINDEXES", "MAKEARRAY", - "SECTION" ) spec ||= "'"name"' 0 -1 V.HOST;" End Call Methods arrayClass, "I", spec - "HASITEM 1 1 V.HASITEM;" "INDEX 1 1 V.INDEX;" "REMOVEITEM 1 1 V.REMOVEITEM;" - "MAKESTRING 0 2 V.MAKESTRING;" "TOSTRING 0 2 V.MAKESTRING;" - "SORT 0 0 V.SORT;" "STABLESORT 0 0 V.SORT;" "SUPPLIER 0 0 V.SUPPLIER" -- Supplier: the items and the indexes of a collection, when it was asked. -- NEW is theirs (its scope shows in a traceback); their INIT checks the -- arguments. Call Methods supplierClass, "C", "NEW 0 -1 O.NEW" Call Methods supplierClass, "I", "INIT 2 2 U.INIT" Call Methods supplierClass, "I", - "AVAILABLE 0 0 U.AVAILABLE;" "INDEX 0 0 U.INDEX;" "ITEM 0 0 U.ITEM;" - "NEXT 0 0 U.NEXT" -- List and Queue: the host's (their indexes are ooRexx's: a List's are -- the slots of its contents, reused as ooRexx reuses them). The index -- arguments are made numbers as ooRexx does (HostIndex), the items stay. listSpec = "" Do name Over .Array~of( "[]", "[]=", "AT", "PUT", "APPEND", "INSERT", - "DELETE", "REMOVE", "ITEMS", "FIRST", "LAST", "NEXT", "PREVIOUS", - "FIRSTITEM", "LASTITEM", "HASINDEX", "ISEMPTY", "EMPTY", "ALLITEMS", - "ALLINDEXES", "MAKEARRAY", "SECTION" ) listSpec ||= "'"name"' 0 -1 L.HOST;" End listSpec ||= "HASITEM 1 1 L.HASITEM;" "INDEX 1 1 L.INDEX;" - "REMOVEITEM 1 1 L.REMOVEITEM;" "SUPPLIER 0 0 L.SUPPLIER;" Call Methods listClass, "C", "OF 0 -1 L.OF;" "NEW 0 -1 O.NEW" Call Methods listClass, "I", listSpec "INIT 0 1 L.INIT" Call Methods queueClass, "C", "OF 0 -1 L.OF;" "NEW 0 -1 O.NEW" Call Methods queueClass, "I", listSpec "INIT 0 1 L.INIT;" - "PUSH 0 -1 L.HOST;" "PULL 0 -1 L.HOST;" "PEEK 0 -1 L.HOST;" - "QUEUE 0 -1 L.HOST;" "SIZE 0 -1 L.HOST" -- Set, Bag and Relation: the host's (the same hashing: the same order). -- What finds an index is the host's; what compares items is the RVM's -- (ItemMatch, as Array's). hashSpec = "" Do name Over .Array~of( "[]", "[]=", "AT", "PUT", "HASINDEX", "REMOVE", - "ITEMS", "ISEMPTY", "EMPTY", "ALLITEMS", "ALLINDEXES", "MAKEARRAY", "SUPPLIER" ) hashSpec ||= "'"name"' 0 -1 H.HOST;" End multiSpec = hashSpec "ALLAT 0 -1 H.HOST;" "REMOVEALL 0 -1 H.HOST;" - "UNIQUEINDEXES 0 -1 H.HOST;" "INDEX 1 1 H.INDEX;" "ALLINDEX 1 1 H.ALLINDEX;" - "INIT 0 1 H.INIT" Call Methods setClass, "C", "OF 0 -1 H.OF;" "NEW 0 -1 O.NEW" Call Methods setClass, "I", hashSpec "HASITEM 0 -1 H.HOST;" "REMOVEITEM 0 -1 H.HOST;" - "INDEX 0 -1 H.HOST;" "INIT 0 1 H.INIT" Call Methods bagClass, "C", "OF 0 -1 H.OF;" "NEW 0 -1 O.NEW" Call Methods bagClass, "I", multiSpec";" "HASITEM 0 -1 H.HOST;" "REMOVEITEM 0 -1 H.HOST" Call Methods relationClass, "C", "NEW 0 -1 O.NEW" -- Method: its native value is the RVM.Method (see methodObject). Call Methods methodClass, "C", "NEW 0 -1 M.NEW;" "NEWFILE 0 2 M.NEWFILE;" - "LOADEXTERNALMETHOD 0 2 M.LOADEXTERNALMETHOD" Call Methods methodClass, "I", - "SOURCE 0 0 M.SOURCE;" "SCOPE 0 0 M.SCOPE;" - "ISGUARDED 0 0 M.ISGUARDED;" "ISPRIVATE 0 0 M.ISPRIVATE;" - "ISPROTECTED 0 0 M.ISPROTECTED;" "ISPACKAGE 0 0 M.ISPACKAGE;" - "ISABSTRACT 0 0 M.ISABSTRACT;" "ISCONSTANT 0 0 M.ISCONSTANT;" - "ISATTRIBUTE 0 0 M.ISATTRIBUTE;" - "SETGUARDED 0 0 M.SETGUARDED;" "SETUNGUARDED 0 0 M.SETUNGUARDED;" - "SETPRIVATE 0 0 M.SETPRIVATE;" "SETPROTECTED 0 0 M.SETPROTECTED;" - "PACKAGE 0 0 M.PACKAGE;" "ANNOTATIONS 0 0 M.ANNOTATIONS;" - "SETSECURITYMANAGER 0 1 M.SETSECURITYMANAGER;" - "ANNOTATION 1 1 M.ANNOTATION name" -- Routine: its native value is the RVM.Routine (see routineObject). Call Methods routineClass, "C", "NEW 0 -1 RT.NEW;" "NEWFILE 0 2 RT.NEWFILE;" - "LOADEXTERNALROUTINE 0 2 RT.LOADEXTERNALROUTINE" Call Methods routineClass, "I", - "CALL 0 -1 RT.CALL;" "'[]' 0 -1 RT.CALL;" "CALLWITH 1 1 RT.CALLWITH;" - "SOURCE 0 0 RT.SOURCE;" "PACKAGE 0 0 RT.PACKAGE;" - "SETSECURITYMANAGER 0 1 RT.SETSECURITYMANAGER;" - "ANNOTATIONS 0 0 RT.ANNOTATIONS;" "ANNOTATION 1 1 RT.ANNOTATION name" -- Package: its native value is the RVM.Program (see packageObject). The -- arguments with names are checked by the natives (88.901 names them). Call Methods packageClass, "C", "NEW 0 -1 PK.NEW;" "DEFAULTOPTIONS 0 2 PK.DEFAULTOPTIONS" Call Methods packageClass, "I", - "NAME 0 0 PK.NAME;" "SOURCE 0 0 PK.SOURCE;" - "SOURCESIZE 0 0 PK.SOURCESIZE;" "SOURCELINE 1 1 PK.SOURCELINE;" - "CLASSES 0 0 PK.CLASSES;" "PUBLICCLASSES 0 0 PK.PUBLICCLASSES;" - "IMPORTEDCLASSES 0 0 PK.IMPORTEDCLASSES;" "ROUTINES 0 0 PK.ROUTINES;" - "PUBLICROUTINES 0 0 PK.PUBLICROUTINES;" - "IMPORTEDROUTINES 0 0 PK.IMPORTEDROUTINES;" - "DEFINEDMETHODS 0 0 PK.DEFINEDMETHODS;" - "IMPORTEDPACKAGES 0 0 PK.IMPORTEDPACKAGES;" - "FINDCLASS 1 1 PK.FINDCLASS name;" "FINDPUBLICCLASS 1 1 PK.FINDPUBLICCLASS name;" - "FINDROUTINE 1 1 PK.FINDROUTINE name;" "FINDPUBLICROUTINE 1 1 PK.FINDPUBLICROUTINE name;" - "FINDNAMESPACE 1 1 PK.FINDNAMESPACE name;" "FINDPROGRAM 1 1 PK.FINDPROGRAM name;" - "ADDCLASS 0 2 PK.ADDCLASS;" "ADDPUBLICCLASS 0 2 PK.ADDPUBLICCLASS;" - "ADDROUTINE 0 2 PK.ADDROUTINE;" "ADDPUBLICROUTINE 0 2 PK.ADDPUBLICROUTINE;" - "ADDPACKAGE 0 2 PK.ADDPACKAGE;" "LOADPACKAGE 1 2 PK.LOADPACKAGE;" - "PROLOG 0 0 PK.PROLOG;" "LOCAL 0 0 PK.LOCAL;" - "NAMESPACES 0 0 PK.NAMESPACES;" "ANNOTATIONS 0 0 PK.ANNOTATIONS;" - "ANNOTATION 1 1 PK.ANNOTATION name;" "RESOURCES 0 0 PK.RESOURCES;" - "RESOURCE 1 1 PK.RESOURCE name;" "DIGITS 0 0 PK.DIGITS;" - "FUZZ 0 0 PK.FUZZ;" "FORM 0 0 PK.FORM;" - "TRACE 0 0 PK.TRACE;" "OPTIONS 0 2 PK.OPTIONS;" - "SETSECURITYMANAGER 0 1 PK.SETSECURITYMANAGER;" - "LOADLIBRARY 1 1 PK.LOADLIBRARY name" -- The natives ooRexx protects (Setup.cpp's AddProtectedMethod): a -- security manager is asked before they run (see the machine's SendLoop). Do name Over .Array~of( "BASECLASS", "INHERITINSTANCEMETHODS", "DELETE", - "METACLASS", "SUBCLASSES", "SUPERCLASSES", "SUPERCLASS", "UNINHERIT" ) classClass~native~imethods[ name ]~flags = "R" End methodClass~native~imethods["SETPROTECTED"]~flags = "R" methodClass~native~imethods["SETSECURITYMANAGER"]~flags = "R" routineClass~native~imethods["SETSECURITYMANAGER"]~flags = "R" packageClass~native~imethods["SETSECURITYMANAGER"]~flags = "R" packageClass~native~imethods["OPTIONS"]~flags = "R" packageClass~native~cmethods["DEFAULTOPTIONS"]~flags = "R" -- RexxContext (.CONTEXT): its native value is the RVM.Level of an -- activation (see contextObject); StackFrame: an RVM.FrameInfo. Call Methods contextClass, "C", "NEW 0 -1 CX.NEW" spec = "COPY 0 0 CX.COPY" Do name Over .Array~of( "ARGS", "CONDITION", "DIGITS", "EXECUTABLE", "FORM", - "FUZZ", "INTERPRETER", "INVOCATION", "LINE", "NAME", "PACKAGE", "RS", - "STACKFRAMES", "THREAD", "VARIABLES" ) spec ||= ";" name "0 0 CX."name End Call Methods contextClass, "I", spec -- RexxInfo (.REXXINFO, its only instance; see RexxInfoNative). Call Methods rexxInfoClass, "C", "NEW 0 -1 RI.NEW" spec = "COPY 0 0 RI.COPY" Do name Over .Array~of( "ARCHITECTURE", "CASESENSITIVEFILES", "DATE", "DEBUG", - "DIGITS", "DIRECTORYSEPARATOR", "ENDOFLINE", "EXECUTABLE", "FORM", "FUZZ", - "INTERNALDIGITS", "INTERNALMAXNUMBER", "INTERNALMINNUMBER", "LANGUAGELEVEL", - "LIBRARYPATH", "MAJORVERSION", "MAXARRAYSIZE", "MAXEXPONENT", "MAXPATHLENGTH", - "MINEXPONENT", "MODIFICATION", "NAME", "PACKAGE", "PATHSEPARATOR", - "PLATFORM", "RELEASE", "REVISION", "VERSION" ) spec ||= ";" name "0 0 RI."name End Call Methods rexxInfoClass, "I", spec Call Methods stackFrameClass, "C", "NEW 0 -1 SF.NEW" Call Methods bufferClass, "C", "NEW 0 -1 SF.NEW" Call Methods pointerClass, "C", "NEW 0 -1 SF.NEW" -- (Its instance methods, for its method list: there are no pointers.) Call Methods pointerClass, "I", "= 1 1 O.EQ;" "== 1 1 O.EQ;" - "\= 1 1 O.NE;" "\== 1 1 O.NE;" "ISNULL 0 0 O.ISNULL" spec = "STRING 0 0 SF.TRACELINE; MAKESTRING 0 0 SF.TRACELINE" Do name Over .Array~of( "ARGUMENTS", "CONTEXT", "EXECUTABLE", "INVOCATION", - "LINE", "NAME", "TARGET", "TRACELINE", "TYPE" ) spec ||= ";" name "0 0 SF."name End Call Methods stackFrameClass, "I", spec -- Stem (ooRexx's StemClass): its native value is an RVM.Stem (see -- stemObjectOf). NEW takes the name; the comparison operators are not -- its (they go to UNKNOWN, as every message it has not: to its default). Call Methods stemClass, "C", "NEW 0 -1 ST.NEW" Call Methods stemClass, "I", - "[] 0 -1 ST.AT;" "AT 0 -1 ST.AT;" "[]= 1 -1 ST.PUT;" - "PUT 1 -1 ST.PUT;" "HASINDEX 0 -1 ST.HASINDEX;" - "REMOVE 0 -1 ST.REMOVE;" "HASITEM 1 1 ST.HASITEM;" - "INDEX 1 1 ST.INDEX;" "REMOVEITEM 1 1 ST.REMOVEITEM;" - "ITEMS 0 0 ST.ITEMS;" "ISEMPTY 0 0 ST.ISEMPTY;" "EMPTY 0 0 ST.EMPTY;" - "ALLINDEXES 0 0 ST.ALLINDEXES;" "ALLITEMS 0 0 ST.ALLITEMS;" - "MAKEARRAY 0 0 ST.ALLINDEXES;" "SUPPLIER 0 0 ST.SUPPLIER;" - "TODIRECTORY 0 0 ST.TODIRECTORY;" "REQUEST 1 1 ST.REQUEST;" - "UNKNOWN 0 2 ST.UNKNOWN" Do op Over .Array~of( "=", "==", "\=", "\==", "<>", "><" ) stemClass~native~imethods[ op ] = .Nil End -- VariableReference (ooRexx's VariableReference): its native value is an -- RVM.VarRef (a variable and its name; see newVarRef). NEW is not -- supported; the comparison operators are not its (they go to UNKNOWN, as -- every message it has not: to the variable's value). Call Methods varRefClass, "C", "NEW 0 -1 VR.NEW" Call Methods varRefClass, "I", - "NAME 0 0 VR.NAME;" "VALUE 0 0 VR.VALUE;" "VALUE= 0 1 VR.SETVALUE;" - "UNKNOWN 0 2 VR.UNKNOWN;" "REQUEST 1 1 VR.REQUEST" Do op Over .Array~of( "=", "==", "\=", "\==", "<>", "><" ) varRefClass~native~imethods[ op ] = .Nil End -- Message (ooRexx's MessageClass): its native value is an -- RVM.MessageState. Call Methods messageClass, "C", "NEW 0 -1 MS.NEW" -- EventSemaphore and MutexSemaphore (ooRexx's EventSemaphoreClass and -- MutexSemaphoreClass: Setup.cpp). Call Methods eventSemClass, "C", "NEW 0 -1 ES.NEW" Call Methods eventSemClass, "I", - "POST 0 0 ES.POST;" "RESET 0 0 ES.RESET;" "WAIT 0 1 ES.WAIT;" - "ISPOSTED 0 0 ES.ISPOSTED;" "UNINIT 0 0 ES.UNINIT" Call Methods mutexSemClass, "C", "NEW 0 -1 MX.NEW" Call Methods mutexSemClass, "I", - "ACQUIRE 0 1 MX.ACQUIRE;" "RELEASE 0 0 MX.RELEASE;" "UNINIT 0 0 MX.UNINIT" -- MutableBuffer (ooRexx's MutableBufferClass: Setup.cpp): its native -- value is an RVM.MBuffer. Call Methods mbufferClass, "C", "NEW 0 -1 MB.NEW" Call Methods mbufferClass, "I", - "APPEND 0 -1 MB.APPEND;" "INSERT 0 4 MB.INSERT;" "OVERLAY 0 4 MB.OVERLAY;" - "REPLACEAT 0 4 MB.REPLACEAT;" "[]= 0 3 MB.[]=;" "DELETE 0 2 MB.DELETE;" - "DELSTR 0 2 MB.DELETE;" "SUBSTR 0 3 MB.SUBSTR;" "[] 0 2 MB.[];" - "POS 0 3 MB.POS;" "LASTPOS 0 3 MB.LASTPOS;" "CONTAINS 0 3 MB.CONTAINS;" - "CASELESSCONTAINS 0 3 MB.CASELESSCONTAINS;" - "CONTAINSWORD 0 2 MB.CONTAINSWORD;" - "CASELESSCONTAINSWORD 0 2 MB.CASELESSCONTAINSWORD;" - "CASELESSPOS 0 3 MB.CASELESSPOS;" "CASELESSLASTPOS 0 3 MB.CASELESSLASTPOS;" - "SUBCHAR 0 1 MB.SUBCHAR;" "GETBUFFERSIZE 0 0 MB.GETBUFFERSIZE;" - "SETBUFFERSIZE 0 1 MB.SETBUFFERSIZE;" "SETTEXT 0 1 MB.SETTEXT;" - "LENGTH 0 0 MB.LENGTH;" "MAKEARRAY 0 1 MB.MAKEARRAY;" "STRING 0 0 MB.STRING;" - "COUNTSTR 0 1 MB.COUNTSTR;" "CASELESSCOUNTSTR 0 1 MB.CASELESSCOUNTSTR;" - "CHANGESTR 0 3 MB.CHANGESTR;" "CASELESSCHANGESTR 0 3 MB.CASELESSCHANGESTR;" - "UPPER 0 2 MB.UPPER;" "LOWER 0 2 MB.LOWER;" "TRANSLATE 0 5 MB.TRANSLATE;" - "MATCH 0 4 MB.MATCH;" "CASELESSMATCH 0 4 MB.CASELESSMATCH;" - "MATCHCHAR 0 2 MB.MATCHCHAR;" "CASELESSMATCHCHAR 0 2 MB.CASELESSMATCHCHAR;" - "VERIFY 0 4 MB.VERIFY;" "SPACE 0 2 MB.SPACE;" "SUBWORD 0 2 MB.SUBWORD;" - "SUBWORDS 0 2 MB.SUBWORDS;" "WORD 0 1 MB.WORD;" "WORDINDEX 0 1 MB.WORDINDEX;" - "WORDLENGTH 0 1 MB.WORDLENGTH;" "WORDS 0 0 MB.WORDS;" - "WORDPOS 0 2 MB.WORDPOS;" "CASELESSWORDPOS 0 2 MB.CASELESSWORDPOS;" - "DELWORD 0 2 MB.DELWORD;" "STARTSWITH 0 1 MB.STARTSWITH;" - "ENDSWITH 0 1 MB.ENDSWITH;" "CASELESSSTARTSWITH 0 1 MB.CASELESSSTARTSWITH;" - "CASELESSENDSWITH 0 1 MB.CASELESSENDSWITH;" "MAKESTRING 0 0 MB.STRING" Call Methods messageClass, "I", - "COMPLETED 0 0 MS.COMPLETED;" "HASERROR 0 0 MS.HASERROR;" - "HASRESULT 0 0 MS.HASRESULT;" "RESULT 0 0 MS.RESULT;" - "TARGET 0 0 MS.TARGET;" "MESSAGENAME 0 0 MS.MESSAGENAME;" - "ARGUMENTS 0 0 MS.ARGUMENTS;" "ERRORCONDITION 0 0 MS.ERRORCONDITION;" - "SEND 0 -1 MS.SEND;" "START 0 -1 MS.START;" - "REPLY 0 -1 MS.REPLY;" "SENDWITH 0 2 MS.SENDWITH;" - "STARTWITH 0 2 MS.STARTWITH;" "REPLYWITH 0 2 MS.REPLYWITH;" - "WAIT 0 0 MS.WAIT;" "NOTIFY 1 1 MS.NOTIFY notification target;" - "MESSAGECOMPLETE 0 1 MS.MESSAGECOMPLETE;" "TRIGGERED 0 1 MS.TRIGGERED;" - "HALT 0 1 MS.HALT" -- SETMETHOD and UNSETMETHOD are private (97.2 from another object). objectClass~native~imethods["SETMETHOD"]~flags = "P" objectClass~native~imethods["UNSETMETHOD"]~flags = "P" objectClass~native~imethods["RUN"]~flags = "P" Call Methods relationClass, "I", multiSpec";" "HASITEM 1 2 H.HASITEM;" - "REMOVEITEM 1 2 H.REMOVEITEM" -- The class methods of Object are also its instance methods (ooRexx's -- buildFinalClassBehaviour): every class has them. Do With Index name Item m Over objectClass~native~imethods If \ objectClass~native~cmethods~hasIndex( name ) Then objectClass~native~cmethods[ name ] = m End classClass~native~isMeta = .True Do c Over classes If c \== objectClass Then Do c~native~superclasses = .Array~of( objectClass ) objectClass~native~subclasses~insert( c, .Nil ) End c~native~primitive = .True c~native~baseClass = c End Do c Over classes self~buildClassBehaviour( c ) End nil = .RVM.Obj~new( self~instanceBehaviour( objectClass ) ) nil~objName = "The NIL object" local = self~newDirectory local~objName = "The Local Directory" environment = self~newDirectory environment~objName = "The Environment Directory" builtins = .Directory~new builtins["OBJECT"] = objectClass builtins["CLASS"] = classClass builtins["STRING"] = stringClass builtins["DIRECTORY"] = directoryClass builtins["ARRAY"] = arrayClass builtins["SUPPLIER"] = supplierClass builtins["TABLE"] = tableClass builtins["IDENTITYTABLE"] = identityTableClass builtins["STRINGTABLE"] = stringTableClass builtins["LIST"] = listClass builtins["QUEUE"] = queueClass builtins["SET"] = setClass builtins["BAG"] = bagClass builtins["RELATION"] = relationClass builtins["METHOD"] = methodClass builtins["ROUTINE"] = routineClass builtins["PACKAGE"] = packageClass builtins["REXXCONTEXT"] = contextClass builtins["STACKFRAME"] = stackFrameClass builtins["BUFFER"] = bufferClass builtins["POINTER"] = pointerClass builtins["STEM"] = stemClass builtins["MESSAGE"] = messageClass builtins["EVENTSEMAPHORE"] = eventSemClass builtins["MUTEXSEMAPHORE"] = mutexSemClass builtins["MUTABLEBUFFER"] = mbufferClass builtins["VARIABLEREFERENCE"] = varRefClass builtins["NIL"] = nil builtins["TRUE"] = "1" builtins["FALSE"] = "0" e = environment~native Do With Index name Item v Over builtins e[ name ] = v End e["LOCAL"] = local e["ENVIRONMENT"] = environment e["ENDOFLINE"] = "0a"x If .File~separator == "\" Then e["ENDOFLINE"] = "0d0a"x -- (Windows) e["REXXINFO"] = .RVM.Obj~new( self~instanceBehaviour( rexxInfoClass ) ) -- A library of the RVM (name, the Directory of its routines) is loaded: its -- routines are found from now on (libraryRoutine). ::Method loadLibrary Expose libraries libraryOrder addressEnvs Use Strict Arg name, table If libraries~hasIndex( name ) Then Return libraries[ name ] = table libraryOrder~append( name ) Do env Over LibraryEnvironments( name ) addressEnvs[ env ] = name End -- The library that registered the ADDRESS environment 'name' (any case), -- or .Nil. ::Method addressEnvironment Expose addressEnvs Use Strict Arg name Return addressEnvs[ Upper( name ) ] -- A routine of a library loaded (its entry), or .Nil ('name' in any case). ::Method libraryRoutine Expose libraries libraryOrder Use Strict Arg name name = Upper( name ) Do lib Over libraryOrder r = libraries[ lib ][ name ] If r \== .Nil Then Return r End Return .Nil -- A class object, before it has a behaviour. ::Method bareClass Expose classes Use Strict Arg id, superclass, kind c = .RVM.Obj~new( .Nil, .RVM.ClassData~new( id, superclass, .Nil, kind ) ) c~native~rexx = .True classes~append( c ) Return c -- The Method object of a method (an RVM.Method), made once: the same -- method is always the same object. ::Method methodObject Expose methodClass Use Strict Arg m If m == .Nil Then Return self~nil If m~obj == .Nil Then m~obj = .RVM.Obj~new( self~instanceBehaviour( methodClass ), m ) Return m~obj -- The Routine object of a routine (an RVM.Routine), made once. ::Method routineObject Expose routineClass Use Strict Arg r -- (A ::ROUTINE ... EXTERNAL: its library's routine, see below.) If r~obj == .Nil, r~lib \== .Nil Then r~obj = self~libraryRoutineObject( r~lib, ExternalSpec( r~external, r~name, .True )[3], r~program ) If r~obj == .Nil Then r~obj = .RVM.Obj~new( self~instanceBehaviour( routineClass ), r ) Return r~obj -- The package of the code of a method of a library (its entry): that of the -- first ::METHOD ... EXTERNAL that resolved it ('home'), or none (.Nil), as -- ooRexx keeps one code per entry (Method~loadExternalMethod gives a new -- Method of it). ::Method libraryHome Expose libHomes Use Strict Arg entry, home = .Nil If \ libHomes~hasIndex( entry ) Then libHomes~put( home, entry ) Return libHomes~at( entry ) -- The Routine object of a routine of a library (lr: its entry), one per -- entry, as ooRexx's package manager keeps them: Routine~loadExternalRoutine -- (by any name), a ::ROUTINE ... EXTERNAL and the StackFrame of the native -- routine running give the same object. Its source is empty; its name is -- the entry as first written ('name'; a call by name: the library's); its -- package, REXX for REXXUTIL's (ooRexx has them inside), else that of the -- ::ROUTINE that made it ('home'), or none. ::Method libraryRoutineObject Expose routineClass libRoutineObjs Use Strict Arg lr, name = ( lr[1] ), home = .Nil o = libRoutineObjs~at( lr ) If o \== .Nil Then Return o r = self~sourceCompiler~libraryRoutine( name, lr ) If IsRexxUtilEntry( lr ) Then home = "REXX" r~libHome = home o = .RVM.Obj~new( self~instanceBehaviour( routineClass ), r ) r~obj = o self~created( o ) libRoutineObjs~put( o, lr ) Return o -- The RexxContext object of an activation (an RVM.Level), made once. ::Method contextObject Expose contextClass Use Strict Arg lv If lv~ctx == .Nil Then lv~ctx = .RVM.Obj~new( self~instanceBehaviour( contextClass ), lv ) Return lv~ctx -- A StackFrame object (of an RVM.FrameInfo): a new one each time, as -- ooRexx's. ::Method stackFrameObject Expose stackFrameClass Use Strict Arg f Return .RVM.Obj~new( self~instanceBehaviour( stackFrameClass ), f ) -- The receiver of a frame: what it is, or what stands for it in the frames -- of a NOTREADY (see RVM.ConditionInfo): an RVM.Stream (its Stream object) -- or .Array~of("LOCAL", name) (that monitor of .LOCAL). ::Method frameTarget Expose local Use Strict Arg t If t~isA( .RVM.Stream ) Then Return self~streamObject( t ) If t~isA( .Array ) Then Do self~ensureLocal v = local~native[ t[2] ] If v == .Nil Then Return self~nil Return v End Return t -- The Stream object of an RVM.Stream of a stream table (whose functions -- have none): made the first time, as ooRexx's resolveStream makes it -- (Stream~new(name)), and then given this stream. ::Method streamObject Expose loader Use Strict Arg rs If rs~rexxObject \== .Nil Then Return rs~rexxObject self~ensureLocal -- (the standard ones: .STDIN...) If rs~rexxObject \== .Nil Then Return rs~rexxObject self~ensurePrelude o = loader~sendSync( self~prelude~classObjs[ "STREAM" ], "NEW", .Array~of( rs~name ) ) o~native = rs rs~rexxObject = o Return o -- The Method object of a method of a class of the REXX package (the -- frames of a NOTREADY: Stream's, Monitor's UNKNOWN). ::Method preludeMethodObject Use Strict Arg className, name self~ensurePrelude m = self~prelude~classObjs[ className ]~native~imethods[ name ] If m == .Nil Then Return self~nil Return self~methodObject( m ) -- .ROUTINES of a program: a StringTable of its ::ROUTINEs (the private ones -- too, and those ADDROUTINE adds) as Routine objects, made once (the same -- object); .Nil when it has none (the symbol is then its name). ::Method routinesTable Expose stringTableClass Use Strict Arg program If program~routinesObj \== .Nil Then Return program~routinesObj If program~routines~isEmpty Then Return .Nil t = self~newInstance( stringTableClass ) Do With Index name Item r Over program~routines t~native[ name ] = self~routineObject( r ) End program~routinesObj = t Return t -- The resources of a program (::RESOURCE), as ooRexx's package's: a -- StringTable, NAME -> an Array of its lines, made once (.RESOURCES is this -- one; Package~resources, a copy). .Nil when it has none. ::Method resourcesTable Expose stringTableClass Use Strict Arg program If program~resourcesObj \== .Nil Then Return program~resourcesObj If program~resources~isEmpty Then Return .Nil t = self~newInstance( stringTableClass ) Do r Over program~resources t~native[ r[1] ] = self~newArray( r[2]~copy ) End program~resourcesObj = t Return t /*----------------------------------------------------------------------------*/ /* Packages: the Package object of a program (an RVM.Program), made once; */ /* the REXX package is the prelude. What they see is ooRexx's PackageClass's: */ /* installed (their classes, and their parents'), public (theirs, those they */ /* import, their parents'), and then REXX, the package's local directory, */ /* .LOCAL and .ENVIRONMENT. */ /*----------------------------------------------------------------------------*/ ::Method packageObject Expose packageClass Use Strict Arg program If program~pkgObj == .Nil Then Do program~pkgObj = .RVM.Obj~new( self~instanceBehaviour( packageClass ), program ) If program == self~prelude Then program~pkgObj~objName = "The REXX Package" End Return program~pkgObj -- A File object (File~new(path)), as ooRexx's RexxInfo makes them. ::Method fileObject Expose environment loader Use Strict Arg path self~ensurePrelude Return loader~sendSync( environment~native[ "FILE" ], "NEW", .Array~of( path ) ) -- The REXX package (the prelude, loaded if it was not). ::Method rexxPackage self~ensurePrelude If self~prelude == .Nil Then Return self~nil Return self~packageObject( self~prelude ) -- The classes of the REXX package: the builtins' and the prelude's (all of -- them, or its public ones). ::Method rexxClasses Expose builtins Use Strict Arg public self~ensurePrelude d = .Directory~new Do With Index name Item v Over builtins If v~isA( .RVM.Obj ), v~isClass Then d[ name ] = v End If self~prelude \== .Nil Then Do If public Then Call Merge d, self~prelude~publicClasses Else Call Merge d, self~prelude~classObjs End Return d -- A program whose classes are not made yet (it has not started) is -- installed now, as ooRexx's install. One with ::REQUIRES is installed when -- it is made (see PendingInstall), so the error is never reached. ::Method ensureInstalled Use Strict Arg program, context If program~classObjs \== .Nil Then Return If \ program~requires~isEmpty Then Raise Syntax 93.900 Additional( - "RVM: package" program~path "has not started yet (it has ::REQUIRES)" ) self~installNow( program, context ) -- Program t is added to program p (ooRexx's addPackage): once, and p sees -- then its public classes and routines (and those it imports). ::Method addPackage Use Strict Arg p, t, context self~ensureInstalled( p, context ) If p~required~hasItem( t ) Then Return p~required~append( t ) Call MergeRequired p, t -- What is public in program t (an external program that returned) goes to -- program p (ooRexx's mergeRequired, without adding the package). ::Method mergePackage Use Strict Arg p, t Call MergeRequired p, t -- A class seen from a program (ooRexx's findClass), or .Nil. ::Method findClass Expose local environment Use Strict Arg program, name name = Upper( name ) p = program Do While p \== .Nil If p == self~prelude Then Do v = self~rexxClasses( .False )[ name ] If v \== .Nil Then Return v End Else If p~classObjs \== .Nil Then Do v = p~classObjs[ name ] If v \== .Nil Then Return v End p = p~parent End v = self~findPublicClass( program, name ) If v \== .Nil Then Return v If program~localObj \== .Nil Then Do v = program~localObj~native[ name ] If v \== .Nil Then Return v End v = local~native[ name ] If v \== .Nil Then Return v Return environment~native[ name ] -- A public class seen from a program (ooRexx's findPublicClass): its own, -- those it imports, its parents', and the REXX package's; or .Nil. ::Method findPublicClass Expose builtins Use Strict Arg program, name name = Upper( name ) p = program Do While p \== .Nil v = p~publicClasses[ name ] If v \== .Nil Then Return v v = p~importedClasses[ name ] If v \== .Nil Then Return v p = p~parent End v = builtins[ name ] If v~isA( .RVM.Obj ), v~isClass Then Return v self~ensurePrelude If self~prelude == .Nil Then Return .Nil Return self~prelude~publicClasses[ name ] -- The package tagged with a namespace (ooRexx's findNamespace): REXX is the -- REXX package; then the program's namespaces, and its parent's. .Nil: none. ::Method findNamespace Use Strict Arg program, name name = Upper( name ) If name == "REXX" Then Do self~ensurePrelude Return self~prelude End p = program Do While p \== .Nil If p~namespaces~hasIndex( name ) Then Return p~namespaces[ name ] p = p~parent End Return .Nil -- The same for the machine: 98.987 when there is none. ::Method namespacePackage Use Strict Arg program, name q = self~findNamespace( program, name ) If q == .Nil Then Raise Syntax 98.987 Array( Upper( name ), program~path ) Return q -- ns:name, a class (ooRexx's ClassResolver): a public class of the package -- tagged ns (98.988 when there is none). ::Method namespaceClass Use Strict Arg program, ns, name q = self~namespacePackage( program, ns ) If q == self~prelude Then c = self~rexxClasses( .True )[ Upper( name ) ] Else c = self~findPublicClass( q, name ) If c == .Nil Then Raise Syntax 98.988 Array( Upper( name ), Upper( ns ) ) Return c -- A public routine of a package (ooRexx's findPublicRoutine): its own, those -- of the packages it requires, its parent's. ::Method findPublicRoutine Class Use Strict Arg program, name name = Upper( name ) p = program Do While p \== .Nil r = p~publicRoutines[ name ] If r \== .Nil Then Return r r = p~importedRoutines[ name ] If r \== .Nil Then Return r p = p~parent End Return .Nil -- A routine seen from a program (ooRexx's findRoutine): its ::ROUTINEs (and -- those it was given), its parents', then the public ones it and its parents -- import; or .Nil. The name is found in any case. ::Method findRoutine Class Use Strict Arg program, name name = Upper( name ) p = program Do While p \== .Nil r = p~routines[ name ] If r \== .Nil Then Return r p = p~parent End p = program Do While p \== .Nil r = p~publicRoutines[ name ] If r \== .Nil Then Return r r = p~importedRoutines[ name ] If r \== .Nil Then Return r p = p~parent End Return .Nil -- .METHODS of a program: a StringTable of its floating methods (the -- directives before the first ::CLASS) as Method objects, made once; .Nil -- when it has none. ::Method methodsTable Expose stringTableClass Use Strict Arg program If program~methodsObj \== .Nil Then Return program~methodsObj If program~floating~isEmpty Then Return .Nil t = self~newInstance( stringTableClass ) Do With Index name Item m Over program~floating t~native[ name ] = self~methodObject( m ) End program~methodsObj = t Return t /*----------------------------------------------------------------------------*/ /* Classes, as ooRexx's RexxClass (ClassClass.cpp): a class has its */ /* superclasses (its superclass, then the classes it inherits) and its */ /* subclasses; the behaviour of its instances is made from the instance */ /* methods of its superclasses, the last first, each once, and then its own */ /* (createInstanceBehaviour); its own behaviour, from the class methods of */ /* its superclasses, then its metaclass's instance behaviour, then its own */ /* class methods (createClassBehaviour). A change (INHERIT, UNINHERIT) makes */ /* again, in place, its behaviours and those of its subclasses */ /* (updateSubClasses); DEFINE and DELETE give it a new instance behaviour */ /* first, so the objects it made before do not see the change */ /* (updateInstanceSubClasses). */ /*----------------------------------------------------------------------------*/ -- The behaviour of the instances of a class (made the first time). ::Method instanceBehaviour Use Strict Arg c data = c~native If data~instBeh \== .Nil Then Return data~instBeh b = .RVM.Behaviour~new( c ) data~instBeh = b self~createInstanceBehaviour( c, b ) Return b ::Method createInstanceBehaviour Use Strict Arg c, target data = c~native supers = data~superclasses Do i = supers~items To 1 By -1 If \ target~hasScope( supers[i] ) Then self~createInstanceBehaviour( supers[i], target ) End If \ target~hasScope( c ) Then Do target~mergeTable( data~imethods ) target~addScope( c ) End ::Method createClassBehaviour Expose objectClass Use Strict Arg c, target data = c~native supers = data~superclasses Do i = supers~items To 1 By -1 If \ target~hasScope( supers[i] ) Then self~createClassBehaviour( supers[i], target ) End If \ target~hasScope( c ) Then Do If c \== objectClass Then Do meta = data~metaclass If \ target~hasScope( meta ) Then target~mergeBehaviour( self~instanceBehaviour( meta ) ) End target~mergeTable( data~cmethods ) target~addScope( c ) End -- The behaviour of a class object, made (again, in place). Object's is its -- class methods (with its instance methods) and Class's instance -- behaviour (as buildFinalClassBehaviour made it). ::Method buildClassBehaviour Expose objectClass classClass Use Strict Arg c b = c~beh If b == .Nil Then Do b = .RVM.Behaviour~new( c~native~metaclass ) c~beh = b End Else b~clear If c == objectClass Then Do b~mergeTable( c~native~cmethods ) b~mergeBehaviour( self~instanceBehaviour( classClass ) ) b~addScope( objectClass ) End Else self~createClassBehaviour( c, b ) -- The behaviour of the instances of a class, made again in place. ::Method rebuildInstanceBehaviour Use Strict Arg c data = c~native If data~instBeh == .Nil Then Return data~instBeh~clear self~createInstanceBehaviour( c, data~instBeh ) -- ooRexx's updateSubClasses: both behaviours again, and its subclasses'. ::Method updateSubClasses Use Strict Arg c self~rebuildInstanceBehaviour( c ) self~buildClassBehaviour( c ) Do s Over c~native~subclasses~copy self~updateSubClasses( s ) End -- ooRexx's updateInstanceSubClasses: the instance behaviours only. ::Method updateInstanceSubClasses Use Strict Arg c self~rebuildInstanceBehaviour( c ) Do s Over c~native~subclasses~copy self~updateInstanceSubClasses( s ) End -- A new instance behaviour for class c (DEFINE, DELETE): the objects it made -- keep the one they have. ::Method newInstanceBehaviour Use Strict Arg c c~native~instBeh = self~instanceBehaviour( c )~copyBehaviour /*----------------------------------------------------------------------------*/ /* A new class (ooRexx's subclass and mixinClass): NEW is sent to the */ /* metaclass (Class's NEW, a native: the new class, whose INIT runs); then */ /* the class gets its superclass, its class methods and its behaviours; and */ /* then INIT is sent again (its class methods are there now: an INIT of its */ /* own runs; the metaclass's INIT runs twice). A native that makes one */ /* returns what subclass returns: the delegate that sends NEW. 'then' (or */ /* .Nil) goes on when the class is made (NEXT, with it). */ /*----------------------------------------------------------------------------*/ ::Method subclass Use Strict Arg receiver, id, meta, methods, home, mixin, after If meta == .Nil Then meta = receiver~native~metaclass ok = meta~isA( .RVM.Obj ) If ok Then ok = meta~isClass If ok Then ok = meta~native~isMeta If \ ok Then Raise Syntax 99.927 Array( ObjectText( meta ) ) steps = .RVM.MakeClass~new( self, receiver, meta, methods, home, mixin, after ) d = .RVM.Delegate~new( meta, "NEW", .Array~of( id ) ) d~then = steps Return d -- The class meta~NEW made (c) becomes a subclass of 'receiver'. ::Method finishSubclass Use Strict Arg receiver, c, meta, methods, home data = c~native sdata = receiver~native data~bare = .False data~home = home If sdata~isMeta Then Do data~isMeta = .True data~metaclass = receiver End data~kind = sdata~kind data~superclass = receiver data~superclasses = .Array~of( receiver ) If methods \== .Nil Then Do With Index name Item m Over methods If m \== .Nil Then m~scope = c data~cmethods[ name ] = m End self~buildClassBehaviour( c ) c~beh~cls = meta If data~instBeh == .Nil Then data~instBeh = .RVM.Behaviour~new( c ) data~instBeh~clear self~createInstanceBehaviour( c, data~instBeh ) data~instBeh~cls = c sdata~subclasses~insert( c, .Nil ) self~created( c ) -- an UNINIT class method, maybe -- Class's NEW (ooRexx's RexxClass~newRexx), to metaclass 'meta': a class -- that is an instance of it, a subclass of Object with no methods of its -- own; INIT is sent to it with the other arguments. ::Method newClassOf Expose objectClass classClass classes Use Strict Arg meta, id, rest mdata = meta~native metaclass = meta If mdata~primitive Then metaclass = classClass data = .RVM.ClassData~new( id, objectClass, metaclass, "OBJECT" ) data~baseClass = .Nil data~home = mdata~home c = .RVM.Obj~new( self~instanceBehaviour( meta )~copyBehaviour, data ) c~beh~cls = meta data~baseClass = c data~bare = .True b = self~instanceBehaviour( objectClass )~copyBehaviour b~cls = objectClass data~instBeh = b classes~append( c ) self~created( c ) Return .RVM.Delegate~new( c, "INIT", rest, c ) -- INHERIT (ooRexx's RexxClass~inherit): mixin m goes last in c's -- superclasses (or before 'position', as ooRexx does: its insertAfter -- inserts at the index), and c and its subclasses are made again. ::Method inherit Use Strict Arg c, m, position = .Nil data = c~native If data~rexx, \ self~building Then Raise Syntax 98.985 ok = m~isA( .RVM.Obj ) If ok Then ok = m~isClass If ok Then ok = m~native~mixin If \ ok Then Raise Syntax 98.942 Array( ObjectText( m ) ) If c == m | c~beh~hasScope( m ) | m~beh~hasScope( c ) Then Raise Syntax 98.944 Array( ObjectText( c ), ObjectText( m ) ) base = m~native~baseClass If \ c~beh~hasScope( base ) | \ self~instanceBehaviour( c )~hasScope( base ) Then Raise Syntax 98.943 Array( ObjectText( c ), ObjectText( m ), ObjectText( base ) ) If position == .Nil Then data~superclasses~append( m ) Else Do k = IdentityIndex( data~superclasses, position ) If k == 0 Then Raise Syntax 98.945 Array( ObjectText( c ), ObjectText( position ) ) If k == 1 Then data~superclasses~insert( m, .Nil ) Else data~superclasses~insert( m, k - 1 ) End m~native~subclasses~insert( c, .Nil ) self~updateSubClasses( c ) -- UNINHERIT (ooRexx's RexxClass~uninherit): not the first superclass -- (98.945). ooRexx then removes the mixin from the class's own subclasses -- (not the class from the mixin's): the mixin keeps it as a subclass. ::Method uninherit Use Strict Arg c, m data = c~native If data~rexx, \ self~building Then Raise Syntax 98.985 ok = m~isA( .RVM.Obj ) If ok Then ok = m~isClass If ok Then ok = m~native~mixin If \ ok Then Raise Syntax 98.942 Array( ObjectText( m ) ) k = IdentityIndex( data~superclasses, m ) If k <= 1 Then Raise Syntax 98.945 Array( ObjectText( c ), ObjectText( m ) ) data~superclasses~delete( k ) k = IdentityIndex( data~subclasses, m ) If k > 0 Then data~subclasses~delete( k ) self~updateSubClasses( c ) /*----------------------------------------------------------------------------*/ /* The prelude: ooRexx's CoreClasses.orx (prelude.orx, see makeprelude.rex), */ /* the Rexx part of the REXX package. It is loaded when a run first needs it */ /* (a method or an environment symbol not found, what a class says of its */ /* scopes): a program that uses no objects never pays for it. Its classes */ /* are made, and then its prolog runs, as in ooRexx's image build */ /* (RVM.Machine~runSync): the class methods of String written in */ /* Rexx, the methods of the mixins copied into Supplier, Relation, Bag and */ /* Set, the INHERITs of the primitive classes, the public classes in */ /* .ENVIRONMENT. The behaviours made before change in place (the objects that */ /* hold them see the new methods). The bootstrap adds the RVM's own part. */ /*----------------------------------------------------------------------------*/ -- While the prelude's prolog runs (ooRexx's image build: the REXX package -- is not internal code yet). ::Attribute building ::Method ensurePrelude Expose prelude loader classClass building If prelude \== .Nil | loader == .Nil Then Return program = loader~load prelude = program context = loader~context -- Its clauses have no text: a traceback line says which method it is. Do c Over program~clauses If c \== .Nil Then c~text = .Nil End self~installNow( program, context ) -- Its classes are the REXX package's (once made: DEFINE, INHERIT... -- 98.985). Do c Over program~classObjs~allItems c~native~rexx = .True End self~bootstrap( program ) -- The prolog of CoreClasses runs, as in ooRexx's image build (the REXX -- package is its argument), and then the setup methods go -- (removeSetupMethods). building = .True loader~runProlog( program, self~packageObject( program ) ) building = .False classClass~native~imethods~remove( "DEFINECLASSMETHOD" ) classClass~native~imethods~remove( "INHERITINSTANCEMETHODS" ) self~refresh -- StreamClasses.orx (prelude-streams.orx): a program of its own that -- sees the prelude's classes; its public classes are the REXX package's -- and in .ENVIRONMENT (what its prolog does in ooRexx). streams = loader~loadStreams If streams == .Nil Then Return Do c Over streams~clauses If c \== .Nil Then c~text = .Nil End Call MergeRequired streams, program self~installNow( streams, context ) Do With Index name Item c Over streams~classObjs c~native~rexx = .True If \ program~classObjs~hasIndex( name ) Then program~classObjs[ name ] = c End Do With Index name Item c Over streams~publicClasses program~publicClasses[ name ] = c self~environment~native[ name ] = c End ::Method bootstrap Private Expose stringClass supplierClass relationClass bagClass setClass arrayClass - listClass queueClass tableClass stringTableClass directoryClass sortMethods - stemClass messageClass Use Strict Arg program classes = program~classObjs -- The RVM's part (prelude-rvm.orx): Array's SORTWITH and STABLESORTWITH, -- and its SORT and STABLESORT of objects (see V.SORT), compiled methods -- in ooRexx. sorts = classes["RVM.ARRAYSORT"]~native~imethods Do name Over .Array~of( "SORTWITH", "STABLESORTWITH" ) m = CopyMethod( sorts["SORTWITH"], name, arrayClass ) m~compiled = .True arrayClass~native~imethods[ name ] = m End Do name Over .Array~of( "SORT", "STABLESORT" ) m = CopyMethod( sorts["SORT"], name, arrayClass ) m~compiled = .True sortMethods[ name ] = m End -- Every behaviour made again, in place, from the classes as they are now. ::Method refresh Expose classes Do c Over classes If \ c~native~bare Then self~rebuildInstanceBehaviour( c ) End Do c Over classes If c~beh \== .Nil, \ c~native~bare Then self~buildClassBehaviour( c ) End -- A new instance of a class (NEW), before its INIT. ::Method newInstance Use Strict Arg c self~checkAbstract( c ) kind = c~native~kind -- (A metaclass instantiated through Object's NEW, .meta~new:.object: a -- plain object, as ooRexx's RexxObject::newRexx makes; Class's methods on -- it read a class it is not, see doc/17.) o = .RVM.Obj~new( self~instanceBehaviour( c ) ) If kind == "DIRECTORY" Then o~native = .Directory~new If kind == "ARRAY" Then o~native = .Array~new If kind == "SUPPLIER" Then o~native = .RVM.SupplierState~new( .Array~new, .Array~new ) If kind == "TABLE" Then o~native = .Table~new If kind == "IDTABLE" Then o~native = .IdentityTable~new -- A List's contents are made by its INIT (their capacity), or when it is -- first used (see ListNative). If kind == "QUEUE" Then o~native = .Queue~new If kind == "STEM" Then Do o~native = .RVM.Stem~new o~native~obj = o End self~created( o ) Return o ::Method newDirectory Expose directoryClass Return self~newInstance( directoryClass ) -- A new Array holding a host array. ::Method newArray Expose arrayClass Use Strict Arg native Return .RVM.Obj~new( self~instanceBehaviour( arrayClass ), native ) -- A new object of class c holding 'native' (no INIT). ::Method newOf Use Strict Arg c, native o = .RVM.Obj~new( self~instanceBehaviour( c ), native ) self~created( o ) Return o -- UNINIT (ooRexx's requiresUninit and lastChanceUninit). An object made -- with an UNINIT method (or given one by SETMETHOD; a class, by its class -- methods) is kept, in the order they are made. When the run is over (see -- RVM.Machine~run), those that cannot be reached from .ENVIRONMENT -- (uninitsDue: ooRexx's last collection) get UNINIT, in that order. ::Method created Expose uninits tracked Use Strict Arg o If o~beh == .Nil Then Return If tracked~hasIndex( o ) Then Return If \ HasUninit( o ) Then Return tracked[ o ] = .True uninits~append( o ) -- Are there objects kept for their UNINIT? ::Method hasUninits Expose uninits Return \ uninits~isEmpty -- The objects kept that are due their UNINIT now (and are forgotten). ::Method uninitsDue Expose uninits tracked environment local due = .Array~new If uninits~isEmpty Then Return due -- .LOCAL is the run's: what only it holds is not reached. marked = .IdentityTable~new marked[ local ] = .True todo = .Array~of( environment ) Do While \ todo~isEmpty v = todo[ todo~last ] todo~delete( todo~last ) Call MarkValue v, marked, todo End Do o Over uninits If marked~hasIndex( o ) Then Iterate If \ HasUninit( o ) Then Iterate due~append( o ) End uninits = .Array~new tracked = .IdentityTable~new Return due -- NEW of an abstract class (ooRexx's checkAbstract, in completeNewObject: -- after the arguments are checked, before INIT). ::Method checkAbstract Use Strict Arg c If c~native~abstract Then Raise Syntax 98.989 Array( c~native~id ) -- The annotations of a class, a method, a routine or a package (h: its -- RVM.ClassData, RVM.Method, RVM.Routine or RVM.Program): a StringTable of -- its own, made from its pairs when it is first asked for; it can be -- changed (ooRexx's getAnnotations). ::Method annotationsOf Expose stringTableClass Use Strict Arg h If h~annotationsObj == .Nil Then Do t = self~newInstance( stringTableClass ) Do pair Over h~annotations t~native[ pair[1] ] = pair[2] End h~annotationsObj = t End Return h~annotationsObj -- ANNOTATION: one of them, by its name in upper case (a StringTable's -- ENTRY), or .NIL. ::Method annotationOf Use Strict Arg h, name v = self~annotationsOf( h )~native[ Upper( name ) ] If v == .Nil Then Return self~nil Return v -- The Stem object of an RVM.Stem (a stem variable's value): made once, so -- that the same stem is always the same object. ::Method stemObjectOf Expose stemClass Use Strict Arg st If st~obj == .Nil Then st~obj = .RVM.Obj~new( self~instanceBehaviour( stemClass ), st ) Return st~obj -- A new VariableReference to 'var' (an RVM.Var), whose name is 'name' (a -- stem's ends in a period): each >x makes a new one, as ooRexx's. ::Method newVarRef Expose varRefClass Use Strict Arg var, name Return .RVM.Obj~new( self~instanceBehaviour( varRefClass ), .RVM.VarRef~new( var, name ) ) -- The RVM.Stem of a value that is a Stem object, or .Nil. Of the class Stem -- itself, as ooRexx's isStem: an instance of a subclass is not one. ::Method stemOf Expose stemClass Use Strict Arg v If \ v~isA( .RVM.Obj ) Then Return .Nil If \ v~native~isA( .RVM.Stem ) Then Return .Nil If v~beh~cls \== stemClass Then Return .Nil Return v~native -- A new Supplier of these items and indexes (host arrays). ::Method newSupplier Expose supplierClass Use Strict Arg items, indexes Return .RVM.Obj~new( self~instanceBehaviour( supplierClass ), - .RVM.SupplierState~new( items, indexes ) ) -- The behaviour of any value. ::Method behaviourOf Expose stringClass Use Strict Arg v If v~isA( .RVM.Obj ) Then Return v~beh Return self~instanceBehaviour( stringClass ) -- The class of any value. ::Method classOf Expose stringClass Use Strict Arg v If v~isA( .RVM.Obj ) Then Return v~beh~cls Return stringClass -- Ask a security manager (mgr) about 'event' (ooRexx's SecurityManager): -- the message of that name, with a Directory holding 'entries' (pairs: -- index, item). .Nil when it lets it go on (0); when it handles it (1), the -- entries as it left them (a host Directory: RESULT, NAME, RC...). No -- result is 91.999; anything but 0 or 1, 34.903. ::Method security Expose loader Use Strict Arg mgr, event, entries info = self~newDirectory Do i = 1 To entries~items By 2 info~native[ entries[i] ] = entries[ i + 1 ] End v = loader~sendSync( mgr, event, .Array~of( info ) ) If v == .Nil Then Raise Syntax 91.999 Array( event ) If v~isA( .RVM.Obj ) Then v = loader~sendSync( v, "STRING", .Array~new ) s = str( v ) If s \== "0", s \== "1" Then Raise Syntax 34.903 Array( s ) If s == "0" Then Return .Nil Return info~native -- An environment symbol (".X", or "X"): the classes of the program, the -- public classes of the packages it requires, the builtins, .LOCAL, -- .ENVIRONMENT, or else its name. ::Method env Expose builtins local environment localState envCached Use Strict Arg symbol, program = .Nil, specials = .False -- (What it finds in the package's classes, those it sees, and the REXX -- package's may be kept by the ENV that asked: envCached.) envCached = .True name = symbol If Left( name, 1 ) == "." Then name = SubStr( name, 2 ) If program \== .Nil Then Do classes = program~classObjs If classes \== .Nil Then Do v = classes[ Upper( name ) ] If v \== .Nil Then Return v End v = program~importedClasses[ Upper( name ) ] If v \== .Nil Then Return v -- A program compiled at run time sees its parent's classes too. parent = program~parent Do While parent \== .Nil If parent~classObjs \== .Nil Then Do v = parent~classObjs[ Upper( name ) ] If v \== .Nil Then Return v End v = parent~importedClasses[ Upper( name ) ] If v \== .Nil Then Return v parent = parent~parent End End -- The package's security manager (ooRexx's PackageClass::findClass): it -- is asked before .LOCAL (LOCAL) and before .ENVIRONMENT (ENVIRONMENT); -- what it gives (its RESULT) is the value. (The prelude first: the -- search is not made twice, see below.) mgr = .Nil If program \== .Nil Then If program~hasMethod( "SECMGR" ) Then mgr = program~secMgr If mgr \== .Nil, self~prelude == .Nil, self~loader \== .Nil Then self~ensurePrelude -- .LOCAL, and what it holds from the start: made now (see ensureLocal). If localState == "" Then If WordPos( Upper( name ), self~LOCALNAMES ) > 0 Then self~ensureLocal v = builtins[ name ] If v \== .Nil Then Return v -- The REXX package's public classes (the prelude's), before the package's -- local directory and .LOCAL (ooRexx's PackageClass::findClass). (Until -- the prelude is loaded nothing can be in those: a message to them loads -- it.) If self~prelude \== .Nil Then Do v = self~prelude~publicClasses[ Upper( name ) ] If v \== .Nil Then Return v End envCached = .False -- The package's own local directory (its LOCAL), before .LOCAL. If program \== .Nil, program~localObj \== .Nil Then Do v = program~localObj~native[ Upper( name ) ] If v \== .Nil Then Return v End If mgr \== .Nil Then Do info = self~security( mgr, "LOCAL", .Array~of( "NAME", Upper( name ) ) ) If info \== .Nil Then If info["RESULT"] \== .Nil Then Return info["RESULT"] End v = local~native[ name ] If v \== .Nil Then Return v If mgr \== .Nil Then Do info = self~security( mgr, "ENVIRONMENT", .Array~of( "NAME", Upper( name ) ) ) If info \== .Nil Then If info["RESULT"] \== .Nil Then Return info["RESULT"] End v = environment~native[ name ] If v \== .Nil Then Return v -- Not found: the ENV instruction asks for the special ones (.ROUTINES) -- after these, with no prelude (see the machine's DotSpecial). If specials, WordPos( Upper( name ), "ROUTINES METHODS RESOURCES LINE" ) > 0 Then Return .Nil -- Not found: it may be a class of the prelude. If self~prelude == .Nil, self~loader \== .Nil Then Do self~ensurePrelude Return self~env( symbol, program, specials ) End If specials Then Return .Nil Return symbol /*----------------------------------------------------------------------------*/ /* .LOCAL: ooRexx's LocalServer (the prelude's) makes it, as the interpreter */ /* does when an instance starts (Interpreter::initLocal). Here, when it is */ /* first seen: a message to the directory, or one of its names (LOCALNAMES) */ /* looked for; until then, and while its monitors are as they were made and */ /* send to the streams they started with, SAY and the standard streams go to */ /* the host straight (localTarget), as they would through them. */ /*----------------------------------------------------------------------------*/ ::Constant LOCALNAMES "LOCAL STDIN INPUT DEBUGINPUT STDOUT OUTPUT STDERR ERROR TRACEOUTPUT STDQUE SYSCARGS" ::Method ensureLocal Expose local localState localOrig localDest loader prelude If localState \== "" | loader == .Nil Then Return localState = "MAKING" self~ensurePrelude -- .LocalServer~new: its INIT opens the standard streams and runs -- INITINSTANCE (STDQUE: a RexxQueue of SESSION, the current queue: see -- RVM.Queues). loader~sendSync( prelude~classObjs[ "LOCALSERVER" ], "NEW", .Array~new ) If local~native[ "STDQUE" ]~isA( .RVM.Obj ), prelude~classObjs~hasIndex( "REXXQUEUE" ) Then Do .RVM.Queues~scope = prelude~classObjs[ "REXXQUEUE" ] .RVM.Queues~stdque = local~native[ "STDQUE" ] End -- SYSCARGS: the arguments of the command line, as the rexx command sets. -- (.False: none, as ooRexx's "rexx -e".) a = loader~context~syscargs If a == .Nil Then a = .Array~new If a \== .False Then local~native[ "SYSCARGS" ] = self~newArray( a~copy ) monitor = prelude~classObjs[ "MONITOR" ] Do name Over .Array~of( "INPUT", "OUTPUT", "ERROR", "TRACEOUTPUT", "DEBUGINPUT" ) m = local~native[ name ] localOrig[ name ] = m localDest[ name ] = MonitorDestination( m, monitor ) End -- .STDIN, .STDOUT and .STDERR are the streams the functions use for -- STDIN, STDOUT and STDERR (ooRexx's resolveStream sends to .INPUT...): -- one state (positions, NOTREADY), which matters when one is a file. std = loader~context~rootStreams( .RVM.StreamTable )~standard Do With Index i Item name Over .Array~of( "STDIN", "STDOUT", "STDERR" ) s = local~native[ name ] If s~isA( .RVM.Obj ), s~native~isA( .RVM.Stream ) Then Do s~native = std[ i ] std[ i ]~rexxObject = s End End localState = "MADE" -- Where a standard stream goes: .Nil, to the host straight (.LOCAL not made -- yet, or the monitor NAME as it was made and sending to its first -- destination, or, for SAY, nothing there: ooRexx's sayOutput writes then); -- else the object to send to. ::Method localTarget Expose local localState localEager localOrig localDest prelude Use Strict Arg name, forSay = .False If localState \== "MADE" Then Return .Nil v = local~native[ name ] If \ v~isA( .RVM.Obj ) Then Return v If v == self~nil Then Do If forSay Then Return .Nil Return v End If localEager Then Return v If v \== localOrig[ name ] Then Return v d = MonitorDestination( v, prelude~classObjs[ "MONITOR" ] ) If d == .Nil Then Return v If d \== localDest[ name ] Then Return v Return .Nil -- Where the queue instructions and functions go (ooRexx sends .STDQUE -- PUSH, QUEUE, PULL, QUEUED, LINEIN): .Nil, the queue straight (.LOCAL not -- made yet, or .STDQUE the RexxQueue it was made with and, when 'strict', -- its queue there: else PUSH and QUEUE fail inside RexxQueue's method, as -- native); else the object to send to (.nil when there is no STDQUE). ::Method queueTarget Expose local localState localEager Use Strict Arg strict = .False If localState \== "MADE" Then Return .Nil v = local~native[ "STDQUE" ] If v == .Nil Then Return self~nil If localEager Then Return v If v \== .RVM.Queues~stdque Then Return v If strict, .RVM.Queues~exists( .RVM.Queues~current ) == 0 Then Return v Return .Nil -- A line of trace output (ooRexx's processTraceInfo, createTraceObject and -- Activity~traceOutput): a TraceObject, sent to .TRACEOUTPUT with LINEOUT. -- Only when someone could tell: .TRACEOUTPUT is not the monitor .LOCAL -- started with, sending to .ERROR, or TraceObject's class attributes are -- not those it starts with (OPTION "N", no COLLECTOR, NOTIFY nor -- makeString method); else (and while a TraceObject is being sent) .False: -- the context writes the line straight, as it did. 'info' (or .Nil): what -- the line traces (see RVM.TraceInfo). If the send fails, .False too (the -- line is not lost; ooRexx: "don't lose the data!"). ::Method traceObject Expose local localState prelude loader traceBusy Use Strict Arg line, context, info = .Nil If traceBusy == .True Then Return .False If prelude == .Nil Then Return .False toc = prelude~classObjs[ "TRACEOBJECT" ] If toc == .Nil Then Return .False -- (.LOCAL not made yet: .TRACEOUTPUT is as it starts.) If localState == "MADE" Then target = self~localTarget( "TRACEOUTPUT" ) Else target = .Nil If target == self~nil Then Return .False If target == .Nil Then Do If \ self~traceObjectsOn Then Return .False If localState == "" Then self~ensureLocal If localState \== "MADE" Then Return .False target = local~native[ "TRACEOUTPUT" ] End pool = toc~pool( toc ) notify = pool~valueOf( "NOTIFY" ) If notify == self~nil Then notify = .Nil traceBusy = .True Signal On Syntax Name TraceFailed obj = loader~sendSync( toc, "NEW", .Array~new ) t = obj~native t[ "TRACELINE" ] = line t[ "INTERPRETER" ] = 1 act = context~activity If act == .Nil Then t[ "THREAD" ] = 1 Else t[ "THREAD" ] = act~id lv = context~level stub = .False If info \== .Nil Then stub = ( info[1] == "STUB" ) If stub Then Do -- The stub routine of an install (see InstallTrace): an activation of -- its own, called from the one running. lv = .Nil t[ "INVOCATION" ] = info[4] st = self~newInstance( self~stringTableClass ) st~native[ "ARGUMENTS" ] = self~newArray( .Array~new ) st~native[ "INVOCATION" ] = info[4] st~native[ "LINE" ] = 1 st~native[ "NAME" ] = info[2] st~native[ "TRACELINE" ] = "" st~native[ "TYPE" ] = "ROUTINE" st~native[ "EXECUTABLE" ] = self~nil st~native[ "TARGET" ] = self~nil t[ "STACKFRAME" ] = st If info[3] == ">I>" Then t[ "CALLERSTACKFRAME" ] = self~frameTable( context ) End Else Do If lv == .Nil Then t[ "INVOCATION" ] = 0 Else t[ "INVOCATION" ] = lv~invocation t[ "STACKFRAME" ] = self~frameTable( context ) End If info \== .Nil, \ stub Then Select Case info[1] -- A variable: its name and value, and whether it is an assignment. When ">V>", ">=>" Then Do vt = self~newInstance( self~stringTableClass ) vt~native[ "NAME" ] = info[2] vt~native[ "VALUE" ] = info[3] vt~native[ "ASSIGNMENT" ] = ( info[1] == ">=>" )~?( "1", "0" ) t[ "VARIABLE" ] = vt End -- An entry: who called (a new activity's: who started it; see -- spawnerInfo). When ">I>" Then Do caller = .Nil If context~stackLines~items > 1 Then caller = self~frameTable( context, 2 ) Else If act \== .Nil Then caller = act~spawnerInfo If caller == .Nil Then caller = self~nil t[ "CALLERSTACKFRAME" ] = caller End Otherwise Nop End -- A method: its object's variables, its lock. If lv \== .Nil, lv~type == "METHOD" Then Do m = lv~exec pool = lv~pool If pool == .Nil, lv~target~isA( .RVM.Obj ), m~isA( .RVM.Method ) Then pool = lv~target~pool( m~scope ) If pool \== .Nil Then Do t[ "ATTRIBUTEPOOL" ] = pool~id t[ "SCOPELOCKCOUNT" ] = pool~reserveCount End Else Do t[ "ATTRIBUTEPOOL" ] = 0 t[ "SCOPELOCKCOUNT" ] = 0 End guarded = .True If m~isA( .RVM.Method ) Then guarded = \ m~hasFlag( "U" ) t[ "ISGUARDED" ] = guarded~?( "1", "0" ) t[ "HASSCOPELOCK" ] = lv~locked~?( "1", "0" ) If lv~target \== .Nil Then t[ "RECEIVER" ] = lv~target If info \== .Nil, info[1] == ">K>", info[2] == "WHEN" Then t[ "ISWAITING" ] = ( str( info[3] ) == "0" )~?( "1", "0" ) End If notify \== .Nil Then loader~sendSync( notify, "APPEND", .Array~of( obj ) ) -- Profiling (OPTION "P"): collected, not written. If t[ "OPTION" ] \== "P" Then loader~sendSync( target, "LINEOUT", .Array~of( obj ) ) traceBusy = .False Return .True -- An error (a destination with no LINEOUT: 97.1) is the program's when -- something there traps it (ooRexx's traceOutput catches only what goes up -- to it); else the line is written directly (ooRexx: its lineOut). TraceFailed: traceBusy = .False If context~trapsBelow( "SYNTAX" ) Then Raise Propagate .RVM.ConditionInfo~syncFailure = .Nil -- (the error is not going on) Return .False -- Could trace lines be TraceObjects now (see traceObject)? A new activity -- keeps who started it only then (spawnerInfo). ::Method traceObjectsOn Expose localState prelude If prelude == .Nil Then Return .False toc = prelude~classObjs[ "TRACEOBJECT" ] If toc == .Nil Then Return .False If localState == "MADE", self~localTarget( "TRACEOUTPUT" ) \== .Nil Then Return .True pool = toc~pool( toc ) If IsSet( pool~valueOf( "NOTIFY" ), self ) Then Return .True If pool~valueOf( "OPTION" ) \== "N" Then Return .True If IsSet( pool~valueOf( "COLLECTOR" ), self ) Then Return .True Return IsSet( pool~valueOf( "MAKESTRINGMETHOD" ), self ) -- Who starts a new activity (START, REPLY), as the CALLERSTACKFRAME of the -- TraceObjects of its first entry (ooRexx's setCallerStackFrameAsStringTable): -- the StackFrame of the activation that started it (skipFirst: the one -- before it), with its THREAD; .Nil unless traceObjectsOn. ::Method spawnerInfo Use Strict Arg context, skipFirst If \ self~traceObjectsOn Then Return .Nil st = self~frameTable( context, 1 + skipFirst ) act = context~activity If act == .Nil Then st~native[ "THREAD" ] = 1 Else st~native[ "THREAD" ] = act~id Return st -- The StackFrame of the activation running, as a StringTable (ooRexx's -- getStackFrameAsStringTable): what the TraceObject of a trace line keeps. ::Method frameTable Use Strict Arg context, which = 1 st = self~newInstance( self~stringTableClass ) lines = context~stackLines If \ lines~hasIndex( which ) Then Return st fi = lines[ which ][ 5 ] If fi == .Nil Then Return st sf = self~stackFrameObject( fi ) Do name Over .Array~of( "ARGUMENTS", "INVOCATION", "LINE", "NAME", - "TRACELINE", "TYPE", "EXECUTABLE", "TARGET" ) st~native[ name ] = StackFrameNative( name, sf, .Array~new, context, self ) End Return st -- The classes of a program (its CLASSES and METHODS), made when it starts -- to run, once the packages it requires have been loaded: first what it -- sees of those (their public classes and routines); then its methods, and -- the order the classes are made in (ooRexx's resolveDependencies: the first -- one whose superclass, metaclass and mixins of this program are made); -- then each class is made as ooRexx's ClassDirective~install does -- (RVM.Installer). What this returns runs them: .Nil when the program has -- no classes, or the delegate that makes the first one (the machine sends -- it; see also installNow). ::Method install Use Strict Arg program, context, ready = .False If program~classObjs \== .Nil Then Return .Nil Do p Over program~required Call MergeRequired program, p End objs = .Directory~new program~classObjs = objs Do r Over program~routineList If r~public, \ program~publicRoutines~hasIndex( r~name ) Then program~publicRoutines[ r~name ] = r End entries = program~classes -- The methods of each class (their scope, when it is made). imethods = .Array~new cmethods = .Array~new Do k = 1 To entries~items imethods[k] = .Table~new cmethods[k] = .Table~new End Do m Over program~methods method = .RVM.Method~new( m~name, .Nil, m~key, 0, -1 ) method~flags = m~flags method~extent = m~extent method~home = program method~annotations = m~annotations Select Case m~key When "R" Then Do method~program = program method~address = m~value method~labels = m~labels method~firstClause = FirstClause( program, m~value ) End When "A.GET" Then Do method~var = m~value method~max = 0 End When "A.SET" Then Do method~var = m~value method~min = 1 method~max = 1 End When "A.DELEGATE" Then method~var = m~value When "A.CONST" Then Do If m~value == "-" Then method~value = .Nil -- calculated Else method~value = program~consts[ m~value ] method~max = 0 End -- EXTERNAL (not REXX): its specification, NAME and prefix; it fails -- when it runs (see CallNative). When "L" Then method~value = m~library Otherwise Nop End Select -- A floating method (before the first ::CLASS). When m~cls == 0 Then program~floating[ m~name ] = method When m~which == "K" Then entries[ m~cls ]~constInit = method When m~which == "I" Then imethods[ m~cls ][ m~name ] = method Otherwise cmethods[ m~cls ][ m~name ] = method End End If entries~isEmpty Then Return .Nil -- The order: what each class needs of this program. ids = .Set~new Do e Over entries ids~put( Upper( e~id ) ) End needs = .Array~new Do k = 1 To entries~items e = entries[k] n = .Set~new names = .Array~new If e~superNS == "" Then names~append( e~super ) If e~metaNS == "" Then names~append( e~meta ) Do i = 1 To e~inherit~items If e~inheritNS[i] == "" Then names~append( e~inherit[i] ) End Do name Over names If name \== "", ids~hasIndex( name ) Then n~put( name ) End needs[k] = n End order = .Array~new pending = .Array~new Do k = 1 To entries~items pending~append( k ) End Do While \ pending~isEmpty next = 0 Do i = 1 To pending~items If needs[ pending[i] ]~isEmpty Then Do next = pending[i] pending~delete( i ) Leave End End If next == 0 Then Do context~clause = program~clauses[ entries[ pending[1] ]~clause ] Raise Syntax 98.911 Array( program~path ) End order~append( next ) Do k Over pending needs[k]~remove( Upper( entries[ next ]~id ) ) End End installer = .RVM.Installer~new( self, program, order, imethods, cmethods ) installer~ready = ready Return installer~nextClass( context ) -- Install a program here, with no machine: every message it sends must -- find a native (the prelude's classes, a package made by a native). ::Method installNow Use Strict Arg program, context clause = context~clause v = self~install( program, context ) Call RunNatives v, context, .True context~clause = clause -- What program p sees of a package t it imports (ooRexx's mergeRequired): -- its public classes and routines, and those it imports in its turn (the -- first wins). ::Routine MergeRequired Use Strict Arg p, t Call Merge p~importedRoutines, t~publicRoutines Call Merge p~importedRoutines, t~importedRoutines Call Merge p~importedClasses, t~publicClasses Call Merge p~importedClasses, t~importedClasses -- A copy of method m, named 'name', with class c as its scope. ::Routine CopyMethod Use Strict Arg m, name, c copy = .RVM.Method~new( name, c, m~key, m~min, m~max, m~argName ) copy~program = m~program copy~address = m~address copy~labels = m~labels copy~firstClause = m~firstClause copy~var = m~var copy~value = m~value copy~compiled = m~compiled copy~flags = m~flags copy~extent = m~extent copy~home = m~home copy~annotations = AnnotationPairs( m ) Return copy -- Has object o an UNINIT method (ooRexx's hasMethod: a private one does -- not count)? ::Routine HasUninit Use Strict Arg o m = o~beh~lookup( "UNINIT" ) If m == .Nil Then Return .False Return \ m~hasFlag( "P" ) -- A value reached from the roots of uninitsDue: what it holds is reached -- too (todo). An object: its class, its variables (and their scopes) and its -- native value; a class, its superclasses and metaclass (not its -- subclasses: ooRexx keeps them as weak references); a stem, its values; a -- message, its receiver, arguments, result and parties; the collections of -- the host, their items (and their indexes). ::Routine MarkValue Use Strict Arg v, marked, todo If v~isA( .String ) Then Return If marked~hasIndex( v ) Then Return marked[ v ] = .True Select When v~isA( .RVM.Obj ) Then Do If v~beh \== .Nil Then todo~append( v~beh~cls ) If v~pools \== .Nil Then Do todo~appendAll( v~pools~allItems ) todo~appendAll( v~pools~allIndexes ) End If v~native \== .Nil Then todo~append( v~native ) End When v~isA( .RVM.Var ) Then If v~value \== .Nil Then todo~append( v~value ) When v~isA( .RVM.VarRef ) Then todo~append( v~var ) When v~isA( .RVM.Stem ) Then Do todo~append( v~value ) todo~appendAll( v~tailItems ) If v~obj \== .Nil Then todo~append( v~obj ) End When v~isA( .RVM.MessageState ) Then Do todo~append( v~receiver ) todo~appendAll( v~args~allItems ) If v~result \== .Nil Then todo~append( v~result ) todo~appendAll( v~parties ) End When v~isA( .RVM.SupplierState ) Then Do todo~appendAll( v~items~allItems ) todo~appendAll( v~indexes~allItems ) End When v~isA( .RVM.ClassData ) Then Do todo~appendAll( v~superclasses ) If v~metaclass \== .Nil Then todo~append( v~metaclass ) If v~annotationsObj \== .Nil Then todo~append( v~annotationsObj ) End When v~isA( .Collection ) Then Do todo~appendAll( UnhashedArray( v~allItems ) ) If v~isA( .MapCollection ) Then todo~appendAll( UnhashedArray( v~allIndexes ) ) End Otherwise Nop End -- The annotations of a method or a routine, as pairs (name, value): those of -- its StringTable, when it has one (a copy has a copy of them). ::Routine AnnotationPairs Use Strict Arg h If h~annotationsObj == .Nil Then Return h~annotations pairs = .Array~new Do With Index name Item v Over h~annotationsObj~native pairs~append( .Array~of( name, v ) ) End Return pairs -- ooRexx's inheritInstanceMethods: the instance methods of 'mixin' copied -- into class c's own (their scope is c). ::Routine InheritInstanceMethods Use Strict Arg c, mixin Do With Index name Item m Over mixin~native~imethods c~native~imethods[ name ] = CopyMethod( m, name, c ) End -- Class c inherits mixin m (no checks: the prelude's own INHERITs). ::Routine AddInherit Use Strict Arg c, m c~native~superclasses~append( m ) m~native~subclasses~insert( c, .Nil ) -- Where x is in an array (the same object; 0: it is not). ::Routine IdentityIndex Use Strict Arg list, x Do i = 1 To list~items If list[i] == x Then Return i End Return 0 -- Run the messages a delegate sends (and those they send), here, with no -- machine: every method must be a native. Returns the result. With 'defer', -- a method in Rexx stops it: what is left (the delegate and those waiting) -- waits in world~deferred, and the machine runs it before its next message -- (see RVM.Machine's DoSend); this returns .Nil. ::Routine RunNatives Public Use Strict Arg v, context, defer = .False world = context~world pend = .Array~new Loop If v~isA( .RVM.Delegate ) Then Do If v~result \== .Nil | v~then \== .Nil Then pend~append( v ) m = v~method If m == .Nil Then m = Lookup( v~receiver, v~name, v~scope, world ) If m == .Nil Then Raise Syntax 97.1 Array( ObjectText( v~receiver ), v~name ) If m~isCode Then Do If \ defer Then Raise Syntax 93.900 Additional( - "RVM: a method in Rexx ("v~name") while a package is made by a native" ) world~deferred~append( .Array~of( v, pend ) ) Return .Nil End natives = context~nativeLines depth = natives~items natives~append( .RVM.NativeCall~new( NativeLine( m ), m, v~receiver, v~name, v~args ) ) Call CheckMethodArgs m, v~args v = CallNative( m, v~receiver, v~args, context, v~name ) Do While natives~items > depth natives~delete( natives~last ) End Iterate End If pend~isEmpty Then Return v p = pend~lastItem pend~delete( pend~last ) If p~result \== .Nil Then v = p~result If p~then \== .Nil Then v = p~then~next( v, context ) End -- Add to directory 'd' the entries of 'e' it does not have (the first wins). ::Routine Merge Use Strict Arg d, e Do With Index name Item v Over e If \ d~hasIndex( name ) Then d[ name ] = v End -- The clause of the first instruction of some code. ::Routine FirstClause Public Use Strict Arg program, address code = program~code Do a = address To code~items If code[a][1] == "CLAUSE", code[a][3] \== "E" Then Return code[a][2] End Return 0 -- Define native methods: "NAME min max key [argName]; ..." (a name in quotes -- may be blank or empty). ::Routine Methods Use Strict Arg c, which, spec data = c~native Do item Over spec~makeArray( ";" ) item = Strip( item ) If Left( item, 1 ) == "'" Then Parse Var item "'" name "'" min max key argName Else Parse Var item name min max key argName m = .RVM.Method~new( name, c, key, min, max, Strip( argName ) ) If which == "I" Then data~imethods[ name ] = m Else data~cmethods[ name ] = m End -- The methods of String. Those with a built-in function of the same name: -- "NAME position min max", where position is the argument of the function -- the receiver goes to (0: none of that name; the method is S.name). ::Routine StringMethods Use Strict Arg c spec = - "ABBREV 1 1 2;" "ABS 1 0 0;" "B2X 1 0 0;" "BITAND 1 0 2;" - "BITOR 1 0 2;" "BITXOR 1 0 2;" "C2D 1 0 1;" "C2X 1 0 0;" - "CENTER 1 1 2;" "CENTRE 1 1 2;" "CHANGESTR 2 2 3;" "COMPARE 1 1 2;" - "COPIES 1 1 1;" "COUNTSTR 2 1 1;" "D2C 1 0 1;" "D2X 1 0 1;" - "DATATYPE 1 0 1;" "DELSTR 1 1 2;" "DELWORD 1 1 2;" "FORMAT 1 0 4;" - "INSERT 2 1 4;" "LASTPOS 2 1 3;" "LEFT 1 1 2;" "LENGTH 1 0 0;" - "LOWER 1 0 2;" "MAX 1 0 -1;" "MIN 1 0 -1;" "OVERLAY 2 1 4;" - "POS 2 1 3;" "REVERSE 1 0 0;" "RIGHT 1 1 2;" "SIGN 1 0 0;" - "SPACE 1 0 2;" "STRIP 1 0 2;" "SUBSTR 1 1 3;" "SUBWORD 1 1 2;" - "TRANSLATE 1 0 4;" "TRUNC 1 0 1;" "UPPER 1 0 2;" "VERIFY 1 1 3;" - "WORD 1 1 1;" "WORDINDEX 1 1 1;" "WORDLENGTH 1 1 1;" "WORDPOS 2 1 2;" - "WORDS 1 0 0;" "X2B 1 0 0;" "X2C 1 0 0;" "X2D 1 0 1;" - "MAKESTRING 0 0 0;" "EQUALS 0 1 1;" "CASELESSEQUALS 0 1 1;" - "[] 0 1 2;" "APPEND 0 1 1;" "SUBCHAR 0 1 1;" "MAKEARRAY 0 0 1;" - "SUBWORDS 0 0 2;" - "CASELESSABBREV 0 0 0;" "CASELESSCHANGESTR 0 0 0;" "CASELESSCOMPARE 0 0 0;" - "CASELESSCOMPARETO 0 0 0;" "COMPARETO 0 0 0;" "CONTAINS 0 0 0;" - "CASELESSCONTAINS 0 0 0;" "CASELESSPOS 0 0 0;" "CASELESSLASTPOS 0 0 0;" - "CASELESSCOUNTSTR 0 0 0;" "CASELESSWORDPOS 0 0 0;" "CONTAINSWORD 0 0 0;" - "CASELESSCONTAINSWORD 0 0 0;" "STARTSWITH 0 0 0;" "ENDSWITH 0 0 0;" - "CASELESSSTARTSWITH 0 0 0;" "CASELESSENDSWITH 0 0 0;" "REPLACEAT 0 0 0;" - "CEILING 0 0 0;" "FLOOR 0 0 0;" "ROUND 0 0 0;" "ENCODEBASE64 0 0 0;" - "DECODEBASE64 0 0 0;" "MATCH 0 0 0;" "CASELESSMATCH 0 0 0;" - "MATCHCHAR 0 0 0;" "CASELESSMATCHCHAR 0 0 0;" "MODULO 0 0 0;" "? 0 0 0" data = c~native specs = .RVM.StringArgs~specs Do item Over spec~makeArray( ";" ) Parse Var item name position min max If position == 0 Then key = "S."name Else key = "B."position -- One whose arguments are checked as ooRexx's method does: they all are -- there, in order (StringMethodArgs). If specs~hasIndex( name ) Then Do min = 0 max = specs[ name ]~words If specs[ name ] == "*" Then max = -1 End data~imethods[ name ] = .RVM.Method~new( name, c, key, min, max ) End -- The operators: "+" etc. (a prefix one when there is no argument). Do op Over .Array~of( "+", "-", "*", "/", "%", "//", "**", "||", " ", "", - "=", "\=", "<>", "><", "<", ">", "<=", ">=", "\<", "\>", - "==", "\==", "<<", ">>", "<<=", ">>=", "\<<", "\>>", - "&", "|", "&&", "\" ) min = 1 If op == "+" | op == "-" | op == "\" Then min = 0 If op == "\" Then max = 0 Else max = 1 data~imethods[ op ] = .RVM.Method~new( op, c, "OP", min, max ) End /******************************************************************************/ /* Sending a message */ /* */ /* Send(receiver, name, args, context) runs the method and returns its */ /* result, or .Nil when it returns none. Today every method is native. */ /* While a native runs, the line the traceback shows for it ("Compiled */ /* method ...") is in context~nativeLines; an error leaves it there for the */ /* report. */ /******************************************************************************/ ::Routine Lookup Public Use Strict Arg receiver, name, start, world beh = world~behaviourOf( receiver ) If start == .Nil Then Return beh~lookup( name ) -- From scope 'start' (ooRexx's messageSend with a scope): one that is not -- one of the receiver's is 93.957 (validateScopeOverride). If \ beh~hasScope( start ) Then Raise Syntax 93.957 Array( ObjectText( receiver ), ObjectText( start ) ) Return beh~superMethod( name, start ) -- An object in an error: the object itself (ADDITIONAL holds it, as -- ooRexx's does; a message shows its name, never its STRING: its string in -- the host is its name). ::Routine ObjectText Public Use Strict Arg v If v~isA( .RVM.Obj ) Then Return v Return str( v ) -- The traceback line of a native method. ::Routine NativeLine Public Use Strict Arg m Return ' *-* Compiled method "'m~name'" with scope "'ScopeName( m )'".' -- The name of a method's scope (ooRexx's getScopeName: ".NIL" for none). ::Routine ScopeName Public Use Strict Arg m If m~scope == .Nil Then Return ".NIL" Return m~scope~native~id -- The number of arguments (93.902, 93.903; 88.901 for the methods that name -- their argument). /******************************************************************************/ /* Message -- the methods of ooRexx's MessageClass. The receiver's native */ /* value is its RVM.MessageState. What waits (RESULT, WAIT before the message */ /* completes), starts a message (START, REPLY) or raises its error again */ /* (RESULT) is the machine's: RVM.Wait, RVM.StartMessage, RVM.Reraise. */ /******************************************************************************/ ::Routine MessageNative Use Strict Arg what, receiver, args, context, world If what == "NEW" Then Return NewMessage( receiver, args, world ) ms = receiver~native Select Case what When "COMPLETED" Then Return ms~complete~?( "1", "0" ) When "HASERROR" Then Return ms~failed~?( "1", "0" ) When "HASRESULT" Then Return ( ms~result \== .Nil )~?( "1", "0" ) When "TARGET" Then Return ms~receiver When "MESSAGENAME" Then Return ms~name When "ARGUMENTS" Then Return world~newArray( ms~args~copy ) When "ERRORCONDITION" Then Do If \ ms~failed Then Return world~nil If ms~condObj == .Nil Then ms~condObj = context~conditionObject( ms~info ) Return ms~condObj End When "WAIT" Then Do If \ ms~complete Then Return .RVM.Wait~new( ms ) Return .Nil End -- HALT (ooRexx's MessageClass~halt): a HALT for the activity it runs in -- (the activation running there, at its next clause); 0 when it was not -- started, or a HALT is pending there already; 1 when it has ended. When "HALT" Then Do desc = .Nil If args~hasIndex( 1 ) Then desc = StringArg( args[1], "description" ) If ms~startActivity == .Nil Then Return "0" If ms~startActivity~state == "ENDED" Then Return "1" Return ms~startActivity~context~halt( desc )~?( "1", "0" ) End -- A party to notify when it completes (an instance of MessageNotification); -- if it has, and all were notified, it is notified now. When "NOTIFY" Then Do world~ensurePrelude target = args[1] If \ IsInstance( target, world~prelude~publicClasses[ "MESSAGENOTIFICATION" ], world ) Then Raise Syntax 88.914 Array( "notification target", "MessageNotification" ) ms~parties~append( target ) If \ ms~notified Then Return .Nil d = .RVM.Delegate~new( target, "MESSAGECOMPLETE", .Array~of( receiver ) ) d~then = .RVM.NoResult~new Return d End -- Its result (.NIL if none); its error, raised again. When "RESULT" Then Do If \ ms~complete Then Return .RVM.Wait~new( ms ) If ms~failed Then Return .RVM.Reraise~new( ms~info ) If ms~result == .Nil Then Return world~nil Return ms~result End -- A new receiver (the first argument), new arguments (the others, or -- an array: WITH). When "SEND", "START", "REPLY" Then Do If args~hasIndex( 1 ) Then ms~receiver = args[1] If args~last \== .Nil, args~last > 1 Then Do rest = .Array~new Do i = 2 To args~last If args~hasIndex( i ) Then rest[ i - 1 ] = args[ i ] End ms~args = rest End End When "SENDWITH", "STARTWITH", "REPLYWITH" Then Do If args~hasIndex( 1 ) Then ms~receiver = args[1] If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "message arguments" ) ms~args = MessageArguments( args[2] ) End Otherwise Nop End Select Case what When "SEND", "SENDWITH" Then Do Call CheckReuse ms ms~clearCompletion Call Lookup ms~receiver, "", ms~scope, world -- the scope is checked ms~startActivity = context~activity context~level~notifyMsg = ms d = .RVM.Delegate~new( ms~receiver, ms~name, ms~args~copy ) d~scope = ms~scope d~then = .RVM.MessageSent~new( ms ) Return d End When "START", "STARTWITH" Then Return StartMessage( ms, .Nil, world ) -- MESSAGECOMPLETE and TRIGGERED (the notifications it gets): it is sent, -- with no result. When "MESSAGECOMPLETE", "TRIGGERED" Then Do Call CheckReuse ms ms~clearCompletion Call Lookup ms~receiver, "", ms~scope, world ms~startActivity = context~activity context~level~notifyMsg = ms d = .RVM.Delegate~new( ms~receiver, ms~name, ms~args~copy ) d~scope = ms~scope d~then = .RVM.MessageSent~new( ms, .True ) Return d End -- REPLY: a copy is started, and it is the result. When "REPLY", "REPLYWITH" Then Do Call CheckReuse ms ms~clearCompletion Call Lookup ms~receiver, "", ms~scope, world copy = ms~copyMessage o = world~newOf( world~messageClass, copy ) copy~obj = o Return StartMessage( copy, o, world ) End End Raise Syntax 93.900 Additional( "RVM: native method MS."what "is missing" ) /******************************************************************************/ /* MutableBuffer (ooRexx's MutableBufferClass.cpp). The native value is an */ /* RVM.MBuffer: its text and its capacity, which grows as the native's */ /* (ensureCapacity) and GETBUFFERSIZE shows. What does not change the buffer */ /* is the method of String of the same name on its text (ooRexx's methods use */ /* the same StringUtil code); what changes it is done here, its arguments */ /* checked as String's (RVM.StringArgs) or, for REPLACEAT and []=, by name. */ /******************************************************************************/ ::Class RVM.MBuffer Public ::Attribute text ::Attribute cap -- the capacity (bufferLength) ::Attribute dflt -- the default size (defaultSize) ::Method init Expose text cap dflt Use Strict Arg text, cap, dflt -- Room for 'added' characters more (ensureCapacity). ::Method ensure Expose text cap Use Strict Arg added n = Length( text ) + added If n > cap Then cap = Max( n, cap * 2 ) ::Routine MBufferNative Use Strict Arg what, receiver, args, context, world, message If what == "NEW" Then Do s = "" If args~hasIndex( 1 ) Then s = MethodString( args[1], 1, world ) size = 256 If args~hasIndex( 2 ) Then Do size = unsignedWholeNumber( str( args[2] ), 18 ) If size == .Nil Then Raise Syntax 93.923 Array( str( args[2] ) ) End o = world~newInstance( receiver ) o~native = .RVM.MBuffer~new( s, Max( size, Length( s ) ), size ) rest = .Array~new n = args~last If n == .Nil Then n = 0 Do i = 3 To n If args~hasIndex( i ) Then rest[ i - 2 ] = args[i] End Return .RVM.Delegate~new( o, "INIT", rest, o ) End b = receiver~native t = b~text Select Case what When "STRING" Then Return t When "GETBUFFERSIZE" Then Return b~cap When "APPEND" Then Do If args~last == .Nil Then Raise Syntax 93.903 Array( 1 ) Do i = 1 To args~last If \ args~hasIndex( i ) Then Raise Syntax 93.903 Array( i ) s = MethodString( args[i], i, world ) b~ensure( Length( s ) ) b~text = b~text || s End Return receiver End When "SETTEXT" Then Do a = StringMethodArgs( "COUNTSTR", args, world ) b~text = "" b~ensure( Length( a[1] ) ) b~text = a[1] Return receiver End When "INSERT" Then Do a = StringMethodArgs( "INSERT", args, world ) s = a[1] begin = 0; If a[2] \== .Nil Then begin = a[2] len = Length( s ); If a[3] \== .Nil Then len = a[3] pad = " "; If a[4] \== .Nil Then pad = a[4] If begin < Length( t ) Then Do If len == 0 Then Return receiver b~ensure( len ) End Else b~ensure( len + begin - Length( t ) ) b~text = Insert( s, t, begin, len, pad ) Return receiver End When "OVERLAY" Then Do a = StringMethodArgs( "OVERLAY", args, world ) s = a[1] begin = 1; If a[2] \== .Nil Then begin = a[2] len = Length( s ); If a[3] \== .Nil Then len = a[3] pad = " "; If a[4] \== .Nil Then pad = a[4] b~ensure( begin - 1 + len ) b~text = Overlay( s, t, begin, len, pad ) Return receiver End When "REPLACEAT", "[]=" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "new" ) s = MethodString( args[1], "new", world ) If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "position" ) begin = unsignedWholeNumber( str( args[2] ), 18 ) If begin == .Nil Then Raise Syntax 88.912 Array( "position", str( args[2] ) ) If begin == 0 Then Raise Syntax 88.912 Array( "position", str( args[2] ) ) len = Length( s ) If args~hasIndex( 3 ) Then Do len = unsignedWholeNumber( str( args[3] ), 18 ) If len == .Nil Then Raise Syntax 88.911 Array( "length", str( args[3] ) ) End pad = " " If what == "REPLACEAT", args~hasIndex( 4 ) Then Do pad = MethodString( args[4], "pad", world ) If Length( pad ) \== 1 Then Raise Syntax 88.910 Array( "pad", pad ) End begin -= 1 n = Length( t ) If begin > n Then len = 0 Else If begin + len > n Then len = n - begin If begin > n Then final = begin - len + Length( s ) Else final = n - len + Length( s ) b~ensure( final ) If begin > n Then b~text = t || Copies( pad, begin - n ) || s Else b~text = Left( t, begin ) || s || SubStr( t, begin + len + 1 ) Return receiver End When "DELETE" Then Do a = StringMethodArgs( "DELSTR", args, world ) begin = 1; If a[1] \== .Nil Then begin = a[1] begin -= 1 -- The default length is from the capacity, not the text. If a[2] \== .Nil Then len = a[2] Else len = Max( b~cap - begin, 0 ) If begin < Length( t ) Then Do If begin + len < Length( t ) Then b~text = Left( t, begin ) || SubStr( t, begin + len + 1 ) Else b~text = Left( t, begin ) End Return receiver End When "SETBUFFERSIZE" Then Do a = StringMethodArgs( "SETBUFFERSIZE", args, world ) size = a[1] If size == 0 Then Do If b~cap > b~dflt Then b~cap = b~dflt b~text = "" End Else If size \== b~cap Then Do b~text = Left( t, Min( Length( t ), size ) ) b~cap = size End Return receiver End When "CHANGESTR", "CASELESSCHANGESTR" Then Do a = StringMethodArgs( what, args, world ) count = 999999999999999999; If a[3] \== .Nil Then count = a[3] If count == 0 | a[1] == "" Then Return receiver new = CallNative( world~stringClass~native~imethods[ what ], t, args, context, message ) new = str( new ) -- Longer: ensureCapacity is given the length of the result (sic). If Length( a[2] ) > Length( a[1] ), new \== t Then b~ensure( Length( new ) ) b~text = new Return receiver End When "UPPER", "LOWER" Then Do a = StringMethodArgs( what, args, world ) Call MBufferCase b, what, a[1], a[2] Return receiver End When "TRANSLATE" Then Do a = StringMethodArgs( "TRANSLATE", args, world ) If \ args~hasIndex( 1 ), \ args~hasIndex( 2 ), \ args~hasIndex( 3 ) Then Do Call MBufferCase b, "UPPER", a[4], a[5] Return receiver End tableo = ""; If a[1] \== .Nil Then tableo = a[1] tablei = ""; If a[2] \== .Nil Then tablei = a[2] pad = " "; If a[3] \== .Nil Then pad = a[3] start = 1; If a[4] \== .Nil Then start = a[4] range = Max( Length( t ) - start + 1, 0 ); If a[5] \== .Nil Then range = a[5] If start > Length( t ) | range == 0 Then Return receiver range = Min( range, Length( t ) - start + 1 ) part = SubStr( t, start, range ) If tablei == "" Then tablei = XRange( "00"x, "FF"x ) part = Translate( part, tableo, tablei, pad ) b~text = Left( t, start - 1 ) || part || SubStr( t, start + range ) Return receiver End When "SPACE" Then Do a = StringMethodArgs( "SPACE", args, world ) n = 1; If a[1] \== .Nil Then n = a[1] pad = " "; If a[2] \== .Nil Then pad = a[2] new = Space( t, n, pad ) -- More than one: the words joined by one blank first, then the room. If n > 1 Then Do b~text = Space( t, 1 ) b~ensure( Max( Words( t ) - 1, 0 ) * ( n - 1 ) ) End b~text = new Return receiver End When "DELWORD" Then Do a = StringMethodArgs( "DELWORD", args, world ) If a[2] == .Nil Then b~text = DelWord( t, a[1] ) Else b~text = DelWord( t, a[1], a[2] ) Return receiver End Otherwise Nop End -- What does not change it: String's method on its text. m = world~stringClass~native~imethods[ what ] Return CallNative( m, t, args, context, message ) -- UPPER and LOWER of a part (start, length) of a buffer, in place. ::Routine MBufferCase Use Strict Arg b, what, start, len t = b~text If start == .Nil Then start = 1 If len == .Nil Then len = Length( t ) If start > Length( t ) Then Return len = Min( len, Length( t ) - start + 1 ) If len == 0 Then Return part = SubStr( t, start, len ) If what == "UPPER" Then part = Translate( part ) Else part = Translate( part, XRange( "a", "z" ), XRange( "A", "Z" ) ) b~text = Left( t, start - 1 ) || part || SubStr( t, start + len ) /******************************************************************************/ /* EventSemaphore and MutexSemaphore (ooRexx's EventSemaphoreClass and */ /* MutexSemaphoreClass). The native value is an RVM.EventSem or an */ /* RVM.MutexSem. A wait (WAIT, ACQUIRE) that cannot end now makes the */ /* activity wait (an RVM.Wait): when it ends, the message is sent again, and */ /* it gives what the wait gave (RVM.Activity~waitResult). */ /******************************************************************************/ ::Routine SemaphoreNative Use Strict Arg family, what, receiver, args, context, world If what == "NEW" Then Do o = world~newInstance( receiver ) If family == "ES" Then o~native = .RVM.EventSem~new Else o~native = .RVM.MutexSem~new Return .RVM.Delegate~new( o, "INIT", args, o ) End sem = receiver~native act = context~activity If WordPos( what, "WAIT ACQUIRE" ) > 0 Then Do If act~waitResult \== .Nil Then Do r = act~waitResult act~waitResult = .Nil Return r End ms = TimeoutArg( args, context ) If what == "WAIT" Then r = sem~wait( act, ms, world~scheduler ) Else r = sem~acquire( act, ms, world~scheduler ) If r == .Nil Then Return .RVM.Wait~new( sem ) Return r End Select Case family"."what When "ES.POST" Then sem~post When "ES.RESET" Then sem~reset When "ES.ISPOSTED" Then Return ( sem~posted & \ sem~closed )~?( "1", "0" ) When "ES.UNINIT" Then sem~close -- (Unix: it goes on working) When "MX.RELEASE" Then Return sem~release( act ) When "MX.UNINIT" Then sem~close( act ) End Return .Nil -- The timeout of a wait, in milliseconds (ooRexx's EventSemaphoreClass~wait): -- none (-1: for ever), a TimeSpan (sent TOTALSECONDS: a subclass's override -- counts; no result is 88.901), or anything else as its string (a number of -- seconds, else 88.902); negative or more than 4294967 seconds is for ever. ::Routine TimeoutArg Use Strict Arg args, context If \ args~hasIndex( 1 ) Then Return -1 v = args[1] world = context~world Numeric Digits 18 -- (A string is no TimeSpan: the prelude is not loaded for it.) If v~isA( .RVM.Obj ) Then Do world~ensurePrelude If IsInstance( v, world~prelude~publicClasses[ "TIMESPAN" ], world ) Then Do v = world~loader~sendSync( v, "TOTALSECONDS", .Array~new ) If v == .Nil Then Raise Syntax 88.901 Array( "timeout" ) End End secs = str( v ) If \ DataType( secs, "N" ) Then Raise Syntax 88.902 Array( "timeout", ObjectText( v ) ) If secs < 0 | secs > 4294967 Then Return -1 Return Trunc( secs * 1000 ) /******************************************************************************/ /* The methods of the REXX library (::METHOD ... EXTERNAL 'LIBRARY REXX f': */ /* ooRexx's NativeMethods.h): the timers of Alarm and Ticker */ /* (TimeSupport.cpp). A timer is an event semaphore (EVENTSEMHANDLE, an */ /* EventSemaphore here) waited for with a timeout; CANCEL posts it. */ /******************************************************************************/ ::Routine LibraryNative Use Strict Arg what, m, receiver, args, context, world act = context~activity Select Case what When "ALARM_STARTTIMER", "TICKER_WAITTIMER" Then Do -- The wait has ended (the timeout, or the timer was stopped). If act~waitResult \== .Nil Then Do act~waitResult = .Nil Return "0" End Numeric Digits 18 If what == "ALARM_STARTTIMER" Then Do days = str( args[1] ); ms = str( args[2] ) handle = world~newOf( world~eventSemClass, .RVM.EventSem~new ) Call SetObjectVariable receiver, m, "EVENTSEMHANDLE", handle Call SetObjectVariable receiver, m, "TIMERSTARTED", "1" End Else Do handle = args[1]; days = str( args[2] ); ms = str( args[3] ) End total = days * 86400000 + ms If total < 0 Then total = 0 r = handle~native~wait( act, total, world~scheduler ) If r == .Nil Then Return .RVM.Wait~new( handle~native ) Return "0" End When "TICKER_CREATETIMER" Then Do handle = world~newOf( world~eventSemClass, .RVM.EventSem~new ) Call SetObjectVariable receiver, m, "EVENTSEMHANDLE", handle Return "0" End When "ALARM_STOPTIMER", "TICKER_STOPTIMER" Then Do If args[1]~isA( .RVM.Obj ), args[1]~native~isA( .RVM.EventSem ) Then args[1]~native~post Return "0" End Otherwise Nop End If Left( what, 5 ) == "FILE_" | what == "THIS_FILE_CASE_SENSITIVE" Then Return FileLibrary( what, receiver, args, context, world ) If Left( what, 5 ) == "REXX_", Pos( "_QUEUE", what ) > 0 Then Return QueueLibrary( what, m, receiver, args, context, world ) If WordPos( what, "STREAM_INIT STREAM_CHARS STREAM_LINES STREAM_POSITION" - "STREAM_STATE STREAM_DESCRIPTION STREAM_QUERY_POSITION STREAM_CHAROUT" - "STREAM_CHARIN STREAM_LINEIN STREAM_LINEOUT QUALIFY QUERY_EXISTS" - "QUERY_SIZE QUERY_TIME HANDLE_SET STD_SET STREAM_FLUSH QUERY_HANDLE" - "QUERY_STREAMTYPE STREAM_CLOSE STREAM_UNINIT STREAM_OPEN STREAM_ARRAYIN" ) > 0 Then Return StreamLibrary( what, receiver, args, context, world ) Raise Syntax 90.998 Array( what ) -- (not a method of the REXX library) /******************************************************************************/ /* The methods of RexxQueue in the REXX library (ooRexx's */ /* RexxQueueMethods.cpp), on the queues of RVM.Queues. The arguments are */ /* checked as ooRexx's API checks them (88.922, 88.901); an instance's queue */ /* is its NAMED_QUEUE (none: 98.901, its INIT did not run). LINEIN waits */ /* (RXQUEUE_WAIT) while its queue is there and empty: for what QUEUE and PUSH */ /* post (the method is UNGUARDED: ooRexx's SetGuardOff). */ /******************************************************************************/ ::Routine QueueLibrary Use Strict Arg what, m, receiver, args, context, world n = args~last If n == .Nil Then n = 0 Select Case what When "REXX_CREATE_QUEUE", "REXX_PUSH_QUEUE", "REXX_QUEUE_QUEUE" Then max = 1 When "REXX_OPEN_QUEUE", "REXX_QUEUE_EXISTS", "REXX_DELETE_QUEUE" Then Do max = 1 If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( 1 ) End Otherwise max = 0 End If n > max Then Raise Syntax 88.922 Array( max ) -- The class methods. Select Case what When "REXX_CREATE_QUEUE" Then Do If \ args~hasIndex( 1 ) Then Return .RVM.Queues~create Return .RVM.Queues~create( MethodString( args[1], 1, world ) ) End When "REXX_OPEN_QUEUE" Then Return .RVM.Queues~open( MethodString( args[1], 1, world ) ) When "REXX_QUEUE_EXISTS" Then Return .RVM.Queues~exists( MethodString( args[1], 1, world ) ) When "REXX_DELETE_QUEUE" Then Return .RVM.Queues~delete( MethodString( args[1], 1, world ) ) Otherwise Nop End name = receiver~pool( m~scope )~valueOf( "NAMED_QUEUE" ) If name == .Nil Then Raise Syntax 98.901 Array( receiver ) name = str( name ) Select Case what When "REXX_PUSH_QUEUE", "REXX_QUEUE_QUEUE" Then Do line = "" If args~hasIndex( 1 ) Then line = MethodString( args[1], 1, world ) .RVM.Queues~addOrFail( name, line, what == "REXX_PUSH_QUEUE" ) Return 0 End When "REXX_PULL_QUEUE" Then Do line = .RVM.Queues~pull( name ) If line == .Nil Then Return world~nil Return line End When "REXX_LINEIN_QUEUE" Then Do act = context~activity act~waitResult = .Nil line = .RVM.Queues~pull( name ) If line \== .Nil Then Return line If .RVM.Queues~exists( name ) == 0 Then Return world~nil w = .RVM.Queues~waitFor( name, .RVM.EventSem ) r = w~wait( act, -1, world~scheduler ) Return .RVM.Wait~new( w ) End When "REXX_QUERY_QUEUE" Then Return .RVM.Queues~count( name ) When "REXX_CLEAR_QUEUE" Then Return .RVM.Queues~clear( name ) End Raise Syntax 90.998 Array( what ) /******************************************************************************/ /* The methods of Stream in the REXX library (ooRexx's StreamNative.cpp): */ /* the receiver's native value is its RVM.Stream (STREAM_INIT makes it; it is */ /* ooRexx's CSELF), whose operations are those of the stream functions, with */ /* the errors of a method (RVM.Stream~methodOp). The arguments are converted */ /* as ooRexx's API converts them (int64_t, size_t: 88.907). */ /******************************************************************************/ ::Routine StreamLibrary Use Strict Arg what, receiver, args, context, world -- Its arguments, as the API checks them first (StreamNative.cpp's -- RexxMethodN; CSELF is not one): too many, 88.922; a required one -- missing, 88.901. Select Case what When "STREAM_CHARIN", "STREAM_CHAROUT", "STREAM_LINEIN", "STREAM_LINEOUT" Then Do max = 2; req = 0 End When "STREAM_LINES", "STREAM_OPEN", "STREAM_QUERY_POSITION" Then Do max = 1; req = 0 End When "STREAM_ARRAYIN", "HANDLE_SET", "STREAM_POSITION", "STREAM_INIT" Then Do max = 1; req = 1 End Otherwise Do max = 0; req = 0 End End n = args~last If n == .Nil Then n = 0 If n > max Then Raise Syntax 88.922 Array( max ) Do i = 1 To req If \ args~hasIndex( i ) Then Raise Syntax 88.901 Array( i ) End If what == "STREAM_INIT" Then Do receiver~native = .RVM.Stream~new( MethodString( args[1], 1, world ) ) receiver~native~rexxObject = receiver Return .Nil End s = receiver~native If \ s~isA( .RVM.Stream ) Then Do -- (CLOSE and UNINIT of one whose INIT did not run: nothing, as ooRexx) If what == "STREAM_CLOSE" | what == "STREAM_UNINIT" Then Return 0 Raise Syntax 93.900 Additional( "RVM: a Stream without its stream (INIT did not run)" ) End Select Case what When "STREAM_CHARIN" Then Do pos = .Nil; If args~hasIndex( 1 ) Then pos = Int64Arg( args[1], 1 ) count = 1; If args~hasIndex( 2 ) Then count = SizeArg( args[2], 2 ) Return StdinWaits( s~methodOp( context, "CHARIN", "", args~hasIndex( 1 ), pos, count ), context ) End When "STREAM_LINEIN" Then Do pos = .Nil; If args~hasIndex( 1 ) Then pos = Int64Arg( args[1], 1 ) count = 1; If args~hasIndex( 2 ) Then count = SizeArg( args[2], 2 ) Return StdinWaits( s~methodOp( context, "LINEIN", "", args~hasIndex( 1 ), pos, count ), context ) End When "STREAM_CHAROUT", "STREAM_LINEOUT" Then Do data = .Nil If args~hasIndex( 1 ) Then data = MethodString( args[1], 1, world ) pos = .Nil; If args~hasIndex( 2 ) Then pos = Int64Arg( args[2], 2 ) If what == "STREAM_CHAROUT" Then Return s~methodOp( context, "CHAROUT", 0, data, args~hasIndex( 2 ), pos ) Return s~methodOp( context, "LINEOUT", 1, data, args~hasIndex( 2 ), pos ) End When "STREAM_LINES" Then Do quick = .False If args~hasIndex( 1 ) Then Do option = MethodString( args[1], 1, world ) Select Case Upper( Left( option, 1 ) ) When "N" Then quick = .True When "C" Then Nop Otherwise Raise Syntax 93.915 Array( "CN", option ) End End Return s~methodOp( context, "LINES", 0, quick ) End When "STREAM_CHARS" Then Return s~methodOp( context, "CHARS", 0 ) When "STREAM_POSITION" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( 1 ) Return s~methodOp( context, "POSITION", 0, MethodString( args[1], 1, world ) ) End When "STREAM_QUERY_POSITION" Then Do options = "" If args~hasIndex( 1 ) Then options = MethodString( args[1], 1, world ) Return s~methodOp( context, "QUERYPOSITION", "", options ) End When "STREAM_OPEN" Then Do options = "" If args~hasIndex( 1 ) Then options = MethodString( args[1], 1, world ) Return s~methodOp( context, "OPEN", "", options ) End When "STREAM_CLOSE" Then Return s~methodOp( context, "CLOSE", "" ) When "STREAM_FLUSH" Then Return s~methodOp( context, "FLUSH", "" ) When "STREAM_UNINIT" Then Do s~methodOp( context, "CLOSE", "" ) Return .Nil End When "STREAM_STATE" Then Return s~state When "STREAM_DESCRIPTION" Then Return s~description When "QUALIFY" Then Return s~methodOp( context, "QUALIFY", "" ) When "QUERY_EXISTS" Then Return s~methodOp( context, "EXISTS", "" ) When "QUERY_SIZE" Then Return s~methodOp( context, "SIZE", "" ) When "QUERY_STREAMTYPE" Then Return s~methodOp( context, "TYPE", "" ) -- The time as ooRexx's (ctime: "Sun Sep 27 13:00:00 2026"), which -- QUERY TIMESTAMP and DATETIME take apart. When "QUERY_TIME" Then Do stamp = s~methodOp( context, "TIME", "" ) If stamp == "" Then Return "" Parse Var stamp yyyy "-" mm "-" dd time base = Date( "B", yyyy || mm || dd, "S" ) Return Left( Date( "W", base, "B" ), 3 ) Left( Date( "M", base, "B" ), 3 ) - Right( dd + 0, 2 ) time yyyy End When "QUERY_HANDLE" Then Return s~methodOp( context, "HANDLE", "" ) When "HANDLE_SET" Then Return 0 When "STD_SET" Then Do s~setStandardStream Return 0 End -- ARRAYIN: the lines left, into the array, until the end (NOTREADY: -- what was appended stays; see RVM.Stream~arrayin). When "STREAM_ARRAYIN" Then Do v = s~methodOp( context, "ARRAYIN", 0, args[1]~native ) If v~isA( .RVM.StdinNeed ) Then Return StdinWaits( v, context ) Return 0 End Otherwise Nop End Raise Syntax 90.998 Array( what ) -- A read of standard input that must wait (an RVM.StdinNeed: see -- RVM.Stream~inputNeed): its activity waits, and the method is sent again. ::Routine StdinWaits Use Strict Arg v, context If \ v~isA( .RVM.StdinNeed ) Then Return v Return .RVM.StdinWait~start( v, context ) -- (An argument converted as ooRexx's API does, int64_t and size_t: RVM.BIFs' -- Int64Arg and SizeArg.) /******************************************************************************/ /* The methods of File in the REXX library (ooRexx's FileNative.cpp, over */ /* SysFileSystem). The host is ooRexx: its File class does what the native's */ /* does, on the same file system. */ /******************************************************************************/ ::Routine FileLibrary Use Strict Arg what, receiver, args, context, world b = .Array~of( "0", "1" ) -- Its arguments, as the API checks them (FileNative.cpp's RexxMethodN): -- too many, 88.922; all of them are required (88.901). Select Case what When "FILE_SEPARATOR", "FILE_PATH_SEPARATOR", "FILE_CASE_SENSITIVE", - "FILE_LIST_ROOTS", "FILE_TEMPORARY_PATH" Then max = 0 When "FILE_SET_LAST_MODIFIED", "FILE_SET_LAST_ACCESSED", "FILE_RENAME", - "FILE_SEARCH_PATH_IMPL" Then max = 2 Otherwise max = 1 End n = args~last If n == .Nil Then n = 0 If n > max Then Raise Syntax 88.922 Array( max ) Do i = 1 To max If \ args~hasIndex( i ) Then Raise Syntax 88.901 Array( i ) End If args~hasIndex( 1 ) Then Do name = MethodString( args[1], 1, world ) f = .File~new( name ) End Select Case what When "FILE_SEPARATOR" Then Return .File~separator When "FILE_PATH_SEPARATOR" Then Return .File~pathSeparator When "FILE_CASE_SENSITIVE" Then Return b[ .File~isCaseSensitive + 1 ] When "THIS_FILE_CASE_SENSITIVE" Then Return b[ f~isCaseSensitive + 1 ] When "FILE_CAN_READ" Then Return b[ f~canRead + 1 ] When "FILE_CAN_WRITE" Then Return b[ f~canWrite + 1 ] When "FILE_EXISTS" Then Return b[ f~exists + 1 ] When "FILE_ISDIRECTORY" Then Return b[ f~isDirectory + 1 ] When "FILE_ISFILE" Then Return b[ f~isFile + 1 ] When "FILE_ISHIDDEN" Then Return b[ f~isHidden + 1 ] When "FILE_LENGTH" Then Return f~length When "FILE_QUALIFY" Then Return .RVM.FileSystem~qualify( name ) -- unlink (write permission needed); remove (a file too). When "FILE_DELETE_FILE" Then Do If \ f~canWrite | f~isDirectory Then Return "0" Return b[ f~delete + 1 ] End When "FILE_DELETE_DIRECTORY" Then Return b[ f~delete + 1 ] When "FILE_MAKE_DIR" Then Return b[ f~makeDir + 1 ] When "FILE_RENAME" Then Return b[ f~renameTo( .File~new( MethodString( args[2], 2, world ) ) ) + 1 ] When "FILE_SET_READ_ONLY" Then Do If \ f~exists Then Return "0" f~setReadOnly Return "1" End When "FILE_SET_WRITABLE" Then Do If \ f~exists Then Return "0" f~setWritable Return "1" End When "FILE_GET_LAST_MODIFIED", "FILE_GET_LAST_ACCESSED" Then Do If what == "FILE_GET_LAST_MODIFIED" Then d = f~lastModified Else d = f~lastAccessed If d == .Nil Then Return "-999999999999999999" Return d~fullDate End When "FILE_SET_LAST_MODIFIED", "FILE_SET_LAST_ACCESSED" Then Do If \ f~exists Then Return "0" d = .DateTime~new( Int64Arg( args[2], 2 ) ) If what == "FILE_SET_LAST_MODIFIED" Then f~lastModified = d Else f~lastAccessed = d Return "1" End When "FILE_LIST" Then Do list = f~list If list == .Nil Then Return world~nil Return world~newArray( list ) End When "FILE_LIST_ROOTS" Then Return world~newArray( .File~listRoots ) When "FILE_TEMPORARY_PATH" Then Do t = Value( "TMPDIR", , "ENVIRONMENT" ) If t == "" Then t = "/tmp" Return t End When "FILE_SEARCH_PATH_IMPL" Then Do found = .File~searchPath( name, MethodString( args[2], 2, world ) ) If found == .Nil Then Return world~nil Return found~path End Otherwise Nop End Raise Syntax 90.998 Array( what ) -- A method of a library of the RVM (lm, an entry of LibraryMethods) that m -- runs: its arguments as the native's (strings: 88.909; one required that -- is missing, 88.901; too many, 88.922), its object variables (CSELF, !POS) -- those of the receiver in the scope of m. ::Routine LibraryMethod Use Strict Arg lm, m, receiver, args, world sig = lm[4]~makeArray( " " ) conv = .Array~new Do i = 1 To sig~items If \ args~hasIndex( i ) Then Do If sig[i] == "r" Then Raise Syntax 88.901 Array( i ) conv[i] = .Nil End Else conv[i] = MethodString( args[i], i, world ) End n = args~last If n == .Nil Then n = 0 If n > sig~items Then Raise Syntax 88.922 Array( sig~items ) Return RxRegExpNative( lm, conv, receiver~pool( m~scope ) ) -- A variable of the receiver, in the scope of method m (ooRexx's -- SetObjectVariable): those watching it (GUARD WHEN) are told. ::Routine SetObjectVariable Use Strict Arg receiver, m, name, v receiver~pool( m~scope )~setValue( name, v ) -- .MESSAGE~NEW(target, name [, "A", array | "I", arg...]). ::Routine NewMessage Use Strict Arg cls, args, world n = args~last If n == .Nil Then n = 0 If n < 2 Then Raise Syntax 93.901 Array( 2 ) If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "message target" ) If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "message name" ) target = args[1] name = MessageName( args[2], world ) scope = .RVM.MessageScope~scope rest = .Array~new If n > 2 Then Do If \ args~hasIndex( 3 ) Then Raise Syntax 88.901 Array( "argument style" ) opt = Upper( Left( str( args[3] ), 1 ) ) If opt \== "A", opt \== "I" Then Raise Syntax 93.915 Array( "AI", str( args[3] ) ) If opt == "A" Then Do If n < 4 Then Raise Syntax 93.901 Array( 4 ) If n > 4 Then Raise Syntax 93.902 Array( 4 ) rest = MessageArguments( args[4] ) End Else Do i = 4 To n If args~hasIndex( i ) Then rest[ i - 3 ] = args[ i ] End End o = world~newInstance( cls ) o~native = .RVM.MessageState~new( target, name, scope, rest ) o~native~obj = o Return .RVM.Delegate~new( o, "INIT", .Array~new, o ) -- A message that was started cannot be sent, started or replied (98.915). ::Routine CheckReuse Use Strict Arg ms If ms~activated Then Raise Syntax 98.915 -- START (ooRexx's MessageClass~start): the machine starts it in a new -- activity; 'result' is the native's. ::Routine StartMessage Use Strict Arg ms, res, world Call CheckReuse ms ms~clearCompletion ms~activated = .True Call Lookup ms~receiver, "", ms~scope, world Return .RVM.StartMessage~new( ms, res ) ::Routine CheckMethodArgs Public Use Strict Arg m, args n = args~last If n == .Nil Then n = 0 If m~max >= 0, n > m~max Then Raise Syntax 93.902 Array( m~max ) Do i = 1 To m~min If \ args~hasIndex( i ) Then Do -- One name for every argument, or one per argument ("a/b"; empty: none) name = m~argName If name~pos( "/" ) > 0 Then name = name~makeArray( "/" )[ i ] If name \== .Nil, name \== "" Then Raise Syntax 88.901 Array( name ) Raise Syntax 93.903 Array( i ) End End -- The message of SEND and SENDWITH: a string (its name), or an Array whose -- last item is the second (the name: 88.901, a string: 88.909; the class -- where the search starts: 88.914); another array 93.946; another object -- 93.972 (ooRexx's RexxObject::decodeMessageName). Returns the name; -- the scope is left in RVM.MessageScope (.Nil: none). ::Routine MessageName Use Strict Arg v, world .RVM.MessageScope~scope = .Nil If \ v~isA( .RVM.Obj ) Then Return Upper( str( v ) ) If \ v~native~isA( .Array ) Then Raise Syntax 93.972 Array( v ) a = v~native If a~dimension > 1 | a~last \== 2 Then Raise Syntax 93.946 If \ a~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "message name" ) If a[1]~isA( .RVM.Obj ) Then Raise Syntax 88.909 Array( "message name" ) .RVM.MessageScope~scope = ClassArg( a[2], "SCOPE" ) Return Upper( str( a[1] ) ) -- The arguments of SENDWITH: an Array (one dimension), or what a collection -- or a string makes an array (88.913 otherwise). ::Routine MessageArguments Use Strict Arg v If \ v~isA( .RVM.Obj ) Then Return str( v )~makeArray If v~native~isA( .Array ) Then Do If v~native~dimension > 1 Then Raise Syntax 88.913 Array( "message arguments" ) rest = .Array~new Do i Over v~native~allIndexes rest[ i ] = v~native[ i ] End Return rest End a = CollectionArray( v ) If a == .Nil Then Raise Syntax 88.913 Array( "message arguments" ) Return a -- What a collection (not an Array) makes an array (its MAKEARRAY): a -- Queue's or a List's items, the indexes of a Set, Bag, Relation, Directory -- or Table; .Nil when it is not one. ::Routine CollectionArray Use Strict Arg v 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 ) If v~native~isA( .Directory ) | TableLike( v~native ) Then Return UnhashedArray( v~native~allIndexes ) Return .Nil /******************************************************************************/ /* Stem -- the methods of ooRexx's StemClass. The receiver's native value is */ /* its RVM.Stem; a tail is made of the arguments as ooRexx's */ /* CompoundVariableTail makes it (StemTail). */ /******************************************************************************/ ::Routine StemNative Use Strict Arg what, receiver, args, world n = args~last If n == .Nil Then n = 0 -- NEW (a class method): the name (optional; its string), and INIT gets -- the rest of the arguments. If what == "NEW" Then Do name = "" If args~hasIndex( 1 ) Then name = StringArg( args[1], 1 ) o = world~newInstance( receiver ) o~native~name = name o~native~value = name rest = .Array~new Do i = 2 To n If args~hasIndex( i ) Then rest[ i - 1 ] = args[ i ] End Return .RVM.Delegate~new( o, "INIT", rest, o ) End st = receiver~native Select Case what -- [] and AT: no arguments, the default value. When "AT" Then Do If n == 0 Then Return st~value Return st~at( StemTail( args, 1, n ) ) End -- []= and PUT: the value first; with no tail, the default value (not a -- stem: 98.976), and every tail goes. When "PUT" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 93.903 Array( 1 ) v = args[1] If n == 1 Then Do If world~stemOf( v ) \== .Nil Then Raise Syntax 98.976 st~value = v st~emptyTails st~dropped = .False Return .Nil End st~setTail( StemTail( args, 2, n ), v ) Return .Nil End When "HASINDEX" Then Do If n == 0 Then Return "1" Return st~hasRealValue( StemTail( args, 1, n ) )~?( "1", "0" ) End -- REMOVE with no tail: the default goes back to the name, but the stem -- is not dropped (a tail it has not reads as the name, as a default). When "REMOVE" Then Do If n == 0 Then Do old = st~value st~value = st~name Return old End node = st~findEntry( StemTail( args, 1, n ) ) If node \== .Nil Then Do node = node~realVariable If node~value \== .RVM.Dropped Then Do old = node~value node~value = .RVM.Dropped Return old End End Return world~nil End -- By item: the first tail (in order) whose own value matches. When "HASITEM", "INDEX", "REMOVEITEM" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 93.903 Array( 1 ) found = .Nil Do node Over st~nodes If node~value == .RVM.Dropped Then Iterate If ItemMatch( args[1], node~value, world ) Then Do found = node Leave End End If what == "HASITEM" Then Return ( found \== .Nil )~?( "1", "0" ) If found == .Nil Then Return world~nil If what == "INDEX" Then Return found~name old = found~value found~value = .RVM.Dropped Return old End When "ITEMS" Then Return st~items When "ISEMPTY" Then Return ( st~items == 0 )~?( "1", "0" ) When "EMPTY" Then Do st~emptyTails Return receiver End When "ALLINDEXES" Then Return world~newArray( st~tailNames ) When "ALLITEMS" Then Return world~newArray( st~tailItems ) When "SUPPLIER" Then Return world~newSupplier( st~tailItems, st~tailNames ) When "TODIRECTORY" Then Do d = world~newDirectory Do node Over st~nodes If node~value \== .RVM.Dropped Then d~native[ node~name ] = node~value End Return d End -- REQUEST: ARRAY is its tails (a subclass: its MAKEARRAY); the rest, its -- default's. When "REQUEST" Then Do name = Upper( StringArg( args[1], 1 ) ) If name == "ARRAY" Then Do If world~classOf( receiver ) == world~stemClass Then Return world~newArray( st~tailNames ) Return .RVM.Delegate~new( receiver, "MAKEARRAY", .Array~new ) End -- What ooRexx's Object~REQUEST does with its default: STRING, its -- string (MAKESTRING); another, its MAKE... method, if it has one. v = st~value If name == "STRING" Then Do If \ v~isA( .RVM.Obj ) Then Return str( v ) r = v~requestString If r == .Nil Then Return world~nil Return r End world~ensurePrelude If Lookup( v, "MAKE"name, .Nil, world ) == .Nil Then Return world~nil Return .RVM.Delegate~new( v, "MAKE"name, .Array~new ) End -- UNKNOWN: the message goes to its default value. When "UNKNOWN" Then Do unk = UnknownArgs( args ) Return .RVM.Delegate~new( st~value, unk[1], unk[2] ) End End /******************************************************************************/ /* VariableReference (ooRexx's VariableReference.cpp): an RVM.VarRef, a */ /* variable (an RVM.Var) and its name. Its value is the variable's, or its */ /* name when it has none (getResolvedValue; a stem variable's is its Stem */ /* object); its string value, trace and REQUEST STRING are that value's */ /* primitive one (string: an object's name, never its STRING method); every */ /* message it does not have goes to that value. */ /******************************************************************************/ ::Class RVM.VarRef Public ::Attribute var ::Attribute name ::Attribute isStem ::Method init Expose var name isStem Use Strict Arg var, name isStem = Right( name, 1 ) == "." -- Its value, or its name when it has none; a stem variable's: its Stem -- object (its stem made if it has none). ::Method resolved Expose var name isStem Use Strict Arg world v = var~value If isStem Then Do If v == .Nil Then Do v = .RVM.Stem~new( name ) var~value = v End Return world~stemObjectOf( v ) End If v == .Nil Then Return name Return v -- The string value of that value (ooRexx's stringValue: an object's is its -- name, a stem's its default's). ::Method string Expose var name isStem v = var~value If v == .Nil Then Return name If isStem Then Return StemString( v ) If v~isA( .RVM.Obj ) Then Return v~string Return str( v ) -- VALUE=: a simple variable takes the value; a stem variable, a Stem -- object's stem, or a new stem whose default is the value (ooRexx's -- RexxVariable~setValue: setStem). ::Method assign Expose var name isStem Use Strict Arg v, world If \ isStem Then Do var~value = v Return End st = world~stemOf( v ) If st == .Nil Then Do st = .RVM.Stem~new( name ) st~setValue( v ) End var~value = st -- A copy of the variable pools of an object (COPY): per scope, a pool of -- new variables with the values of the old ones (ooRexx's -- VariableDictionary~deepCopy: copyValues; no lock, no watchers). ::Routine CopyPools Use Strict Arg pools copies = .IdentityTable~new Do With Index scope Item pool Over pools p = .RVM.Pool~new Do With Index name Item var Over pool If \ var~isA( .RVM.Var ) Then Iterate v = .RVM.Var~new v~value = var~value p[ name ] = v End copies[ scope ] = p End Return copies -- The natives of VariableReference (receiver: a VariableReference; NEW: the -- class). ::Routine VarRefNative Use Strict Arg what, receiver, args, world If what == "NEW" Then Raise Syntax 93.967 Array( receiver~native~id ) ref = receiver~native Select Case what When "NAME" Then Return ref~name When "VALUE" Then Return ref~resolved( world ) When "SETVALUE" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "VALUE" ) ref~assign( args[1], world ) Return .Nil End -- UNKNOWN, REQUEST: the message goes to its value. When "UNKNOWN" Then Do unk = UnknownArgs( args ) Return .RVM.Delegate~new( ref~resolved( world ), unk[1], unk[2] ) End When "REQUEST" Then Return .RVM.Delegate~new( ref~resolved( world ), "REQUEST", args~copy ) End -- A tail from the arguments first..n (CompoundVariableTail): their string -- values, with a period between them; an omitted one is "". ::Routine StemTail Use Strict Arg args, first, n tail = "" Do i = first To n If i > first Then tail ||= "." If args~hasIndex( i ) Then tail ||= str( args[i] ) End Return tail -- The string value of a stem: its default's (an object: its name, as the -- native's primitive stringValue gives it). ::Routine StemString Public Use Strict Arg st v = st~value If v~isA( .RVM.Obj ) Then Return v~objectName Return str( v ) -- The natives of Method (receiver: a Method object; NEW: the class). ::Routine MethodNative Use Strict Arg what, receiver, args, context, world -- loadExternalMethod(name, descriptor): a method of a library of the RVM -- (see ExternalMethod), or .nil; 99.917. If what == "LOADEXTERNALMETHOD" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "name" ) If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "descriptor" ) name = MethodString( args[1], "name", world ) spec = MethodString( args[2], "descriptor", world ) lm = ExternalMethod( name, spec, "-", world, .False ) If lm == .Nil Then Return world~nil nm = .RVM.Method~new( Upper( name ), .Nil, "L", 0, -1 ) nm~value = .Array~of( spec, name, "-", world~libraryHome( lm ) ) Return world~methodObject( nm ) End If what == "NEW" | what == "NEWFILE" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "name" ) name = MethodNameArg( args[1], "name" ) If what == "NEWFILE" Then Do parent = context~rvmProgram If args~hasIndex( 2 ) Then parent = SourceContext( args[2], context, world, what, 2 ) lines = SourceFileLines( name ) last = 2 End Else Do If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "source" ) lines = SourceArg( args[2], "source", 93.961 ) parent = context~rvmProgram If args~hasIndex( 3 ) Then parent = SourceContext( args[3], context, world ) last = 3 End m = world~sourceCompiler~method( name, lines, parent ) Call PendingInstall m~program, name, context world~checkAbstract( receiver ) o = .RVM.Obj~new( world~instanceBehaviour( receiver ), m ) world~created( o ) If receiver == world~methodClass Then m~obj = o rest = .Array~new Do i = last + 1 To args~last If args~hasIndex( i ) Then rest[ i - last ] = args[ i ] End Return .RVM.Delegate~new( o, "INIT", rest, o ) End m = receiver~native Select Case what When "SOURCE" Then Return world~newArray( SourceOf( m ) ) When "SCOPE" Then Do If m~scope == .Nil Then Return world~nil Return m~scope End When "ISGUARDED" Then Return ( \ m~hasFlag( "U" ) )~?( "1", "0" ) When "ISPRIVATE" Then Return m~hasFlag( "P" )~?( "1", "0" ) When "ISPROTECTED" Then Return m~hasFlag( "R" )~?( "1", "0" ) When "ISPACKAGE" Then Return m~hasFlag( "K" )~?( "1", "0" ) When "ISABSTRACT" Then Return ( m~key == "ABSTRACT" )~?( "1", "0" ) When "ANNOTATIONS" Then Return world~annotationsOf( m ) When "ANNOTATION" Then Return world~annotationOf( m, MethodString( args[1], "name", world ) ) When "ISCONSTANT" Then Return ( m~key == "A.CONST" )~?( "1", "0" ) When "ISATTRIBUTE" Then Return ( m~hasFlag( "A" ) | WordPos( m~key, "A.GET A.SET" ) > 0 )~?( "1", "0" ) When "SETGUARDED" Then m~flags = SetFlag( m~flags, "U", .False ) When "SETUNGUARDED" Then m~flags = SetFlag( m~flags, "U", .True ) When "SETPRIVATE" Then m~flags = SetFlag( m~flags, "P", .True ) When "SETPROTECTED" Then m~flags = SetFlag( m~flags, "R", .True ) -- Its code's package gets it (ooRexx's RexxCode::setSecurityManager); -- a native's cannot (0). When "SETSECURITYMANAGER" Then Do If \ m~isCode Then Return "0" m~program~secMgr = SecurityManagerArg( args, world ) Return "1" End -- Its home program's (Method~new: its own); a native's is REXX; one of a -- library loaded by loadExternalMethod, its code's (RVM.World~libraryHome). When "PACKAGE" Then Do If m~home \== .Nil Then Return world~packageObject( m~home ) If m~key == "L" Then Do If m~value~hasIndex( 4 ) Then Return PackageOf( m~value[4], world ) Return world~nil End Return world~rexxPackage End End Return .Nil -- The natives of Routine (receiver: a Routine object; NEW: the class). CALL -- and CALLWITH are run by the machine (RVM.RoutineCall): the routine is -- called as an external routine is (a SUBROUTINE). ::Routine RoutineNative Use Strict Arg what, receiver, args, context, world -- loadExternalRoutine(name, descriptor): the routine of a library of the -- RVM (see ExternalRoutine, RVM.World~libraryRoutineObject); .nil when it -- is not there. If what == "LOADEXTERNALROUTINE" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "name" ) If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "descriptor" ) name = MethodString( args[1], "name", world ) spec = MethodString( args[2], "descriptor", world ) lr = ExternalRoutine( name, spec, world, .False ) If lr == .Nil Then Return world~nil Return world~libraryRoutineObject( lr, ExternalSpec( spec, name )[3] ) End If what == "NEW" | what == "NEWFILE" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "name" ) name = MethodNameArg( args[1], "name" ) If what == "NEWFILE" Then Do parent = context~rvmProgram If args~hasIndex( 2 ) Then parent = SourceContext( args[2], context, world, what, 2 ) lines = SourceFileLines( name ) last = 2 End Else Do If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "source" ) lines = SourceArg( args[2], "source", 93.961 ) parent = context~rvmProgram If args~hasIndex( 3 ) Then parent = SourceContext( args[3], context, world ) last = 3 End r = world~sourceCompiler~routine( name, lines, parent ) Call PendingInstall r~program, name, context world~checkAbstract( receiver ) o = .RVM.Obj~new( world~instanceBehaviour( receiver ), r ) world~created( o ) If receiver == world~routineClass Then r~obj = o rest = .Array~new Do i = last + 1 To args~last If args~hasIndex( i ) Then rest[ i - last ] = args[ i ] End Return .RVM.Delegate~new( o, "INIT", rest, o ) End r = receiver~native Select Case what When "CALL" Then Return .RVM.RoutineCall~new( r, args ) When "CALLWITH" Then Return .RVM.RoutineCall~new( r, CallWithArgs( args[1] ) ) When "SOURCE" Then Do If r~lib \== .Nil Then Return world~newArray( .Array~new ) Return world~newArray( ExtentLines( r~extent, r~program ) ) End When "PACKAGE" Then Do If r~lib \== .Nil Then Return PackageOf( r~libHome, world ) If r~program == .Nil Then Return world~nil Return world~packageObject( r~program ) End When "ANNOTATIONS" Then Return world~annotationsOf( r ) When "ANNOTATION" Then Return world~annotationOf( r, MethodString( args[1], "name", world ) ) -- Its package gets it; a library's routine has none (0). When "SETSECURITYMANAGER" Then Do If r~program == .Nil | r~lib \== .Nil Then Return "0" r~program~secMgr = SecurityManagerArg( args, world ) Return "1" End End Return .Nil -- The argument of SETSECURITYMANAGER: the manager, or .Nil (none: the -- package has none from now on). ::Routine SecurityManagerArg Use Strict Arg args, world If \ args~hasIndex( 1 ) Then Return .Nil Return args[1] -- The natives of Package (receiver: a Package object; NEW: the class), as -- ooRexx's PackageClass. What changes the REXX package (the prelude) is -- 98.984; what needs its classes made makes them (ensureInstalled). -- A setting of a package's ::OPTIONS (see RVM.Program), or all of them -- (OPTIONS). ::Routine PackageOption Use Strict Arg p, what If \ p~hasMethod( "OPTDIGITS" ) Then Do Select Case what When "DIGITS" Then Return "9" When "FUZZ" Then Return "0" When "FORM" Then Return "SCIENTIFIC" When "TRACE" Then Return "N" Otherwise p = .RVM.Program~new End End -- The REXX package's TRACE is not set (ooRexx: "", and "?n/a?"). rexx = ( p~path == "REXX" ) Select Case what When "DIGITS" Then Return p~optDigits When "FUZZ" Then Return p~optFuzz When "FORM" Then Return p~optForm When "TRACE" Then Return rexx~?( "", p~optTrace ) Otherwise Nop End Return SettingsString( p~settingsLine, rexx ) -- Settings (an RVM.Program's settingsLine) as an ::OPTIONS directive -- (ooRexx's PackageSetting::toString); the REXX package's TRACE is "?n/a?". ::Routine SettingsString Use Strict Arg settings, rexx = .False Parse Var settings digits fuzz form trace inherit prolog conds . conds = conds~changeStr( ",", " " ) line = "::OPTIONS DIGITS" digits "FORM" form "FUZZ" fuzz "NUMERIC" inherit Do c Over .Array~of( "ERROR", "FAILURE", "LOSTDIGITS", "NOSTRING", "NOTREADY", "NOVALUE" ) line = line c ( WordPos( c, conds ) > 0 )~?( "SYNTAX", "CONDITION" ) End line = line ( prolog \== 0 )~?( "PROLOG", "NOPROLOG" ) "TRACE" If rexx Then Return line "?n/a?" Return line TraceName( trace ) -- The long name of a TRACE setting ("?R": RESULTS). ::Routine TraceName Use Strict Arg trace names = "N NORMAL I INTERMEDIATES R RESULTS A ALL C COMMANDS E ERROR F FAILURE L LABELS O OFF" k = WordPos( Right( trace, 1 ), names ) If k == 0 Then Return "?n/a?" Return Word( names, k + 1 ) -- An optional string argument of OPTIONS and DEFAULTOPTIONS (.Nil: none). ::Routine OptionArg Use Strict Arg args, i If \ args~hasIndex( i ) Then Return .Nil v = args[i] If v~isA( .RVM.Obj ) Then Do s = v~requestString If s == .Nil Then Raise Syntax 93.938 Array( i ) Return str( s ) End Return str( v ) -- Settings from a string that must be one ::OPTIONS directive (ooRexx's -- PackageClass::setPackageSettings): a source of its own, compiled (a -- package made: the defaults may override it too), whose settings they are. ::Routine SettingsOf Use Strict Arg text, world If Strip( text )~left( 1 ) \== ":" Then Raise Syntax 93.900 Additional( "argument is not an ::OPTIONS directive" ) Do i = 1 To Length( text ) c = SubStr( text, i, 1 ) Select Case c When ";" Then hint = '";" (end of clause)' When "0D"x Then hint = '"0d"x (CR)' When "0A"x Then hint = '"0a"x (LF)' Otherwise Iterate End Raise Syntax 93.900 Additional( "argument must not contain a semi-colon, CR, or LF, found:" hint ) End program = world~sourceCompiler~package( "PackageSettingsFromOptionsDirectiveString", - .Array~of( text ), .Nil ) Return program~settingsLine -- Package~options with arguments (ooRexx's PackageClass::options): an -- option by its first letters, its value now; with a new value, set to it -- (the value before is returned). ::Routine PackageOptions Use Strict Arg p, args, world name = OptionArg( args, 1 ) value = OptionArg( args, 2 ) If name == .Nil Then Raise Syntax 93.903 Array( 1 ) Parse Upper Var name c1 +1 c2 +1 c3 +1 Parse Value p~settingsLine With digits fuzz form trace inherit prolog conds . syntaxOf = "SYNTAX CONDITION" cond = ""; key = ""; current = .Nil Select Case c1 When "A" Then Do If value == .Nil Then Raise Syntax 93.903 Array( 2 ) key = "ALL" End When "D" Then Do; key = "DIGITS"; current = digits; End When "E" Then cond = "ERROR" When "F" Then Select Case c2 When "A" Then cond = "FAILURE" When "O" Then Do; key = "FORM"; current = form; End When "U" Then Do; key = "FUZZ"; current = fuzz; End Otherwise Nop End When "I" Then Do; key = "INITIAL"; current = SettingsString( p~initialLine ); End When "L" Then cond = "LOSTDIGITS" When "N" Then Do If c2 == "U" Then Do; key = "NUMERIC"; current = inherit; End Else If c2 == "O" Then Select Case c3 When "S" Then cond = "NOSTRING" When "T" Then cond = "NOTREADY" When "V" Then cond = "NOVALUE" Otherwise Nop End End When "P" Then Do; key = "PROLOG"; current = ( prolog \== 0 )~?( "PROLOG", "NOPROLOG" ); End When "R" Then Do; key = "RESET"; current = SettingsString( p~settingsLine ); End When "S" Then Do If value == .Nil Then Raise Syntax 93.901 Array( 2 ) key = "SET"; current = SettingsString( p~settingsLine ) End When "T" Then Do; key = "TRACE"; current = TraceName( trace ); End When "X" Then Do; key = "EXPLICIT"; current = p~explicit; End Otherwise Nop End If cond \== "" Then Do key = "COND" current = ( WordPos( cond, p~syntaxConds ) > 0 )~?( "SYNTAX", "CONDITION" ) End If key == "" Then Do If value == .Nil Then Raise Syntax 93.914 Array( 1, '"D[igits], E[rror], FA[ilure],' - 'FO[rm], FU[zz], I[nitialOptions], L[ostdigits], NU[meric], NOS[tring], NOT[ready],' - 'NOV[alue], P[rolog], R[esetOptions], S[etOptions], T[race] or X[explicitlyDefined]"', name ) Raise Syntax 93.914 Array( 1, '"A[ll], D[igits], E[rror], FA[ilure], FO[rm], FU[zz],' - 'I[nitialOptions], L[ostdigits], NU[meric], NOS[tring], NOT[ready], NOV[alue],' - 'P[rolog], R[esetOptions], S[etOptions] or T[race]"', name ) End If value == .Nil Then Do If key == "RESET" Then p~settings = p~initialLine Return current End If value == "" Then Raise Syntax 93.900 Additional( "argument 2 must not be empty" ) v1 = Upper( Left( value, 1 ) ) Select Case key When "ALL" Then Do current = "" Do c Over "ERROR FAILURE LOSTDIGITS NOSTRING NOTREADY NOVALUE"~makeArray( " " ) current = current c ( WordPos( c, p~syntaxConds ) > 0 )~?( "SYNTAX", "CONDITION" ) End current = Strip( current ) If v1 \== "S", v1 \== "C" Then Raise Syntax 93.914 Array( 2, '"C[ondition] or S[yntax]"', value ) If v1 == "S" Then p~syntaxConds = "ERROR FAILURE LOSTDIGITS NOSTRING NOTREADY NOVALUE" Else p~syntaxConds = "" End When "COND" Then Do If v1 \== "S", v1 \== "C" Then Raise Syntax 93.914 Array( 2, '"C[ondition] or S[yntax]"', value ) list = p~syntaxConds k = WordPos( cond, list ) If k > 0 Then list = DelWord( list, k, 1 ) If v1 == "S" Then list = list cond new = "" Do c Over "ERROR FAILURE LOSTDIGITS NOSTRING NOTREADY NOVALUE"~makeArray( " " ) If WordPos( c, list ) > 0 Then new = new c End p~syntaxConds = Strip( new ) End When "DIGITS" Then Do If \ DataType( value, "W" ) Then Raise Syntax 93.905 Array( 2, value ) If value < 1 Then Raise Syntax 93.907 Array( 2, value ) If value <= fuzz Then Raise Syntax 33.1 Array( value / 1, fuzz ) p~optDigits = value / 1 End When "FORM" Then Do If v1 \== "E", v1 \== "S" Then Raise Syntax 93.914 Array( 2, '"E[ngineering] or S[cientific]"', value ) p~optForm = ( v1 == "E" )~?( "ENGINEERING", "SCIENTIFIC" ) End When "FUZZ" Then Do If \ DataType( value, "W" ) Then Raise Syntax 93.906 Array( 2, value ) If value < 0 Then Raise Syntax 93.906 Array( 2, value ) If value >= digits Then Raise Syntax 26.900 Additional( - 'NUMERIC FUZZ value ("'value / 1'") must be smaller than NUMERIC DIGITS ("'digits'")' ) p~optFuzz = value / 1 End When "NUMERIC" Then Do If v1 \== "I", v1 \== "N" Then Raise Syntax 93.914 Array( 2, '"I[nherit] or N[oInherit]"', value ) p~optInherit = ( v1 == "I" ) End When "PROLOG" Then Do If v1 \== "P", v1 \== "N" Then Raise Syntax 93.914 Array( 2, '"N[oprolog] or P[rolog]"', value ) p~optProlog = ( v1 == "P" ) End When "SET" Then p~settings = SettingsOf( value, world ) When "TRACE" Then Do t = value prefix = "" Do While Left( t, 1 ) == "?" prefix = ( prefix == "" )~?( "?", "" ) t = SubStr( t, 2 ) End letter = Upper( Left( t, 1 ) ) If letter == "" | Pos( letter, "ACEFILNOR" ) == 0 Then Raise Syntax 24.1 Array( Left( t, 1 ) ) p~optTrace = prefix || letter End -- (INITIAL, RESET, EXPLICIT: no new value.) Otherwise Raise Syntax 93.902 Array( 1 ) End Return current -- .Package~defaultOptions (ooRexx's PackageClass::clzOptions): the default -- options that override those a package made later does not set -- (D[efineDefaultOptions]), and for how many packages (C[ountOverrides]; see -- the machine's OverrideOptions). ::Routine DefaultOptions Use Strict Arg args, world If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "optionName" ) name = OptionArg( args, 1 ) value = OptionArg( args, 2 ) Select Case Upper( Left( name, 1 ) ) When "D" Then current = SettingsString( world~overrideLine ) When "C" Then current = world~overrideCount Otherwise Raise Syntax 93.914 Array( 1, '"D[efineDefaultOptions] or C[ountOverrides]"', name ) End If value == .Nil Then Return current If value == "" Then Raise Syntax 93.900 Additional( "argument 2 must not be empty" ) If Upper( Left( name, 1 ) ) == "D" Then world~overrideLine = SettingsOf( value, world ) Else Do If \ DataType( value, "W" ) Then Raise Syntax 93.905 Array( 2, value ) world~overrideCount = value / 1 End Return current ::Routine PackageNative Use Strict Arg what, receiver, args, context, world If what == "NEW" Then Return PackageNew( receiver, args, context, world ) If what == "DEFAULTOPTIONS" Then Return DefaultOptions( args, world ) p = receiver~native -- (The prelude's own routines and floating methods are the RVM's: the -- REXX package shows none, as ooRexx's.) isRexx = ( p == world~prelude ) & \ world~building Select Case what When "NAME" Then Return p~path When "SOURCE" Then Return world~newArray( SourceLines( p )~copy ) When "SOURCESIZE" Then Return SourceLines( p )~items When "SOURCELINE" Then Do n = args[1] ok = \ n~isA( .RVM.Obj ) If ok Then n = str( n ) If ok Then ok = DataType( n, "W" ) If ok Then ok = n > 0 If \ ok Then Raise Syntax 93.924 Array( ObjectText( n ) ) lines = SourceLines( p ) If n > lines~items Then Return "" Return lines[ n % 1 ] End When "CLASSES" Then Do -- (Not the RVM's own classes of the prelude, RVM.*.) If isRexx Then Do d = world~rexxClasses( .False ) Do name Over d~allIndexes If Left( name, 4 ) == "RVM." Then d~remove( name ) End Return StringTableOf( d, world ) End world~ensureInstalled( p, context ) Return StringTableOf( p~classObjs, world ) End When "PUBLICCLASSES" Then Do If isRexx Then Return StringTableOf( world~rexxClasses( .True ), world ) world~ensureInstalled( p, context ) Return StringTableOf( p~publicClasses, world ) End When "IMPORTEDCLASSES" Then Do If isRexx Then Return StringTableOf( .Nil, world ) world~ensureInstalled( p, context ) Return StringTableOf( p~importedClasses, world ) End When "ROUTINES" Then Do If isRexx Then Return StringTableOf( .Nil, world ) world~ensureInstalled( p, context ) Return StringTableOf( p~routines, world ) End When "PUBLICROUTINES" Then Do If isRexx Then Return StringTableOf( .Nil, world ) world~ensureInstalled( p, context ) Return StringTableOf( p~publicRoutines, world ) End When "IMPORTEDROUTINES" Then Do If isRexx Then Return StringTableOf( .Nil, world ) world~ensureInstalled( p, context ) Return StringTableOf( p~importedRoutines, world ) End When "DEFINEDMETHODS" Then Do If isRexx Then Return StringTableOf( .Nil, world ) world~ensureInstalled( p, context ) Return StringTableOf( p~floating, world ) End When "IMPORTEDPACKAGES" Then Do world~ensureInstalled( p, context ) list = .Array~new Do q Over p~required list~append( world~packageObject( q ) ) End Return world~newArray( list ) End When "FINDCLASS" Then Do name = MethodString( args[1], "name", world ) -- (Not the RVM's own classes of the prelude, RVM.*: past them, .LOCAL -- and .ENVIRONMENT.) If isRexx, Left( Upper( name ), 4 ) == "RVM." Then Do v = world~local~native[ Upper( name ) ] If v == .Nil Then v = world~environment~native[ Upper( name ) ] End Else v = world~findClass( p, name ) If v == .Nil Then Return world~nil Return v End When "FINDPUBLICCLASS" Then Do v = world~findPublicClass( p, MethodString( args[1], "name", world ) ) If v == .Nil Then Return world~nil Return v End -- FINDPUBLICROUTINE is FINDROUTINE in ooRexx (it finds the private ones -- too: a bug of the native, imitated). When "FINDROUTINE", "FINDPUBLICROUTINE" Then Do r = world~class~findRoutine( p, MethodString( args[1], "name", world ) ) If r == .Nil | isRexx Then Return world~nil Return world~routineObject( r ) End When "FINDNAMESPACE" Then Do q = world~findNamespace( p, MethodString( args[1], "name", world ) ) If q == .Nil Then Return world~nil Return world~packageObject( q ) End When "FINDPROGRAM" Then Do path = world~sourceCompiler~findProgram( MethodString( args[1], "name", world ), p ) If path == "" Then Return world~nil Return path End When "ADDCLASS", "ADDPUBLICCLASS" Then Do name = NamedArg( args, 1, "name", world ) If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "class" ) c = args[2] ok = c~isA( .RVM.Obj ) If ok Then ok = c~isClass If \ ok Then Raise Syntax 88.914 Array( "class", "Class" ) If isRexx Then Raise Syntax 98.984 world~ensureInstalled( p, context ) p~classObjs[ Upper( name ) ] = c If what == "ADDPUBLICCLASS" Then p~publicClasses[ Upper( name ) ] = c Return receiver End When "ADDROUTINE", "ADDPUBLICROUTINE" Then Do name = Upper( NamedArg( args, 1, "name", world ) ) If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "routine" ) v = args[2] If \ IsInstance( v, world~routineClass, world ) Then Raise Syntax 88.914 Array( "routine", "Routine" ) If isRexx Then Raise Syntax 98.984 world~ensureInstalled( p, context ) r = v~native p~routines[ name ] = r If p~routinesObj \== .Nil Then p~routinesObj~native[ name ] = v If what == "ADDPUBLICROUTINE" Then p~publicRoutines[ name ] = r Return receiver End When "ADDPACKAGE" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "package" ) v = args[1] If \ IsInstance( v, world~packageClass, world ) Then Raise Syntax 88.914 Array( "package", "Package" ) namespace = .Nil If args~hasIndex( 2 ) Then namespace = MethodString( args[2], "namespace", world ) If isRexx Then Raise Syntax 98.984 world~ensureInstalled( v~native, context ) world~addPackage( p, v~native, context ) If namespace \== .Nil Then p~namespaces[ Upper( namespace ) ] = v~native Return receiver End -- A package in a file (found from this one's directory), or made from -- source lines with that name: loaded once, its prolog run, and added. When "LOADPACKAGE" Then Do name = MethodString( args[1], 1, world ) If isRexx Then Raise Syntax 98.984 If args~hasIndex( 2 ) Then target = world~sourceCompiler~named( name, SourceArray( args[2] ) ) Else target = world~sourceCompiler~file( name, p~path, context ) Return .RVM.PackageRun~new( target, world~packageObject( target ), p ) End -- Its prolog as a Routine (the same one); .NIL for the package of a -- Method~new or a Routine~new. When "PROLOG" Then Do If p~kind \== "" | isRexx Then Return world~nil Return world~routineObject( world~sourceCompiler~prolog( p ) ) End When "LOCAL" Then Do If p~localObj == .Nil Then p~localObj = world~newDirectory Return p~localObj End When "NAMESPACES" Then Do t = world~newInstance( world~stringTableClass ) Do With Index name Item q Over p~namespaces t~native[ name ] = world~packageObject( q ) End Return t End -- Its annotations (::ANNOTATE PACKAGE): a StringTable of its own, the -- same one. When "ANNOTATIONS" Then Return world~annotationsOf( p ) When "ANNOTATION" Then Return world~annotationOf( p, MethodString( args[1], "name", world ) ) -- Its resources (::RESOURCE): a copy of its StringTable (the same -- Arrays), or an empty one; RESOURCE looks the name up in uppercase -- (ooRexx's StringTable ENTRY), .nil if there is none. When "RESOURCES" Then Do copy = world~newInstance( world~stringTableClass ) t = world~resourcesTable( p ) If t \== .Nil Then Do With Index name Item v Over t~native copy~native[ name ] = v End Return copy End When "RESOURCE" Then Do name = MethodString( args[1], "name", world ) t = world~resourcesTable( p ) If t == .Nil Then Return world~nil v = t~native[ Upper( name ) ] If v == .Nil Then Return world~nil Return v End -- Its ::OPTIONS (see RVM.Program; the REXX package's: the defaults). When "DIGITS" Then Return PackageOption( p, "DIGITS" ) When "FUZZ" Then Return PackageOption( p, "FUZZ" ) When "FORM" Then Return PackageOption( p, "FORM" ) When "TRACE" Then Return PackageOption( p, "TRACE" ) -- With no arguments, all of them, as an ::OPTIONS directive (ooRexx's -- PackageSetting::toString); else one, or a new value (PackageOptions). When "OPTIONS" Then Do If args~items == 0 Then Return PackageOption( p, "OPTIONS" ) Return PackageOptions( p, args, world ) End When "SETSECURITYMANAGER" Then Do If isRexx Then Raise Syntax 98.984 p~secMgr = SecurityManagerArg( args, world ) Return "1" End -- A library of the RVM (RVMLibrary): loaded, 1; else 0. When "LOADLIBRARY" Then Do name = MethodString( args[1], "name", world ) If isRexx Then Raise Syntax 98.984 table = RVMLibrary( name ) If table == .Nil Then Return "0" world~loadLibrary( name, table ) Return "1" End End Return .Nil -- Package~new(name): the package in that file (found from the current -- directory, as a ::REQUIRES, and loaded once); Package~new(name, source -- [, context]): a package of its own from the source lines, that sees what -- the context sees (a Method's, a Routine's or a Package's package; none by -- default). Its prolog runs (EnterPackageRun). /*----------------------------------------------------------------------------*/ /* RexxContext (.CONTEXT) and StackFrame, as ooRexx's ContextClass and */ /* StackFrameClass. A RexxContext is the RVM.Level of an activation; what it */ /* says of its NUMERIC settings, its clause, its variables and its condition */ /* is the activation's now (the context's, or the caller's saved state: see */ /* RVM.Context~levelState). Once the activation is over, 98.981. */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* RexxInfo (.REXXINFO), as ooRexx's RexxInfoClass. NAME, LANGUAGELEVEL and */ /* DATE are what PARSE VERSION says; the version is that of the ooRexx the */ /* RVM ports; the platform's values are the host's (ooRexx's own .RexxInfo); */ /* the numbers, ooRexx's for 64 bits. EXECUTABLE is the launcher (rvm) or the */ /* host's rexx, LIBRARYPATH the directory of the RVM; both File objects. */ /*----------------------------------------------------------------------------*/ ::Routine RexxInfoNative Use Strict Arg what, receiver, context, world If what == "NEW" Then Raise Syntax 93.967 Array( receiver~native~id ) If what == "COPY" Then Raise Syntax 93.970 Array( receiver ) host = .RexxInfo Parse Value context~VERSION With name level date -- The ooRexx the RVM ports: its version and its revision. Parse Value "5.3.0 13237" With version revision Select Case what When "NAME" Then Return context~VERSION When "LANGUAGELEVEL" Then Return level When "DATE" Then Return date When "VERSION" Then Return version When "MAJORVERSION" Then Return version~makeArray( "." )[1] When "RELEASE" Then Return version~makeArray( "." )[2] When "MODIFICATION" Then Return version~makeArray( "." )[3] When "REVISION" Then Return revision When "PACKAGE" Then Return world~rexxPackage When "DIGITS" Then Return "9" When "INTERNALDIGITS" Then Return "18" When "FUZZ" Then Return "0" When "FORM" Then Return "SCIENTIFIC" When "INTERNALMAXNUMBER" Then Return "999999999999999999" When "INTERNALMINNUMBER" Then Return "-999999999999999999" When "MAXEXPONENT" Then Return "999999999" When "MINEXPONENT" Then Return "-999999999" When "MAXARRAYSIZE" Then Return "100000000000000000" When "DEBUG" Then Return "0" When "PLATFORM" Then Return host~platform When "ARCHITECTURE" Then Return host~architecture When "ENDOFLINE" Then Return host~endOfLine When "PATHSEPARATOR" Then Return host~pathSeparator When "DIRECTORYSEPARATOR" Then Return host~directorySeparator When "CASESENSITIVEFILES" Then Return host~caseSensitiveFiles When "MAXPATHLENGTH" Then Return host~maxPathLength -- The launcher the RVM was started with (rvm: RVM_EXECUTABLE), so -- that a program started from here runs on the RVM too; else the -- host's rexx. When "EXECUTABLE" Then Do e = Value( "RVM_EXECUTABLE", , "ENVIRONMENT" ) If e \== "" Then Return world~fileObject( e ) f = host~executable If f == .Nil Then Return world~nil Return world~fileObject( f~absolutePath ) End When "LIBRARYPATH" Then Do Parse Value .context~package~name With dir "RVM.Objects.cls" Return world~fileObject( Strip( dir, "T", host~directorySeparator ) ) End End Return .Nil ::Routine ContextNative Use Strict Arg what, receiver, args, context, world If what == "NEW" Then Raise Syntax 93.967 Array( receiver~native~id ) If what == "COPY" Then Raise Syntax 93.970 Array( receiver ) own = receiver~native If \ own~active Then Raise Syntax 98.981 -- An INTERPRET's is its parent's (its variables, its settings). lv = own If lv~type == "INTERPRET" Then lv = lv~parent Select Case what When "NAME" Then Return lv~name When "ARGS" Then Return world~newArray( lv~args~copy ) When "EXECUTABLE" Then Return ExecObject( lv~exec, lv~kind, world ) When "PACKAGE" Then Return PackageOf( LevelPackage( lv ), world ) When "RS" Then Do If lv~rs == .Nil Then Return world~nil Return lv~rs End When "INVOCATION" Then Return own~invocation -- The thread: the activity's number (ooRexx's activity id: the program -- 1, then one for each START, REPLY...: as a condition's THREAD). One -- interpreter. When "THREAD" Then Do -- (Asked from another activity: still the activation's.) If own~thread \== .Nil Then Return own~thread act = context~activity If act == .Nil Then Return 1 Return act~id End When "INTERPRETER" Then Return 1 -- The frames now, without that of this method (ooRexx skips it). When "STACKFRAMES" Then Return context~stackFrames( .True ) Otherwise Nop End state = context~levelState( lv ) Select Case what When "DIGITS" Then Return state~digits When "FUZZ" Then Return state~fuzz When "FORM" Then Return state~form When "LINE" Then Do If state~clause == .Nil Then Return 1 Return context~clauseText( state~clause )[1] End When "CONDITION" Then Return context~conditionObject( state~condition ) -- A Directory of its variables (a stem: its Stem object). When "VARIABLES" Then Do frame = state~frame d = world~newDirectory Do name Over frame~variableNames v = frame[ name ]~value If v~isA( .RVM.Stem ) Then v = world~stemObjectOf( v ) -- its Stem object d~native[ frame~ownName( name ) ] = v End Return d End End Return .Nil ::Routine StackFrameNative Use Strict Arg what, receiver, args, context, world If what == "NEW" Then Raise Syntax 93.967 Array( receiver~native~id ) f = receiver~native Select Case what When "TYPE" Then Return f~type When "NAME" Then Return f~name When "TRACELINE" Then Return f~traceLine When "LINE" Then Do If f~line == .Nil Then Return world~nil Return f~line End When "EXECUTABLE" Then Return ExecObject( f~exec, f~kind, world ) When "TARGET" Then Do If f~target == .Nil Then Return world~nil Return world~frameTarget( f~target ) End When "ARGUMENTS" Then Do If f~args == .Nil Then Return world~newArray( .Array~new ) a = f~args~copy If f~kind == "L" Then Do -- (an Array of them: an Array) Do i = 1 To a~size If a~hasIndex( i ), a[i]~isA( .Array ) Then a[i] = world~newArray( a[i]~copy ) End End Return world~newArray( a ) End When "INVOCATION" Then Do If f~level == .Nil Then Return world~nil Return f~level~invocation End When "CONTEXT" Then Do If f~level == .Nil Then Return world~nil Return world~contextObject( f~level ) End End Return .Nil -- The object of what runs (see RVM.Level): a Method, a Routine, a program's -- prolog (a Routine); .NIL if none. ::Routine ExecObject Public Use Strict Arg exec, kind, world If exec == .Nil Then Return world~nil Select Case kind When "M" Then Return world~methodObject( exec ) When "L" Then Return world~preludeMethodObject( exec[1], exec[2] ) When "R" Then Return world~routineObject( exec ) When "LR" Then Return world~libraryRoutineObject( exec ) When "P" Then Return world~routineObject( world~sourceCompiler~prolog( exec ) ) Otherwise Return world~nil End -- Is lr (an entry of a library of the RVM) a routine of REXXUTIL? (Those of -- the others name their library.) ::Routine IsRexxUtilEntry Public Use Strict Arg lr If \ lr~hasIndex( 5 ) Then Return .True Return lr[5] == .Nil -- The Package object of a package (an RVM.Program; "REXX"; .Nil: .NIL). ::Routine PackageOf Public Use Strict Arg p, world If p == .Nil Then Return world~nil If p == "REXX" Then Return world~rexxPackage Return world~packageObject( p ) ::Routine PackageNew Use Strict Arg cls, args, context, world If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "name" ) name = MethodString( args[1], "name", world ) If \ args~hasIndex( 2 ) Then Do program = world~sourceCompiler~file( name, "", context ) Return .RVM.PackageRun~new( program, world~packageObject( program ) ) End parent = .Nil If args~hasIndex( 3 ) Then Do v = args[3] type = .Nil If v~isA( .RVM.Obj ) Then type = v~native~class~id Select Case type When "RVM.METHOD" Then parent = v~native~home When "RVM.ROUTINE" Then parent = v~native~program When "RVM.PROGRAM" Then parent = v~native Otherwise Raise Syntax 93.953 Array( 3, "Method, Routine, or Package object" ) End End lines = SourceArg( args[2], "source", 93.961 ) program = world~sourceCompiler~package( name, lines, parent ) world~checkAbstract( cls ) o = .RVM.Obj~new( world~instanceBehaviour( cls ), program ) world~created( o ) If cls == world~packageClass Then program~pkgObj = o -- Its prolog runs, then INIT, with no arguments (ooRexx's newRexx). run = .RVM.PackageRun~new( program, o ) run~runInit = .True Return run -- The source lines of a program (none: an empty array). ::Routine SourceLines Use Strict Arg p If p~source == .Nil Then Return .Array~new Return p~source -- A StringTable with the entries of directory d (the RVM's routines and -- methods as their objects). ::Routine StringTableOf Use Strict Arg d, world t = world~newInstance( world~stringTableClass ) If d == .Nil Then Return t Do With Index name Item v Over d If v~isA( .RVM.Method ) Then v = world~methodObject( v ) Else If v~isA( .RVM.Obj ) Then Nop Else If v~class~id == "RVM.ROUTINE" Then v = world~routineObject( v ) t~native[ name ] = v End Return t -- Argument i of a native, a string named 'name' (88.901, 88.909). ::Routine NamedArg Use Strict Arg args, i, name, world If \ args~hasIndex( i ) Then Raise Syntax 88.901 Array( name ) Return MethodString( args[i], name, world ) -- Is v an instance of class c (or of a subclass of it)? ::Routine IsInstance Use Strict Arg v, c, world If \ v~isA( .RVM.Obj ) Then Return .False Return IsSubclass( world~classOf( v ), c ) -- The source lines of loadPackage: an array (single-dimensional: 88.913), -- or a string's lines. ::Routine SourceArray Use Strict Arg v If \ v~isA( .RVM.Obj ) Then Return str( v )~makeArray n = v~native If \ n~isA( .Array ) Then Raise Syntax 88.913 Array( "source" ) If n~dimension > 1 Then Raise Syntax 88.913 Array( "source" ) lines = .Array~new Do item Over n~allItems lines~append( str( item ) ) End Return lines -- The argument of CALLWITH: an Array, or what makes one (MAKEARRAY: a -- string's lines, a collection); 98.913 otherwise. ::Routine CallWithArgs Public Use Strict Arg v If \ v~isA( .RVM.Obj ) Then Return str( v )~makeArray n = v~native If n~isA( .Array ) Then Do If n~dimension > 1 Then Raise Syntax 98.913 Array( ObjectText( v ) ) rest = .Array~new Do i Over n~allIndexes rest[ i ] = n[ i ] End Return rest End If n~isA( .Queue ) Then Return n~allItems If v~beh~cls~native~kind == "LIST" Then Return ListNative( v )~allItems If HashKind( v ) Then Return UnhashedArray( HashNative( v )~allIndexes ) If n~isA( .Directory ) | TableLike( n ) Then Return UnhashedArray( n~allIndexes ) Raise Syntax 98.913 Array( ObjectText( v ) ) -- Flag f of a method's options set (or not). ::Routine SetFlag Use Strict Arg flags, f, on If flags == "-" Then flags = "" flags = flags~changeStr( f, "" ) If on Then flags ||= f -- In their order: P R K U A. out = "" Do c Over .Array~of( "P", "R", "K", "U", "A" ) If flags~pos( c ) > 0 Then out ||= c End If out == "" Then Return "-" Return out -- The source lines of a method (ooRexx's Method~source): those of its body -- in its home program, from where its directive ends to where its implicit -- EXIT is (see RVM.Compiler's Extent, and ExtentLines). ::Routine SourceOf Public Use Strict Arg m Return ExtentLines( m~extent, m~home ) -- The lines of a source (program p's) from l.c to l.c ('extent'); the -- first and the last line are cut at their columns, and left out if nothing -- is left of them ("-" or no source: none). But the first, after a -- directive that ends in a semicolon, is kept (ooRexx's body starts after -- the ";": `::method m;` and then lines has "" first), unless nothing at -- all comes before the next directive. ::Routine ExtentLines Use Strict Arg extent, p lines = .Array~new If extent == "-" | p == .Nil Then Return lines source = p~source If source == .Nil Then Return lines Parse Value extent With sl "." sc "-" el "." ec -- (Nothing between the directive and the next one: none.) If sl == el, ec <= sc Then Return lines Do l = sl To el If \ source~hasIndex( l ) Then Leave text = source[ l ] semi = .False If l == sl, sc > 1 Then semi = ( SubStr( text, sc - 1, 1 ) == ";" ) If l == el Then text = Left( text, Max( 0, Min( Length( text ), ec - 1 ) ) ) If l == sl Then text = SubStr( text, sc ) If ( l == sl | l == el ), text == "", \ semi Then Iterate lines~append( text ) End Return lines -- A method name argument: its string value; an object, its REQUEST STRING -- (none: 88.909 naming 'name', as ooRexx's stringArgument). ::Routine MethodNameArg Use Strict Arg v, name = "method name" If v~isA( .RVM.Obj ) Then Do s = v~requestString If s == .Nil Then Raise Syntax 88.909 Array( name ) Return str( s ) End Return str( v ) -- A method argument of DEFINE or SETMETHOD: a Method object, or a source -- (compiled as Method~new compiles it). ::Routine MethodArg Use Strict Arg v, name, context, position world = context~world If v~isA( .RVM.Obj ), v~native~isA( .RVM.Method ) Then Return v~native lines = SourceArg( v, position ) m = world~sourceCompiler~method( name, lines, context~rvmProgram ) Call PendingInstall m~program, name, context Return m -- The methods of SUBCLASS, MIXINCLASS, ENHANCED and DEFINEMETHODS (ooRexx's -- createMethodDictionary): the pairs of what the SUPPLIER of 'v' gives (any -- object: a Directory, StringTable or Table, an Array...; one with no -- SUPPLIER, 97.1), Method objects or sources (.NIL: hidden), as a Table -- NAME -> RVM.Method (.Nil). A MapCollection is read directly (its SUPPLIER -- gives the same pairs); for the rest, the message is sent and the Supplier -- it returns is read as ooRexx does, natively (its state, not its methods). ::Routine MethodTable Use Strict Arg v, context, world t = .Table~new direct = v~isA( .RVM.Obj ) If direct Then direct = v~native~isA( .MapCollection ) If direct Then Do Do With Index name Item x Over v~native Call AddMethodEntry t, str( name ), x, context, world End Return t End sup = world~loader~sendSync( v, "SUPPLIER", .Array~new ) If sup == .Nil Then Raise Syntax 91.999 Array( "SUPPLIER" ) ok = sup~isA( .RVM.Obj ) If ok Then ok = sup~native~isA( .RVM.SupplierState ) If \ ok Then Raise Syntax 93.900 Additional( "RVM: SUPPLIER did not return a Supplier" ) st = sup~native Do While st~available name = st~indexes[ st~pos ] -- (Its REQUEST STRING, or its STRING: ooRexx's requestString.) If name~isA( .RVM.Obj ) Then name = name~stringValue Call AddMethodEntry t, str( name ), st~items[ st~pos ], context, world st~pos = st~pos + 1 End Return t -- An entry of a table of methods (see MethodTable): its name in uppercase, -- and the method (a Method object or a source; .NIL: hidden, .Nil here). ::Routine AddMethodEntry Use Strict Arg t, given, x, context, world If x == world~nil Then t[ Upper( given ) ] = .Nil Else t[ Upper( given ) ] = MethodArg( x, given, context, "method source" ) -- Method m with class c as its scope (ooRexx's newScope): m itself when it -- has none yet; else a copy. (.NIL is a scope too, SETMETHOD's FLOAT: ooRexx -- tells OREF_NULL from TheNilObject; here, 'scoped'.) ::Routine NewScope Use Strict Arg m, c, name If m~scope == .Nil, m~scoped \== .True Then Do m~scope = c m~scoped = .True Return m End copy = CopyMethod( m, name, c ) copy~scoped = .True Return copy -- The source of a method or a routine: a string (one line), or an array of -- strings (93.952), or what makes one (MAKEARRAY: a collection). ::Routine SourceArg Use Strict Arg v, position, code = 93.974 If \ v~isA( .RVM.Obj ) Then Return .Array~of( str( v ) ) If v~native~isA( .Array ) Then Do items = v~native~allItems -- (A hole is not a string either.) If v~native~items > 0, items~items < v~native~last Then Raise Syntax 93.952 Array( position ) End Else Do -- What makes an array (REQUEST ARRAY); else its REQUEST STRING, a line -- (none: 'code', 93.974 or 93.961; BaseExecutable's -- processExecutableSource). items = CollectionArray( v ) If items == .Nil Then Do line = v~requestString If line == .Nil, code == 93.961 Then Raise Syntax 93.961 Array( position ) If line == .Nil Then Raise Syntax 93.974 Array( position ) Return .Array~of( str( line ) ) End End Do item Over items If item~isA( .RVM.Obj ) Then Raise Syntax 93.952 Array( position ) End Return items -- The context argument of Method~new and Routine~new (the third) and of -- their NEWFILE (the second), as ooRexx's BaseExecutable: a Method (its home -- program; a native's is the REXX package), a Routine (its program), a -- Package, or "PROGRAMSCOPE" (the program running); a string that is not -- that, 40.904; an object with no string, 93.953. ::Routine SourceContext Use Strict Arg v, context, world, what = "NEW", position = 3 If v~isA( .RVM.Obj ), v~native~isA( .RVM.Method ) Then Do If v~native~home \== .Nil Then Return v~native~home world~ensurePrelude If world~prelude \== .Nil Then Return world~prelude Return context~rvmProgram End -- (RVM.Routine and RVM.Program are the machine's: not seen from here.) If v~isA( .RVM.Obj ), v~native~class~id == "RVM.ROUTINE" Then Return v~native~program If v~isA( .RVM.Obj ), v~native~class~id == "RVM.PROGRAM" Then Return v~native s = v -- Its string: ooRexx's requestString (REQUEST STRING, else its string -- value, with NOSTRING), which always gives one (its 93.953 is never -- raised). (.nil is a primitive of ooRexx: its string value.) If v == world~nil Then s = "The NIL object" Else If v~isA( .RVM.Obj ) Then s = v~stringValue If Upper( str( s ) ) == "PROGRAMSCOPE" Then Return context~rvmProgram Raise Syntax 40.904 Array( what, position, '"PROGRAMSCOPE", Method, Routine, or Package object', str( s ) ) -- The lines of the source in file 'name' (NEWFILE), as ooRexx reads a -- program: the name as it is (from the current directory), its lines with -- no CR at their ends; 3.1 when it cannot be read. ::Routine SourceFileLines Use Strict Arg name s = .Stream~new( name ) If s~query( "exists" ) == "" | s~open( "read shareread" ) \== "READY:" Then Raise Syntax 3.1 Array( name ) lines = s~arrayIn s~close Do i = 1 To lines~items If Right( lines[i], 1 ) == "0D"x Then lines[i] = Left( lines[i], Length( lines[i] ) - 1 ) End Return lines -- A Supplier of methods (NAME -> RVM.Method; those DEFINE hid left out), -- as Method objects; only those of class 'scope', when it is given. ::Routine MethodSupplier Use Strict Arg beh, scope, world pair = beh~allMethods( scope ) items = .Array~new Do m Over pair[2] items~append( world~methodObject( m ) ) End Return world~newSupplier( items, pair[1] ) -- A class argument (88.914). ::Routine ClassArg Use Strict Arg v, argName If v~isA( .RVM.Obj ), v~isClass Then Return v Raise Syntax 88.914 Array( argName, "Class" ) -- Is class c the same as, or a subclass of, class k (one of its scopes: a -- class it inherits counts)? ::Routine IsSubclass Public Use Strict Arg c, k If c == k Then Return .True Do s Over c~native~superclasses If IsSubclass( s, k ) Then Return .True End Return .False -- A string argument of a native (ooRexx's stringArgument: an object, its -- REQUEST STRING; none, 88.909). ::Routine StringArg Use Strict Arg v, position If \ v~isA( .RVM.Obj ) Then Return str( v ) s = v~requestString If s == .Nil Then Raise Syntax 88.909 Array( position ) Return str( s ) -- The arguments of an UNKNOWN method (ooRexx's unknownRexx), as an array: -- the message name (stringArgument: 88.909) and its arguments -- (arrayArgument: an Array, or what makes one, as CALLWITH; 98.913 -- otherwise). From the machine's dispatch of an unknown message, the -- arguments come as a host array. ::Routine UnknownArgs Use Strict Arg args If \ args~hasIndex( 1 ) Then Raise Syntax 93.903 Array( 1 ) name = StringArg( args[1], 1 ) If \ args~hasIndex( 2 ) Then Raise Syntax 93.903 Array( 2 ) If args[2]~isA( .RVM.Obj ) | \ args[2]~isA( .Array ) Then rest = CallWithArgs( args[2] ) Else rest = args[2]~copy Return .Array~of( name, rest ) -- A directory index: its string value; an object, its REQUEST STRING -- (none: 88.909, as ooRexx's stringArgument). ::Routine Index Use Strict Arg v If v~isA( .RVM.Obj ) Then Do s = v~requestString If s == .Nil Then Raise Syntax 88.909 Array( "index" ) Return str( s ) End Return str( v ) -- An index of a directory (its string value) or of a table (an object is -- itself: the same object is the same index; in a Table, one with HASHCODE -- or "==" in Rexx goes in an RVM.HashKey). ::Routine Key Use Strict Arg d, v, world If TableLike( d ), v~isA( .RVM.Obj ) Then Do If d~isA( .IdentityTable ) Then Return v Return .RVM.HashKey~for( v, world ) End Return Index( v ) /*----------------------------------------------------------------------------*/ /* The entries of a Directory that are methods (ooRexx's DirectoryClass: */ /* methodTable and unknownMethod). SETMETHOD name, method makes one (its */ /* scope .NIL; UNKNOWN is the unknown method; the entry goes away); with no */ /* method, and UNSETMETHOD, removes it. An index that is not an entry is */ /* looked up among them: the method runs to give its value (the directory is */ /* the receiver; the message, the index; no result is .NIL); else, the */ /* unknown method runs with the index. PUT replaces one. ITEMS, ALLINDEXES, */ /* HASINDEX count them; ALLITEMS, SUPPLIER, INDEX, HASITEM, REMOVEITEM run */ /* them (RVM.DirMethodsRun); REMOVE runs the one it removes. ISEMPTY and */ /* EMPTY see only the entries (ooRexx's contents), as ooRexx's. */ /*----------------------------------------------------------------------------*/ ::Class RVM.DirMethods Public ::Attribute table -- NAME -> RVM.Method (a host Directory) ::Attribute unknown -- the UNKNOWN one (RVM.Method), or .Nil ::Method init Expose table unknown table = .Directory~new unknown = .Nil ::Method copy Expose table c = self~copy:super c~table = table~copy Return c ::Routine DirSetMethod Use Strict Arg what, receiver, args, context name = Upper( Index( args[1] ) ) dm = receiver~dirMethods If what == "SETMETHOD", args~hasIndex( 2 ) Then Do m = NewScope( MethodArg( args[2], name, context, "method" ), .Nil, name ) If dm == .Nil Then Do dm = .RVM.DirMethods~new receiver~dirMethods = dm End If name == "UNKNOWN" Then dm~unknown = m Else dm~table[ name ] = m End Else If dm \== .Nil Then Do If name == "UNKNOWN" Then dm~unknown = .Nil Else dm~table~remove( name ) End If what == "SETMETHOD" Then receiver~native~remove( name ) Return .Nil -- A method of the entries run: its value (.NIL when it gives none). ::Routine DirRun Use Strict Arg receiver, m, name, args, world d = .RVM.Delegate~new( receiver, name, args ) d~method = m d~then = .RVM.OrNil~new( world~nil ) Return d -- The value of index k when it is not an entry: its method's, the unknown -- method's, or .NIL. ::Routine DirGet Use Strict Arg receiver, k, world dm = receiver~dirMethods If dm~table~hasIndex( k ) Then Return DirRun( receiver, dm~table[k], k, .Array~new, world ) If dm~unknown \== .Nil Then Return DirRun( receiver, dm~unknown, "UNKNOWN", .Array~of( k ), world ) Return world~nil -- The natives of Directory that see the methods: an array of the result, -- or .Nil (the native as without them). ::Routine DirMethodsNative Use Strict Arg what, receiver, args, context, world d = receiver~native t = receiver~dirMethods~table Select Case what When "AT", "ENTRY" Then Do If what == "AT" Then k = Key( d, args[1], world ) Else k = Upper( Index( args[1] ) ) If d~hasIndex( k ) Then Return .Nil Return .Array~of( DirGet( receiver, k, world ) ) End -- UNKNOWN: NAME= replaces a method (SETENTRY); NAME is ENTRY. When "UNKNOWN" Then Do name = UnknownArgs( args )[1] If Right( name, 1 ) == "=" Then Do t~remove( Upper( Left( name, Length( name ) - 1 ) ) ) Return .Nil End k = Upper( name ) If d~hasIndex( k ) Then Return .Nil Return .Array~of( DirGet( receiver, k, world ) ) End When "PUT" Then t~remove( Key( d, args[2], world ) ) When "SETENTRY" Then t~remove( Upper( Index( args[1] ) ) ) When "HASINDEX", "HASENTRY" Then Do If what == "HASINDEX" Then k = Key( d, args[1], world ) Else k = Upper( Index( args[1] ) ) Return .Array~of( ( d~hasIndex( k ) | t~hasIndex( k ) )~?( "1", "0" ) ) End -- REMOVE: the value it had (a method's: it runs), and it is removed. When "REMOVE", "REMOVEENTRY" Then Do If what == "REMOVE" Then k = Key( d, args[1], world ) Else k = Upper( Index( args[1] ) ) If d~hasIndex( k ) Then Return .Nil If t~hasIndex( k ) Then Do m = t[k] t~remove( k ) Return .Array~of( DirRun( receiver, m, k, .Array~new, world ) ) End Return .Array~of( DirGet( receiver, k, world ) ) End When "ITEMS" Then Return .Array~of( d~items + t~items ) When "ALLINDEXES" Then Do a = UnhashedArray( d~allIndexes ) Do n Over t~allIndexes a~append( n ) End Return .Array~of( world~newArray( a ) ) End When "ALLITEMS", "SUPPLIER" Then Do If t~isEmpty Then Return .Nil Return .Array~of( .RVM.DirMethodsRun~new( receiver, what, .Nil, world )~next( .Nil, context ) ) End -- (An entry first: then no method runs.) When "HASITEM", "INDEX", "REMOVEITEM" Then Do If t~isEmpty Then Return .Nil If ItemIndex( d, args[1], world ) \== .Nil Then Return .Nil Return .Array~of( .RVM.DirMethodsRun~new( receiver, what, args[1], world )~next( .Nil, context ) ) End Otherwise Nop End Return .Nil -- The methods of a directory's entries run one after the other (ooRexx's -- DirectoryClass allItems, supplier, getIndex), for 'op': ALLITEMS and -- SUPPLIER (the entries, then the methods' names and values); INDEX, -- HASITEM and REMOVEITEM (until one gives the target; REMOVEITEM removes it, -- and its method runs again, as ooRexx's remove). ::Class RVM.DirMethodsRun Public ::Method init Expose receiver op target world names methods values k Use Strict Arg receiver, op, target, world t = receiver~dirMethods~table names = t~allIndexes methods = t~allItems values = .Array~new k = 0 ::Method next Expose receiver op target world names methods values k Use Strict Arg v, context If k > 0 Then Do If .Nil == v Then v = world~nil values~append( v ) If op \== "ALLITEMS", op \== "SUPPLIER" Then If ItemMatch( target, v, world ) Then Signal Found End k += 1 If k <= names~items Then Do d = .RVM.Delegate~new( receiver, names[k], .Array~new ) d~method = methods[k] d~then = self Return d End d = receiver~native Select Case op When "ALLITEMS" Then Return world~newArray( d~allItems~~appendAll( values ) ) When "SUPPLIER" Then Return world~newSupplier( d~allItems~~appendAll( values ), - UnhashedArray( d~allIndexes )~~appendAll( names ) ) When "HASITEM" Then Return "0" Otherwise Return world~nil End Found: name = names[k] Select Case op When "HASITEM" Then Return "1" When "INDEX" Then Return name Otherwise Do t = receiver~dirMethods~table m = t[ name ] t~remove( name ) Return DirRun( receiver, m, name, .Array~new, world ) End End -- The object a DELEGATE method sends its message to: the value of its -- variable in the pool (ooRexx's getRetriever): a simple variable (its name -- when it has none), a stem (its Stem object), or a compound variable (its -- tail as it is written, as ooRexx does: no symbol in it is replaced; its -- name when it has none). ::Routine DelegateTarget Use Strict Arg pool, var, world p = Pos( ".", var ) If p == 0 Then Do v = pool~valueOf( var ) If .Nil == v Then Return var Return v End stemName = Left( var, p ) st = pool~valueOf( stemName ) If p == Length( var ) Then Do If .Nil == st Then Do st = .RVM.Stem~new( stemName ) pool~setValue( stemName, st ) End Return world~stemObjectOf( st ) End tail = SubStr( var, p + 1 ) If .Nil == st Then Return var Return st~at( tail ) -- A host Table or IdentityTable (the natives of Table and IdentityTable). ::Routine TableLike Public Use Strict Arg d Return d~isA( .Table ) | d~isA( .IdentityTable ) -- A Method or Routine made from a source whose package needs installing -- (classes, requires): ooRexx installs it now (LanguageParser's -- installPackage): the packages it requires start, its classes are made. -- The native that compiled it (its line, the last one) keeps it, and the -- machine installs it when the native returns, before its result (see -- InstallsFirst, and EnterPackageRun in the machine). Outside a native, -- it is installed when it first runs. ::Routine PendingInstall Use Strict Arg program, name, context If program == .Nil Then Return If program~state \== "NEW" Then Return If program~classes~isEmpty, program~requires~isEmpty Then Return natives = context~nativeLines If natives~isEmpty Then Do Call InstallTrace program, name, context Return End nc = natives~lastItem If nc~installs == .Nil Then nc~installs = .Array~new nc~installs~append( .Array~of( program, name ) ) .RVM.NativeCall~pending = .True -- What a native gave (v), after the installs it left (see PendingInstall): -- a PackageRun per package to install, in order, the last one's result v. ::Routine InstallsFirst Public Use Strict Arg v, context .RVM.NativeCall~pending = .False natives = context~nativeLines If natives~isEmpty Then Return v nc = natives~lastItem list = nc~installs If list == .Nil Then Return v nc~installs = .Nil Do i = list~items To 1 By -1 run = .RVM.PackageRun~new( list[i][1], v ) run~install = list[i][2] v = run End Return v -- The stub routine of an install: ooRexx calls one named as the package, -- whose entry and exit are traced (after the install) when the package's -- ::OPTIONS TRACE shows them. ::Routine InstallTrace Public Use Strict Arg program, name, context If program == .Nil Then Return If program~classes~isEmpty, program~requires~isEmpty Then Return t = Strip( program~optTrace, "L", "?" ) If Pos( Left( t, 1 ), "ARIL" ) == 0 Then Return text = 'Routine "'name'" in package "'name'".' n = .RVM.Level~counter If \ DataType( n, "W" ) Then n = 0 .RVM.Level~counter = n + 1 context~traceOut( " >I>" text, .Array~of( "STUB", name, ">I>", n + 1 ) ) context~traceOut( " 1 Then Do If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "argument style" ) opt = Upper( Left( str( args[2] ), 1 ) ) If opt \== "A", opt \== "I" Then Raise Syntax 93.915 Array( "AI", str( args[2] ) ) If opt == "A" Then Do If n < 3 Then Raise Syntax 88.901 Array( "argument array" ) If n > 3 Then Raise Syntax 93.902 Array( 3 ) rest = MessageArguments( args[3] ) End Else Do i = 3 To n If args~hasIndex( i ) Then rest[ i - 2 ] = args[ i ] End End Call CheckRestricted receiver, "RUN", world d = .RVM.Delegate~new( receiver, "*UNNAMED*", rest ) d~method = m Return d End When "UNSETMETHOD" Then Do name = Upper( MethodNameArg( args[1] ) ) Call CheckRestricted receiver, "UNSETMETHOD", world If receiver~isA( .RVM.Obj ) Then Do receiver~beh = receiver~beh~copyBehaviour receiver~beh~removeInstanceMethod( name ) End Return .Nil End -- REQUEST(class): its MAKEclass (.NIL when that returns nothing), or -- itself when it is of that class, or .NIL (ooRexx's requestRexx). When "REQUEST" Then Do world~ensurePrelude name = Upper( MethodString( args[1], 1, world ) ) If world~behaviourOf( receiver )~lookup( "MAKE"name ) \== .Nil Then Do d = .RVM.Delegate~new( receiver, "MAKE"name, .Array~new ) d~then = .RVM.OrNil~new( world~nil ) Return d End If Upper( world~classOf( receiver )~native~id ) == name Then Return receiver Return world~nil End When "HASMETHOD" Then Do world~ensurePrelude name = Upper( StringArg( args[1], 1 ) ) Return ( world~behaviourOf( receiver )~lookup( name ) \== .Nil )~?( "1", "0" ) End When "IDENTITYHASH" Then Do If receiver~isA( .RVM.Obj ) Then Return receiver~oid Return receiver~identityHash End -- HASHCODE: its hash value, a binary string (ooRexx's -- RexxObject~hashCode): a string's is the host's (getStringHash); an -- object's, its identity number (ooRexx: its address), 8 bytes. When "HASHCODE" Then Do If \ receiver~isA( .RVM.Obj ) Then Return str( receiver )~hashCode -- (An instance of a subclass of String: its string's.) If receiver~native~isA( .String ) Then Return receiver~native~hashCode Return Reverse( Right( D2C( receiver~oid ), 8, "00"x ) ) End When "INIT" Then Return .Nil When "ISA" Then Do world~ensurePrelude k = ClassArg( args[1], "class" ) Return IsSubclass( world~classOf( receiver ), k )~?( "1", "0" ) End When "ISNIL" Then Return ( receiver == world~nil )~?( "1", "0" ) -- Pointer's (ooRexx's PointerClass::isNull): there are no pointers. When "ISNULL" Then Return "0" When "SEND" Then Do name = MessageName( args[1], world ) rest = .Array~new Do i = 2 To args~last If args~hasIndex( i ) Then rest[ i - 1 ] = args[ i ] End d = .RVM.Delegate~new( receiver, name, rest ) d~scope = .RVM.MessageScope~scope Return d End When "NEW" Then Do o = world~newInstance( receiver ) Return .RVM.Delegate~new( o, "INIT", args, o ) End When "SENDWITH" Then Do name = MessageName( args[1], world ) d = .RVM.Delegate~new( receiver, name, MessageArguments( args[2] ) ) d~scope = .RVM.MessageScope~scope Return d End -- START, STARTWITH: a Message object, started (ooRexx's startCommon). When "START", "STARTWITH" Then Do name = MessageName( args[1], world ) scope = .RVM.MessageScope~scope If what == "START" Then Do rest = .Array~new Do i = 2 To args~last If args~hasIndex( i ) Then rest[ i - 1 ] = args[ i ] End End Else rest = MessageArguments( args[2] ) ms = .RVM.MessageState~new( receiver, name, scope, rest ) o = world~newOf( world~messageClass, ms ) ms~obj = o Return StartMessage( ms, o, world ) End End When "MS" Then Return MessageNative( what, receiver, args, context, world ) When "ES", "MX" Then Return SemaphoreNative( family, what, receiver, args, context, world ) When "MB" Then Return MBufferNative( what, receiver, args, context, world, message ) When "VR" Then Return VarRefNative( what, receiver, args, world ) When "X" Then Return LibraryNative( what, m, receiver, args, context, world ) When "M" Then Return MethodNative( what, receiver, args, context, world ) When "ST" Then Return StemNative( what, receiver, args, world ) When "RT" Then Return RoutineNative( what, receiver, args, context, world ) When "PK" Then Return PackageNative( what, receiver, args, context, world ) When "CX" Then Return ContextNative( what, receiver, args, context, world ) When "RI" Then Return RexxInfoNative( what, receiver, context, world ) When "SF" Then Return StackFrameNative( what, receiver, args, context, world ) When "C" Then Do data = receiver~native -- A plain object made by Object's NEW from a metaclass -- (.meta~new:.object) has Class's methods but is no class: COPY, -- DEFAULTNAME and HASHCODE as an object's; the others read a class it -- is not (ooRexx: undefined, even a crash), 93.900. If \ receiver~isClass Then Select Case what When "COPY", "DEFAULTNAME" Then Nop When "HASHCODE" Then Return Reverse( Right( D2C( receiver~oid ), 8, "00"x ) ) Otherwise Raise Syntax 93.900 Additional( "RVM: method" what "of Class on an object that is no class" ) End Select Case what When "COPY" Then Raise Syntax 93.970 Array( receiver ) When "DEFAULTNAME" Then Return receiver~defaultName When "ID" Then Return data~id -- Its id's (ooRexx's RexxClass::getHashValue: the same before and -- after the image is saved). When "HASHCODE" Then Return data~id~hashCode -- The first of its superclasses (ooRexx's getSuperClass). When "SUPERCLASS" Then Do If data~superclasses~isEmpty Then Return world~nil Return data~superclasses[1] End -- Class's own NEW (to a metaclass): a new class (newRexx). When "NEW" Then Do If args~last == .Nil Then Raise Syntax 93.901 Array( 1 ) If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "class id" ) id = StringArg( args[1], 1 ) rest = .Array~new Do i = 2 To args~last If args~hasIndex( i ) Then rest[ i - 1 ] = args[ i ] End Return world~newClassOf( receiver, id, rest ) End -- SUBCLASS and MIXINCLASS: the id, the metaclass, the class methods -- (a collection of methods, or sources). When "SUBCLASS", "MIXINCLASS" Then Do id = .Nil If args~hasIndex( 1 ) Then id = args[1] meta = .Nil If args~hasIndex( 2 ) Then meta = args[2] methods = .Nil If args~hasIndex( 3 ) Then methods = MethodTable( args[3], context, world ) -- ooRexx checks the id in the NEW the metaclass gets. If id == .Nil Then Do m = meta If m == .Nil Then m = data~metaclass context~nativeLines~append( ' *-* Compiled method "NEW" with scope "Class".' ) Raise Syntax 88.901 Array( "class id" ) End Return world~subclass( receiver, id, meta, methods, .Nil, what == "MIXINCLASS", .Nil ) End When "INHERIT" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "mixin class" ) position = .Nil If args~hasIndex( 2 ) Then position = args[2] world~ensurePrelude world~inherit( receiver, args[1], position ) Return .Nil End -- Only while the prelude's prolog runs (ooRexx's image build: -- removeSetupMethods takes them away after it). When "DEFINECLASSMETHOD" Then Do name = Upper( StringArg( args[1], 1 ) ) data~cmethods[ name ] = CopyMethod( args[2]~native, name, receiver ) Return .Nil End When "INHERITINSTANCEMETHODS" Then Do Call InheritInstanceMethods receiver, args[1] Return .Nil End When "UNINHERIT" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "mixin class" ) world~ensurePrelude world~uninherit( receiver, args[1] ) Return .Nil End When "ISSUBCLASSOF" Then Do world~ensurePrelude k = ClassArg( args[1], "class" ) Return IsSubclass( receiver, k )~?( "1", "0" ) End When "BASECLASS" Then Return data~baseClass When "QUERYMIXINCLASS" Then Return data~mixin~?( "1", "0" ) When "ISABSTRACT" Then Return data~abstract~?( "1", "0" ) When "ANNOTATIONS" Then Return world~annotationsOf( data ) When "ANNOTATION" Then Return world~annotationOf( data, MethodString( args[1], "name", world ) ) -- An instance method of its own: .NIL when DEFINE hid it; not -- there, 97.1. When "METHOD" Then Do world~ensurePrelude name = Upper( MethodNameArg( args[1] ) ) If \ data~imethods~hasIndex( name ) Then Raise Syntax 97.1 Array( receiver, name ) Return world~methodObject( data~imethods[ name ] ) End -- Its instance methods (with those it inherits, and those they -- hide), or those of one of its scopes (.NIL: its own). When "METHODS" Then Do world~ensurePrelude beh = world~instanceBehaviour( receiver ) If \ args~hasIndex( 1 ) Then Return MethodSupplier( beh, .Nil, world ) scope = args[1] If scope == world~nil Then scope = receiver Else scope = ClassArg( scope, "class" ) Return MethodSupplier( beh, scope, world ) End -- DEFINE: a new instance behaviour (the objects made before keep -- theirs), and its subclasses' made again. When "DEFINE" Then Do If data~rexx, \ world~building Then Raise Syntax 98.985 world~ensurePrelude given = MethodNameArg( args[1] ) name = Upper( given ) m = .Nil -- A source is compiled with the name as given (its package's). If args~hasIndex( 2 ), args[2] \== world~nil Then Do m = MethodArg( args[2], given, context, "method" ) If \ args[2]~isA( .RVM.Obj ) Then m~name = name Else If \ args[2]~native~isA( .RVM.Method ) Then m~name = name m = NewScope( m, receiver, name ) End world~newInstanceBehaviour( receiver ) data~imethods[ name ] = m world~updateInstanceSubClasses( receiver ) Return .Nil End When "DEFINEMETHODS" Then Do If data~rexx, \ world~building Then Raise Syntax 98.985 If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "methods" ) world~ensurePrelude methods = MethodTable( args[1], context, world ) world~newInstanceBehaviour( receiver ) Do With Index name Item m Over methods If m \== .Nil Then m = NewScope( m, receiver, name ) data~imethods[ name ] = m End world~updateInstanceSubClasses( receiver ) Return .Nil End When "DELETE" Then Do If data~rexx, \ world~building Then Raise Syntax 98.985 name = Upper( MethodNameArg( args[1] ) ) world~newInstanceBehaviour( receiver ) If data~imethods~hasIndex( name ) Then Do data~imethods~remove( name ) world~updateInstanceSubClasses( receiver ) End Return .Nil End When "SUPERCLASSES" Then Do world~ensurePrelude Return world~newArray( data~superclasses~copy ) End When "SUBCLASSES" Then Do world~ensurePrelude Return world~newArray( data~subclasses~copy ) End When "METACLASS" Then Return data~metaclass When "ISMETACLASS" Then Return data~isMeta~?( "1", "0" ) -- ENHANCED: an object of a subclass of its own ("Enhanced -- Subclass"), with the methods (their scope .NIL, as SETMETHOD's); -- its class is this one. When "ENHANCED" Then Do If args~last == .Nil Then Raise Syntax 93.901 Array( 1 ) If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "methods" ) methods = MethodTable( args[1], context, world ) rest = .Array~new Do i = 2 To args~last If args~hasIndex( i ) Then rest[ i - 1 ] = args[ i ] End steps = .RVM.Enhance~new( world, receiver, methods, rest ) Return world~subclass( receiver, "Enhanced Subclass", .Nil, .Nil, .Nil, .False, steps ) End -- The package of its ::CLASS; REXX's; .NIL (made by SUBCLASS). When "PACKAGE" Then Do If data~home \== .Nil Then Return world~packageObject( data~home ) If data~rexx Then Return world~rexxPackage Return world~nil End End End When "D" Then Do -- .LOCAL: made when it is first used (see RVM.World~ensureLocal). If world~localState == "" Then If receiver == world~local Then world~ensureLocal -- .ENVIRONMENT holds the prelude's public classes: it is loaded when -- the directory is first asked (see RVM.World~ensurePrelude). If world~prelude == .Nil Then If receiver == world~environment Then world~ensurePrelude d = receiver~native -- A Directory's entries that are methods (SETMETHOD): what they change -- (an array of the result), or .Nil (as without them). -- PUT and UNKNOWN check their arguments themselves (ooRexx's -- validateValueIndex; StringHashCollection::unknownRexx). If what == "PUT" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "item" ) If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "index" ) End If what == "UNKNOWN" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 93.903 Array( 1 ) Call StringArg args[1], 1 If \ args~hasIndex( 2 ) Then Raise Syntax 93.903 Array( 2 ) End If what == "SETMETHOD" | what == "UNSETMETHOD" Then Return DirSetMethod( what, receiver, args, context ) If receiver~dirMethods \== .Nil Then Do v = DirMethodsNative( what, receiver, args, context, world ) If v \== .Nil Then Return v[1] End Select Case what -- INIT: the capacity (93.923): the order of the host's items (made -- again with it while it is empty). When "INIT" Then Do If args~hasIndex( 1 ) Then Do capacity = HostNumber( args[1] ) If capacity~isA( .RVM.Obj ) Then Raise Syntax 93.923 Array( capacity ) If unsignedWholeNumber( capacity, .RVM.Number~WholeDigits ) == .Nil Then Raise Syntax 93.923 Array( capacity ) If d~isEmpty Then receiver~native = d~class~new( capacity ) End Return .Nil End When "AT" Then Do v = d[ Key( d, args[1], world ) ] If .Nil == v Then Return world~nil Return v End When "PUT" Then Do d[ Key( d, args[2], world ) ] = args[1] Return .Nil End -- The first index of an item (equalValue, see ItemIndex). When "HASITEM" Then Return ( ItemIndex( d, args[1], world ) \== .Nil )~?( "1", "0" ) When "INDEX", "REMOVEITEM" Then Do k = ItemIndex( d, args[1], world ) If .Nil == k Then Return world~nil If what == "INDEX" Then Return Unhashed( k ) Return d~remove( k ) End When "REMOVEENTRY" Then Do v = d~remove( Upper( Index( args[1] ) ) ) If .Nil == v Then Return world~nil Return v End When "ENTRY" Then Do v = d[ Upper( Index( args[1] ) ) ] If .Nil == v Then Return world~nil Return v End When "SETENTRY" Then Do name = Upper( Index( args[1] ) ) If args~hasIndex( 2 ) Then d[ name ] = args[2] Else d~remove( name ) Return .Nil End When "HASENTRY" Then Return d~hasIndex( Upper( Index( args[1] ) ) )~?( "1", "0" ) When "HASINDEX" Then Return d~hasIndex( Key( d, args[1], world ) )~?( "1", "0" ) When "REMOVE" Then Do v = d~remove( Key( d, args[1], world ) ) If .Nil == v Then Return world~nil Return v End When "ITEMS" Then Return d~items When "ALLINDEXES" Then Return world~newArray( UnhashedArray( d~allIndexes ) ) When "SUPPLIER" Then Return world~newSupplier( d~allItems, UnhashedArray( d~allIndexes ) ) When "ALLITEMS" Then Return world~newArray( d~allItems ) When "ISEMPTY" Then Return d~isEmpty~?( "1", "0" ) When "EMPTY" Then Do d~empty Return receiver End -- UNKNOWN (StringHashCollection::unknown): NAME= is SETENTRY (no -- value: a removal), NAME is ENTRY. When "UNKNOWN" Then Do unk = UnknownArgs( args ) name = unk[1] rest = unk[2] If Right( name, 1 ) == "=" Then Do name = Upper( Left( name, Length( name ) - 1 ) ) If rest~hasIndex( 1 ) Then d[ name ] = rest[1] Else d~remove( name ) Return .Nil End v = d[ Upper( name ) ] If .Nil == v Then Return world~nil Return v End End End When "V" Then Select Case what -- Class methods: a new array, then its INIT. When "NEW" Then Do If args~last == .Nil Then a = .Array~new Else Do -- The dimensions may be in an array: its host array. hostArgs = HostArgs( args ) If ArrayObj( args[1] ) Then hostArgs[1] = HostArray( args[1] ) a = .Array~sendWith( "NEW", hostArgs ) End world~checkAbstract( receiver ) o = .RVM.Obj~new( world~instanceBehaviour( receiver ), a ) world~created( o ) Return .RVM.Delegate~new( o, "INIT", .Array~new, o ) End When "OF" Then Do n = args~last If n == .Nil Then n = 0 a = .Array~new( n ) Do i = 1 To n If args~hasIndex( i ) Then a[i] = args[i] End world~checkAbstract( receiver ) o = .RVM.Obj~new( world~instanceBehaviour( receiver ), a ) world~created( o ) Return .RVM.Delegate~new( o, "INIT", .Array~new, o ) End -- The host's method of the same name: the items as they are, the -- other arguments as strings (an array as an index: its host array). -- SUPPLIER: the items there, and their indexes (an array of subscripts -- when there are several). When "SUPPLIER" Then Do a = receiver~native items = a~allItems indexes = a~allIndexes Do i = 1 To indexes~items If indexes[i]~isA( .Array ) Then indexes[i] = world~newArray( indexes[i] ) End Return world~newSupplier( items, indexes ) End When "HOST" Then Do a = receiver~native items = 0 If WordPos( m~name, "PUT []= APPEND INSERT FILL" ) > 0 Then items = 1 hostArgs = .Array~new n = args~last If n == .Nil Then n = 0 Do i = 1 To n If \ args~hasIndex( i ) Then Iterate v = args[i] Select When i <= items Then Nop When ArrayObj( v ) Then v = HostArray( v ) When v~isA( .RVM.Obj ) Then If v == world~nil Then v = .Nil Otherwise v = str( v ) End hostArgs[i] = v End a~sendWith( m~name, hostArgs ) If \ Var( "RESULT" ) Then Return .Nil v = result If .Nil == v Then Return world~nil If a == v Then Return receiver -- A host array (ALLINDEXES of a multidimensional array holds arrays). If v~isA( .Array ) Then Do Do i Over v~allIndexes If v[i]~isA( .Array ) Then v[i] = world~newArray( v[i] ) End Return world~newArray( v ) End Return v End When "HASITEM" Then Return ( ItemIndex( receiver~native, args[1], world ) \== .Nil )~?( "1", "0" ) When "INDEX" Then Do k = ItemIndex( receiver~native, args[1], world ) If .Nil == k Then Return world~nil If k~isA( .Array ) Then Return world~newArray( k ) Return k End When "REMOVEITEM" Then Do k = ItemIndex( receiver~native, args[1], world ) If .Nil == k Then Return world~nil Return receiver~native~remove( k ) End -- MAKESTRING / TOSTRING: the host's, over the items made strings. An -- object as the option or the separator: its REQUEST STRING (the -- host's optionArgument and stringArgument; none: the object, and the -- host raises 88.909); the separator of the C form is not asked for -- one (the host raises 93.902 first). When "MAKESTRING" Then Do hostArgs = .Array~new Do i = 1 To 2 If args~hasIndex( i ) Then Do v = args[i] If \ v~isA( .RVM.Obj ) Then hostArgs[i] = str( v ) Else If i == 2, CForm( hostArgs ) Then hostArgs[i] = v Else Do s = v~requestString If s == .Nil Then hostArgs[i] = v Else hostArgs[i] = str( s ) End End End Return ItemStrings( receiver~native )~sendWith( "TOSTRING", hostArgs ) End -- SORT: ooRexx's merge sort (see MergeSort), the items compared with -- their COMPARETO; a missing item is error 98.975. When "SORT" Then Do a = receiver~native last = a~items If last == 0 Then Return receiver -- A multidimensional array is sorted as the flat array it is. flat = a If a~dimension > 1 Then Do flat = .Array~new( a~size ) items = a~allItems indexes = a~allIndexes Do j = 1 To items~items flat[ FlatPosition( a, indexes[j] ) ] = items[j] End End Do i = 1 To last If \ flat~hasIndex( i ) Then Raise Syntax 98.975 Array( i ) End -- An object with a COMPARETO (written in Rexx) needs the prelude's -- sort (RVM.ArraySort), shown as this method (a multidimensional -- array too: it sorts it as its flat sequence, see RVM.FlatArray). Do v Over flat If \ v~isA( .RVM.Obj ) Then Iterate If Lookup( v, "COMPARETO", .Nil, world ) == .Nil Then Iterate world~ensurePrelude natives = context~nativeLines natives~delete( natives~last ) d = .RVM.Delegate~new( receiver, message, .Array~new ) d~method = world~sortMethods[ message ] Return d End Call MergeSort flat, .Array~new( last ), 1, last If flat \== a Then Do i = 1 To last a[ Subscripts( a, i ) ] = flat[i] End Return receiver End End When "S" Then Do If .RVM.StringArgs~specs~hasIndex( what ) Then Return StringMethod( what, 0, receiver, args, context ) -- (NEW goes to the class: it is not converted, as that would be -- NOSTRING.) -- A subclass's (ooRexx's newRexx and completeNewObject): an object -- whose native value is the string; INIT gets the rest of the -- arguments. If what == "NEW" Then Do v = StringArg( args[1], 1 ) world~checkAbstract( receiver ) rest = .Array~new n = args~last If n == .Nil Then n = 0 Do i = 2 To n If args~hasIndex( i ) Then rest[ i - 1 ] = args[ i ] End If receiver == world~stringClass Then Do If n <= 1 Then Return v Return .RVM.Delegate~new( v, "INIT", rest, v ) End o = .RVM.Obj~new( world~instanceBehaviour( receiver ), v ) world~created( o ) Return .RVM.Delegate~new( o, "INIT", rest, o ) End s = str( receiver ) Select Case what When "STRING", "MAKESTRING" Then Return s -- An object: its REQUEST STRING, or else its STRING (never .NIL). When "EQUALS", "CASELESSEQUALS" Then Do v = args[1] -- An object: its MAKESTRING, or else its STRING (its name); .NIL -- is never equal. If v == world~nil Then Return "0" If v~isA( .RVM.Obj ) Then Do w = v~requestString If .Nil == w Then w = v~stringValue v = w End If what == "EQUALS" Then Return ( s == str( v ) )~?( "1", "0" ) Return ( Upper( s ) == Upper( str( v ) ) )~?( "1", "0" ) End When "APPEND" Then Return s || str( args[1] ) -- The separator of MAKEARRAY is a string argument (an object with a -- MAKESTRING gives it). When "MAKEARRAY" Then Do a = HostArgs( args ) If args~hasIndex( 1 ) Then a[1] = MethodString( args[1], 1, world ) Return world~newArray( s~sendWith( what, a ) ) End When "SUBWORDS" Then Return world~newArray( s~sendWith( what, HostArgs( args ) ) ) End End -- A built-in function of the same name, the receiver as argument 'what' -- (a method of String: its arguments checked first as ooRexx's method -- does, see StringMethod). When "B" Then Do If .RVM.StringArgs~specs~hasIndex( m~name ) Then Return StringMethod( m~name, what, receiver, args, context ) a = .Array~new n = args~last If n == .Nil Then n = 0 j = 0 Do i = 1 To Max( n + 1, what ) If i == what Then a[i] = receiver Else Do j += 1 If args~hasIndex( j ) Then a[i] = args[j] End End Return ComputeBIF( m~name, a, context ) End When "OP" Then Return StringOperator( m~name, receiver, args, context ) -- Supplier. When "U" Then Do If what == "INIT" Then Do items = SupplierArray( args[1] ) indexes = SupplierArray( args[2] ) receiver~native = .RVM.SupplierState~new( items, indexes ) Return .Nil End u = receiver~native Select Case what When "AVAILABLE" Then Return u~available~?( "1", "0" ) When "SUPPLIER" Then Return receiver When "ALLITEMS", "ALLINDEXES" Then Do If what == "ALLITEMS" Then from = u~items Else from = u~indexes out = .Array~new Do i = u~pos To u~items~size v = from[i] If .Nil == v Then v = world~nil out~append( v ) End u~drained = .True Return world~newArray( out ) End Otherwise Nop End If \ u~available Then Raise Syntax 93.937 Select Case what When "ITEM" Then v = u~items[ u~pos ] When "INDEX" Then v = u~indexes[ u~pos ] When "NEXT" Then Do u~pos += 1 Return .Nil End End If .Nil == v Then Return world~nil Return v End -- List and Queue: the host's (see HostCollection). When "L" Then Do Select Case what -- OF: a new one (its INIT first, as ooRexx), then the items (an -- omitted one: 93.903). When "OF" Then Do n = args~last If n == .Nil Then n = 0 Do i = 1 To n If \ args~hasIndex( i ) Then Raise Syntax 93.903 Array( i ) End If receiver~native~kind == "LIST" Then native = .List~new Else native = .Queue~new Do i = 1 To n native~append( args[i] ) End world~checkAbstract( receiver ) o = world~newOf( receiver, native ) Return .RVM.Delegate~new( o, "INIT", .Array~new, o ) End -- INIT: the capacity (a length: 93.923). A List's contents are made -- by the first one (at least 8 slots, as ooRexx). When "INIT" Then Do capacity = 8 If args~hasIndex( 1 ) Then Do h = HostNumber( args[1] ) capacity = .Nil If \ h~isA( .RVM.Obj ) Then capacity = unsignedWholeNumber( h, .RVM.Number~WholeDigits ) If capacity == .Nil Then Raise Syntax 93.923 Array( h ) End If receiver~native == .Nil Then receiver~native = .List~new( capacity ) Return .Nil End Otherwise Nop End a = ListNative( receiver ) Select Case what When "HOST" Then Return HostCollection( m, receiver, a, args, world ) -- The first index of an item (equalValue, see ItemIndex). When "HASITEM" Then Return ( ItemIndex( a, args[1], world ) \== .Nil )~?( "1", "0" ) When "INDEX", "REMOVEITEM" Then Do k = ItemIndex( a, args[1], world ) If .Nil == k Then Return world~nil If what == "INDEX" Then Return k Return a~remove( k ) End When "SUPPLIER" Then Return world~newSupplier( a~allItems, a~allIndexes ) End End -- Set, Bag and Relation: the host's (see HashHost). When "H" Then Do Select Case what -- OF: a new one (its INIT first, as ooRexx), then the items. When "OF" Then Do n = args~last If n == .Nil Then n = 0 Do i = 1 To n If \ args~hasIndex( i ) Then Raise Syntax 93.903 Array( i ) End native = HashNew( receiver~native~kind, .Nil ) Do i = 1 To n native~put( HashValue( args[i], world ) ) End world~checkAbstract( receiver ) o = world~newOf( receiver, native ) Return .RVM.Delegate~new( o, "INIT", .Array~new, o ) End -- INIT: its capacity (the number of buckets: the order of its items) -- is that of the first one. When "INIT" Then Do capacity = .Nil If args~hasIndex( 1 ) Then Do capacity = HostNumber( args[1] ) If capacity~isA( .RVM.Obj ) Then Raise Syntax 93.923 Array( capacity ) If unsignedWholeNumber( capacity, .RVM.Number~WholeDigits ) == .Nil Then Raise Syntax 93.923 Array( capacity ) End If receiver~native == .Nil Then receiver~native = HashNew( receiver~beh~cls~native~kind, capacity ) Return .Nil End Otherwise Nop End h = HashNative( receiver ) Select Case what When "HOST" Then Do hostArgs = .Array~new Do i Over args~allIndexes hostArgs[i] = HashValue( args[i], world ) End h~sendWith( m~name, hostArgs ) If \ Var( "RESULT" ) Then Return .Nil Return HostResult( result, h, receiver, world ) End -- INDEX: the index of the first item that is that one; ALLINDEX: of -- all of them (in the order of the collection). When "INDEX", "ALLINDEX" Then Do items = h~allItems indexes = h~allIndexes out = .Array~new Do j = 1 To items~items If \ ItemMatch( args[1], Unhashed( items[j] ), world ) Then Iterate If what == "INDEX" Then Return Unhashed( indexes[j] ) out~append( Unhashed( indexes[j] ) ) End If what == "INDEX" Then Return world~nil Return world~newArray( out ) End -- HASITEM, REMOVEITEM (a Relation): the first item that is that one, -- of those at the index when there is one. When "HASITEM", "REMOVEITEM" Then Do -- At an index: the host's, which compares index, then item, in -- its chain (HashContents::hasItem), the item as ItemMatch does. If args~hasIndex( 2 ) Then Do index = HashValue( args[2], world ) item = .RVM.ItemKey~new( args[1], world ) If what == "HASITEM" Then Return h~hasItem( item, index )~?( "1", "0" ) v = h~removeItem( item, index ) If .Nil == v Then Return world~nil Return Unhashed( v ) End items = h~allItems indexes = h~allIndexes Do j = 1 To items~items If \ ItemMatch( args[1], Unhashed( items[j] ), world ) Then Iterate If what == "HASITEM" Then Return "1" Return Unhashed( h~removeItem( items[j], indexes[j] ) ) End If what == "HASITEM" Then Return "0" Return world~nil End End End -- ::ATTRIBUTE and ::CONSTANT. -- A guarded attribute takes the lock of the pool while it reads or -- writes it (ooRexx's AttributeGetterCode): when another activity has -- it, the message waits and is sent again (RVM.Wait); the lock is then -- the activity's already (granted). When "A" Then Select Case what When "GET", "SET" Then Do pool = receiver~pool( m~scope ) guarded = \ m~hasFlag( "U" ) act = .Nil If guarded Then act = context~activity If act == .Nil Then guarded = .False If guarded Then Do If act~granted == pool Then act~granted = .Nil Else If \ pool~reserve( act ) Then Return .RVM.Wait~new( pool ) End -- A stem attribute (a.) is a stem variable: GET gives its Stem -- object (the stem made if it has none), and SET assigns it as -- "a. = value" does (a Stem object: the variable is that stem). isStem = m~var~endsWith( "." ) If what == "GET" Then Do v = pool~valueOf( m~var ) If isStem Then Do If .Nil == v Then Do v = .RVM.Stem~new( m~var ) pool~setValue( m~var, v ) End v = world~stemObjectOf( v ) End Else If .Nil == v Then v = m~var End Else Do v = args[1] If isStem Then Do st = world~stemOf( v ) If st == .Nil Then Do st = .RVM.Stem~new( m~var ) st~setValue( v ) End v = st End pool~setValue( m~var, v ) v = .Nil End If guarded Then pool~release Return v End -- DELEGATE var (ooRexx's DelegateCode): the message, as it was sent, -- goes to the object in the variable (its name, when it has none), -- with the same arguments, and its result is the method's. A guarded -- one takes the lock only while it reads the variable. The message is -- sent (not delegated): the private and package checks apply. When "DELEGATE" Then Do pool = receiver~pool( m~scope ) guarded = \ m~hasFlag( "U" ) act = .Nil If guarded Then act = context~activity If act == .Nil Then guarded = .False If guarded Then Do If act~granted == pool Then act~granted = .Nil Else If \ pool~reserve( act ) Then Return .RVM.Wait~new( pool ) End v = DelegateTarget( pool, m~var, world ) If guarded Then pool~release d = .RVM.Delegate~new( v, message, args ) d~resend = .True Return d End When "CONST" Then Do -- A calculated one whose initializer has not run (or failed). If m~value == .Nil Then Raise Syntax 97.4 Array( receiver, m~name ) Return m~value End End Otherwise Nop End Raise Syntax 93.900 Additional( "RVM: native method" key "is missing" ) /******************************************************************************/ /* List and Queue */ /* */ /* Their native values are the host's List and Queue, so their indexes are */ /* ooRexx's (a List's: the slots of its contents, a freed one reused first). */ /******************************************************************************/ -- The host List of a List object: made by its INIT; when INIT did not make -- it (a subclass's INIT that does not forward it), the default one (ooRexx -- does the same after NEW). ::Routine ListNative Public Use Strict Arg obj If obj~native == .Nil Then obj~native = .List~new Return obj~native -- A number argument for the host (an index, a count): a string as it is; an -- object as ooRexx makes it a number (its MAKESTRING, or else its STRING), -- or, when that is not one, the object itself (the host's error holds it -- and names it). ::Routine HostNumber Use Strict Arg v If \ v~isA( .RVM.Obj ) Then Return str( v ) s = v~requestString If s == .Nil Then s = v~stringValue If unsignedWholeNumber( s, .RVM.Number~WholeDigits ) \== .Nil Then Return s Return v -- A method of List or Queue: the host's method of the same name, with the -- same checks and errors. The items (the first argument of PUT, []=, INSERT, -- APPEND, PUSH and QUEUE) go as they are; .NIL as the host's; the other -- arguments as numbers (HostNumber). An omitted item of a List's PUT or -- INSERT is 93.903 (ooRexx would store a null there: a bug). ::Routine HostCollection Use Strict Arg m, receiver, a, args, world name = m~name items = 0 If WordPos( name, "PUT []= INSERT APPEND PUSH QUEUE" ) > 0 Then items = 1 hostArgs = .Array~new named = .Nil n = args~last If n == .Nil Then n = 0 Do i = 1 To n If \ args~hasIndex( i ) Then Iterate v = args[i] Select When i <= items Then Nop When v == world~nil Then v = .Nil Otherwise Do -- An index that is an object: ooRexx's error names the object. If v~isA( .RVM.Obj ), named == .Nil Then named = v v = HostNumber( v ) End End hostArgs[i] = v End Signal On Syntax Name HostError -- A List's PUT or INSERT without an item: ooRexx checks the index first -- (as SECTION does), and then stores a null (a bug): 93.903 here. If a~isA( .List ), WordPos( name, "PUT []= INSERT" ) > 0, \ args~hasIndex( 1 ) Then Do If name == "INSERT" Then Do If hostArgs~hasIndex( 2 ), hostArgs[2] \== .Nil Then a~section( hostArgs[2], 0 ) End Else If hostArgs~hasIndex( 2 ) Then a~section( hostArgs[2], 0 ) If name == "INSERT" | hostArgs~hasIndex( 2 ) Then Raise Syntax 93.903 Array( 1 ) End a~sendWith( name, hostArgs ) Signal Off Syntax If \ Var( "RESULT" ) Then Return .Nil v = result If .Nil == v Then Return world~nil If v == a Then Return receiver If v~isA( .Array ) Then Return world~newArray( v ) -- SECTION: a List (ooRexx makes a List), or a Queue of the receiver's -- class (ooRexx sends it NEW: its INIT is not run here). If v~isA( .List ) Then Return world~newOf( world~listClass, v ) If v~isA( .Queue ) Then Return .RVM.Obj~new( receiver~beh, v ) Return v HostError: co = condition( "O" ) If co~code == "93.918", named \== .Nil Then Raise Syntax 93.918 Array( named ) Raise Propagate /******************************************************************************/ /* Set, Bag and Relation */ /* */ /* Their native values are the host's, made by their INIT with its capacity: */ /* the host hashes as ooRexx does, so the order of their items is ooRexx's. */ /******************************************************************************/ -- Is it a Set, a Bag or a Relation? ::Routine HashKind Public Use Strict Arg v If \ v~isA( .RVM.Obj ) Then Return .False If v~isClass Then Return .False Return WordPos( v~beh~cls~native~kind, "SET BAG RELATION" ) > 0 -- A new host collection of a kind, of a capacity (.Nil: the default). ::Routine HashNew Use Strict Arg kind, capacity Select Case kind When "SET" Then cls = .Set When "BAG" Then cls = .Bag Otherwise cls = .Relation End If capacity == .Nil Then Return cls~new Return cls~new( capacity ) -- The host collection of a Set, Bag or Relation: made by its INIT; when INIT -- did not make it, the default one (ooRexx does the same after NEW). ::Routine HashNative Public Use Strict Arg obj If obj~native == .Nil Then obj~native = HashNew( obj~beh~cls~native~kind, .Nil ) Return obj~native -- An item or an index for the host: an object as it is (the same object is -- the same index; one with HASHCODE or "==" in Rexx, in an RVM.HashKey), a -- string (or a number) as its string. ::Routine HashValue Use Strict Arg v, world If v~isA( .RVM.Obj ) Then Return .RVM.HashKey~for( v, world ) Return str( v ) -- A result of the host: .NIL, arrays, suppliers and the collection itself -- made the RVM's (and the objects in an RVM.HashKey, themselves). ::Routine HostResult Use Strict Arg v, h, receiver, world If .Nil == v Then Return world~nil -- (An RVM.HashKey first: its "==" is the object's, in Rexx.) If v~isA( .RVM.HashKey ) Then Return v~obj If v~isA( .RVM.StringKey ) Then Return v~obj If v == h Then Return receiver If v~isA( .Array ) Then Return world~newArray( UnhashedArray( v ) ) If v~isA( .Supplier ) Then Return world~newSupplier( UnhashedArray( v~allItems ), UnhashedArray( v~allIndexes ) ) Return Unhashed( v ) -- An index or item of the host's: the object when it is in an RVM.HashKey -- or an RVM.StringKey. ::Routine Unhashed Public Use Strict Arg v If v~isA( .RVM.HashKey ) Then Return v~obj If v~isA( .RVM.StringKey ) Then Return v~obj Return v -- A host array with the objects in an RVM.HashKey or an RVM.StringKey made -- themselves. ::Routine UnhashedArray Public Use Strict Arg a Do i Over a~allIndexes If a[i]~isA( .RVM.HashKey ) | a[i]~isA( .RVM.StringKey ) Then Do a = a~copy Do k Over a~allIndexes a[k] = Unhashed( a[k] ) End Return a End End Return a -- An item to look for in a host hash collection (HASITEM, REMOVEITEM of a -- Relation at an index): the host sends it "==" with each item it looks -- at (equalValue), and that is ItemMatch. ::Class RVM.ItemKey Public ::Attribute v ::Attribute world ::Method init Expose v world Use Strict Arg v, world ::Method "==" Expose v world Use Strict Arg other Return ItemMatch( v, Unhashed( other ), world )~?( "1", "0" ) /******************************************************************************/ /* RVM.HashKey -- an object of the RVM whose HASHCODE or "==" is written in */ /* Rexx, as an index (or an item) of a host hash collection (Table, Set, Bag, */ /* Relation). The host is ooRexx: it sends HASHCODE and "==" to an object */ /* that is not of a primitive class, as it does to the RVM's in ooRexx */ /* (RexxObject::hash, isEqual); these send them to the object now. */ /******************************************************************************/ ::Class RVM.HashKey Public ::Attribute obj ::Attribute world ::Method for Class Use Strict Arg v, world beh = world~behaviourOf( v ) m = beh~lookup( "HASHCODE" ) e = beh~lookup( "==" ) code = .False If m \== .Nil Then code = m~isCode If e \== .Nil, \ code Then code = e~isCode If \ code Then Do -- An instance of a subclass of String: in an RVM.StringKey (equal to -- its string, and kept as the object). If v~isA( .RVM.Obj ), v~native~isA( .String ) Then Do k = .RVM.StringKey~new( v~native ) k~obj = v Return k End Return v End k = self~new k~obj = v k~world = world Return k ::Method hashCode Expose obj world v = world~loader~sendSync( obj, "HASHCODE", .Array~new ) If v == .Nil Then Raise Syntax 91.999 Array( "HASHCODE" ) Return str( v ) ::Method "==" Expose obj world Use Strict Arg other other = Unhashed( other ) -- The same object first (RexxInternalObject::equalValue). If other == obj Then Return "1" v = world~loader~sendSync( obj, "==", .Array~of( other ) ) If v == .Nil Then Raise Syntax 91.999 Array( "==" ) Return str( v ) /******************************************************************************/ /* RVM.StringKey -- an instance of a subclass of String of the RVM, as an */ /* index (or an item) of a host hash collection. It is itself an instance of */ /* a subclass of String of the host, which hashes and compares it as its */ /* string and keeps it as the index, as ooRexx does with the RVM's */ /* (RexxObject::hash sends HASHCODE, String's). */ /******************************************************************************/ ::Class RVM.StringKey Public Subclass String ::Attribute obj /******************************************************************************/ /* The methods of String: their arguments */ /* */ /* A method of String checks its arguments as ooRexx's does (StringClass*.cpp */ /* and its helpers: stringArgument, positionArgument, lengthArgument, */ /* nonNegativeArgument, padArgument, optionArgument), in order, with the */ /* method's errors (93.9xx; the built-in functions that ooRexx runs as these */ /* methods come here too, after their own checks: RVM.BIFs' CallBIF). Then */ /* the built-in function's code computes it (ComputeBIF, with the arguments */ /* made plain), or the method does what the function cannot. */ /******************************************************************************/ -- Per method, a kind per argument (upper case: required): -- S s a string (88.909: an object without a string value) -- A any value -- P p a position: a whole number > 0 (93.924) -- L l a length: a whole number >= 0 (93.923) -- N n a whole number >= 0 (93.906) -- D d a pad: one character (93.922) -- o an option: its first character, upper case; o:LIST, one of LIST -- (93.915) -- t:LIST a type (DATATYPE): its first character, upper case ("00"x for -- ""), one of LIST (93.915 names that character) -- * any number of numbers (MAX, MIN: see StringMethod) -- M a string named "match" (88.901, 88.909 name it) -- # checked by the method itself, which may return before it looks at -- the rest (MATCH, MATCHCHAR, MODULO, "?": see StringMethod) ::Class RVM.StringArgs Public ::Attribute specs Class ::Method activate Class Expose specs -- The built-in functions that ooRexx runs as methods of String run this -- method's code (RVM.BIFs' CallBIF). Call SetStringMethod .context~package~findRoutine( "StringMethod" ) specs = .Directory~new list = "ABBREV S l;" "BITAND s d;" "BITOR s d;" "BITXOR s d;" "C2D l;" - "CENTER L d;" "CENTRE L d;" "CHANGESTR S S n;" "COMPARE S d;" "COPIES N;" - "COUNTSTR S;" "DELSTR p l;" "DELWORD P l;" "INSERT S n l d;" - "LASTPOS S p l;" "LEFT L d;" "LOWER p l;" "OVERLAY S p l d;" "POS S p l;" - "RIGHT L d;" "SPACE l d;" "STRIP o:BLT s;" "SUBSTR P l d;" "SUBWORD P l;" - "TRANSLATE s s d p l;" "UPPER p l;" "VERIFY S o:MN p l;" "WORD P;" - "WORDINDEX P;" "WORDLENGTH P;" "WORDPOS S p;" "X2D l;" "SUBCHAR P;" - "[] P l;" "LENGTH;" "REVERSE;" "WORDS;" "C2X;" "ABS;" "SIGN;" "TRUNC n;" - "FORMAT n n n n;" "D2C l;" "D2X l;" "X2C;" "X2B;" "B2X;" "MAX *;" "MIN *;" - "DATATYPE t:ABILMNOSUVWX9;" - "CASELESSABBREV S l;" "CASELESSCHANGESTR S S n;" "CASELESSCOMPARE S d;" - "CASELESSCOMPARETO S p l;" "COMPARETO S p l;" "CONTAINS S p l;" - "CASELESSCONTAINS S p l;" "CASELESSPOS S p l;" "CASELESSLASTPOS S p l;" - "CASELESSCOUNTSTR S;" "CASELESSWORDPOS S p;" "CONTAINSWORD S p;" - "CASELESSCONTAINSWORD S p;" "STARTSWITH M;" "ENDSWITH M;" - "CASELESSSTARTSWITH M;" "CASELESSENDSWITH M;" "REPLACEAT S P l d;" - "CEILING;" "FLOOR;" "ROUND;" "ENCODEBASE64;" "DECODEBASE64;" - "MATCH # # # #;" "CASELESSMATCH # # # #;" "MATCHCHAR # #;" - "CASELESSMATCHCHAR # #;" "MODULO #;" "? # #;" - "SETBUFFERSIZE L" -- (of MutableBuffer) Do item Over list~makeArray( ";" ) Parse Var item name kinds specs[ Strip( name ) ] = Strip( kinds ) End -- The arguments of String method 'name' checked (see RVM.StringArgs): their -- plain values (a string, or a whole number), .Nil where omitted. ::Routine StringMethodArgs Use Strict Arg name, args, world kinds = .RVM.StringArgs~specs[ name ]~makeArray( " " ) If kinds~isEmpty Then kinds = .Array~new If kinds~items > 0 Then If kinds[1] == "*" | kinds[1] == "#" Then Return args n = args~last If n == .Nil Then n = 0 If n > kinds~items Then Raise Syntax 93.902 Array( kinds~items ) out = .Array~new( kinds~items ) Do i = 1 To kinds~items Parse Value kinds[i] With kind ":" choices If \ args~hasIndex( i ) Then Do If kind == "M" Then Raise Syntax 88.901 Array( "match" ) If kind == Upper( kind ) Then Raise Syntax 93.903 Array( i ) Iterate End v = args[i] Select Case Upper( kind ) When "A" Then out[i] = v When "M" Then out[i] = MethodString( v, "match", world ) When "S" Then out[i] = MethodString( v, i, world ) When "P" Then Do k = unsignedWholeNumber( str( v ), 18 ) If k == .Nil Then Raise Syntax 93.924 Array( str( v ) ) If k == 0 Then Raise Syntax 93.924 Array( str( v ) ) out[i] = k End When "L" Then Do k = unsignedWholeNumber( str( v ), 18 ) If k == .Nil Then Raise Syntax 93.923 Array( str( v ) ) out[i] = k End When "N" Then Do k = unsignedWholeNumber( str( v ), 18 ) If k == .Nil Then Raise Syntax 93.906 Array( i, str( v ) ) out[i] = k End When "D" Then Do c = MethodString( v, i, world ) If Length( c ) \== 1 Then Raise Syntax 93.922 Array( c ) out[i] = c End When "T" Then Do c = MethodString( v, i, world ) option = Upper( Left( c, 1 ) ) If c == "" Then option = "00"x If Pos( option, choices ) == 0 Then Raise Syntax 93.915 Array( choices, option ) out[i] = option End When "O" Then Do c = MethodString( v, i, world ) option = Upper( Left( c, 1 ) ) If choices \== "" Then If c == "" | Pos( option, choices ) == 0 Then Raise Syntax 93.915 Array( choices, c ) out[i] = option End End End Return out -- A string argument of a method (ooRexx's stringArgument: REQUEST STRING, -- which only an object with a MAKESTRING answers: an array; else 88.909). ::Routine MethodString Public Use Strict Arg v, position, world If \ v~isA( .RVM.Obj ) Then Return str( v ) s = v~requestString If s == .Nil Then Raise Syntax 88.909 Array( position ) Return s -- A method of String: its arguments checked, then the built-in function of -- its name (the receiver as argument 'at'), or what the method does that the -- function cannot. ::Routine StringMethod Use Strict Arg name, at, receiver, args, context s = str( receiver ) -- The receiver of an arithmetic method must be a number (93.943); D2C and -- D2X say so in their own words (93.929, 93.928). Select Case name When "ABS", "SIGN", "TRUNC", "FORMAT", "MAX", "MIN" Then If \ isNum( s ) Then Raise Syntax 93.943 Array( name, s ) When "D2C" Then If \ isNum( s ) Then Raise Syntax 93.929 Array( s ) When "D2X" Then If \ isNum( s ) Then Raise Syntax 93.928 Array( s ) Otherwise Nop End world = context~world Select Case name -- MATCH: start (93.924: beyond the end, false), other, offset (beyond -- the other, false), length: the parts must be equal (none: false). When "MATCH", "CASELESSMATCH" Then Do start = MethodPosition( args, 1 ) If start > Length( s ) Then Return "0" If \ args~hasIndex( 2 ) Then Raise Syntax 93.903 Array( 2 ) other = MethodString( args[2], 2, world ) offset = 1 If args~hasIndex( 3 ) Then Do offset = MethodPosition( args, 3 ) If offset > Length( other ) Then Return "0" End len = Length( other ) - offset + 1 If args~hasIndex( 4 ) Then Do len = unsignedWholeNumber( str( args[4] ), 18 ) If len == .Nil Then Raise Syntax 93.923 Array( str( args[4] ) ) End If offset + len - 1 > Length( other ) Then Return "0" If start + len - 1 > Length( s ) | len == 0 Then Return "0" a1 = SubStr( s, start, len ); a2 = SubStr( other, offset, len ) If name == "CASELESSMATCH" Then Return ( Upper( a1 ) == Upper( a2 ) )~?( "1", "0" ) Return ( a1 == a2 )~?( "1", "0" ) End -- MATCHCHAR: the character at position (93.924; beyond the end, false) -- is one of the set. When "MATCHCHAR", "CASELESSMATCHCHAR" Then Do position = MethodPosition( args, 1 ) If position > Length( s ) Then Return "0" If \ args~hasIndex( 2 ) Then Raise Syntax 93.903 Array( 2 ) set = MethodString( args[2], 2, world ) c = SubStr( s, position, 1 ) If name == "CASELESSMATCHCHAR" Then Do c = Upper( c ); set = Upper( set ) End Return ( Pos( c, set ) > 0 )~?( "1", "0" ) End -- "?": the first argument when the receiver is 1, the second when it is 0 -- (34.901 otherwise); both are required (88.901). When "?" Then Do If \ args~hasIndex( 1 ) Then Raise Syntax 88.901 Array( "true value" ) If \ args~hasIndex( 2 ) Then Raise Syntax 88.901 Array( "false value" ) If s == "1" Then Return args[1] If s == "0" Then Return args[2] Raise Syntax 34.901 Array( s ) End -- MODULO: a whole receiver (93.940), a positive whole divisor (93.907); -- the remainder, made positive. When "MODULO" Then Do If \ isNum( s ) Then Raise Syntax 93.943 Array( name, s ) If \ IsInteger( s, context~digits ) Then Raise Syntax 93.940 Array( name, s ) If \ args~hasIndex( 1 ) Then Raise Syntax 93.903 Array( 1 ) d = args[1] If d~isA( .RVM.Obj ) Then Do If d~native~isA( .Array ) Then d = d~stringValue Else Raise Syntax 93.907 Array( 1, d ) End d = str( d ) If \ IsInteger( d, context~digits ) Then Raise Syntax 93.907 Array( 1, d ) If num( d, context )~sign \== 1 Then Raise Syntax 93.907 Array( 1, d ) r = num( s, context )~remainder( num( d, context ), context ) If r~sign < 0 Then r = r~plus( num( d, context ), context ) Return r End When "CEILING", "FLOOR", "ROUND" Then If \ isNum( s ) Then Raise Syntax 93.943 Array( name, s ) Otherwise Nop End a = StringMethodArgs( name, args, world ) Select Case name When "CEILING", "FLOOR", "ROUND" Then Do -- The number at the current DIGITS, then to a whole number: up, down, -- or half away from zero. Rounded to DIGITS with no LOSTDIGITS (ooRexx's -- prepareNumber ROUND, as TRUNC): in a working context. work = .RVM.NumCtx~new( context~digits, 0, context~form ) n = num( s, work )~plus( num( "0", work ), work ) t = ComputeBIF( "TRUNC", .Array~of( n ), context ) If n~compare( num( t, work ), work ) == 0 Then Return t Select Case name When "FLOOR" Then If n~sign < 0 Then Return num( t, work )~minus( num( "1", work ), work ) When "CEILING" Then If n~sign > 0 Then Return num( t, work )~plus( num( "1", work ), work ) Otherwise Do half = num( "0.5", work ) If n~sign < 0 Then half = half~negate( work ) Return ComputeBIF( "TRUNC", .Array~of( n~plus( half, work ) ), context ) End End Return t End When "ENCODEBASE64" Then Return EncodeBase64( s ) When "DECODEBASE64" Then Return DecodeBase64( s ) When "STARTSWITH", "CASELESSSTARTSWITH", "ENDSWITH", "CASELESSENDSWITH" Then Do m = a[1] If m == "" | Length( m ) > Length( s ) Then Return "0" If Left( name, 8 ) == "CASELESS" Then Do m = Upper( m ); s = Upper( s ) End If Right( name, 10 ) == "STARTSWITH" Then Return ( Left( s, Length( m ) ) == m )~?( "1", "0" ) Return ( Right( s, Length( m ) ) == m )~?( "1", "0" ) End When "COMPARETO", "CASELESSCOMPARETO" Then Do o = a[1] If name == "CASELESSCOMPARETO" Then Do s = Upper( s ); o = Upper( o ) End start = 1 If a[2] \== .Nil Then start = a[2] If start > Length( s ) Then Return ( start > Length( o ) )~?( "0", "-1" ) If start > Length( o ) Then Return "1" l1 = Length( s ) - start + 1 l2 = Length( o ) - start + 1 If a[3] \== .Nil Then Do l1 = Min( a[3], l1 ); l2 = Min( a[3], l2 ) End p1 = SubStr( s, start, Min( l1, l2 ) ); p2 = SubStr( o, start, Min( l1, l2 ) ) If p1 << p2 Then Return "-1" If p1 >> p2 Then Return "1" If l1 == l2 Then Return "0" If l1 > l2 Then Return "1" Return "-1" End When "REPLACEAT" Then Do new = a[1]; position = a[2] len = Length( new ) If a[3] \== .Nil Then len = a[3] pad = " " If a[4] \== .Nil Then pad = a[4] If position > Length( s ) Then Return s || Copies( pad, position - Length( s ) - 1 ) || new Return Left( s, position - 1 ) || new || SubStr( s, position + len ) End When "CASELESSCHANGESTR" Then Do count = 999999999999999999 If a[3] \== .Nil Then count = a[3] needle = Upper( a[1] ) If count == 0 | needle == "" Then Return s u = Upper( s ) out = ""; from = 1; done = 0 Do While done < count p = Pos( needle, u, from ) If p == 0 Then Leave out = out || SubStr( s, from, p - from ) || a[2] from = p + Length( needle ) done += 1 End Return out || SubStr( s, from ) End -- The others: a function on the receiver and the needle in upper case, -- or a function's answer as a truth value. When "CASELESSABBREV" Then Return ComputeBIF( "ABBREV", Plain( .Array~of( Upper( s ), Upper( a[1] ) ), a, 2 ), context ) When "CASELESSCOMPARE" Then Do b = .Array~of( Upper( s ), Upper( a[1] ) ) If a[2] \== .Nil Then b[3] = Upper( a[2] ) Return ComputeBIF( "COMPARE", b, context ) End When "CASELESSPOS", "CASELESSLASTPOS", "CONTAINS", "CASELESSCONTAINS", - "CASELESSCOUNTSTR", "CASELESSWORDPOS", "CONTAINSWORD", "CASELESSCONTAINSWORD" Then Do needle = a[1]; hay = s If Pos( "CASELESS", name ) > 0 Then Do needle = Upper( needle ); hay = Upper( hay ) End Select Case name When "CASELESSPOS", "CONTAINS", "CASELESSCONTAINS" Then bif = "POS" When "CASELESSLASTPOS" Then bif = "LASTPOS" When "CASELESSCOUNTSTR" Then bif = "COUNTSTR" Otherwise bif = "WORDPOS" End r = ComputeBIF( bif, Plain( .Array~of( needle, hay ), a, 2 ), context ) If Pos( "CONTAINS", name ) > 0 Then Return ( r > 0 )~?( "1", "0" ) Return r End Otherwise Nop End Select Case name -- The numbers to compare: a hole is 40.5 (ooRexx's NumberString::maxMin; -- its RexxInteger's says 93.903 for the argument before it: not -- followed, see doc/17), anything else not a number 93.904. When "MAX", "MIN" Then Do n = args~last If n == .Nil Then n = 0 Do i = 1 To n If \ args~hasIndex( i ) Then Raise Syntax 40.5 Array( name, i ) v = args[i] If v~isA( .RVM.Obj ) Then Do If v~native~isA( .Array ) Then v = v~stringValue Else Raise Syntax 93.904 Array( i, v ) End If \ isNum( str( v ) ) Then Raise Syntax 93.904 Array( i, str( v ) ) a[i] = str( v ) End End -- A whole number at the current DIGITS (any DIGITS: not only up to 18 -- digits); a negative one needs a length. When "D2C", "D2X" Then Do If WholeValue( s, context~digits ) == .Nil Then Do If name == "D2C" Then Raise Syntax 93.929 Array( s ) Raise Syntax 93.928 Array( s ) End If a[1] == .Nil, num( s, context )~sign < 0 Then Raise Syntax 93.927 End -- A hexadecimal or binary string (ValidateSet); X2D of length 0 is 0. When "X2C", "X2B" Then Call ValidateSet s, 1 When "X2D" Then Do If a[1] == 0 Then Return "0" Call ValidateSet s, 1 End When "B2X" Then Call ValidateSet s, 0 Otherwise Nop End Select Case name When "SUBCHAR" Then Do If a[1] > Length( s ) Then Return "" Return SubStr( s, a[1], 1 ) End When "[]" Then Do If a[1] > Length( s ) Then Return "" If a[2] == .Nil Then a[2] = 1 Return SubStr( s, a[1], Min( a[2], Length( s ) - a[1] + 1 ) ) End -- The position may be omitted (1). When "DELSTR" Then If a[1] == .Nil Then a[1] = 1 -- TRANSLATE of a part: start (4) and length (5). When "TRANSLATE" Then If a[4] \== .Nil | a[5] \== .Nil Then Do p = a[4] If p == .Nil Then p = 1 If p > Length( s ) Then Return s l = Length( s ) - p + 1 If a[5] \== .Nil Then l = Min( a[5], l ) b = .Array~of( SubStr( s, p, l ) ) Do i = 1 To 3 If a[i] \== .Nil Then b[i + 1] = a[i] End Return Left( s, p - 1 ) || ComputeBIF( "TRANSLATE", b, context ) || SubStr( s, p + l ) End -- VERIFY in a range: the string up to its end (with a null reference, -- the whole string: the start is the answer, whatever the range). When "VERIFY" Then If a[4] \== .Nil Then Do p = a[3] If p == .Nil Then p = 1 If \ ( a[1]~isA( .String ) & a[1] == "" ) Then s = Left( s, Min( Length( s ), p + a[4] - 1 ) ) a~remove( 4 ) End Otherwise Nop End -- The built-in function, the receiver as its argument 'at'. b = .Array~new n = a~last If n == .Nil Then n = 0 j = 0 Do i = 1 To Max( n + 1, at ) If i == at Then b[i] = s Else Do j += 1 If a~hasIndex( j ) Then b[i] = a[j] End End Signal On Syntax Name BifFailed Return ComputeBIF( name, b, context ) -- An error of the function that the method gives in its own words: the one -- it carries (BifMethodError), or C2D's and X2D's whole number (93.936, -- 93.935). BifFailed: co = Condition( "O" ) If WordPos( co~description, "RVM.NeedString" ) > 0 Then Raise Propagate extra = co~additional If extra~isA( .Array ), extra~hasIndex( 3 ), extra[3]~isA( .Array ) Then Do method = extra[3] Raise Syntax ( method[1] ) Array( method[2], method[3] ) End If BifCodeOf( co ) == "40.35" Then Do If name == "C2D" Then Raise Syntax 93.936 Array( context~digits ) If name == "X2D" Then Raise Syntax 93.935 Array( context~digits ) End Raise Propagate -- The arguments 'a' from 'from' on after those in 'b' (none after the -- last one given), for a function. ::Routine Plain Use Strict Arg b, a, from k = b~items Do i = from To a~size If a[i] \== .Nil Then b[ k + i - from + 1 ] = a[i] End Return b -- An array for a Supplier (NEW): an Array's (one dimension: 98.913), a -- string's lines, a directory's items. ::Routine SupplierArray Use Strict Arg v If v~isA( .RVM.Obj ) Then Do If v~native~isA( .Array ) Then Do If v~native~dimension > 1 Then Raise Syntax 98.913 Array( v ) Return v~native~copy End If v~native~isA( .Directory ) | 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 ) Raise Syntax 98.913 Array( v ) End Return str( v )~makeArray -- A position argument (93.903 missing, 93.924). ::Routine MethodPosition Use Strict Arg args, i If \ args~hasIndex( i ) Then Raise Syntax 93.903 Array( i ) k = unsignedWholeNumber( str( args[i] ), 18 ) If k == .Nil Then Raise Syntax 93.924 Array( str( args[i] ) ) If k == 0 Then Raise Syntax 93.924 Array( str( args[i] ) ) Return k -- Is string s a whole number as ooRexx's NumberString::isInteger says (its -- integer part within DIGITS, unless it has no exponent; no decimals)? ::Routine IsInteger Use Strict Arg s, digits parsed = .RVM.Number~parseNumber( s ) If parsed == "" Then Return .False Parse Var parsed sign dig exp If sign == 0 | Verify( dig, "0" ) == 0 Then Return .True If exp == 0 Then Return .True adjusted = exp + Length( dig ) If adjusted > digits | adjusted <= 0 Then Return .False If exp > 0 Then Return .True Return Verify( SubStr( dig, adjusted + 1 ), "0" ) == 0 -- Base64 (ooRexx's encodeBase64 and decodeBase64: 93.962). ::Routine EncodeBase64 Use Strict Arg s digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" out = "" Do i = 1 To Length( s ) By 3 chunk = SubStr( s, i, Min( 3, Length( s ) - i + 1 ) ) n = Length( chunk ) bits = Left( X2B( C2X( chunk ) ), 24, "0" ) Do k = 1 To 4 If k > n + 1 Then out = out"=" Else out = out || SubStr( digits, X2D( B2X( SubStr( bits, ( k - 1 ) * 6 + 1, 6 ) ) ) + 1, 1 ) End End Return out ::Routine DecodeBase64 Use Strict Arg s digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" If s == "" Then Return "" If Length( s ) // 4 > 0 Then Raise Syntax 93.962 size = Length( s ) % 4 * 3 If Right( s, 1 ) == "=" Then size -= 1 If SubStr( s, Length( s ) - 1, 1 ) == "=" Then size -= 1 bits = "" Do i = 1 To Length( s ) c = SubStr( s, i, 1 ) v = Pos( c, digits ) If v == 0 Then Do -- "=" ends it: the last of the last four, or the last two. k = ( i - 1 ) // 4 last = ( i > Length( s ) - 4 ) If c == "=", last, k == 3 | ( k == 2 & SubStr( s, i + 1, 1 ) == "=" ) Then Leave Raise Syntax 93.962 End bits = bits || Right( X2B( D2X( v - 1 ) ), 6, "0" ) End bits = Left( bits, size * 8, "0" ) If bits == "" Then Return "" Return X2C( B2X( bits ) ) -- The receiver of X2C, X2B, X2D (hex = 1) or B2X (0) checked as ooRexx's -- StringUtil::validateSet does: whitespace neither first nor last (93.931, -- 93.932), only digits of the base (93.933, 93.934), and every group after -- the first one of whole bytes or nibbles (93.976, 93.977). ::Routine ValidateSet Use Strict Arg s, hex If hex Then Do set = "0123456789abcdefABCDEF"; modulus = 2 blank = 93.931; bad = 93.933; group = 93.976 End Else Do set = "01"; modulus = 4 blank = 93.932; bad = 93.934; group = 93.977 End If s == "" Then Return white = " " || "09"x If Pos( Left( s, 1 ), white ) > 0 Then Raise Syntax ( blank ) Array( 1 ) count = 0; spaceFound = .False; residue = 0 Do i = 1 To Length( s ) c = SubStr( s, i, 1 ) If Pos( c, set ) > 0 Then count += 1 Else If Pos( c, white ) > 0 Then Do If \ spaceFound Then Do residue = count // modulus spaceFound = .True End Else If count // modulus \== residue Then Raise Syntax ( group ) If i == Length( s ) Then Raise Syntax ( blank ) Array( i ) End Else Raise Syntax ( bad ) Array( c ) End If spaceFound, count // modulus \== residue Then Raise Syntax ( group ) -- An operator sent to a string (a number): "+" etc. as the RVM computes them. ::Routine StringOperator Public Use Strict Arg op, a, args, context -- (An instance of a subclass of String: its string.) If a~isA( .RVM.Obj ) Then a = str( a ) If \ args~hasIndex( 1 ) Then Select Case op When "+" Then Return num( a, context )~identity( context ) When "-" Then Return num( a, context )~negate( context ) When "\" Then Return ( \ Boolean( str( a ) ) )~?( "1", "0" ) End b = args[1] If b~isA( .RVM.Obj ) Then b = str( b ) Select Case op When "+" Then Return num( a, context )~plus( num( b, context ), context ) When "-" Then Return num( a, context )~minus( num( b, context ), context ) When "*" Then Return num( a, context )~times( num( b, context ), context ) When "/" Then Return num( a, context )~divide( num( b, context ), context ) When "%" Then Return num( a, context )~intDivide( num( b, context ), context ) When "//" Then Return num( a, context )~remainder( num( b, context ), context ) When "**" Then Return num( a, context )~power( b, context ) When "||", "" Then Return str( a ) || str( b ) When " " Then Return str( a ) || " " || str( b ) When "&" Then Return ( Boolean( str( a ) ) & Boolean( str( b ) ) )~?( "1", "0" ) When "|" Then Return ( Boolean( str( a ) ) | Boolean( str( b ) ) )~?( "1", "0" ) When "&&" Then Return ( Boolean( str( a ) ) && Boolean( str( b ) ) )~?( "1", "0" ) When "==" Then Return ( str( a ) == str( b ) )~?( "1", "0" ) When "\==" Then Return ( str( a ) \== str( b ) )~?( "1", "0" ) When "<<" Then Return ( str( a ) << str( b ) )~?( "1", "0" ) When ">>" Then Return ( str( a ) >> str( b ) )~?( "1", "0" ) When "<<=", "\>>" Then Return ( str( a ) <<= str( b ) )~?( "1", "0" ) When ">>=", "\<<" Then Return ( str( a ) >>= str( b ) )~?( "1", "0" ) Otherwise Nop End cmp = CompareNormal( a, b, context ) Select Case op When "=" Then r = ( cmp == 0 ) When "\=", "<>", "><" Then r = ( cmp \== 0 ) When "<" Then r = ( cmp < 0 ) When ">" Then r = ( cmp > 0 ) When "<=", "\>" Then r = ( cmp <= 0 ) When ">=", "\<" Then r = ( cmp >= 0 ) End Return r~?( "1", "0" ) /******************************************************************************/ /* Shared with the machine */ /******************************************************************************/ -- A strict logical value, 0 or 1 (error 34 otherwise). ::Routine Boolean Public Use Strict Arg v If v == "0" Then Return .False If v == "1" Then Return .True Raise Syntax 34.901 Additional( v ) -- A non-strict comparison: -1, 0 or 1. -- Numeric when both are numbers, else as strings (blanks around ignored, -- the shorter padded with blanks). ::Routine CompareNormal Public Use Strict Arg a, b, context na = NumOrNil( a, context ) nb = .Nil If na \== .Nil Then nb = NumOrNil( b, context ) If nb \== .Nil Then Return na~compare( nb, context ) x = Strip( str(a) ) y = Strip( str(b) ) len = Max( Length(x), Length(y) ) x = Left(x, len) y = Left(y, len) If x == y Then Return 0 If x << y Then Return -1 Return 1 ::Routine NumOrNil Public Use Strict Arg v, context If v~isA( .RVM.Number ) Then Return v Return .RVM.Number~fromString( v, context ) /******************************************************************************/ /* Arrays */ /******************************************************************************/ -- Is it an array of the RVM (its native value, a host array)? ::Routine ArrayObj Public Use Strict Arg v If \ v~isA( .RVM.Obj ) Then Return .False Return v~native~isA( .Array ) -- An array of the RVM as an argument of a host method (dimensions, -- subscripts): a copy of its host array, its numbers as strings. ::Routine HostArray Use Strict Arg obj a = obj~native~copy Do i Over a~allIndexes If \ a[i]~isA( .RVM.Obj ) Then a[i] = str( a[i] ) End Return a -- Arguments for a host method: strings (numbers as strings); objects as -- they are. ::Routine HostArgs Use Strict Arg args hostArgs = .Array~new Do i Over args~allIndexes v = args[i] If \ v~isA( .RVM.Obj ) Then v = str( v ) hostArgs[i] = v End Return hostArgs -- The index of the first item that is 'target' (.Nil: none), as ooRexx's -- equalValue: an object is the same object; a string (or number) the item -- as a string (an object's string value too; .NIL never). The index is the -- host's: a number, or an array of subscripts. ::Routine ItemIndex Use Strict Arg a, target, world items = a~allItems -- An IdentityTable's items are the same object (ooRexx's -- IdentityHashContents): an object is, never an equal one; a string is -- its value (the RVM's strings keep no identity: a literal and the same -- literal in a variable may be two). If a~isA( .IdentityTable ) Then Do isObj = target~isA( .RVM.Obj ) Do j = 1 To items~items v = items[j] If isObj Then Do If v == target Then Return a~allIndexes[j] End Else If \ v~isA( .RVM.Obj ), str( v ) == str( target ) Then Return a~allIndexes[j] End Return .Nil End Do j = 1 To items~items If ItemMatch( target, items[j], world ) Then Return a~allIndexes[j] End Return .Nil -- Is item v the 'target' (ooRexx's target~equalValue(v): an object is the -- same object; a string (or number) is the item as a string, .NIL never)? ::Routine ItemMatch Use Strict Arg target, v, world If target~isA( .RVM.Obj ) Then Do If v == target Then Return .True -- One whose "==" is written in Rexx: its "==" (RexxObject::isEqual). e = world~behaviourOf( target )~lookup( "==" ) If e \== .Nil, e~isCode Then Do r = world~loader~sendSync( target, "==", .Array~of( v ) ) If r == .Nil Then Raise Syntax 91.999 Array( "==" ) Return str( r ) == "1" End Return v == target End If v~isA( .RVM.Obj ), v == world~nil Then Return .False Return str( v ) == str( target ) -- Whether the host arguments of an array's MAKESTRING ask for the C form -- (an option that is a string starting with C). ::Routine CForm Use Strict Arg hostArgs If \ hostArgs~hasIndex( 1 ) Then Return .False If hostArgs[1]~isA( .RVM.Obj ) Then Return .False Return Upper( Left( hostArgs[1], 1 ) ) == "C" -- A host array of the items made strings, in order: an object is its name -- (ooRexx's primitive stringValue: neither its STRING nor its MAKESTRING). ::Routine ItemStrings Use Strict Arg a strings = .Array~new Do v Over a~allItems -- (Its stringValue: a String subclass instance's string, a Stem's -- default's, a MutableBuffer's text, a StackFrame's line; else its -- name: RVM.Obj~string.) If \ v~isA( .RVM.Obj ) Then strings~append( str( v ) ) Else strings~append( v~string ) End Return strings -- ooRexx's primitiveMakeString: the string of a value with no message sent -- and no condition raised (a string, a number, an array's lines, a -- MutableBuffer's text), or .Nil. What a STRING or a MAKESTRING in Rexx -- returned is made a string with it (RVM.Machine, Deliver STRING / REQUEST). -- The string of v with no NOSTRING condition (see stringValue). ::Routine QuietString Public Use Strict Arg v If v~isA( .RVM.Obj ) Then Return v~stringValue( .False ) Return str( v ) -- RUN, SETMETHOD and UNSETMETHOD (after their arguments are checked): only -- from a method of the same object or of one of its classes, else 98.991 -- (ooRexx's checkRestrictedMethod; the private check, 97.2, came first). ::Routine CheckRestricted Use Strict Arg receiver, name, world sender = .RVM.Obj~sender If sender == receiver Then Return If sender~isA( .RVM.Obj ) Then If sender~native~isA( .RVM.ClassData ) Then If IsSubclass( world~classOf( receiver ), sender ) Then Return Raise Syntax 98.991 Array( name ) ::Routine PrimitiveString Public Use Strict Arg v If v~isA( .String ) Then Return v If v~isA( .RVM.Number ) Then Return v~string If \ v~isA( .RVM.Obj ) Then Return .Nil n = v~native If n~isA( .RVM.MBuffer ) Then Return n~text If n~isA( .Array ) Then Return ArrayString( v, "L" ) Return .Nil -- An array as a string (its MAKESTRING): the items, a line each ("L"). ::Routine ArrayString Public Use Strict Arg obj, format Return ItemStrings( obj~native )~toString( format ) -- SORT: ooRexx's stable merge sort (ArrayClass::mergeSort, merge, find), -- step by step: the comparisons are the same, and so are the errors when an -- item cannot be compared. ::Routine MergeSort Use Strict Arg a, working, left, right len = right - left + 1 If len <= 10 Then Do Do i = left + 1 To right current = a[i] prev = a[i - 1] If SortCompare( current, prev ) < 0 Then Do j = i Loop a[j] = prev j -= 1 If j <= left Then Leave prev = a[j - 1] If SortCompare( current, prev ) >= 0 Then Leave End a[j] = current End End Return End mid = ( right + left ) % 2 Call MergeSort a, working, left, mid Call MergeSort a, working, mid + 1, right Call SortMerge a, working, left, mid + 1, right ::Routine SortMerge Use Strict Arg a, working, left, mid, right leftEnd = mid - 1 If SortCompare( a[leftEnd], a[mid] ) <= 0 Then Return leftCursor = left rightCursor = mid workingPosition = left Loop fromVal = a[leftCursor] rightVal = a[rightCursor] If SortCompare( fromVal, rightVal ) <= 0 Then Do leftInsertion = SortFind( a, rightVal, -1, leftCursor + 1, leftEnd ) toCopy = leftInsertion - leftCursor + 1 Call SortCopy a, leftCursor, working, workingPosition, toCopy workingPosition += toCopy working[ workingPosition ] = rightVal workingPosition += 1 rightCursor += 1 leftCursor = leftInsertion + 1 End Else Do rightInsertion = SortFind( a, fromVal, 0, rightCursor + 1, right ) toCopy = rightInsertion - rightCursor + 1 Call SortCopy a, rightCursor, working, workingPosition, toCopy workingPosition += toCopy working[ workingPosition ] = fromVal workingPosition += 1 leftCursor += 1 rightCursor = rightInsertion + 1 End If \ ( right >= rightCursor & mid > leftCursor ) Then Leave End If leftCursor < mid Then Call SortCopy a, leftCursor, working, workingPosition, mid - leftCursor Else Call SortCopy a, rightCursor, working, workingPosition, right - rightCursor + 1 Call SortCopy working, left, a, left, right - left + 1 ::Routine SortCopy Use Strict Arg source, start, target, index, count Do i = start To start + count - 1 target[ index ] = source[ i ] index += 1 End ::Routine SortFind Use Strict Arg a, val, limit, left, right checkPoint = left delta = 1 Do While checkPoint <= right If SortCompare( val, a[ checkPoint ] ) > limit Then left = checkPoint + 1 Else Do right = checkPoint - 1 Leave End checkPoint += delta delta *= 2 End Do While left <= right checkPoint = ( left + right ) % 2 If SortCompare( val, a[ checkPoint ] ) > limit Then left = checkPoint + 1 Else right = checkPoint - 1 End Return left - 1 -- first~compareTo(second): strings compare as strings (strictly); an -- object has no COMPARETO (97.1); a string's argument must have a string -- value (88.909: an array has one, its MAKESTRING). ::Routine SortCompare Use Strict Arg first, second If first~isA( .RVM.Obj ) Then Raise Syntax 97.1 Array( first, "COMPARETO" ) If second~isA( .RVM.Obj ) Then Do y = second~requestString If .Nil == y Then Raise Syntax 88.909 Array( 1 ) End Else y = str( second ) x = str( first ) If x == y Then Return 0 If x << y Then Return -1 Return 1 -- The flat position of subscripts (an array) in a multidimensional host -- array (the first subscript varies fastest), and back. ::Routine FlatPosition Use Strict Arg a, subs dims = a~dimensions position = 0 mult = 1 Do i = 1 To dims~items position += mult * ( subs[i] - 1 ) mult *= dims[i] End Return position + 1 ::Routine Subscripts Use Strict Arg a, position dims = a~dimensions subs = .Array~new( dims~items ) idx = position - 1 Do i = 1 To dims~items subs[i] = idx // dims[i] + 1 idx = idx % dims[i] End Return subs /******************************************************************************/ /* RVM.StdinWait -- an activity waits for standard input (a terminal or a */ /* pipe) while the others run (see RVM.StdinReader, RVM.Stream~inputNeed): */ /* it is among the scheduler's I/O waits (RVM.StdinPoller polls them) until */ /* what its read needs has been read (or the end has come); then its */ /* activity goes on, and the read runs again. */ /******************************************************************************/ ::Class RVM.StdinWait Public ::Attribute kind ::Attribute count -- The activity of 'context' waits for 'need' (an RVM.StdinNeed): the -- RVM.Wait a native gives. ::Method start Class Use Strict Arg need, context act = context~activity sched = context~world~scheduler w = self~new( need~kind, need~count, act, sched ) act~waitingOn = w sched~addIO( w, .RVM.StdinPoller ) .RVM.StdinReader~fetch Return .RVM.Wait~new( w ) ::Method init Expose kind count act sched Use Strict Arg kind, count, act, sched ::Method owningActivity Return .Nil -- What it needs is there: its activity goes on. ::Method retry Expose act sched sched~removeIO( self ) act~semDone( .Nil ) -- Its activity ended while it waited (what is read stays for later reads). ::Method cancel Expose sched sched~removeIO( self ) -- A HALT (Ctrl-C: RVM.Scheduler~haltAll): its activity goes on, and gets it -- in the instruction that read (what is read stays for later reads). ::Method halted Expose act sched sched~removeIO( self ) act~semDone( "HALT" ) /******************************************************************************/ /* The scheduler's poll of the waits for standard input (pollIO): those */ /* whose reads have what they need go on; when no job reads for the others, */ /* one does for the first of them; for 'ms' milliseconds at most (-1: until */ /* one goes on), waiting on the reader's semaphore in steps of 100 ms. The */ /* host's HALT (Ctrl-C) is the scheduler's (haltAll), and ends the poll. */ /******************************************************************************/ ::Class RVM.StdinPoller ::Method poll Class Use Strict Arg sched, ms Call On Halt Name HostHalt -- Ctrl-C while it waits (haltAll) halted = .False reader = .RVM.StdinReader sem = reader~sem Numeric Digits 18 left = ms Loop sem~reset any = .False first = .Nil Do w Over sched~ios~copy If \ w~isA( .RVM.StdinWait ) Then Iterate If reader~has( w~kind, w~count ) Then Do w~retry any = .True End Else If first == .Nil Then first = w End If first \== .Nil, \ reader~reading Then reader~fetch 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