/******************************************************************************/ /* */ /* RVM.BIFs.cls - Built-in functions: argument checking and errors */ /* =================================================================== */ /* */ /* Every built-in function checks its arguments the same way, before doing */ /* anything else, from a CHECKLIST: one word per argument, 'r' (required) or */ /* 'o' (optional) followed by the argument's type. By default the checklist */ /* comes from the parser's BIF table (.Parser.BIFInfo); a function whose */ /* checklist depends on its arguments (ARG with an option, D2C/D2X...) passes */ /* its own. */ /* */ /* CheckArgs(bif, args, context [, checklist]) */ /* -> an Array with the arguments NORMALISED by their type (holes kept): */ /* a whole number for WHOLE types, a Number for NUM, the upper-cased */ /* first letter for an option, the value itself otherwise. */ /* */ /* Types and errors (40.x): */ /* count fewer than required 40.3, more than allowed 40.4, a missing */ /* required argument 40.5 */ /* ANY any string */ /* NUM a number at the CALLER's DIGITS and FORM (40.11; 40.9 when */ /* the exponent has more than 9 digits) */ /* WHOLE a whole number at the BIF precision, WholeDigits (40.12) */ /* WHOLE>=0 ... and zero or positive (40.13) (also LENGTH) */ /* WHOLE>0 ... and positive (40.14) (also POS) */ /* WHOLENUM a whole number at the caller's DIGITS (40.12); WHOLENUM>=0 */ /* also zero or positive (40.13) (D2 picks one of them) */ /* PAD exactly one character (40.23) */ /* BIN / HEX a binary / hexadecimal string (40.24 / 40.25) */ /* SYM a valid symbol (40.26) */ /* ACEFILNOR a TRACE setting: '?'s, then one of those letters or nothing */ /* (40.28) */ /* (letters) an option: not null (40.21), and its first letter, in any */ /* case, one of those letters (40.28) */ /* MAX / MIN every argument is a required NUM */ /* STREAM, SEP, RANGE, 0_99, 0_90 -- left to the function itself */ /* */ /* A whole number, at a given precision, as ooRexx decides it: v is a number; */ /* rounded to the precision, it can be written without an exponent (so at 9 */ /* digits 1000000000 is not whole) and has no fractional part (1.5E1 is 15, */ /* 123E-2 is not whole; at 3 digits 475.7 rounds to 476, whole). The */ /* standard's DATATYPE(v, 'W') looks for the fraction in the text of v. */ /* */ /* BifError(code, bif, insert...) raises the error with its message. */ /* BifMessageOf(conditionObject) is the message to show for any error. */ /* */ /* 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: FORMAT */ /* (NumberStringClass.cpp), the conversions of DATE and TIME */ /* (RexxDateTime.cpp), RANDOM (BuiltinFunctions.cpp) and the texts of the */ /* error messages (rexxmsg.xml). 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 */ /* */ /******************************************************************************/ -- Whole numbers of up to WholeDigits (18) digits are handled as host numbers. ::Options Digits 20 ::Requires "RVM.Number.cls" ::Requires "RVM.Stream.cls" ::Requires "RVM.RxRegExp.cls" /******************************************************************************/ /* CheckArgs */ /******************************************************************************/ ::Routine CheckArgs Public Use Strict Arg bif, args, context, checklist = .Nil If args~isEmpty Then numArgs = 0 Else numArgs = args~last -- The checklist: types[i] and minArgs, maxArgs. types = .Array~new If checklist == .Nil Then Do info = .Parser.BIFInfo[ bif ] If info~maxArgs == "*" Then Do -- Any number of arguments. MAX and MIN: every one a required number. If bif == "MAX" | bif == "MIN" Then Do minArgs = Max( numArgs, 1 ) -- an omitted one is 40.5 Do i = 1 To Max( numArgs, 1 ) types[i] = "NUM" End maxArgs = Max( numArgs, 1 ) End Else Do -- XRANGE: checked by the function minArgs = info~minArgs maxArgs = numArgs Do i = 1 To numArgs types[i] = "ANY" End End End Else Do minArgs = info~minArgs maxArgs = info~maxArgs Do i = 1 To maxArgs types[i] = info~argType[i] End End End Else Do minArgs = 0 Do word Over checklist~makeArray(" ") If Left( word, 1 ) == "r" Then minArgs += 1 types~append( Substr( word, 2 ) ) End maxArgs = types~items End If numArgs < minArgs Then Call BifError 40.3, bif, minArgs If numArgs > maxArgs Then Call BifError 40.4, bif, maxArgs checked = .Array~new( numArgs ) Do argPos = 1 To numArgs If args~hasIndex( argPos ) Then checked[ argPos ] = CheckType( bif, argPos, args[ argPos ], types[ argPos ], numArgs, context ) Else If argPos <= minArgs Then Call BifError 40.5, bif, argPos End Return checked /* One argument against its type: its normalised value, or the error. */ ::Routine CheckType Use Strict Arg bif, argPos, arg, type, numArgs, context -- (Any object, as it is: it is not converted, as that would be NOSTRING.) If type == "ANY" Then Return arg -- A whole number (a length, a position): a Stem object is its value, with -- no NOSTRING (ooRexx's StemClass numberValue). -- Any other object: its name (ooRexx's numberValue of an object is that of -- its stringValue, the OBJECTNAME message; not REQUEST STRING). If WordPos( type, "LENGTH POS WHOLE WHOLE>0 WHOLE>=0" ) > 0 Then Do arg = StemValue( arg ) If Upper( arg~class~id ) == "RVM.OBJ" Then arg = arg~stringName End value = str( arg ) -- The parser's own names for types that are the standard ones. Select When type == "LENGTH" Then type = "WHOLE>=0" When type == "POS" Then type = "WHOLE>0" When type == "D2" Then Do -- D2C / D2X, argument 1 If numArgs >= 2 Then type = "WHOLENUM" Else type = "WHOLENUM>=0" End Otherwise Nop End Select When type == "ANY" Then Return arg -- A string (ooRexx's requiredStringArg: the string value). When type == "STR" Then Return value When type == "NUM" Then Do -- At the caller's DIGITS and FORM. n = NumberValue( value, context~digits, context~form ) If n == .Nil Then Call BifError 40.11, bif, argPos, value If n~isA( .String ) Then Call BifError 40.9, bif, argPos, value Return n End When WordPos( type, "WHOLE WHOLE>=0 WHOLE>0" ) > 0 Then Do -- At the precision of the built-in functions. w = WholeValue( value, .RVM.Number~WholeDigits ) If w == .Nil Then Call BifError 40.12, bif, argPos, value If type == "WHOLE>=0", w < 0 Then Call BifError 40.13, bif, argPos, value If type == "WHOLE>0", w <= 0 Then Call BifError 40.14, bif, argPos, value Return w End When type == "WHOLENUM" | type == "WHOLENUM>=0" Then Do -- At the caller's DIGITS (D2C / D2X). w = WholeValue( value, context~digits ) If w == .Nil Then Call BifError 40.12, bif, argPos, value If type == "WHOLENUM>=0", w < 0 Then Call BifError 40.13, bif, argPos, value Return w End When type == "PAD" Then Do If Length( value ) \== 1 Then Call BifError 40.23, bif, argPos, value Return value End When type == "BIN" Then Do If \ IsBinaryString( value ) Then Call BifError 40.24, bif, value Return value End When type == "HEX" Then Do If \ IsHexString( value ) Then Call BifError 40.25, bif, value Return value End When type == "SYM" Then Do If \ IsSymbol( value ) Then Call BifError 40.26, bif, value Return value End When type == "ACEFILNOR" Then Do -- TRACE: any number of '?', then (optionally) one of the letters. The -- null string is accepted, as in ooRexx (it means N). val = Strip( value, "L", "?" ) If val \== "", Pos( Upper( Left( val, 1 ) ), type ) == 0 Then Call BifError 40.28, bif, argPos, type, val Return value End -- Checked by the function itself. -- A stream name: its string (ooRexx's optional_string). When type == "STREAM" Then Return value When WordPos( type, "SEP RANGE 0_99 0_90" ) > 0 Then Return arg Otherwise Do -- An option: a list of letters. If value == "" Then Call BifError 40.21, bif, argPos letter = Upper( Left( value, 1 ) ) If Pos( letter, type ) == 0 Then Call BifError 40.28, bif, argPos, type, value Return letter End End /******************************************************************************/ /* Numbers and whole numbers, the way DATATYPE decides them. */ /******************************************************************************/ /* NumberValue(s, digits, form) : the number s stands for, rounded to 'digits' */ /* (a Number); .Nil when s is not a number; "E" when it is written as one but */ /* its exponent has more than 9 digits. */ ::Routine NumberValue Use Strict Arg s, digits, form text = NumberSyntax( s, form ) If text == .Nil | text == "E" Then Return text n = .RVM.Number~fromString( text ) -- (Not a number for ooRexx: 1.0E-999999999, its exponent -1000000000.) If n == .Nil Then Return .Nil ctx = .RVM.Number~ctxWith( digits, 0, form ) Return .RVM.Number~fromPartsSigned( n~sign, n~digits, n~exp, ctx ) /* WholeValue(s, digits) : the whole number s stands for at 'digits' of */ /* precision, as a host whole number, or .Nil. (DATATYPE(s, 'W').) */ ::Routine WholeValue Public Use Strict Arg s, digits -- The common case, quickly: up to 9 plain digits, within the precision, -- are exactly that whole number. If Length( s ) <= 9, Length( s ) <= digits, s \== "", - Verify( s, "0123456789" ) == 0 Then Return s + 0 text = NumberSyntax( s, "SCIENTIFIC" ) If text == .Nil | text == "E" Then Return .Nil -- Rounded to the precision, it must not need an exponent. n = .RVM.Number~fromString( text ) If n == .Nil Then Return .Nil ctx = .RVM.Number~ctxWith( digits, 0, "SCIENTIFIC" ) r = .RVM.Number~fromPartsSigned( n~sign, n~digits, n~exp, ctx ) If Pos( "E", r~string ) > 0 Then Return .Nil -- The ROUNDED value has no fractional part, as in ooRexx (so at 3 digits -- 475.7 is 476, whole). (The standard looks for a non-zero digit after the -- decimal point in the TEXT, which makes 123E-2 whole and 1.5E1 not; we -- look at the value.) If r~exp < 0 Then If Right( r~digits, Min( -r~exp, Length( r~digits ) ) )~verify( "0" ) > 0 Then Return .Nil -- The rounded value, integer-divided by one. If r~sign == 0 Then Return 0 If r~exp >= 0 Then whole = r~digits || Copies( "0", r~exp ) Else Do intLen = Length( r~digits ) + r~exp If intLen <= 0 Then Return 0 whole = Left( r~digits, intLen ) End whole = Strip( whole, "L", "0" ) If whole == "" Then Return 0 If r~sign < 0 Then Return "-"whole Return whole /* NumberSyntax(s, form) : s as a plain numeric text (no blanks) if it is a */ /* number, "E" if it is written as one but its exponent (adjusted to the form) */ /* has more than 9 digits, .Nil if it is not a number at all. */ ::Routine NumberSyntax Use Strict Arg s, form blanks = " " || "09"x residue = s~strip( "B", blanks ) If residue == "" Then Return .Nil sign = "" If Pos( Left( residue, 1 ), "+-" ) > 0 Then Do sign = Left( residue, 1 ) residue = Substr( residue, 2 )~strip( "L", blanks ) If residue == "" Then Return .Nil End before = "" after = "" If Left( residue, 1 ) == "." Then Do residue = Substr( residue, 2 ) Parse Value DigitRun( residue ) With after "00"x residue If after == "" Then Return .Nil End Else Do Parse Value DigitRun( residue ) With before "00"x residue If before == "" Then Return .Nil If Left( residue, 1 ) == "." Then Do residue = Substr( residue, 2 ) Parse Value DigitRun( residue ) With after "00"x residue End End exponent = 0 If residue \== "" Then Do If Pos( Left( residue, 1 ), "eE" ) == 0 Then Return .Nil residue = Substr( residue, 2 ) If residue == "" Then Return .Nil esign = "" If Pos( Left( residue, 1 ), "+-" ) > 0 Then Do esign = Left( residue, 1 ) residue = Substr( residue, 2 ) If residue == "" Then Return .Nil End Parse Value DigitRun( residue ) With exponent "00"x residue If exponent == "" Then Return .Nil If Length( Strip( exponent, "L", "0" ) ) > 9 Then Return "E" exponent = esign || exponent End If residue \== "" Then Return .Nil If before == "" Then text = sign"0" Else text = sign || before If after \== "" Then text = text"."after If exponent \== 0 Then text = text"E"exponent -- The exponent of the number written in exponential form. before = Strip( before, "L", "0" ) If before == "" Then before = "0" Numeric Digits 30 exponent = exponent + Length( before ) - 1 If form == "ENGINEERING" Then Do g = exponent // 3 If g < 0 Then g = g + 3 exponent = exponent - g End If Abs( exponent ) > 999999999 Then Return "E" Return text /* The leading run of digits of s, and the rest, separated by "00"x. */ ::Routine DigitRun Use Strict Arg s p = Verify( s, "0123456789" ) If p == 0 Then Return s || "00"x Return Left( s, p - 1 ) || "00"x || Substr( s, p ) /******************************************************************************/ /* Binary strings, hexadecimal strings, symbols. */ /******************************************************************************/ /* A binary string: 0s and 1s, blanks allowed between groups of four digits */ /* (counting from the right), none at either end. The null string is one. */ ::Routine IsBinaryString Use Strict Arg s Return IsRadixString( s, "01", 4 ) /* A hexadecimal string: hex digits, blanks allowed between groups of two. */ ::Routine IsHexString Use Strict Arg s Return IsRadixString( s, "0123456789abcdefABCDEF", 2 ) ::Routine IsRadixString Use Strict Arg s, alphabet, group blanks = " " || "09"x If s == "" Then Return 1 If Pos( Left( s, 1 ), blanks ) > 0 Then Return 0 If Pos( Right( s, 1 ), blanks ) > 0 Then Return 0 count = 0 Do j = Length( s ) To 1 By -1 c = Substr( s, j, 1 ) If Pos( c, blanks ) > 0 Then Do If count // group \== 0 Then Return 0 End Else Do If Pos( c, alphabet ) == 0 Then Return 0 count = count + 1 End End Return 1 /* A valid symbol, as ooRexx's LanguageParser::scanSymbol says: 1 to 250 */ /* letters, digits and . ! ? _, except that it can have a sign (+ or -) after */ /* an E, followed by digits only, to the end (1E+5; also AE+5 or 1AE+5, and */ /* 1E+1000000000: the check is only a syntactic one); then, if it starts with */ /* a digit or a period, it must not have more than one period. */ ::Routine IsSymbol Use Strict Arg s chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.!?_" If s == "" | Length( s ) > 250 Then Return 0 p = Verify( s, chars ) If p == 0 Then Return 1 If p == 1 | p == Length( s ) Then Return 0 If Pos( SubStr( s, p, 1 ), "+-" ) == 0 Then Return 0 If Pos( SubStr( s, p - 1, 1 ), "eE" ) == 0 Then Return 0 If Verify( SubStr( s, p + 1 ), "0123456789" ) > 0 Then Return 0 If Pos( Left( s, 1 ), "0123456789." ) > 0, - CountStr( ".", Left( s, p - 1 ) ) > 1 Then Return 0 Return 1 /******************************************************************************/ /* Errors */ /******************************************************************************/ /* BifError(code, bif, insert...) : raise error 'code' for built-in function */ /* 'bif', filling the message's inserts in order. The code and the message */ /* travel in the condition's description, "RVM.Message code text": the */ /* host is only asked for the generic major.900, since it does not know every */ /* standard code (it cannot raise 40.9, for instance). See BifCodeOf and */ /* BifMessageOf. */ ::Routine BifError Public Use Arg code, bif inserts = .Array~new Do i = 3 To Arg() inserts~append( Arg( i ) ) End Call BifRaise code, bif, inserts, .Nil /* BifMethodError(method, code, bif, insert...) : BifError, carrying the */ /* error ooRexx's method of the same name gives in its place ('method': the */ /* code, then its inserts), for the RVM's methods of String (the third item */ /* of the additional). */ ::Routine BifMethodError Public Use Arg method, code, bif inserts = .Array~new Do i = 4 To Arg() inserts~append( Arg( i ) ) End Call BifRaise code, bif, inserts, method ::Routine BifRaise Use Strict Arg code, bif, inserts, method -- "40.28/CLASS": the code 40.28 with the message of variant CLASS. Parse Value code~string With code "/" variant code = .RVM.BifMessages~canonical( code ) key = code If variant \== "" Then key = code"/"variant text = .RVM.BifMessages~format( key, bif, inserts ) used = .RVM.BifMessages~filled( key, bif, inserts ) Parse Var code major "." If method == .Nil Then Raise Syntax ( major".900" ) Array( text, used ) Description( "RVM.Message" code text ) Raise Syntax ( major".900" ) Array( text, used, method ) Description( "RVM.Message" code text ) /* The additional information of an error condition (the substitutions of its */ /* message): for one that carries its own message, the values it filled in */ /* (the second item), else the interpreter's own. */ ::Routine ErrorAdditional Public Use Strict Arg co description = co~description a = co~additional If description~isA( .String ), Word( description, 1 ) == "RVM.Message" Then Do If a~isA( .Array ), a~hasIndex( 2 ) Then Return a[2] Return .Array~new End If a == .Nil Then Return .Array~new Return a /* The error code of an error condition: the one it carries, if any, else the */ /* interpreter's own. */ ::Routine BifCodeOf Public Use Strict Arg co description = co~description If description~isA( .String ), Word( description, 1 ) == "RVM.Message" Then Return Word( description, 2 ) Return co~code /* The message of an error condition: the one it carries, if any, else the */ /* interpreter's own. */ ::Routine BifMessageOf Public Use Strict Arg co description = co~description If description~isA( .String ), Word( description, 1 ) == "RVM.Message" Then Return SubWord( description, 3 ) -- An object among the substitutions: its string value (ooRexx's -- messageSubstitution: stringValue, a MutableBuffer's text, a StackFrame's -- line, a stem's default...: RVM.Obj~string), not the name the host gives -- it. The message is made again with the strings; ADDITIONAL keeps the -- objects. a = co~additional If \ a~isA( .Array ) Then Return co~message n = a~last If n == .Nil Then Return co~message redo = .False strings = .Array~new Do i = 1 To n If \ a~hasIndex( i ) Then Iterate v = a[i] -- (RVM.Obj: RVM.Objects.cls requires this package, not the other way.) If Upper( v~class~id ) == "RVM.OBJ" Then Do s = v~string( .True ) If s \== v~objectName Then redo = .True v = s End strings[i] = v End If \ redo Then Return co~message Return MessageWith( co~code, strings ) -- The secondary message of error 'code' with the substitutions 'a' (the -- host makes it: the error raised and trapped here). ::Routine MessageWith Use Strict Arg code, a Signal On Syntax Name MessageMade Raise Syntax ( code ) Additional( a ) MessageMade: Return Condition( "O" )~message ::Class RVM.BifMessages -- The messages of error 40. is the function; every other <...> is an -- insert, filled in order. 40.9 names the largest exponent: 9 digits. ::Method activate Class Expose texts texts = .StringTable~new texts["40.3" ] = 'Not enough arguments in invocation of ; minimum expected is ' texts["40.4" ] = 'Too many arguments in invocation of ; maximum expected is ' texts["40.5" ] = 'Missing argument in invocation of ; argument is required' texts["40.9" ] = ' argument exponent exceeds 9 digits; found ""' texts["40.11"] = ' argument must be a number; found ""' texts["40.12"] = ' argument must be a whole number; found ""' texts["40.13"] = ' argument must be zero or positive; found ""' texts["40.14"] = ' argument must be positive; found ""' texts["40.15"] = ' argument must fit in digits; found ""' texts["40.16"] = ' argument 1 requires a whole number fitting within DIGITS(); found ""' texts["40.17"] = ' argument 1 must have an integer part in the range 0:90 and a decimal part no larger than .9; found ""' texts["40.18"] = ' conversion must have a year in the range 0001 to 9999' texts["40.19"] = ' argument 2, "", is not in the format described by argument 3, ""' texts["40.21"] = ' argument must not be null' texts["40.23"] = ' argument must be a single character; found ""' texts["40.24"] = ' argument 1 must be a binary string; found ""' texts["40.25"] = ' argument 1 must be a hexadecimal string; found ""' texts["40.26"] = ' argument 1 must be a valid symbol; found ""' texts["40.26/2"] = ' argument 2 must be a valid symbol; found ""' texts["40.27"] = ' argument 1 must be a valid stream name; found ""' texts["40.28"] = ' argument , option must start with one of ""; found ""' -- ooRexx's own text for XRANGE (a class name or a character, not an option). texts["40.28/CLASS"] = ' argument must be a character class name or a single character; found ""' -- ooRexx's own code for the stream functions that cannot use the queue. texts["40.915"] = ' cannot be used with QUEUE:' -- ooRexx's own code for ERRORTEXT (the standard has 0:90 and 40.16/40.17). texts["40.903"] = ' argument must be in the range 0-99; found ""' texts["40.29"] = ' conversion to format "" is not allowed' texts["40.31"] = ' argument 1 ("") must not exceed 100000' texts["40.32"] = ' the difference between argument 1 ("") and argument 2 ("") must not exceed 100000' -- ooRexx's own text and limit for RANDOM (the standard's is 100000). texts["40.32/RANDOM"] = ' difference between argument 1 ("") and argument 2 ("") must not exceed 999,999,999' -- ooRexx's own codes and texts for DATE and TIME (not in the standard). texts["40.43"] = ' argument must be a single non-alphanumeric character or the null string; found ""' texts["40.44"] = ' argument , "", is a format incompatible with the separator specified in argument ' -- A message of its own (malformed stream commands, fixed-length records). texts["40.900"] = ' ' texts["40.904"] = ' argument must be one of ; found ""' -- ooRexx's own code for an object with no string value (VALUE's new -- environment value: native gives 88.909). texts["40.913"] = ' argument must have a string value; found ""' texts["40.33"] = ' argument 1 ("") must be less than or equal to argument 2 ("")' texts["40.34"] = ' argument 1 ("") must be less than or equal to the number of lines in the program ()' texts["40.35"] = ' argument 1 cannot be expressed as a whole number; found ""' texts["40.36"] = ' argument 1 must be the name of a variable in the pool; found ""' texts["40.37"] = ' argument 3 must be the name of a pool; found ""' texts["40.38"] = ' argument is not large enough to format ""' texts["40.39"] = ' argument 3 is not zero or one; found ""' texts["40.41"] = ' argument must be within the bounds of the stream; found ""' texts["40.42"] = ' argument 1; cannot position on this stream; found ""' /* canonical(code) : "40.3" for 40.003, 40.30 or "40.3". */ ::Method canonical Class Use Strict Arg code Parse Value code~string With major "." minor If minor == "" Then Return major If Length( minor ) == 3, Left( minor, 1 ) == 9 Then Return major"."minor -- 40.900 minor = Strip( minor, "T", "0" ) If minor == "" Then minor = 0 Return major"."||( minor + 0 ) /* format(code, bif, inserts) : the message text with its inserts filled. */ ::Method format Class Expose texts Use Strict Arg code, bif, inserts text = texts[ code ] If text == .Nil Then Return "" -- Fill left to right, never looking again at what was filled in. out = "" i = 0 Loop While Pos( "<", text ) > 0 Parse Var text head "<" name ">" text out = out || head If name == "bif" Then out = out || bif Else Do i += 1 If inserts~hasIndex( i ) Then out = out || inserts[ i ] End End Return out || text -- The values format fills in, in order (the additional information of the -- error: the substitutions of its message). ::Method filled Class Expose texts Use Strict Arg code, bif, inserts used = .Array~new text = texts[ code ] If text == .Nil Then Return used i = 0 Loop While Pos( "<", text ) > 0 Parse Var text . "<" name ">" text If name == "bif" Then used~append( bif ) Else Do i += 1 If inserts~hasIndex( i ) Then used~append( inserts[ i ] ) End End Return used /******************************************************************************/ /* */ /* Calling a built-in function */ /* */ /******************************************************************************/ /* IsBIF(name) : is there a built-in function of that (upper-case) name? */ ::Routine IsBIF Public Use Strict Arg name Return .RVM.BIFTable~has( name ) /* CallBIF(name, args, context) : run the built-in function and return its */ /* value. 'args' is the argument Array (omitted arguments are holes). */ /* */ /* A function that ooRexx runs as a method of String (BuiltinFunctions.cpp: */ /* SUBSTR is string->substr(n, length, pad)) is run the same way, so that its */ /* errors are ooRexx's: first the function's own checks, in the order of its */ /* arguments (the count, 40.3/40.4; an omitted required argument, 40.5; a */ /* string; a whole number, 40.12; a pad, 40.23), then the method of String on */ /* the argument that is its receiver ('at'), with the method's checks */ /* (93.9xx, in the method's own order and numbering: RVM.Objects' */ /* StringMethod), which then computes it with ComputeBIF. */ /* */ /* The function's own code checks the same things (with the standard's */ /* errors), so it runs first when every argument is a string or a number: a */ /* string function has no side effects, and only when it fails is the call */ /* made again as ooRexx makes it, for ooRexx's error. */ ::Routine CallBIF Public Use Strict Arg name, args, context spec = .RVM.BIFTable~viaMethod( name ) If spec == .Nil Then Return .RVM.BIFTable~routine( name )~call( name, args, context ) plain = .True n = args~last If n == .Nil Then n = 0 Do i = 1 To n If args~hasIndex( i ) Then Do v = args[i] If \ v~isA( .String ), \ v~isA( .RVM.Number ) Then Do plain = .False Leave End End End If plain Then Do Signal On Syntax Name AsOoRexx Return .RVM.BIFTable~routine( name )~call( name, args, context ) End AsOoRexx: Signal Off Syntax Parse Var spec at checklist If checklist == "*" Then Do -- MAX and MIN If args~isEmpty Then Call BifError 40.3, name, 1 If \ args~hasIndex( 1 ) Then Call BifError 40.5, name, 1 a = args~copy a[1] = str( a[1] ) End Else a = CheckArgs( name, args, context, checklist ) receiver = a[ at ] m = .Array~new n = a~last If n == .Nil Then n = 0 j = 0 Do i = 1 To n If i == at Then Iterate j += 1 If a~hasIndex( i ) Then m[j] = a[i] End Return .RVM.BIFTable~stringMethod~call( name, at, receiver, m, context ) /* SetStringMethod(routine) : RVM.Objects' StringMethod, for CallBIF. */ ::Routine SetStringMethod Public Use Strict Arg routine .RVM.BIFTable~stringMethod = routine /* ComputeBIF(name, args, context) : the function's own code, for a method of */ /* String that has checked its arguments (StringMethod). */ ::Routine ComputeBIF Public Use Strict Arg name, args, context Return .RVM.BIFTable~routine( name )~call( name, args, context ) /******************************************************************************/ /* REXXUTIL's table (RVM.RexxUtil.cls runs its routines; RXFUNCQUERY looks */ /* them up): name, the arguments it requires, those it takes, its key */ /* (RexxUtilNative). A Directory, by name, made once. SysVersion always; */ /* SysLinVer and SysWinVer where the host has them (ooRexx: SysLinVer is */ /* SysVersion on Unix; SysWinVer, Windows only). Windows's REXXUTIL has no */ /* SysGetMessage nor SysGetMessageX, its SysMkDir takes no mode, and its */ /* SysSetPriority takes a class and a level (both required, any objects). */ /******************************************************************************/ ::Routine RexxUtilRoutines Public table = .RVM.RexxUtil~table If table \== .Nil Then Return table table = .Directory~new list = "SYSSLEEP 1 1 SLEEP rSTR;" "SYSFILEEXISTS 1 1 FILEEXISTS rSTR;" - "SYSISFILE 1 1 ISFILE rSTR;" "SYSISFILEDIRECTORY 1 1 ISDIR rSTR;" - "SYSISFILELINK 1 1 ISLINK rSTR;" "SYSFILEDELETE 1 1 FILEDELETE rSTR;" - "SYSRMDIR 1 1 RMDIR rSTR;" - "SYSVERSION 0 0 VERSION" -- With a signature (the types of its arguments, r required, o optional: -- see RVM.RexxUtil's NativeArgs), the arguments are converted as ooRexx's -- native routines' are. list ||= ";" - "SYSSTEMSORT 1 7 STEMSORT rANY oSTR oSTR oPOSW oPOSW oPOSW oPOSW;" - "SYSSTEMDELETE 2 3 STEMDELETE rSTEM rPOSW oPOSW;" - "SYSSTEMINSERT 3 3 STEMINSERT rSTEM rPOSW rANY;" - "SYSSTEMCOPY 2 6 STEMCOPY rSTEM rSTEM oPOSW oPOSW oNNEGW oSTR;" - "SYSUTILVERSION 0 0 UTILVERSION -;" "SYSLOADFUNCS 0 0 LOADFUNCS -;" - "SYSCLS 0 0 CLS -;" "SYSQUERYPROCESS 0 1 QUERYPROCESS oSTR;" - "SYSGETKEY 0 1 GETKEY oSTR;" - "SYSDROPFUNCS 0 0 DROPFUNCS -;" "SYSDUMPVARIABLES 0 1 DUMPVARS oSTR;" - "SYSFORMATMESSAGE 2 2 FORMATMESSAGE rSTR rARRAY;" - "SYSGETERRORTEXT 1 1 ERRORTEXT rINT32;" - "SYSFILETREE 2 5 FILETREE rSTR rANY oSTR oSTR oSTR;" - "SYSFILESEARCH 3 4 FILESEARCH rSTR rSTR rANY oSTR;" - "SYSSEARCHPATH 2 3 SEARCHPATH rSTR rSTR oSTR;" - "SYSFILECOPY 2 2 FILECOPY rSTR rSTR;" "SYSFILEMOVE 2 2 FILEMOVE rSTR rSTR;" - "SYSTEMPFILENAME 1 2 TEMPFILENAME rSTR oSTR;" - "SYSGETFILEDATETIME 1 2 GETFILEDATETIME rSTR oSTR;" - "SYSSETFILEDATETIME 1 3 SETFILEDATETIME rSTR oSTR oSTR;" - "SYSADDREXXMACRO 2 3 ADDMACRO rSTR rSTR oSTR;" - "SYSDROPREXXMACRO 1 1 DROPMACRO rSTR;" "SYSQUERYREXXMACRO 1 1 QUERYMACRO rSTR;" - "SYSREORDERREXXMACRO 2 2 REORDERMACRO rSTR rSTR;" - "SYSCLEARREXXMACROSPACE 0 0 CLEARMACROS -;" - "SYSSAVEREXXMACROSPACE 1 1 SAVEMACROS rSTR;" - "SYSLOADREXXMACROSPACE 1 1 LOADMACROS rSTR" If .RVM.FileSystem~windows Then list ||= "; SYSMKDIR 1 1 MKDIR rSTR" - "; SYSSETPRIORITY 2 2 SETPRIORITY rANY rANY" Else list ||= "; SYSMKDIR 1 2 MKDIR rSTR oINT32" - "; SYSSETPRIORITY 0 2 SETPRIORITY oINT32 rINT32" - "; SYSGETMESSAGE 1 999 GETMESSAGE rPOSW oSTR *" - "; SYSGETMESSAGEX 2 999 GETMESSAGEX rPOSW rPOSW oSTR *" If RxFuncQuery( "SysLinVer" ) == 0 Then list ||= "; SYSLINVER 0 0 LINVER" If RxFuncQuery( "SysWinVer" ) == 0 Then list ||= "; SYSWINVER 0 0 WINVER" Do entry Over list~makeArray( ";" ) Parse Var entry name min max key sig sig = Strip( sig ) If sig == "" Then table[ name ] = .Array~of( name, min, max, key ) Else Do If sig == "-" Then sig = "" table[ name ] = .Array~of( name, min, max, key, .Nil, sig ) End End .RVM.RexxUtil~table = table Return table -- A routine of REXXUTIL, or .Nil ('name' in any case: ooRexx finds a -- native routine so). ::Routine RexxUtilRoutine Public Use Strict Arg name Return RexxUtilRoutines()[ Upper( name ) ] ::Class RVM.RexxUtil Public ::Attribute table Class ::Attribute rxmath Class ::Attribute rxsock Class -- the routines of rxsock (RxSockRoutines) ::Attribute rxregexp Class -- the methods of rxregexp (RxRegExpMethods) ::Attribute macros Class -- REXXUTIL's macrospace: NAME -> (order, program) ::Attribute registered Class -- RXFUNCADD's functions the RVM cannot load -- (rxapi's table): NAME -> how many times ::Attribute loader Class -- the machine's LoadProgram (RVM.MacroLoader) ::Attribute reader Class -- and its ProgramOfRCode ::Method activate Class Expose table rxmath rxsock rxregexp macros registered registered = .Directory~new table = .Nil rxmath = .Nil rxsock = .Nil rxregexp = .Nil macros = .Directory~new /******************************************************************************/ /* The libraries of the RVM: ::REQUIRES "lib" LIBRARY, EXTERNAL 'LIBRARY lib */ /* f', Package~loadLibrary, Routine~loadExternalRoutine. The registry is */ /* closed: a library is one the RVM implements itself, in both RVMs (as */ /* REXXUTIL); any other is 98.903, as ooRexx when it cannot load it. Its name */ /* is as given (ooRexx on Unix: librxmath.so; RXMATH is not found); on */ /* Windows, a library that is a file (a DLL) is found in any case: RXMATH is */ /* rxmath.dll (LibraryName). Its routines are as REXXUTIL's: name, required, */ /* allowed, key, and the library. */ /* */ /* rxmath RVM.RxMath.cls (ooRexx's extensions/rxmath). The RVM of ooRexx */ /* runs the host's own (so, when the host has none, 98.903). */ /* rxsock RVM.RxSock.cls (ooRexx's extensions/rxsock). The RVM of ooRexx */ /* runs the host's own sockets; the RVM of JS, js/rxsock.mjs and */ /* the host's (Node: sockets-node.mjs). */ /* rxregexp RVM.RxRegExp.cls (ooRexx's extensions/rxregexp): no routines; */ /* the methods of RegularExpression (LibraryMethods). The RVM of */ /* ooRexx runs the host's own; the RVM of JS, js/rxregexp.mjs. */ /* REXX, rexxutil ooRexx's own, inside it (REXXUTIL: RVM.RexxUtil.cls). */ /* hostemu ooRexx's extensions/hostemu: the ADDRESS environment HOSTEMU */ /* (RVM.HostEmu.cls: EXECIO, HI, TE and TS). */ /* */ /* RVMLibrary(name): the Directory of its routines (NAME -> entry), or .Nil. */ /******************************************************************************/ ::Routine RVMLibrary Public Use Strict Arg name Select Case LibraryName( name ) When "rxmath" Then Return RxMathRoutines() When "rxsock" Then Return RxSockRoutines() -- The two that ooRexx has inside, as it names them: REXX (its routines -- are none; its methods, LIBRARY REXX f, are the RVM's X.f) and -- REXXUTIL (always loaded, as "rexxutil"). When "REXX" Then Return .Directory~new When "rexxutil" Then Return RexxUtilRoutines() -- hostemu: no routines; an ADDRESS environment (LibraryEnvironments). When "hostemu" Then Return .Directory~new -- rxregexp: no routines; methods (LibraryMethods), the host's. When "rxregexp" Then Do If RxRegExpHost() == .Nil Then Return .Nil Return .Directory~new End Otherwise Return .Nil End -- The name of a library as the RVM knows it: as given; on Windows, where -- the name of a file is in any case, that of one of the libraries that are -- files (DLLs) in lower case. (REXX and rexxutil are inside ooRexx, found -- by their names as they are.) ::Routine LibraryName Public Use Strict Arg name If \ .RVM.FileSystem~caseless Then Return name lower = Lower( name ) If WordPos( lower, "rxmath rxsock rxregexp hostemu rxunixsys orxncurses" - "orexxole oodialog rxwinsys" ) > 0 Then Return lower Return name -- What the RVM knows of a library of ooRexx it does not have (its name as -- ooRexx on Unix gives it): "NONE", one with no methods (so an EXTERNAL -- method in it is 90.998, as ooRexx says when it translates it); "METHODS", -- one with methods (such a method fails only when it runs: 98.903, so that -- a package that wraps the library still loads); "" (not one of ooRexx's: -- 98.903 when the program starts, as ooRexx, which cannot load it either). ::Routine OoRexxLibrary Public Use Strict Arg name name = LibraryName( name ) -- (rxunixsys is ooRexx's on Unix only: on Windows it is not there.) If WordPos( name, "rxunixsys" ) > 0 Then Do If .File~separator == "\" Then Return "" Return "NONE" End If WordPos( name, "orxncurses rxregexp orexxole oodialog rxwinsys" ) > 0 Then Return "METHODS" Return "" -- The methods of a library of the RVM (NAME -> entry), or .Nil. An entry: -- the NAME, the key, the library, and the arguments ("o" optional, "r" -- required: all strings). ::Routine LibraryMethods Public Use Strict Arg name name = LibraryName( name ) If name == "rxregexp" Then Return RxRegExpMethods() Return .Nil ::Routine RxRegExpMethods Public table = .RVM.RexxUtil~rxregexp If table \== .Nil Then Return table table = .Directory~new list = "REGEXP_INIT INIT o o; REGEXP_UNINIT UNINIT; REGEXP_PARSE PARSE r o;" - "REGEXP_MATCH MATCH r; REGEXP_POS POS r" Do entry Over list~makeArray( ";" ) Parse Var entry name key sig table[ name ] = .Array~of( name, key, "rxregexp", Space( sig ) ) End .RVM.RexxUtil~rxregexp = table Return table -- The ADDRESS environments a library of the RVM registers when it is loaded -- (RVM.World~loadLibrary; RVM.HostEmu.cls runs their commands). ::Routine LibraryEnvironments Public Use Strict Arg name If LibraryName( name ) == "hostemu" Then Return .Array~of( "HOSTEMU" ) Return .Array~new /* The words of an EXTERNAL specification (ooRexx's decodeExternalMethod, */ /* routineDirective, loadExternalRoutine): "LIBRARY lib [entry]", the first */ /* word in any case (and, for a ::ROUTINE, "REGISTERED lib [entry]"); else */ /* 99.917. An Array: the kind (upper case), the library, the entry ('name' */ /* when it is omitted). */ ::Routine ExternalSpec Public Use Strict Arg spec, name, registered = .False n = Words( spec ) kind = Upper( Word( spec, 1 ) ) ok = ( kind == "LIBRARY" | ( registered & kind == "REGISTERED" ) ) If \ ok | n < 2 | n > 3 Then Raise Syntax 99.917 Array( spec ) entry = name If n == 3 Then entry = Word( spec, 3 ) Return .Array~of( kind, Word( spec, 2 ), entry ) /* The routine of an EXTERNAL specification (a ::ROUTINE's, 'strict'; or */ /* Routine~loadExternalRoutine's, which gives .Nil for what is not there): */ /* the entry of a routine of a library of the RVM, which is now loaded. Not */ /* there: the library, 98.903; the entry, 90.999. The RVM has no registered */ /* (classic) functions: REGISTERED is always 90.999. */ ::Routine ExternalRoutine Public Use Strict Arg name, spec, world, strict e = ExternalSpec( spec, name, strict ) If e[1] == "REGISTERED" Then Raise Syntax 90.999 Array( e[3] ) table = RVMLibrary( e[2] ) If table == .Nil Then Do If strict Then Raise Syntax 98.903 Array( e[2] ) Return .Nil End world~loadLibrary( e[2], table ) lr = table[ Upper( e[3] ) ] If lr == .Nil, strict Then Raise Syntax 90.999 Array( e[3] ) Return lr /* The method of an EXTERNAL specification (a ::METHOD's or ::ATTRIBUTE's, */ /* 'strict', with its prefix: GET, SET, or -; or Method~loadExternalMethod's, */ /* .Nil when it is not there): the entry of a method of a library of the RVM */ /* (LibraryMethods), which is now loaded. Not there: the library, 98.903; */ /* the method, 90.998. */ ::Routine ExternalMethod Public Use Strict Arg name, spec, suffix, world, strict e = ExternalSpec( spec, name ) table = RVMLibrary( e[2] ) If table == .Nil Then Do If strict Then Raise Syntax 98.903 Array( e[2] ) Return .Nil End world~loadLibrary( e[2], table ) entry = e[3] If suffix \== "-" Then entry = suffix || entry -- (GETFOO, SETFOO) methods = LibraryMethods( e[2] ) lm = .Nil If methods \== .Nil Then lm = methods[ Upper( entry ) ] If lm == .Nil, strict Then Raise Syntax 90.998 Array( entry ) Return lm ::Routine RxMathRoutines Public table = .RVM.RexxUtil~rxmath If table \== .Nil Then Return table If \ .context~package~loadLibrary( "rxmath" ) Then Return .Nil table = .Directory~new list = "MATHLOADFUNCS 0 1 LOAD; MATHDROPFUNCS 0 0 DROP; RXCALCPI 0 1 PI;" - "RXCALCSQRT 1 2 SQRT; RXCALCEXP 1 2 EXP; RXCALCLOG 1 2 LOG;" - "RXCALCLOG10 1 2 LOG10; RXCALCSINH 1 2 SINH; RXCALCCOSH 1 2 COSH;" - "RXCALCTANH 1 2 TANH; RXCALCPOWER 2 3 POWER; RXCALCSIN 1 3 SIN;" - "RXCALCCOS 1 3 COS; RXCALCTAN 1 3 TAN; RXCALCCOTAN 1 3 COTAN;" - "RXCALCARCSIN 1 3 ARCSIN; RXCALCARCCOS 1 3 ARCCOS; RXCALCARCTAN 1 3 ARCTAN" Do entry Over list~makeArray( ";" ) Parse Var entry name min max key . table[ name ] = .Array~of( name, min, max, key, "rxmath" ) End .RVM.RexxUtil~rxmath = table Return table -- rxsock (RVM.RxSock.cls): its routines, with the types of their arguments -- (NativeArgs: INT32 the API's int, STR CSTRING or RexxStringObject, ANY -- RexxObjectPtr, FLOAT float). The RVM of ooRexx needs the host's. ::Routine RxSockRoutines Public table = .RVM.RexxUtil~rxsock If table \== .Nil Then Return table If \ .context~package~loadLibrary( "rxsock" ) Then Return .Nil table = .Directory~new list = "SOCKLOADFUNCS 0 1 LOAD oSTR; SOCKDROPFUNCS 0 0 DROP -;" - "SOCKVERSION 0 0 VERSION -; SOCKINIT 0 0 INIT -;" - "SOCKSOCK_ERRNO 0 0 ERRNO -; SOCKPSOCK_ERRNO 0 1 PERRNO oSTR;" - "SOCKSOCKET 3 3 SOCKET rSTR rSTR rSTR; SOCKCLOSE 1 1 CLOSE rINT32;" - "SOCKSOCLOSE 1 1 CLOSE rINT32; SOCKBIND 2 2 BIND rINT32 rANY;" - "SOCKCONNECT 2 2 CONNECT rINT32 rANY; SOCKLISTEN 2 2 LISTEN rINT32 rINT32;" - "SOCKACCEPT 1 2 ACCEPT rINT32 oANY; SOCKSHUTDOWN 2 2 SHUTDOWN rINT32 rINT32;" - "SOCKGETPEERNAME 2 2 PEERNAME rINT32 rANY;" - "SOCKGETSOCKNAME 2 2 SOCKNAME rINT32 rANY;" - "SOCKGETHOSTBYNAME 2 2 HOSTBYNAME rSTR rANY;" - "SOCKGETHOSTBYADDR 2 3 HOSTBYADDR rSTR rANY oINT32;" - "SOCKGETHOSTID 0 0 HOSTID -; SOCKGETHOSTNAME 0 0 HOSTNAME -;" - "SOCKGETSOCKOPT 4 4 GETOPT rINT32 rSTR rSTR rSTR;" - "SOCKSETSOCKOPT 4 4 SETOPT rINT32 rSTR rSTR rSTR;" - "SOCKIOCTL 3 3 IOCTL rINT32 rSTR rANY;" - "SOCKRECV 3 4 RECV rINT32 rSTR rINT32 oSTR;" - "SOCKRECVFROM 4 5 RECVFROM rINT32 rSTR rINT32 rANY oANY;" - "SOCKSEND 2 3 SEND rINT32 rSTR oSTR; SOCKSENDTO 3 4 SENDTO rINT32 rSTR rANY oANY;" - "SOCKSELECT 0 4 SELECT oANY oANY oANY oFLOAT" Do entry Over list~makeArray( ";" ) Parse Var entry name min max key sig sig = Space( sig ) If sig == "-" Then sig = "" table[ name ] = .Array~of( name, min, max, key, "rxsock", sig ) End .RVM.RexxUtil~rxsock = table Return table ::Class RVM.BIFTable ::Method activate Class Expose routines viaMethod routines = .StringTable~new names = "ADDRESS ARG CONDITION DIGITS FORM FUZZ QUEUED ABS MAX MIN SIGN TRUNC FORMAT" - "B2X C2X X2B X2C C2D D2C D2X X2D BITAND BITOR BITXOR XRANGE" - "DATATYPE SYMBOL VALUE SOURCELINE ERRORTEXT RANDOM DATE TIME" - "ABBREV CENTER CENTRE CHANGESTR COMPARE COPIES COUNTSTR DELSTR" - "DELWORD INSERT LASTPOS LEFT LENGTH LOWER OVERLAY POS REVERSE" - "RIGHT SPACE STRIP SUBSTR SUBWORD TRANSLATE UPPER VERIFY WORD" - "WORDINDEX WORDLENGTH WORDPOS WORDS" - "CHARIN CHAROUT CHARS LINEIN LINEOUT LINES STREAM" - "QUALIFY FILESPEC VAR DIRECTORY USERID BEEP GC SETLOCAL ENDLOCAL" - "TRACE RXFUNCQUERY RXFUNCADD RXFUNCDROP RXQUEUE" package = .context~package Do name Over names~makeArray(" ") routines[ name ] = package~findRoutine( "BIF."name ) End routines[ "CENTRE" ] = routines[ "CENTER" ] -- The functions ooRexx runs as methods of String (see CallBIF): the -- position of the receiver, then the kind of each argument as the -- function checks it (S a string, W a whole number, P a pad; required or -- not as the parser's table says); "*", every argument (MAX, MIN). viaMethod = .StringTable~new list = "ABBREV 1 SSW;" "ABS 1 S;" "B2X 1 S;" "BITAND 1 SSP;" "BITOR 1 SSP;" - "BITXOR 1 SSP;" "C2D 1 SW;" "C2X 1 S;" "CENTER 1 SWP;" "CENTRE 1 SWP;" - "CHANGESTR 2 SSSW;" "COMPARE 1 SSP;" "COPIES 1 SW;" "COUNTSTR 2 SS;" - "D2C 1 SW;" "D2X 1 SW;" "DATATYPE 1 SS;" "DELSTR 1 SWW;" "DELWORD 1 SWW;" - "FORMAT 1 SWWWW;" "INSERT 2 SSWWP;" "LASTPOS 2 SSWW;" "LEFT 1 SWP;" - "LENGTH 1 S;" "LOWER 1 SWW;" "MAX 1 *;" "MIN 1 *;" "OVERLAY 2 SSWWP;" - "POS 2 SSWW;" "REVERSE 1 S;" "RIGHT 1 SWP;" "SIGN 1 S;" "SPACE 1 SWP;" - "STRIP 1 SSS;" "SUBSTR 1 SWWP;" "SUBWORD 1 SWW;" "TRANSLATE 1 SSSPWW;" - "TRUNC 1 SW;" "UPPER 1 SWW;" "VERIFY 1 SSSWW;" "WORD 1 SW;" - "WORDINDEX 1 SW;" "WORDLENGTH 1 SW;" "WORDPOS 2 SSW;" "WORDS 1 S;" - "X2B 1 S;" "X2C 1 S;" "X2D 1 SW" Do item Over list~makeArray( ";" ) Parse Var item name at kinds viaMethod[ name ] = .Array~of( at, kinds ) End ::Attribute stringMethod Class -- RVM.Objects' StringMethod (it sets it) -- "at checklist" for CallBIF (the checklist made at the first call, when the -- parser's table exists), or .Nil. ::Method viaMethod Class Expose viaMethod Use Strict Arg name spec = viaMethod[ name ] If spec == .Nil Then Return .Nil If spec~isA( .String ) Then Return spec Parse Value spec[1] spec[2] With at kinds If kinds == "*" Then spec = at "*" Else Do info = .Parser.BIFInfo[ name ] checklist = "" Do i = 1 To Length( kinds ) If i <= info~minArgs Then req = "r" Else req = "o" Select Case SubStr( kinds, i, 1 ) When "S" Then type = "STR" When "W" Then type = "WHOLE" When "P" Then type = "PAD" End checklist ||= " "req || type End spec = at Strip( checklist ) End viaMethod[ name ] = spec Return spec ::Method has Class Expose routines Use Strict Arg name Return routines~hasIndex( name ) ::Method routine Class Expose routines Use Strict Arg name Return routines[ name ] /******************************************************************************/ /* */ /* The byte layer */ /* */ /* The string functions below are written against a handful of operations on */ /* strings of bytes, and nothing else: the length, a slice INSIDE the string, */ /* concatenation, repetition (copies), reversal, searching a byte sequence */ /* from a position (Pos, like indexOf), and a byte builder (MutableBuffer). */ /* Everything else -- padding, defaults, ranges, words and blanks, options, */ /* translation tables -- is spelled out here, never left to the host's own */ /* functions of the same name. */ /* */ /******************************************************************************/ -- Blanks separate words: the blank and the horizontal tab. ::Routine Blanks Return " " || "09"x ::Routine IsBlank Use Strict Arg c Return c == " " | c == "09"x /* PadSlice(s, p, n, pad) : n characters of s from position p (p >= 1); those */ /* beyond the end of s are the pad character. */ ::Routine PadSlice Use Strict Arg s, p, n, pad avail = Min( n, Max( Length( s ) - p + 1, 0 ) ) If avail > 0 Then out = Substr( s, p, avail ) Else out = "" Return out || Copies( pad, n - avail ) /* Tail(s, p) : s from position p to its end ("" when p is past the end). */ ::Routine Tail Use Strict Arg s, p If p > Length( s ) Then Return "" Return Substr( s, p ) /* Words(s) : the words of s, as an Array of "start end" positions. */ ::Routine WordSpans Use Strict Arg s spans = .Array~new len = Length( s ) i = 1 Loop While i <= len Loop While i <= len If \ IsBlank( Substr( s, i, 1 ) ) Then Leave i += 1 End If i > len Then Leave start = i Loop While i <= len If IsBlank( Substr( s, i, 1 ) ) Then Leave i += 1 End spans~append( start (i - 1) ) End Return spans /* The first position in [start, last] whose byte is (match=1) / is not */ /* (match=0) in the set 'ref', or 0. */ ::Routine ScanSet Use Strict Arg s, ref, start, last, match Do i = start To last inSet = ( Pos( Substr( s, i, 1 ), ref ) > 0 ) If inSet == match Then Return i End Return 0 /* Map the bytes of s in [start, start+len-1] through 'from' -> 'to' (same */ /* length); bytes not in 'from' are unchanged. The first occurrence of a byte */ /* in 'from' decides. */ ::Routine MapBytes Use Strict Arg s, start, len, from, to map = .StringTable~new Do k = Length( from ) To 1 By -1 map[ Substr( from, k, 1 ) ] = Substr( to, k, 1 ) End out = .MutableBuffer~new If start > 1 Then out~append( Substr( s, 1, start - 1 ) ) Do i = start To start + len - 1 c = Substr( s, i, 1 ) m = map[ c ] If m == .Nil Then out~append( c ) Else out~append( m ) End out~append( Tail( s, start + len ) ) Return out~string /* The range [start, start+len-1] of a string of length 'size' that the */ /* optional start/length arguments select, clipped to the string: "first last" */ /* (last < first when empty). */ ::Routine Range Use Strict Arg size, start, len last = size If len \== .Nil Then last = Min( size, start + len - 1 ) Return start last /******************************************************************************/ /* */ /* The string functions. Each checks its arguments (CheckArgs, with the */ /* signature of the BIF table) and then does what the standard describes, */ /* with ooRexx's additional arguments (the start/length range of POS, */ /* LASTPOS, TRANSLATE, VERIFY, UPPER and LOWER; the count of CHANGESTR; a */ /* character set as STRIP's third argument). */ /* */ /******************************************************************************/ ::Routine BIF.LENGTH Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return Length( str( a[1] ) ) ::Routine BIF.LEFT Use Strict Arg name, args, context a = CheckArgs( name, args, context ) pad = " "; If a~hasIndex(3) Then pad = a[3] Return PadSlice( str( a[1] ), 1, a[2], pad ) ::Routine BIF.RIGHT Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ); n = a[2] pad = " "; If a~hasIndex(3) Then pad = a[3] trim = Length( s ) - n If trim >= 0 Then Return Tail( s, trim + 1 ) Return Copies( pad, -trim ) || s ::Routine BIF.SUBSTR Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ); n = a[2] If a~hasIndex(3) Then len = a[3] Else len = Max( Length( s ) + 1 - n, 0 ) pad = " "; If a~hasIndex(4) Then pad = a[4] Return PadSlice( s, n, len, pad ) ::Routine BIF.CENTER Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ); len = a[2] pad = " "; If a~hasIndex(3) Then pad = a[3] trim = Length( s ) - len If trim > 0 Then Return Substr( s, trim % 2 + 1, len ) before = ( -trim ) % 2 Return Copies( pad, before ) || s || Copies( pad, len - before - Length( s ) ) ::Routine BIF.COPIES Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return Copies( str( a[1] ), a[2] ) ::Routine BIF.REVERSE Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return Reverse( str( a[1] ) ) ::Routine BIF.ABBREV Use Strict Arg name, args, context a = CheckArgs( name, args, context ) subject = str( a[1] ); subj = str( a[2] ) If a~hasIndex(3) Then len = a[3] Else len = Length( subj ) If Length( subject ) < Length( subj ) Then Return 0 If Length( subj ) < len Then Return 0 Return ( Substr( subject, 1, Length( subj ) ) == subj ) + 0 ::Routine BIF.COMPARE Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s1 = str( a[1] ); s2 = str( a[2] ) pad = " "; If a~hasIndex(3) Then pad = a[3] len = Max( Length( s1 ), Length( s2 ) ) s1 = PadSlice( s1, 1, len, pad ) s2 = PadSlice( s2, 1, len, pad ) Do i = 1 To len If Substr( s1, i, 1 ) \== Substr( s2, i, 1 ) Then Return i End Return 0 ::Routine BIF.CHANGESTR Use Strict Arg name, args, context a = CheckArgs( name, args, context ) needle = str( a[1] ); haystack = str( a[2] ); new = str( a[3] ) limit = .Nil; If a~hasIndex(4) Then limit = a[4] If needle == "" Then Return haystack out = .MutableBuffer~new position = 1 count = 0 Loop If limit \== .Nil, count >= limit Then Leave found = Pos( needle, haystack, position ) If found == 0 Then Leave out~append( Substr( haystack, position, found - position ), new ) position = found + Length( needle ) count += 1 End out~append( Tail( haystack, position ) ) Return out~string ::Routine BIF.COUNTSTR Use Strict Arg name, args, context a = CheckArgs( name, args, context ) needle = str( a[1] ); haystack = str( a[2] ) If needle == "" Then Return 0 count = 0 position = Pos( needle, haystack ) Loop While position > 0 count += 1 position = Pos( needle, haystack, position + Length( needle ) ) End Return count ::Routine BIF.DELSTR Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ) n = 1; If a~hasIndex(2) Then n = a[2] If n > Length( s ) Then Return s out = Substr( s, 1, n - 1 ) If a~hasIndex(3) Then out = out || Tail( s, n + a[3] ) Return out ::Routine BIF.INSERT Use Strict Arg name, args, context a = CheckArgs( name, args, context ) new = str( a[1] ); target = str( a[2] ) n = 0; If a~hasIndex(3) Then n = a[3] len = Length(new); If a~hasIndex(4) Then len = a[4] pad = " "; If a~hasIndex(5) Then pad = a[5] Return PadSlice( target, 1, n, pad ) || PadSlice( new, 1, len, pad ) || Tail( target, n + 1 ) ::Routine BIF.OVERLAY Use Strict Arg name, args, context a = CheckArgs( name, args, context ) new = str( a[1] ); target = str( a[2] ) n = 1; If a~hasIndex(3) Then n = a[3] len = Length(new); If a~hasIndex(4) Then len = a[4] pad = " "; If a~hasIndex(5) Then pad = a[5] Return PadSlice( target, 1, n - 1, pad ) || PadSlice( new, 1, len, pad ) || Tail( target, n + len ) /* POS(needle, haystack [, start [, length]]) : searched in the range. */ ::Routine BIF.POS Use Strict Arg name, args, context a = CheckArgs( name, args, context ) needle = str( a[1] ); haystack = str( a[2] ) start = 1; If a~hasIndex(3) Then start = a[3] len = .Nil; If a~hasIndex(4) Then len = a[4] Parse Value Range( Length( haystack ), start, len ) With first last n = Length( needle ) If n == 0 Then Return 0 If last - first + 1 < n Then Return 0 found = Pos( needle, haystack, first ) If found == 0 | found + n - 1 > last Then Return 0 Return found /* LASTPOS(needle, haystack [, start [, length]]) : the last occurrence that */ /* ends at or before 'start', within the 'length' characters ending there. */ ::Routine BIF.LASTPOS Use Strict Arg name, args, context a = CheckArgs( name, args, context ) needle = str( a[1] ); haystack = str( a[2] ) n = Length( needle ) last = Length( haystack ); If a~hasIndex(3) Then last = Min( a[3], last ) first = 1; If a~hasIndex(4) Then first = Max( last - a[4] + 1, 1 ) If n == 0 Then Return 0 Do i = last - n + 1 To first By -1 If Substr( haystack, i, n ) == needle Then Return i End Return 0 ::Routine BIF.SPACE Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ) n = 1; If a~hasIndex(2) Then n = a[2] pad = " "; If a~hasIndex(3) Then pad = a[3] padding = Copies( pad, n ) out = .MutableBuffer~new Do Counter k span Over WordSpans( s ) Parse Var span p q If k > 1 Then out~append( padding ) out~append( Substr( s, p, q - p + 1 ) ) End Return out~string /* STRIP(string [, option [, chars]]) : chars is a set (default: the blanks). */ ::Routine BIF.STRIP Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ) option = "B"; If a~hasIndex(2) Then option = a[2] unwanted = Blanks(); If a~hasIndex(3) Then unwanted = str( a[3] ) first = 1; last = Length( s ) If option == "L" | option == "B" Then Loop While first <= last If Pos( Substr( s, first, 1 ), unwanted ) == 0 Then Leave first += 1 End If option == "T" | option == "B" Then Loop While last >= first If Pos( Substr( s, last, 1 ), unwanted ) == 0 Then Leave last -= 1 End If last < first Then Return "" Return Substr( s, first, last - first + 1 ) ::Routine BIF.WORDS Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return WordSpans( str( a[1] ) )~items /* SUBWORD(string, n [, length]) : from the start of word n to the end of the */ /* last word taken (no blanks at either end). */ ::Routine BIF.SUBWORD Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ); n = a[2] spans = WordSpans( s ) count = spans~items - n + 1 If a~hasIndex(3) Then count = Min( count, a[3] ) If count <= 0 Then Return "" Parse Value spans[ n ] With p . Parse Value spans[ n + count - 1 ] With . q Return Substr( s, p, q - p + 1 ) ::Routine BIF.WORD Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ); spans = WordSpans( s ) If a[2] > spans~items Then Return "" Parse Value spans[ a[2] ] With p q Return Substr( s, p, q - p + 1 ) ::Routine BIF.WORDINDEX Use Strict Arg name, args, context a = CheckArgs( name, args, context ) spans = WordSpans( str( a[1] ) ) If a[2] > spans~items Then Return 0 Return spans[ a[2] ]~word(1) ::Routine BIF.WORDLENGTH Use Strict Arg name, args, context a = CheckArgs( name, args, context ) spans = WordSpans( str( a[1] ) ) If a[2] > spans~items Then Return 0 Parse Value spans[ a[2] ] With p q Return q - p + 1 /* WORDPOS(phrase, string [, start]) : the word number in string where the */ /* words of phrase appear, in sequence, from word 'start' on; or 0. */ ::Routine BIF.WORDPOS Use Strict Arg name, args, context a = CheckArgs( name, args, context ) phrase = str( a[1] ); s = str( a[2] ) start = 1; If a~hasIndex(3) Then start = a[3] pw = WordList( phrase ); sw = WordList( s ) np = pw~items If np == 0 Then Return 0 Do k = start To sw~items - np + 1 Do j = 1 To np If sw[ k + j - 1 ] \== pw[ j ] Then Iterate k End Return k End Return 0 /* The words of s, as an Array of strings. */ ::Routine WordList Use Strict Arg s list = .Array~new Do span Over WordSpans( s ) Parse Var span p q list~append( Substr( s, p, q - p + 1 ) ) End Return list /* DELWORD(string, n [, length]) : delete words n.. (and the blanks after the */ /* last one deleted); the blanks before word n stay. */ ::Routine BIF.DELWORD Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ); n = a[2] spans = WordSpans( s ) If n > spans~items Then Return s Parse Value spans[ n ] With p . out = Substr( s, 1, p - 1 ) If a~hasIndex(3) Then Do If n + a[3] <= spans~items Then Do Parse Value spans[ n + a[3] ] With r . out = out || Substr( s, r ) End End Return out /* TRANSLATE(string [, tableo [, tablei [, pad [, start [, length]]]]]) */ ::Routine BIF.TRANSLATE Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ) start = 1; If a~hasIndex(5) Then start = a[5] len = .Nil; If a~hasIndex(6) Then len = a[6] Parse Value Range( Length( s ), start, len ) With first last If last < first Then Return s -- Upper case when no table and no pad is given (a pad alone pads). If \ a~hasIndex(2), \ a~hasIndex(3), \ a~hasIndex(4) Then Return MapBytes( s, first, last - first + 1, LowerLetters(), UpperLetters() ) If a~hasIndex(3) Then tablei = str( a[3] ) Else tablei = AllBytes() tableo = ""; If a~hasIndex(2) Then tableo = str( a[2] ) pad = " "; If a~hasIndex(4) Then pad = a[4] tableo = PadSlice( tableo, 1, Length( tablei ), pad ) Return MapBytes( s, first, last - first + 1, tablei, tableo ) ::Routine BIF.UPPER Use Strict Arg name, args, context Return CaseRange( name, args, context, LowerLetters(), UpperLetters() ) ::Routine BIF.LOWER Use Strict Arg name, args, context Return CaseRange( name, args, context, UpperLetters(), LowerLetters() ) ::Routine CaseRange Use Strict Arg name, args, context, from, to a = CheckArgs( name, args, context ) s = str( a[1] ) start = 1; If a~hasIndex(2) Then start = a[2] len = .Nil; If a~hasIndex(3) Then len = a[3] Parse Value Range( Length( s ), start, len ) With first last If last < first Then Return s Return MapBytes( s, first, last - first + 1, from, to ) ::Routine LowerLetters Return "abcdefghijklmnopqrstuvwxyz" ::Routine UpperLetters Return "ABCDEFGHIJKLMNOPQRSTUVWXYZ" /* Every byte, in order: '00'x .. 'FF'x. */ ::Routine AllBytes Use Strict Arg out = .MutableBuffer~new Do b = 0 To 255 out~append( b~d2c ) End Return out~string /* VERIFY(string, reference [, option [, start [, length]]]) */ ::Routine BIF.VERIFY Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ); ref = str( a[2] ) option = "N"; If a~hasIndex(3) Then option = a[3] start = 1; If a~hasIndex(4) Then start = a[4] len = .Nil; If a~hasIndex(5) Then len = a[5] -- A null reference: no match at the start (whatever the length, even 0: -- ooRexx's StringUtil::verify), unless it is beyond the string. If ref == "" Then Do If option == "N", start <= Length( s ) Then Return start Return 0 End Parse Value Range( Length( s ), start, len ) With first last If first > last Then Return 0 Return ScanSet( s, ref, first, last, option == "M" ) /******************************************************************************/ /* */ /* The state functions: the program's own arguments, conditions, settings. */ /* */ /******************************************************************************/ /* ARG() -- the number of arguments of the current routine. */ /* ARG(n) -- the n-th argument, or "" if it was omitted or is beyond the count. */ /* ARG(n, option) -- E: does it exist ("1"/"0"); O: was it omitted; N: its */ /* value; A: an Array of the arguments from n on. With an option both */ /* arguments are required. */ ::Routine BIF.ARG Use Strict Arg name, args, context -- ooRexx's order: n a whole number (40.12); an option without n, 40.5; n -- positive (40.14); then the option's first character, one of AENO -- (40.904 with the whole option). checklist = "oWHOLE>0 oSTR" If args~hasIndex(2) Then checklist = "rWHOLE>0 rSTR" a = CheckArgs( name, args, context, checklist ) If \ a~hasIndex(1) Then Return context~argCount If a~hasIndex(2) Then Do option = Upper( Left( a[2], 1 ) ) If option == "" | Pos( option, "AENO" ) == 0 Then Call BifError "40.904", name, 2, "AENO", a[2] a[2] = option End which = a[1] If which > context~argCount Then v = .Nil -- beyond the count Else v = context~argValue( which ) option = "N" If a~hasIndex(2) Then option = a[2] Select When option == "N" Then Do If v == .Nil Then Return "" -- An object (of the RVM) is itself. If \ v~isA( .String ), \ v~isA( .RVM.Number ) Then Return v Return str( v ) End When option == "E" Then Return ( v \== .Nil )~?( "1", "0" ) When option == "O" Then Return ( v == .Nil )~?( "1", "0" ) -- An Array of the arguments from n on (omitted ones are holes; none -- beyond the count: an empty one), as ooRexx's new_array. When option == "A" Then Do list = .Array~new Do i = which To context~argCount v = context~argValue( i ) If v \== .Nil Then list[ i - which + 1 ] = v End Return context~world~newArray( list ) End End /* CONDITION([option]) -- the condition trapped in this activation (or */ /* inherited from the caller): C its name, D its description, I the trapping */ /* instruction (the default), S the current state of its trap (ON, OFF or */ /* DELAY), E the SYNTAX error subcode, R forget it (returns ""). Without a */ /* condition every option gives "". A and O (objects) are the context's. */ ::Routine BIF.CONDITION Use Strict Arg name, args, context a = CheckArgs( name, args, context, "oSTR" ) option = "I" -- The first character of the option, one of ACDEIORS (40.904 with the -- whole option, as ooRexx). If a~hasIndex(1) Then Do option = Upper( Left( a[1], 1 ) ) If option == "" | Pos( option, "ACDEIORS" ) == 0 Then Call BifError "40.904", name, 1, "ACDEIORS", a[1] End info = context~condition If option == "R" Then Do context~condition = .Nil Return "" End If option == "O" Then Return context~conditionObject( info ) If option == "A" Then Return context~conditionAdditional( info ) If info == .Nil Then Return "" Select When option == "C" Then Return info~condition When option == "D" Then Return info~description When option == "I" Then Return info~instruction When option == "E" Then Return info~extra When option == "S" Then Return context~trapState( info~condition ) End ::Routine BIF.ADDRESS Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return context~address ::Routine BIF.QUEUED Use Strict Arg name, args, context a = CheckArgs( name, args, context ) -- .STDQUE's QUEUED, when someone could tell (RVM.World~queueTarget). target = context~queueTarget If target \== .Nil Then Return .RVM.BifSend~new( target, "QUEUED", .Array~new, "" ) Return context~queued -- RXQUEUE(option [, name]): the messages ooRexx's function sends (to .STDQUE: -- GET, SET; to the RexxQueue class: CREATE, OPEN, EXISTS, DELETE), sent by -- the machine (RVM.BifSend). The name must be a symbol (40.26). ::Routine BIF.RXQUEUE Use Strict Arg name, args, context a = CheckArgs( name, args, context, "rANY oANY" ) option = Upper( Left( a[1], 1 ) ) If option == "" | Pos( option, "CDEGOS" ) == 0 Then Call BifError 40.904, name, 1, "CDEGOS", a[1] world = context~world world~ensureLocal stdque = world~local~native[ "STDQUE" ] cls = world~prelude~classObjs[ "REXXQUEUE" ] If option == "G" Then Do If a~hasIndex( 2 ) Then Call BifError 40.4, name, 1 Return .RVM.BifSend~new( stdque, "GET", .Array~new, "" ) End If option == "C", \ a~hasIndex( 2 ) Then Return .RVM.BifSend~new( cls, "CREATE", .Array~new, "" ) If \ a~hasIndex( 2 ) Then Call BifError 40.3, name, 2 q = a[2] If \ IsSymbol( q ) | Length( q ) > 250 Then Call BifError "40.26/2", name, q Select Case option When "C" Then message = "CREATE" When "S" Then Return .RVM.BifSend~new( stdque, "SET", .Array~of( q ), "" ) When "O" Then message = "OPEN" When "E" Then message = "EXISTS" When "D" Then message = "DELETE" End Return .RVM.BifSend~new( cls, message, .Array~of( q ), "" ) ::Routine BIF.DIGITS Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return context~digits ::Routine BIF.FUZZ Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return context~fuzz ::Routine BIF.FORM Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return context~form /******************************************************************************/ /* */ /* The arithmetic functions. They work at the numeric settings of the caller: */ /* CheckArgs hands over every NUM argument already as a Number rounded to the */ /* caller's DIGITS and laid out in its FORM (trailing zeros kept: ABS(-1.50) */ /* is 1.50). */ /* */ /******************************************************************************/ /* ABS(number) -- the number without its sign. */ ::Routine BIF.ABS Use Strict Arg name, args, context a = CheckArgs( name, args, context ) n = a[1] If n~sign >= 0 Then Return n~string ctx = .RVM.Number~ctxWith( context~digits, 0, context~form ) Return .RVM.Number~fromPartsSigned( 1, n~digits, n~exp, ctx )~string /* MAX(number, ...) / MIN(number, ...) -- the largest / smallest, compared */ /* like the '<' operator (at DIGITS-FUZZ); among equal ones, the first. */ ::Routine BIF.MAX Use Strict Arg name, args, context Return MaxMin( name, args, context, 1 ) ::Routine BIF.MIN Use Strict Arg name, args, context Return MaxMin( name, args, context, -1 ) ::Routine MaxMin Use Strict Arg name, args, context, wanted a = CheckArgs( name, args, context ) ctx = .RVM.Number~ctxWith( context~digits, context~fuzz, context~form ) best = a[1] Do i = 2 To a~items If a[i]~compare( best, ctx ) == wanted Then best = a[i] End Return best~string /* TRUNC(number [, n]) -- the number with exactly n decimal digits (default */ /* 0), the rest cut off, never in exponential form. As ooRexx does it: the */ /* number (already rounded to DIGITS) is cut on its digits, so TRUNC(1E20) is */ /* 100000000000000000000 at any DIGITS; and when only zeros are left the sign */ /* goes (TRUNC(-0.5) is 0, TRUNC(-0.001, 2) is 0.00). The standard's */ /* (10**n * number) % 1 would raise 26.11 on the first and loses the second. */ ::Routine BIF.TRUNC Use Strict Arg name, args, context a = CheckArgs( name, args, context ) n = a[1] decimals = 0 If a~hasIndex(2) Then decimals = a[2] -- The integer and fractional digits of the number. If n~sign == 0 Then Do int = "0" frac = "" End Else Do d = n~digits e = n~exp len = Length( d ) Select When e >= 0 Then Do int = d || Copies( "0", e ) frac = "" End When len + e > 0 Then Do int = Left( d, len + e ) frac = Substr( d, len + e + 1 ) End Otherwise int = "0" frac = Copies( "0", -e - len ) || d End End -- Exactly 'decimals' fractional digits: cut, or padded with zeros. If decimals <= Length( frac ) Then frac = Left( frac, decimals ) Else frac = frac || Copies( "0", decimals - Length( frac ) ) out = int If decimals > 0 Then out = out"."frac -- The sign stays only if some digit that is left is not zero. If n~sign < 0, int \== "0" | Verify( frac, "0" ) > 0 Then out = "-"out Return out /* FORMAT: no room for the integer part (argument 2) or the exponent (4): */ /* 40.38; ooRexx's method gives 93.942 or 93.941, naming the number as it is */ /* at that point (rounded; the mantissa) and the room. */ ::Routine FormatRoom Use Strict Arg argNumber, name, n, sign, digits, exp, room, context working = .RVM.Number~fromParts( sign, digits, exp, context )~string If argNumber == 2 Then method = .Array~of( "93.942", working, room ) Else method = .Array~of( "93.941", working, room ) Call BifMethodError method, 40.38, name, argNumber, n~string /* FORMAT(number [, before] [, after] [, expp] [, expt]) -- the number laid */ /* out in 'before' characters for the integer part (sign included), 'after' */ /* decimals (rounded), 'expp' digits of exponent (0: never exponential) and */ /* with exponential notation when the integer part would need more than */ /* 'expt' digits (default DIGITS) or the number is very small. A port of */ /* ooRexx's NumberString::formatInternal, which is what decides the results */ /* (rounding at 'after' can switch to, or keep, exponential notation: bug */ /* #1474). Not enough room in 'before' or 'expp' is 40.38. */ ::Routine BIF.FORMAT Use Strict Arg name, args, context a = CheckArgs( name, args, context ) n = a[1] integers = -1; decimals = -1; mathexp = -1; trigger = context~digits If a~hasIndex(2) Then integers = a[2] If a~hasIndex(3) Then decimals = a[3] If a~hasIndex(4) Then mathexp = a[4] If a~hasIndex(5) Then trigger = a[5] engineering = ( context~form == "ENGINEERING" ) -- The number: sign, digits (a string of digit characters), exponent. If n~sign == 0 Then Do sign = 0; digits = "0"; exp = 0 End Else Do sign = n~sign; digits = n~digits; exp = n~exp End count = Length( digits ) showExp = 0; shownExp = 0; expSize = 0; leadExpZeros = 0 leadingSpaces = 0; integerDigits = 0; trailingIntegerZeros = 0 leadingDecimalZeros = 0; decimalDigits = 0; decimalSpace = 0 trailingDecimalZeros = 0 -- Exponential notation, unless expp is explicitly 0. If mathexp \= 0 Then Do adjusted = exp + count - 1 If adjusted >= trigger | ( adjusted < 0 & Abs( exp ) > trigger * 2 ) Then Do showExp = 1 If engineering Then Do If adjusted < 0 Then adjusted -= 2 adjusted = ( adjusted % 3 ) * 3 End exp -= adjusted shownExp = adjusted expSize = Length( Abs( shownExp ) ) If mathexp \= -1 Then Do leadExpZeros = mathexp - expSize If expSize > mathexp Then Call FormatRoom 4, name, n, sign, Left( digits, count ), exp, mathexp, context End End End If decimals == -1 Then Do -- As many decimals as the number has. If exp < 0 Then Do decimalDigits = -exp If decimalDigits > count Then Do leadingDecimalZeros = decimalDigits - count decimalDigits = count End decimalSpace = decimalDigits + leadingDecimalZeros End End Else Do If exp < 0 Then Do adjDecimals = -exp If adjDecimals > decimals Then Do -- More decimals than requested: round. adjDecimals = adjDecimals - decimals exp = exp + adjDecimals If adjDecimals >= count Then Do -- Every digit goes: a single digit is left, 1 or 0. If adjDecimals == count & Left( digits, 1 ) >= 5 Then digits = "1" Else Do digits = "0"; exp = 0; sign = 0 End count = 1 End Else Do -- Some digits go: round on the first one dropped. next = Substr( digits, count - adjDecimals + 1, 1 ) count = count - adjDecimals digits = Left( digits, count ) If next >= 5 Then Do If Verify( digits, "9" ) == 0 Then Do -- a carry out digits = "1"Copies( "0", count - 1 ) exp += 1 End Else Do -- no carry out: fits k = LastNonNine( digits ) digits = Left( digits, k - 1 ) - || ( Substr( digits, k, 1 ) + 1 ) - || Copies( "0", count - k ) End End -- Redo the exponent decision on the rounded number, keeping it on -- if it was on (bug #1474). wasShown = showExp If mathexp \= 0 & shownExp \= 0 Then Do exp += shownExp shownExp = 0 expSize = 1 showExp = 0 End adjusted = exp + count - 1 If wasShown | ( mathexp \= 0 & ( adjusted >= trigger | - ( adjusted < 0 & Abs( exp ) > trigger * 2 ) ) ) Then Do showExp = 1 If engineering Then Do If adjusted < 0 Then adjusted -= 2 adjusted = ( adjusted % 3 ) * 3 End exp -= adjusted shownExp = adjusted expSize = Length( Abs( shownExp ) ) If mathexp \= -1 Then Do leadExpZeros = mathexp - expSize If expSize > mathexp Then Call FormatRoom 4, name, n, sign, Left( digits, count ), exp, mathexp, context End End End End -- The decimal part, now that the number will not change any more. adjDecimals = -exp If adjDecimals > count Then Do leadingDecimalZeros = adjDecimals - count decimalDigits = count End Else decimalDigits = adjDecimals If adjDecimals > decimals Then Do adjDecimals = decimals decimalDigits = decimals End trailingDecimalZeros = decimals - adjDecimals End Else trailingDecimalZeros = decimals decimalSpace = decimalDigits + leadingDecimalZeros + trailingDecimalZeros End -- The integer part. needed = count + exp If needed <= 0 Then Do needed = 1 integerDigits = 0 trailingIntegerZeros = 1 End Else Do integerDigits = needed If needed > count Then Do integerDigits = count trailingIntegerZeros = needed - count End End If integers \= -1 Then Do room = integers If sign < 0 Then room -= 1 -- the sign takes one If room < needed Then Call FormatRoom 2, name, n, sign, Left( digits, count ), exp, integers, context leadingSpaces = room - needed End -- Put it together. out = .MutableBuffer~new out~append( Copies( " ", leadingSpaces ) ) If sign < 0 Then out~append( "-" ) out~append( Left( digits, integerDigits ), Copies( "0", trailingIntegerZeros ) ) If decimalSpace > 0 Then out~append( ".", Copies( "0", leadingDecimalZeros ), - Substr( digits, integerDigits + 1, decimalDigits ), - Copies( "0", trailingDecimalZeros ) ) If showExp Then Do If shownExp \= 0 Then Do If shownExp < 0 Then out~append( "E-" ) Else out~append( "E+" ) out~append( Copies( "0", leadExpZeros ), Abs( shownExp ) ) End Else If mathexp \= -1 Then -- A zero exponent is shown as blanks, but only with an explicit expp. out~append( Copies( " ", leadExpZeros + expSize + 2 ) ) End Return out~string /******************************************************************************/ /* */ /* The conversion functions. Binary and hexadecimal arguments come checked by */ /* CheckArgs (BIN / HEX: digits, and blanks only between whole groups); */ /* here the blanks are dropped and the digits converted one by one: a byte */ /* is two hexadecimal digits, a hexadecimal digit four binary ones. Bytes */ /* and their values meet in AllBytes (byte k at position k+1). */ /* */ /******************************************************************************/ ::Routine HexDigits Return "0123456789ABCDEF" /* s without its blanks (and tabs). */ ::Routine Unblank Use Strict Arg s out = .MutableBuffer~new Do i = 1 To Length( s ) c = Substr( s, i, 1 ) If \ IsBlank( c ) Then out~append( c ) End Return out~string /* The value, 0-15, of a hexadecimal digit, in either case. */ ::Routine HexValue Use Strict Arg c p = Pos( c, HexDigits() ) If p == 0 Then p = Pos( c, "abcdef" ) + 10 Return p - 1 /* The four binary digits of a value 0-15, and back. */ ::Routine Nibble Use Strict Arg v Return v % 8 || v % 4 // 2 || v % 2 // 2 || v // 2 ::Routine NibbleValue Use Strict Arg bits Return Substr( bits, 1, 1 ) * 8 + Substr( bits, 2, 1 ) * 4 - + Substr( bits, 3, 1 ) * 2 + Substr( bits, 4, 1 ) /* B2X(binary) -- the hexadecimal digits (upper case) of the binary string, */ /* padded on the left with zeros to a multiple of four. */ ::Routine BIF.B2X Use Strict Arg name, args, context a = CheckArgs( name, args, context ) bits = Unblank( a[1] ) extra = Length( bits ) // 4 If extra > 0 Then bits = Copies( "0", 4 - extra ) || bits hex = HexDigits() out = .MutableBuffer~new Do i = 1 To Length( bits ) By 4 out~append( Substr( hex, NibbleValue( Substr( bits, i, 4 ) ) + 1, 1 ) ) End Return out~string /* X2B(hex) -- four binary digits per hexadecimal digit. */ ::Routine BIF.X2B Use Strict Arg name, args, context a = CheckArgs( name, args, context ) digits = Unblank( a[1] ) out = .MutableBuffer~new Do i = 1 To Length( digits ) out~append( Nibble( HexValue( Substr( digits, i, 1 ) ) ) ) End Return out~string /* C2X(string) -- two hexadecimal digits (upper case) per byte. */ ::Routine BIF.C2X Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ) bytes = AllBytes() hex = HexDigits() out = .MutableBuffer~new Do i = 1 To Length( s ) v = Pos( Substr( s, i, 1 ), bytes ) - 1 out~append( Substr( hex, v % 16 + 1, 1 ), Substr( hex, v // 16 + 1, 1 ) ) End Return out~string /* X2C(hex) -- one byte per two hexadecimal digits, the digits padded on the */ /* left with a zero to an even count. */ ::Routine BIF.X2C Use Strict Arg name, args, context a = CheckArgs( name, args, context ) digits = Unblank( a[1] ) If Length( digits ) // 2 == 1 Then digits = "0"digits bytes = AllBytes() out = .MutableBuffer~new Do i = 1 To Length( digits ) By 2 v = HexValue( Substr( digits, i, 1 ) ) * 16 + HexValue( Substr( digits, i + 1, 1 ) ) out~append( Substr( bytes, v + 1, 1 ) ) End Return out~string /* The hexadecimal digits of a whole number m >= 0 (no leading zeros; "0" for */ /* zero). The caller has set NUMERIC DIGITS wide enough for m. */ ::Routine HexOf Use Strict Arg m Numeric Digits Max( Length( m ) + 2, 20 ) hex = HexDigits() out = "" Loop Until m == 0 out = Substr( hex, m // 16 + 1, 1 ) || out m = m % 16 End Return out /* The value of a string of hexadecimal digits (no blanks), exact. */ ::Routine ValueOfHex Use Strict Arg digits Numeric Digits Max( 2 * Length( digits ) + 5, 20 ) v = 0 Do i = 1 To Length( digits ) v = v * 16 + HexValue( Substr( digits, i, 1 ) ) End Return v /* D2X(whole [, length]) / D2C(whole [, length]) -- the hexadecimal digits, */ /* or the bytes, of a whole number at the caller's DIGITS. With a length the */ /* result has exactly that many digits (bytes), cut on the left or extended */ /* with 0 (00x) or, for a negative number (two's complement), F (FFx); */ /* without one a negative number is 40.13 (CheckArgs, type D2). */ ::Routine BIF.D2X Use Strict Arg name, args, context Return D2XD2C( name, args, context, 1 ) ::Routine BIF.D2C Use Strict Arg name, args, context Return D2XD2C( name, args, context, 2 ) ::Routine D2XD2C Use Strict Arg name, args, context, perUnit -- hex digits per unit a = CheckArgs( name, args, context ) n = a[1] negative = ( Left( n, 1 ) == "-" ) If negative Then n = Substr( n, 2 ) hex = HexOf( n ) If negative Then Do -- Two's complement in as many digits: invert each digit of m - 1. Numeric Digits Length( n ) + 2 minus1 = HexOf( n - 1 ) minus1 = Copies( "0", Length( hex ) - Length( minus1 ) ) || minus1 digitsHex = HexDigits() hex = "" Do i = 1 To Length( minus1 ) hex = hex || Substr( digitsHex, 16 - HexValue( Substr( minus1, i, 1 ) ), 1 ) End End If a~hasIndex(2) Then Do size = a[2] * perUnit If size <= Length( hex ) Then hex = Right( hex, size ) Else Do pad = "0"; If negative Then pad = "F" hex = Copies( pad, size - Length( hex ) ) || hex End End If perUnit == 1 Then Return hex Return X2CDigits( hex ) /* The bytes of a string of hexadecimal digits (padded with a leading zero to */ /* an even count). */ ::Routine X2CDigits Use Strict Arg digits If Length( digits ) // 2 == 1 Then digits = "0"digits bytes = AllBytes() out = .MutableBuffer~new Do i = 1 To Length( digits ) By 2 v = HexValue( Substr( digits, i, 1 ) ) * 16 + HexValue( Substr( digits, i + 1, 1 ) ) out~append( Substr( bytes, v + 1, 1 ) ) End Return out~string /* X2D(hex [, length]) / C2D(string [, length]) -- the whole number the */ /* digits (bytes) stand for: unsigned without a length; with one, the */ /* rightmost 'length' digits (bytes), padded on the left with zeros, as a two's */ /* complement number. More digits than NUMERIC DIGITS is 40.35. */ ::Routine BIF.X2D Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return X2DC2D( name, a, Unblank( a[1] ), 1, context ) ::Routine BIF.C2D Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return X2DC2D( name, a, BIF.C2X( "C2X", .Array~of( a[1] ), context ), 2, context ) ::Routine X2DC2D Use Strict Arg name, a, hex, perUnit, context negative = 0 If a~hasIndex(2) Then Do size = a[2] * perUnit If size == 0 Then Return 0 If size <= Length( hex ) Then Do hex = Right( hex, size ) negative = ( HexValue( Left( hex, 1 ) ) >= 8 ) End Else hex = Copies( "0", size - Length( hex ) ) || hex End -- The magnitude: m, or 16**k - m when negative (invert, add one). If negative Then Do digitsHex = HexDigits() inverted = "" Do i = 1 To Length( hex ) inverted = inverted || Substr( digitsHex, 16 - HexValue( Substr( hex, i, 1 ) ), 1 ) End hex = inverted End -- Leading zeros do not count; beyond DIGITS decimal digits is an error -- (k significant hex digits make at least 1.2 * (k - 1) + 1 decimal ones). p = Verify( hex, "0" ) If p == 0 Then hex = "" Else hex = Substr( hex, p ) If Length( hex ) > context~digits + 2 Then Call BifError 40.35, name, a[1] m = ValueOfHex( hex ) Numeric Digits Length( hex ) * 2 + 5 If negative Then m = m + 1 If Length( m ) > context~digits Then Call BifError 40.35, name, a[1] If negative Then Return "-"m Return m /* BITAND / BITOR / BITXOR(string1 [, string2] [, pad]) -- byte by byte, bit */ /* by bit. With a pad the shorter string is extended with it; without one the */ /* rest of the longer string is appended as it is. string2 defaults to "". */ ::Routine BIF.BITAND Use Strict Arg name, args, context Return BitOp( name, args, context, "AND" ) ::Routine BIF.BITOR Use Strict Arg name, args, context Return BitOp( name, args, context, "OR" ) ::Routine BIF.BITXOR Use Strict Arg name, args, context Return BitOp( name, args, context, "XOR" ) ::Routine BitOp Use Strict Arg name, args, context, op a = CheckArgs( name, args, context ) s1 = str( a[1] ) s2 = "" If a~hasIndex(2) Then s2 = str( a[2] ) If a~hasIndex(3) Then Do If Length( s1 ) > Length( s2 ) Then s2 = PadSlice( s2, 1, Length( s1 ), a[3] ) Else s1 = PadSlice( s1, 1, Length( s2 ), a[3] ) End If Length( s1 ) < Length( s2 ) Then Do t = s1; s1 = s2; s2 = t End bytes = AllBytes() out = .MutableBuffer~new Do i = 1 To Length( s2 ) x = Pos( Substr( s1, i, 1 ), bytes ) - 1 y = Pos( Substr( s2, i, 1 ), bytes ) - 1 v = 0 Do k = 7 To 0 By -1 bit = 2 ** k bx = x % bit; x = x // bit by = y % bit; y = y // bit Select When op == "AND" Then b = bx & by When op == "OR" Then b = bx | by Otherwise b = bx && by End v = v + b * bit End out~append( Substr( bytes, v + 1, 1 ) ) End out~append( Tail( s1, Length( s2 ) + 1 ) ) Return out~string /* XRANGE([start] [, end] ...) -- ooRexx's form: the arguments are read left */ /* to right as pieces, all concatenated. A piece is a character class name */ /* (ALNUM ALPHA BLANK CNTRL DIGIT GRAPH LOWER PRINT PUNCT SPACE UPPER XDIGIT, */ /* any case: one argument), or a range: a start byte (default '00'x) and the */ /* next argument, an end byte (default 'FF'x), wrapping past 'FF'x. With no */ /* arguments, all 256 bytes. The standard's XRANGE is the one-range case. */ /* Errors: a start neither one character nor a class name 40.28, an end not */ /* one character 40.23. */ ::Routine BIF.XRANGE Use Strict Arg name, args, context a = CheckArgs( name, args, context ) bytes = AllBytes() out = .MutableBuffer~new If a~isEmpty Then numArgs = 0 Else numArgs = a~last i = 0 Loop Until i >= numArgs i += 1 start = 0; last = 255 If a~hasIndex( i ) Then Do first = str( a[i] ) If Length( first ) \== 1 Then Do out~append( CharClass( first, i ) ) Iterate End start = Pos( first, bytes ) - 1 End i += 1 If a~hasIndex( i ) Then Do second = str( a[i] ) If Length( second ) \== 1 Then Call BifError 40.23, name, i, second last = Pos( second, bytes ) - 1 End If last >= start Then out~append( Substr( bytes, start + 1, last - start + 1 ) ) Else out~append( Substr( bytes, start + 1 ), Left( bytes, last + 1 ) ) End Return out~string /* The bytes of a POSIX character class, in ascending order. */ ::Routine CharClass Use Strict Arg className, argPos upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lower = "abcdefghijklmnopqrstuvwxyz" digits = "0123456789" punct = "!""#$%&'()*+,-./:;<=>?@[\]^_`{|}~" graph = "!""#$%&'()*+,-./" || digits || ":;<=>?@" || upper || "[\]^_`" || lower || "{|}~" cntrl = Left( AllBytes(), 32 ) || "7F"x Select Case Upper( className ) When "ALNUM" Then Return digits || upper || lower When "ALPHA" Then Return upper || lower When "BLANK" Then Return "09 20"x When "CNTRL" Then Return cntrl When "DIGIT" Then Return digits When "GRAPH" Then Return graph When "LOWER" Then Return lower When "PRINT" Then Return " " || graph When "PUNCT" Then Return punct When "SPACE" Then Return "09 0A 0B 0C 0D 20"x When "UPPER" Then Return upper When "XDIGIT" Then Return digits || "ABCDEFabcdef" Otherwise Call BifError "40.28/CLASS", "XRANGE", argPos, className End /* DATATYPE(string [, type]) -- without a type NUM or CHAR; with one, 1 or 0. */ /* Types (rexxref 7.4.23): Alphanumeric, Binary, Internal whole number (at */ /* WholeDigits), Lowercase, Mixed case, Number, lOgical ("0" or "1"), Symbol, */ /* Uppercase, Variable (a symbol that can be assigned: not a constant one), */ /* Whole number (at DIGITS), heXadecimal, 9 (whole at 9 digits). The null */ /* string is 0 for every type but B and X. Numbers and whole numbers are the */ /* ones CheckArgs accepts (NumberValue / WholeValue). */ ::Routine BIF.DATATYPE Use Strict Arg name, args, context a = CheckArgs( name, args, context ) s = str( a[1] ) If \ a~hasIndex(2) Then Do If IsNumber( s, context ) Then Return "NUM" Return "CHAR" End type = a[2] If s == "" Then Return ( type == "B" | type == "X" )~?( "1", "0" ) upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" lower = "abcdefghijklmnopqrstuvwxyz" Select When type == "A" Then r = Verify( s, upper || lower || "0123456789" ) == 0 When type == "B" Then r = IsBinaryString( s ) When type == "I" Then r = WholeValue( s, .RVM.Number~WholeDigits ) \== .Nil When type == "L" Then r = Verify( s, lower ) == 0 When type == "M" Then r = Verify( s, upper || lower ) == 0 When type == "N" Then r = IsNumber( s, context ) When type == "O" Then r = ( s == "0" | s == "1" ) When type == "S" Then r = IsSymbol( s ) When type == "U" Then r = Verify( s, upper ) == 0 When type == "V" Then r = IsSymbol( s ) & Pos( Left( s, 1 ), "0123456789." ) == 0 When type == "W" Then r = WholeValue( s, context~digits ) \== .Nil When type == "X" Then r = IsHexString( s ) When type == "9" Then r = WholeValue( s, 9 ) \== .Nil End Return r~?( "1", "0" ) /* A number, as NUM arguments are: .Nil and "E" (exponent too big) are not. */ ::Routine IsNumber Use Strict Arg s, context n = NumberValue( s, context~digits, context~form ) Return n \== .Nil & \ n~isA( .String ) /******************************************************************************/ /* */ /* Variables named by a string: SYMBOL and VALUE. */ /* */ /******************************************************************************/ /* NameRef(name, context) -- what a name given as a string refers to, as an */ /* Array: ("BAD") not a symbol; ("CONST", value) a constant or environment */ /* symbol (its value is the name in upper case); ("SIMPLE", NAME); */ /* ("STEM", "NAME."); ("COMPOUND", "NAME.", tail), the tail derived as in the */ /* program: each component that starts with a digit is itself (upper case), */ /* any other is replaced by the value of that variable, verbatim. */ ::Routine NameRef Public Use Strict Arg name, context If \ IsSymbol( name ) Then Return .Array~of( "BAD" ) up = Upper( name ) If Pos( Left( up, 1 ), "0123456789." ) > 0 Then Return .Array~of( "CONST", up ) dot = Pos( ".", up ) If dot == 0 Then Return .Array~of( "SIMPLE", up ) stemKey = Left( up, dot ) If dot == Length( up ) Then Return .Array~of( "STEM", stemKey ) tail = "" rest = Substr( up, dot + 1 ) Loop p = Pos( ".", rest ) If p == 0 Then component = rest Else Do component = Left( rest, p - 1 ) rest = Substr( rest, p + 1 ) End If component \== "", Pos( Left( component, 1 ), "0123456789" ) == 0 Then component = str( context~getVar( component ) ) tail = tail || component If p == 0 Then Leave tail = tail || "." End Return .Array~of( "COMPOUND", stemKey, tail ) /* SYMBOL(name) -- BAD if name is not a symbol; VAR if it is a variable that */ /* has a value (a stem: that exists); LIT otherwise (constant symbols too). */ /* As in ooRexx, asking about a compound variable creates its stem. */ ::Routine BIF.SYMBOL Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return SymbolState( str( a[1] ), context ) /* VAR(name) -- 1 when SYMBOL(name) would be VAR, else 0 (a name that is not */ /* a symbol is simply 0). Asking about a compound variable creates its stem, */ /* as with SYMBOL. */ ::Routine BIF.VAR Use Strict Arg name, args, context a = CheckArgs( name, args, context, "rANY" ) Return ( SymbolState( str( a[1] ), context ) == "VAR" ) + 0 /* BAD, LIT or VAR, for SYMBOL and VAR. */ ::Routine SymbolState Use Strict Arg s, context ref = NameRef( s, context ) Select Case ref[1] When "BAD" Then Return "BAD" When "CONST" Then Return "LIT" When "SIMPLE" Then has = context~isSet( ref[2] ) When "STEM" Then has = context~stemObject( ref[2] ) \== .Nil When "COMPOUND" Then has = context~lookupCompound( ref[2], ref[3] ) \== .Nil End Return has~?( "VAR", "LIT" ) /* VALUE(name [, newvalue] [, selector]) -- the value of the variable 'name' */ /* (never NOVALUE), then, with a newvalue, assign it. 'name' must be a symbol */ /* (40.26), and a variable to be assigned (40.26 too, as ooRexx). Selector */ /* ENVIRONMENT (any case): the process environment variables, through the */ /* host (the standard's Config_Get / Config_Set); '' is ooRexx's global */ /* .environment; any other selector is 40.914. */ ::Routine BIF.VALUE Use Strict Arg name, args, context If args~hasIndex(3) Then Do a = CheckArgs( name, args, context, "rANY oANY oANY" ) -- (3 is there) selector = str( a[3] ) If Upper( selector ) == "ENVIRONMENT" Then Do var = str( a[1] ) -- .nil removes the variable (ooRexx's setEnvironmentVariable). If a~hasIndex(2), a[2]~class~id == "RVM.OBJ" Then If a[2]~identityHash == context~world~nil~identityHash Then Return .RVM.SystemHost~setEnv( var, .Nil ) -- The new value as ooRexx's stringArgument has it (requestString: a -- string, or what answers REQUEST STRING); none is 88.909. If a~hasIndex(2) Then Do new = a[2] If new~class~id == "RVM.OBJ" Then Do s = new~requestString If s == .Nil Then Raise Syntax 88.909 Array( 2 ) new = s End Return .RVM.SystemHost~setEnv( var, str( new ) ) End Return Value( var, , "ENVIRONMENT" ) End -- '': .environment (ooRexx's TheEnvironment~entry and setEntry): the -- entry (any object), or .NAME when there is none; then the new value. If selector == "" Then Do env = context~world~environment~native key = Upper( str( a[1] ) ) old = env[ key ] If old == .Nil Then old = "."key If a~hasIndex(2) Then env[ key ] = a[2] Return old End Raise Syntax 40.914 Array( selector ) End a = CheckArgs( name, args, context, "rSYM oANY" ) ref = NameRef( str( a[1] ), context ) Select Case ref[1] -- A symbol that starts with a period and is not a number is an -- environment symbol (ooRexx's getVariableRetriever: a RexxDotVariable). When "CONST" Then Do If DotSymbol( ref[2] ) Then old = context~dotValue( ref[2] ) Else old = ref[2] End When "SIMPLE" Then old = context~getVar( ref[2] ) When "STEM" Then old = context~getStem( ref[2] ) When "COMPOUND" Then old = context~getCompound( ref[2], ref[3] ) End If a~hasIndex(2) Then Do new = a[2] Select Case ref[1] When "CONST" Then Call BifError 40.26, name, str( a[1] ) When "SIMPLE" Then context~setVar( ref[2], new ) When "STEM" Then context~setStem( ref[2], new ) When "COMPOUND" Then context~setCompound( ref[2], ref[3], new ) End End Return old /* Is the symbol 'up' (upper case) an environment symbol: a period, then */ /* something that makes it no number? */ ::Routine DotSymbol Use Strict Arg up If Length( up ) < 2 | Left( up, 1 ) \== "." Then Return .False Parse Var up mantissa "E" exponent If mantissa == "." | Verify( mantissa, "0123456789." ) > 0 Then Return .True If CountStr( ".", mantissa ) > 1 Then Return .True If Pos( "E", up ) == 0 Then Return .False If Pos( Left( exponent, 1 ), "+-" ) > 0 Then exponent = SubStr( exponent, 2 ) If exponent == "" | Verify( exponent, "0123456789" ) > 0 Then Return .True Return .False /* SOURCELINE([n]) -- without n, the number of lines of the program (0 when */ /* the source is not available); with n, line n. n beyond the last line is */ /* 40.34. */ ::Routine BIF.SOURCELINE Use Strict Arg name, args, context a = CheckArgs( name, args, context ) lines = context~sourceLines count = 0 If lines \== .Nil Then count = lines~items If \ a~hasIndex(1) Then Return count If a[1] > count Then Call BifError 40.34, name, a[1], count Return lines[ a[1] ] /* ERRORTEXT(n) -- the message of error n, a whole number 0-99 (ooRexx's */ /* range: the standard's is 0:90 with a decimal part); "" when n is not an */ /* error number. The texts are the configuration's: the host's. Out of range */ /* is ooRexx's 40.903 (no standard code says 0-99). */ ::Routine BIF.ERRORTEXT Use Strict Arg name, args, context a = CheckArgs( name, args, context, "rWHOLE" ) If a[1] < 0 | a[1] > 99 Then Call BifError 40.903, name, 1, a[1] Return ErrorText( a[1] ) /******************************************************************************/ /* */ /* RANDOM -- ooRexx's generator, bit for bit, so that a seed gives the same */ /* sequence as in ooRexx (portability). A 64-bit linear congruential */ /* generator: */ /* */ /* next(s) = (s * 25214903917 + 11) mod 2**64 */ /* */ /* A seed s sets the state to next^13(NOT s) (all 64 bits flipped: supplied */ /* seeds are small numbers, mostly zero bits). EVERY call, with a range or */ /* not, then advances the state once and draws from the new state: its 64 */ /* bits reversed, modulo the size of the range, added to the minimum. */ /* The state belongs to the activation, as in ooRexx: the program, each */ /* method and each external routine have their own; internal routines and */ /* INTERPRET use their caller's (see RVM.BaseContext~randomSeed). Without a */ /* seed it starts from an unpredictable value. */ /* */ /******************************************************************************/ /* RANDOM([min] [, [max] [, seed]]) -- ooRexx's argument rules: with only one */ /* argument, it is the MAXIMUM; min and max default to 0 and 999; max - min */ /* at most 999,999,999 (ooRexx's limit, 40.32; the standard's is 100000); */ /* max < min is 40.33. min and max are any whole numbers, seed >= 0. */ ::Routine BIF.RANDOM Use Strict Arg name, args, context a = CheckArgs( name, args, context, "oWHOLE oWHOLE oWHOLE>=0" ) Numeric Digits 40 -- 64-bit products: up to 31 digits state = context~randomSeed If a~hasIndex(3) Then Do state = RandomNot( a[3] ) Do 13 state = RandomNext( state ) End End Else If state == .Nil Then state = RandomInitialSeed() state = RandomNext( state ) context~randomSeed = state minimum = 0 maximum = 999 If a~hasIndex(1) Then Do -- Alone (no max, no seed: RANDOM(n), RANDOM(n,,)), it is the maximum. If \ a~hasIndex(2), \ a~hasIndex(3) Then maximum = a[1] Else Do minimum = a[1] If a~hasIndex(2) Then maximum = a[2] End End Else If a~hasIndex(2) Then maximum = a[2] -- The inserts are the arguments as given (normalised), "" when omitted. ins1 = ""; If a~hasIndex(1) Then ins1 = a[1] ins2 = ""; If a~hasIndex(2) Then ins2 = a[2] If maximum < minimum Then Call BifError 40.33, name, ins1, ins2 If maximum - minimum > 999999999 Then Call BifError "40.32/RANDOM", name, ins1, ins2 If minimum = maximum Then Return minimum + 0 Return minimum + RandomReverse( state ) // ( maximum - minimum + 1 ) /* s * 25214903917 + 11, modulo 2**64. */ ::Routine RandomNext Use Strict Arg s Numeric Digits 40 Return ( s * 25214903917 + 11 ) // 18446744073709551616 /* The 64 bits of s flipped. */ ::Routine RandomNot Use Strict Arg s Numeric Digits 40 Return 18446744073709551615 - s /* The 64 bits of s in reverse order: bit 0 becomes bit 63. */ ::Routine RandomReverse Use Strict Arg s Numeric Digits 40 work = 0 Do 64 work = work * 2 + s // 2 s = s % 2 End Return work /* An unpredictable 64-bit state: four 16-bit draws from the host. */ ::Routine RandomInitialSeed Numeric Digits 40 s = 0 Do 4 s = s * 65536 + Random( 0, 65535 ) End Return s /******************************************************************************/ /* */ /* DATE and TIME -- the clock */ /* */ /* A time is one number: the microseconds since 0001-01-01 00:00:00.000000, */ /* local time, in the proleptic Gregorian calendar (ooRexx's DATE('F')). Only */ /* the current one comes from the host (HostNow); every field, name and */ /* conversion is computed here. All the DATE and TIME of a clause see the */ /* same time: the context keeps it for the clause (see RVM.BaseContext). */ /* */ /******************************************************************************/ /* The time of the current clause, taken from the host the first time. */ /* (ooRexx's RexxActivation::getTime: a TIME('R') waiting to take effect */ /* restarts the elapsed clock at the time of ITS clause -- the stale stamp */ /* -- just before a new one is taken.) */ ::Routine ClauseTime Use Strict Arg context clock = context~clock If \ clock~valid Then Do If clock~elapsedReset Then Do clock~elapsedStart = clock~stamp - clock~offset clock~elapsedReset = .False End now = HostNow() -- The virtual clock (RVM_CLOCK=virtual) moves the time on. sched = context~world~scheduler If sched \== .Nil Then now[1] = now[1] + sched~skipped clock~stamp = now[1] clock~offset = now[2] clock~valid = .True End Return clock~stamp /* The host's clock: now, local time, as microseconds since 0001-01-01, and */ /* the local offset from UTC, in microseconds. */ ::Routine HostNow Numeric Digits 20 d = .DateTime~new Return .Array~of( d~fullDate, d~fullDate - d~utcDate ) /* DaysFromCivil(y, m, d) : the days from 0001-01-01 to that date. (Counted */ /* from 0000-03-01, so that the leap day is the last of the year.) */ ::Routine DaysFromCivil Use Strict Arg y, m, d If m <= 2 Then Do; y = y - 1; m = m + 9; End Else m = m - 3 era = y % 400 -- y >= 0 here yoe = y - era * 400 doy = ( 153 * m + 2 ) % 5 + d - 1 doe = yoe * 365 + yoe % 4 - yoe % 100 + doy Return era * 146097 + doe - 306 /* CivilFromDays(days) : the date that many days after 0001-01-01, as an */ /* Array (year, month, day). */ ::Routine CivilFromDays Use Strict Arg days z = days + 306 era = z % 146097 doe = z - era * 146097 yoe = ( doe - doe % 1460 + doe % 36524 - doe % 146096 ) % 365 y = yoe + era * 400 doy = doe - ( 365 * yoe + yoe % 4 - yoe % 100 ) mp = ( 5 * doy + 2 ) % 153 d = doy - ( 153 * mp + 2 ) % 5 + 1 If mp < 10 Then m = mp + 3 Else Do; m = mp - 9; y = y + 1; End Return .Array~of( y, m, d ) ::Routine MonthName Use Strict Arg m Return Word( "January February March April May June July August" - "September October November December", m ) ::Routine WeekDayName Use Strict Arg n -- 0 = Monday Return Word( "Monday Tuesday Wednesday Thursday Friday Saturday Sunday", n + 1 ) /* Zero-padded to n digits. */ ::Routine Pad0 Use Strict Arg v, n Return Right( v, n, "0" ) /* DATE([option] [, [indate] [, [option2] [, [osep] [, isep]]]]) */ /* ooRexx's DATE, checked in ooRexx's order: an empty option is 40.904; an */ /* option2 or isep without indate 40.5; osep only for E I N O S U (40.44), */ /* one character that is not a letter or a digit, or null (40.43); an */ /* unknown option is 40.904, but only after all of that. Only the first */ /* character of an option counts. */ ::Routine BIF.DATE Use Strict Arg name, args, context a = CheckArgs( name, args, context, "oANY oANY oANY oANY oANY" ) outList = "BDEFILMNOSTUW" style = "N" If a~hasIndex(1) Then Do option = str( a[1] ) If option == "" Then Call BifError "40.904", name, 1, outList, option style = Upper( Left( option, 1 ) ) End If \ a~hasIndex(2), ( a~hasIndex(3) | a~hasIndex(5) ) Then Call BifError 40.5, name, 2 inList = "BDEFINOSTU" style2 = "N" If a~hasIndex(3) Then Do option2 = str( a[3] ) If option2 == "" Then Call BifError "40.904", name, 3, inList, option2 style2 = Upper( Left( option2, 1 ) ) End osep = .Nil If a~hasIndex(4) Then Do If Pos( style, "EINOSU" ) == 0 Then Call BifError 40.44, name, 1, style, 4 osep = str( a[4] ) If \ IsDateSeparator( osep ) Then Call BifError 40.43, name, 4, osep osep = CString( osep ) -- ooRexx writes it as a C string End full = ClauseTime( context ) If a~hasIndex(2) Then full = DateInput( name, str( a[2] ), style2, a, full ) days = full % 86400000000 ymd = CivilFromDays( days ) y = ymd[1]; m = ymd[2]; d = ymd[3] Select Case style When "B" Then Return days When "D" Then Return days - DaysFromCivil( y, 1, 1 ) + 1 When "F" Then Return full When "T" Then Return ( full - DaysFromCivil( 1970, 1, 1 ) * 86400000000 ) % 1000000 When "E" Then Return DateJoin( osep, "/", Pad0( d, 2 ), Pad0( m, 2 ), Pad0( y // 100, 2 ) ) When "I" Then Return DateJoin( osep, "-", Pad0( y, 4 ), Pad0( m, 2 ), Pad0( d, 2 ) ) When "L" Then Return d MonthName( m ) Pad0( y, 4 ) When "M" Then Return MonthName( m ) When "N" Then Return DateJoin( osep, " ", d, Left( MonthName( m ), 3 ), Pad0( y, 4 ) ) When "O" Then Return DateJoin( osep, "/", Pad0( y // 100, 2 ), Pad0( m, 2 ), Pad0( d, 2 ) ) When "S" Then Return DateJoin( osep, "", Pad0( y, 4 ), Pad0( m, 2 ), Pad0( d, 2 ) ) When "U" Then Return DateJoin( osep, "/", Pad0( m, 2 ), Pad0( d, 2 ), Pad0( y // 100, 2 ) ) When "W" Then Return WeekDayName( days // 7 ) -- 0001-01-01 was a Monday Otherwise Call BifError "40.904", name, 1, outList, style End /* DateInput(bif, indate, style2, args, now) : the time DATE's argument 2 */ /* stands for, read in the format style2 (ooRexx's order of checks: isep */ /* first, 40.44 for B D F L M T W, 40.43 when not a separator; then the */ /* date; 40.19 when it does not read, or 40.44 when isep was given). */ /* */ /* B and D are whole numbers at 9 digits (ooRexx's numberValue, whatever */ /* the caller's DIGITS); F and T whole numbers at 20 digits within 64 */ /* bits (objectToInt64). The formats with fields are read by */ /* ParseDateTime, a port of ooRexx's parseDateTimeFormat. */ /* */ /* Two deliberate departures from ooRexx 5.3, both bugs there: */ /* - DATE(, 0, 'D') is accepted by ooRexx and makes a month 0 (a garbage */ /* date, and DATE('M') on it crashes the interpreter); here it is */ /* 40.19, like any other day of the year that does not exist; */ /* - T values beyond about 9.2E12 seconds overflow ooRexx's 64-bit */ /* arithmetic and wrap to some other date; here they are 40.19 (out of */ /* range, as they are). */ ::Routine DateInput Use Strict Arg bif, indate, style2, a, now sep = .Nil If a~hasIndex(5) Then Do If Pos( style2, "BDFLMTW" ) > 0 Then Call BifError 40.44, bif, 3, style2, 5 sep = str( a[5] ) If \ IsDateSeparator( sep ) Then Call BifError 40.43, bif, 5, sep sep = CString( sep ) End maxFull = 315537897599999999 -- 9999-12-31 23:59:59.999999 unixBase = 62135596800000000 -- 1970-01-01, in microseconds curYear = CivilFromDays( now % 86400000000 )[1] text = CString( indate ) -- what ooRexx's parsers see full = .Nil Select Case style2 When "N" Then full = FieldsTime( ParseDateTime( text, "DD/MMM/YYYY", Default( sep, " " ), 0 ) ) When "E" Then full = FieldsTime( ParseDateTime( text, "dd/mm/yy", Default( sep, "/" ), curYear ) ) When "O" Then full = FieldsTime( ParseDateTime( text, "yy/mm/dd", Default( sep, "/" ), curYear ) ) When "U" Then full = FieldsTime( ParseDateTime( text, "mm/dd/yy", Default( sep, "/" ), curYear ) ) When "I" Then full = FieldsTime( ParseDateTime( text, "YYYY/mm/dd", Default( sep, "-" ), 0 ) ) When "S" Then full = FieldsTime( ParseDateTime( text, "YYYY/mm/dd", Default( sep, "" ), 0 ) ) When "B" Then Do w = WholeValue( indate, 9 ) If w \== .Nil, w >= 0, w <= maxFull % 86400000000 Then full = w * 86400000000 End When "D" Then Do w = WholeValue( indate, 9 ) yearDays = 365 + IsLeap( curYear ) If w \== .Nil, w >= 1, w <= yearDays Then full = ( DaysFromCivil( curYear, 1, 1 ) + w - 1 ) * 86400000000 End When "F" Then Do w = Int64Value( indate ) If w \== .Nil, w >= 0, w <= maxFull Then full = w End When "T" Then Do w = Int64Value( indate ) If w \== .Nil Then Do f = w * 1000000 + unixBase If f >= 0, f <= maxFull Then full = f End End Otherwise Call BifError "40.904", bif, 3, "BDEFINOSTU", style2 End If full == .Nil Then Do If a~hasIndex(5) Then Call BifError 40.44, bif, 2, indate, 5 Call BifError 40.19, bif, indate, style2 End Return full /* A 64-bit whole number, as ooRexx's objectToInt64 reads it: whole at 20 */ /* digits, and within -2**63 .. 2**63-1; .Nil otherwise. */ ::Routine Int64Value Use Strict Arg s Numeric Digits 40 w = WholeValue( s, 20 ) If w == .Nil Then Return .Nil If w > 9223372036854775807 | w < -9223372036854775808 Then Return .Nil Return w ::Routine IsLeap Use Strict Arg y Return y // 4 == 0 & ( y // 100 \== 0 | y // 400 == 0 ) ::Routine Default Use Strict Arg v, d If v == .Nil Then Return d Return v /* A string as C sees it: up to its first NUL. (ooRexx hands DATE's and */ /* TIME's strings to C, so "20260923"||"00"x||"junk" reads as 20260923, */ /* and a separator "00"x is a null one.) */ ::Routine CString Use Strict Arg s p = Pos( "00"x, s ) If p == 0 Then Return s Return Left( s, p - 1 ) /* The time the fields of ParseDateTime stand for, or .Nil. */ ::Routine FieldsTime Use Strict Arg f If f == .Nil Then Return .Nil Numeric Digits 20 days = DaysFromCivil( f~year, f~month, f~day ) Return ( ( days * 24 + f~hours ) * 60 + f~minutes ) * 60000000 + - f~seconds * 1000000 + f~micro /* ParseDateTime(text, format, sep, currentYear) : a port of ooRexx's */ /* RexxDateTime::parseDateTimeFormat. The fields read from text by the */ /* format, as a Directory (year month day hours minutes seconds micro), */ /* or .Nil when text does not match it. Format letters: */ /* m two-digit month (<= 12) d two-digit day */ /* D day of one or two digits y two-digit year, windowed on */ /* Y four-digit year currentYear (-50 .. +49) */ /* M a month's first three letters, as in "Sep" (case counts) */ /* H two-digit hour (<= 23) c civil hour, one or two digits */ /* i two-digit minutes (<= 59) (<= 12) */ /* s two-digit seconds (<= 59) C "am" or "pm" */ /* u microseconds, 1 to 6 digits : . themselves */ /* / the separator sep (nothing, when sep is null) */ /* The format may be longer than the text (D and c take one digit), never */ /* shorter; nothing may be left over; the date must exist. */ ::Routine ParseDateTime Public Use Strict Arg text, format, sep, currentYear f = .Directory~new f~day = 1; f~month = 1; f~year = 1 f~hours = 0; f~minutes = 0; f~seconds = 0; f~micro = 0 If Length( format ) < Length( text ) Then Return .Nil ip = 1; fp = 1 Loop While fp <= Length( format ) c = Substr( format, fp, 1 ) Select Case c When "m" Then Do v = DigitsAt( text, ip, 2 ); If v == .Nil Then Return .Nil; If v > 12 Then Return .Nil f~month = v; ip += 2; fp += 2 End When "d" Then Do v = DigitsAt( text, ip, 2 ); If v == .Nil Then Return .Nil f~day = v; ip += 2; fp += 2 End When "D", "c" Then Do n = 1 If IsDigitChar( CharAt( text, ip + 1 ) ) Then n = 2 v = DigitsAt( text, ip, n ); If v == .Nil Then Return .Nil If c == "D" Then f~day = v Else Do If v > 12 Then Return .Nil f~hours = v End ip += n; fp += 2 End When "H" Then Do v = DigitsAt( text, ip, 2 ); If v == .Nil Then Return .Nil; If v > 23 Then Return .Nil f~hours = v; ip += 2; fp += 2 End When "i" Then Do v = DigitsAt( text, ip, 2 ); If v == .Nil Then Return .Nil; If v > 59 Then Return .Nil f~minutes = v; ip += 2; fp += 2 End When "s" Then Do v = DigitsAt( text, ip, 2 ); If v == .Nil Then Return .Nil; If v > 59 Then Return .Nil f~seconds = v; ip += 2; fp += 2 End When "u" Then Do n = Min( 6, Max( 1, Length( text ) - ip + 1 ) ) v = DigitsAt( text, ip, n ); If v == .Nil Then Return .Nil f~micro = v * 10 ** ( 6 - n ); ip += n; fp += 6 End When "y" Then Do v = DigitsAt( text, ip, 2 ); If v == .Nil Then Return .Nil y = v + ( currentYear % 100 ) * 100 If y < currentYear Then Do If currentYear - y > 50 Then y += 100 End Else If y - currentYear > 49 Then y -= 100 f~year = y; ip += 2; fp += 2 End When "Y" Then Do v = DigitsAt( text, ip, 4 ); If v == .Nil Then Return .Nil f~year = v; ip += 4; fp += 4 End When "M" Then Do abbr = Substr( text, ip, 3 ) f~month = 0 Do k = 1 To 12 If Left( MonthName( k ), 3 ) == abbr Then Do; f~month = k; Leave; End End If f~month == 0 Then Return .Nil ip += 3; fp += 3 End When "C" Then Do mer = Substr( text, ip, 2 ) Select When mer == "am" Then If f~hours == 12 Then f~hours = 0 When mer == "pm" Then If f~hours \== 12 Then f~hours += 12 Otherwise Return .Nil End ip += 2; fp += 2 End When "/" Then Do If sep \== "" Then Do If CharAt( text, ip ) \== sep Then Return .Nil ip += 1 End fp += 1 End When ":", "." Then Do If CharAt( text, ip ) \== c Then Return .Nil ip += 1; fp += 1 End Otherwise Return .Nil End End If ip <= Length( text ) Then Return .Nil If f~day == 0 | f~month == 0 | f~year == 0 Then Return .Nil maxDay = Word( "31 28 31 30 31 30 31 31 30 31 30 31", f~month ) If f~month == 2, IsLeap( f~year ) Then maxDay = 29 If f~day > maxDay Then Return .Nil Return f /* The character at position p, or "" past the end (C's terminator). */ ::Routine CharAt Use Strict Arg s, p If p > Length( s ) Then Return "" Return Substr( s, p, 1 ) ::Routine IsDigitChar Use Strict Arg c Return c \== "" & Pos( c, "0123456789" ) > 0 /* n decimal digits at position p of s, as a number, or .Nil. */ ::Routine DigitsAt Use Strict Arg s, p, n v = 0 Do k = 0 To n - 1 c = CharAt( s, p + k ) If \ IsDigitChar( c ) Then Return .Nil v = v * 10 + c End Return v /* TIME([option] [, [intime] [, option2]]) -- ooRexx's TIME. Options, only */ /* the first character: C E F H L M N O R S T (40.904 for an empty or an */ /* unknown one, the unknown one only at the end); option2 without intime */ /* is 40.5. E and R read the elapsed-time clock (see RVM.Clock): its */ /* first reading starts it (and is 0); R also restarts it, at the time of */ /* this clause, from the next clause that takes a time on. A clock that */ /* reads negative (the local time went back) is 0 and restarts. */ ::Routine BIF.TIME Use Strict Arg name, args, context a = CheckArgs( name, args, context, "oANY oANY oANY" ) Numeric Digits 20 style = "N" If a~hasIndex(1) Then Do option = str( a[1] ) If option == "" Then Call BifError "40.904", name, 1, "CEFHLMNORST", option style = Upper( Left( option, 1 ) ) End style2 = "N" If a~hasIndex(3) Then Do If \ a~hasIndex(2) Then Call BifError 40.5, name, 2 option2 = str( a[3] ) If option2 == "" Then Call BifError "40.904", name, 3, "CFHLMNOST", option2 style2 = Upper( Left( option2, 1 ) ) End full = ClauseTime( context ) clock = context~clock offset = clock~offset If a~hasIndex(2) Then Do If style == "E" | style == "R" Then Call BifError 40.29, name, style conv = TimeInput( name, str( a[2] ), style2, full, offset ) full = conv[1] offset = conv[2] End -- Microseconds into the day. Floored: a time read as H, M or S has no date -- (see TimeInput), and lies before 0001-01-01. day = full % 86400000000 If full < 0, full // 86400000000 \= 0 Then day = day - 1 inDay = full - day * 86400000000 secs = inDay % 1000000 micro = inDay // 1000000 h = secs % 3600 m = secs // 3600 % 60 s = secs // 60 Select Case style When "E", "R" Then Do If clock~elapsedStart == 0 Then clock~elapsedStart = full - offset spent = ( full - offset ) - clock~elapsedStart Select When spent < 0 Then Do out = 0 clock~elapsedReset = .True End When spent == 0 Then out = 0 Otherwise out = spent % 1000000"."Pad0( spent // 1000000, 6 ) End If style == "R" Then clock~elapsedReset = .True Return out End When "C" Then Do ch = h If ch == 0 Then ch = 12 Else If ch > 12 Then ch = ch - 12 If h >= 12 Then Return ch":"Pad0( m, 2 )"pm" Return ch":"Pad0( m, 2 )"am" End When "H" Then Return h When "L" Then Return Pad0( h, 2 )":"Pad0( m, 2 )":"Pad0( s, 2 )"."Pad0( micro, 6 ) When "M" Then Return h * 60 + m When "N" Then Return Pad0( h, 2 )":"Pad0( m, 2 )":"Pad0( s, 2 ) When "S" Then Return secs When "F" Then Return full When "T" Then Return ( full - 62135596800000000 ) % 1000000 When "O" Then Return offset Otherwise Call BifError "40.904", name, 1, "CEFHLMNORST", style End /* TimeInput(bif, intime, style2, now, offset) : the time TIME's argument 2 */ /* stands for, read in the format style2, and its UTC offset, as an Array. */ /* 40.19 when it does not read; 40.904 for an unknown style2. */ /* */ /* As in ooRexx: */ /* - N, C and L read a time on 0001-01-01 (so TIME('F') of it is the time */ /* alone); */ /* - H, M and S (whole numbers at 9 digits, within the day) leave the */ /* date empty: year, month and day 0, which ooRexx's arithmetic makes */ /* day -366 (TIME('F', 5, 'H') is -31604400000000). That comes from */ /* reading one entry before a table in C, so another build of ooRexx */ /* may say something else; this is what 5.3 on Linux says; */ /* - F and T as in DATE; O takes the clause's time to another offset, by */ /* ooRexx's formula (local + current offset - new offset), and keeps */ /* the time unchanged when that falls out of range. */ ::Routine TimeInput Use Strict Arg bif, intime, style2, now, offset Numeric Digits 20 maxFull = 315537897599999999 unixBase = 62135596800000000 noDate = -366 * 86400000000 -- year, month and day 0 text = CString( intime ) full = .Nil Select Case style2 When "N" Then full = FieldsTime( ParseDateTime( text, "HH:ii:ss", "", 0 ) ) When "C" Then full = FieldsTime( ParseDateTime( text, "cc:iiCC", "", 0 ) ) When "L" Then full = FieldsTime( ParseDateTime( text, "HH:ii:ss.uuuuuu", "", 0 ) ) When "H", "M", "S" Then Do w = WholeValue( intime, 9 ) unit = Word( "3600 60 1", Pos( style2, "HMS" ) ) limit = 86400 / unit If w \== .Nil, w >= 0, w < limit Then full = noDate + w * unit * 1000000 End When "F" Then Do w = Int64Value( intime ) If w \== .Nil, w >= 0, w <= maxFull Then full = w End When "T" Then Do w = Int64Value( intime ) If w \== .Nil Then Do f = w * 1000000 + unixBase If f >= 0, f <= maxFull Then full = f End End When "O" Then Do w = Int64Value( intime ) If w \== .Nil Then Do full = now moved = now + offset - w If moved >= 0, moved <= maxFull Then full = moved offset = w End End Otherwise Call BifError "40.904", bif, 3, "CFHLMNOST", style2 End If full == .Nil Then Call BifError 40.19, bif, intime, style2 Return .Array~of( full, offset ) /* A date separator: null, or one character that is not a letter or a digit */ /* (ASCII, as ooRexx checks it). */ ::Routine IsDateSeparator Use Strict Arg sep If sep == "" Then Return .True If Length( sep ) > 1 Then Return .False -- ooRexx looks the character up with C's strchr, which also finds the -- string's terminating NUL: "00"x counts as alphanumeric, and is refused. Return Pos( sep, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"||"00"x ) == 0 /* Three fields joined by the separator given (osep, .Nil when none) or else */ /* by the format's own. */ ::Routine DateJoin Use Strict Arg osep, default, f1, f2, f3 If osep == .Nil Then osep = default Return f1 || osep || f2 || osep || f3 /* The position of the last digit that is not a 9 (there is one). */ ::Routine LastNonNine Use Strict Arg digits Do k = Length( digits ) To 1 By -1 If Substr( digits, k, 1 ) \== "9" Then Return k End Return 0 /* SIGN(number) -- -1, 0 or 1. */ ::Routine BIF.SIGN Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return a[1]~sign /******************************************************************************/ /* */ /* Streams: CHARIN CHAROUT CHARS LINEIN LINEOUT LINES STREAM */ /* */ /* The name is resolved in the activation's stream table (see RVM.Stream): */ /* the null name is the default input or output stream. The work is done by */ /* the stream; a NOTREADY condition ends it early with the function's value */ /* for that case ("" for CHARIN and LINEIN, the characters not written for */ /* CHAROUT, 1 for LINEOUT, 0 for CHARS and LINES). The name QUEUE: stands for */ /* the external data queue with the line functions (LINEIN is .STDQUE's */ /* LINEIN, LINEOUT queues, LINES counts); the character functions cannot use */ /* it. */ /* */ /* ooRexx's functions send the stream object the method of their name */ /* (BuiltinFunctions.cpp: stream->sendMessage(CHARIN, position, count)), so */ /* after their own checks (a whole number, 40.12) the errors are those of the */ /* methods of Stream: the arguments converted as the API converts them */ /* (MethodStreamArgs: int64_t, size_t, 88.907), then the stream's (93.907, */ /* 93.958, 93.914, 93.0: RVM.Stream~error). */ /* */ /******************************************************************************/ -- The position and count arguments (from argument 2 on) as the methods of -- Stream take them: 'kinds' has one letter per argument, P an int64_t, S a -- size_t, - none; numbered as the method's arguments. ::Routine MethodStreamArgs Use Strict Arg a, kinds Do i = 1 To Length( kinds ) If \ a~hasIndex( i + 1 ) Then Iterate Select Case SubStr( kinds, i, 1 ) When "P" Then a[ i + 1 ] = Int64Arg( a[ i + 1 ], i ) When "S" Then a[ i + 1 ] = SizeArg( a[ i + 1 ], i ) Otherwise Nop End End -- An int64_t / size_t argument of a native method (ooRexx's API): a whole -- number in its range, else 88.907. ::Routine Int64Arg Public Use Strict Arg v, position Numeric Digits 30 s = str( v ) ok = DataType( s, "W" ) If ok Then ok = ( s >= -9223372036854775808 & s <= 9223372036854775807 ) If \ ok Then Raise Syntax 88.907 Array( position, "-9223372036854775808", - "9223372036854775807", s ) Return s / 1 ::Routine SizeArg Public Use Strict Arg v, position Numeric Digits 30 s = str( v ) ok = DataType( s, "W" ) If ok Then ok = ( s >= 0 & s <= 18446744073709551615 ) If \ ok Then Raise Syntax 88.907 Array( position, "0", "18446744073709551615", s ) Return s / 1 -- The stream table of the current activation (see -- RVM.BaseContext~activeStreams). ::Routine Streams Use Strict Arg context Return context~activeStreams( .RVM.StreamTable ) -- QUEUE: (in any case) is the external data queue, not a stream. ::Routine IsQueueName Use Strict Arg a If \ a~hasIndex(1) Then Return .False Return Upper( a[1] ) == "QUEUE:" ::Routine StreamName Use Strict Arg a If a~hasIndex(1) Then Return a[1] Return "" -- The null name, STDIN, STDOUT and STDERR are .LOCAL's INPUT, OUTPUT and -- ERROR (ooRexx's resolveStream): the object to send the function's message -- to, or .Nil (the host's streams, straight: see RVM.Context~localTarget). ::Routine LocalStream Use Strict Arg a, input, context n = Upper( StreamName( a ) ) Select When n == "" Then which = input~?( "INPUT", "OUTPUT" ) When n == "STDIN" | n == "STDIN:" Then which = "INPUT" When n == "STDOUT" | n == "STDOUT:" Then which = "OUTPUT" When n == "STDERR" | n == "STDERR:" Then which = "ERROR" Otherwise Return .Nil End Return context~localTarget( which ) -- A file stream, when the activation has a security manager: one not asked -- about in the activation's scope (RVM.BaseContext~streamScope) is asked -- about (STREAM, with the name qualified: ooRexx's resolveStream); the -- stream object it gives (STREAM) is kept for the name, and the function -- sends its message to it. The RVM's stream is remembered when 'add' (the -- function keeps it). The object kept, or .Nil. ::Routine SecureStream Use Strict Arg a, context, add = .True If context~secMgr == .Nil Then Return .Nil n = StreamName( a ) If n == "" Then Return .Nil If WordPos( Upper( n ), "STDIN STDIN: STDOUT STDOUT: STDERR STDERR:" ) > 0 Then Return .Nil key = .RVM.FileSystem~qualify( n ) scope = context~streamScope If scope == .Nil Then Do scope = .StringTable~new context~streamScope = scope End If scope~hasIndex( key ) Then Do obj = scope[ key ] If obj == "" Then Return .Nil Return obj End info = context~world~security( context~secMgr, "STREAM", .Array~of( "NAME", key ) ) obj = .Nil If info \== .Nil Then obj = info["STREAM"] If obj \== .Nil Then scope[ key ] = obj Else If add Then scope[ key ] = "" Return obj -- A stream closed (or not opened): its name is asked about again. ::Routine SecureForget Use Strict Arg n, context If context~streamScope == .Nil Then Return context~streamScope~remove( .RVM.FileSystem~qualify( n ) ) -- The message of a stream function to .LOCAL's object (target), with the -- arguments from 'from' on (those omitted, omitted): what the function -- returns, for the machine to send (its result is the function's; 'post' -- LINESN makes it 1 or 0, as ooRexx's LINES does). ::Routine LocalSend Use Strict Arg target, message, a, from, context, post = "" args = .Array~new last = a~last If last == .Nil Then last = 0 Do i = from To last If a~hasIndex( i ) Then args[ i - from + 1 ] = a[i] End Return .RVM.BifSend~new( target, message, args, post ) -- A message a built-in function sends (see LocalSend): the machine sends it -- from the instruction (RVM.Machine, FUNCB and CALLB), or now (result). ::Class RVM.BifSend Public ::Attribute target ::Attribute message ::Attribute args ::Attribute post ::Method init Expose target message args post Use Strict Arg target, message, args, post -- Its result, when the message has been sent. ::Method finish Class Use Strict Arg v, post If post == "LINESN", v \== .Nil Then If v~isA( .String ) | v~isA( .RVM.Number ) Then Do s = str( v ) If DataType( s, "W" ) Then Return ( s \= 0 )~?( "1", "0" ) End Return v -- Sent now (see RVM.Machine~sendSync): its result. ::Method result Expose target message args post Use Strict Arg context v = context~world~loader~sendSync( target, message, args ) Return self~class~finish( v, post ) ::Routine BIF.CHARIN Use Strict Arg name, args, context a = CheckArgs( name, args, context, "oSTREAM oWHOLE oWHOLE" ) If IsQueueName( a ) Then Call BifError 40.915, name target = LocalStream( a, .True, context ) If target \== .Nil Then Return LocalSend( target, "CHARIN", a, 2, context ) target = SecureStream( a, context ) If target \== .Nil Then Return LocalSend( target, "CHARIN", a, 2, context ) stream = Streams( context )~resolve( StreamName( a ), .True, .True ) Call MethodStreamArgs a, "PS" count = 1 If a~hasIndex(3) Then count = a[3] stream~opArgs = a~section( 2 ) Return stream~charinOp( context, name, a~hasIndex(2), a[2], count ) ::Routine BIF.CHAROUT Use Strict Arg name, args, context a = CheckArgs( name, args, context, "oSTREAM oANY oWHOLE" ) If IsQueueName( a ) Then Call BifError 40.915, name target = LocalStream( a, .False, context ) If target \== .Nil Then Return LocalSend( target, "CHAROUT", a, 2, context ) target = SecureStream( a, context ) If target \== .Nil Then Return LocalSend( target, "CHAROUT", a, 2, context ) stream = Streams( context )~resolve( StreamName( a ), .False, .True ) Call MethodStreamArgs a, "-P" data = .Nil If a~hasIndex(2) Then data = a[2] stream~opArgs = a~section( 2 ) Return stream~charoutOp( context, name, data, a~hasIndex(3), a[3] ) ::Routine BIF.CHARS Use Strict Arg name, args, context a = CheckArgs( name, args, context ) If IsQueueName( a ) Then Call BifError 40.915, name target = LocalStream( a, .True, context ) If target \== .Nil Then Return LocalSend( target, "CHARS", a, 2, context ) target = SecureStream( a, context ) If target \== .Nil Then Return LocalSend( target, "CHARS", a, 2, context ) stream = Streams( context )~resolve( StreamName( a ), .True, .True ) stream~opArgs = .Array~new Return stream~charsOp( context, name ) + 0 ::Routine BIF.LINEIN Use Strict Arg name, args, context a = CheckArgs( name, args, context, "oSTREAM oWHOLE oWHOLE" ) -- QUEUE: is .STDQUE's LINEIN (no arguments): it waits for a line. If IsQueueName( a ) Then Do world = context~world world~ensureLocal Return .RVM.BifSend~new( world~local~native[ "STDQUE" ], "LINEIN", .Array~new, "" ) End target = LocalStream( a, .True, context ) If target \== .Nil Then Return LocalSend( target, "LINEIN", a, 2, context ) target = SecureStream( a, context ) If target \== .Nil Then Return LocalSend( target, "LINEIN", a, 2, context ) stream = Streams( context )~resolve( StreamName( a ), .True, .True ) Call MethodStreamArgs a, "PS" count = 1 If a~hasIndex(3) Then count = a[3] stream~opArgs = a~section( 2 ) Return stream~lineinOp( context, name, a~hasIndex(2), a[2], count ) ::Routine BIF.LINEOUT Use Strict Arg name, args, context a = CheckArgs( name, args, context, "oSTREAM oANY oWHOLE" ) -- QUEUE: is .STDQUE's QUEUE (straight when no one could tell). If IsQueueName( a ) Then Do If \ a~hasIndex(2) Then Return 0 target = context~queueTarget( .True ) If target \== .Nil Then Return .RVM.BifSend~new( target, "QUEUE", .Array~of( a[2] ), "" ) context~queueLine( a[2] ) Return 0 End target = LocalStream( a, .False, context ) If target \== .Nil Then Return LocalSend( target, "LINEOUT", a, 2, context ) target = SecureStream( a, context ) If target \== .Nil Then Return LocalSend( target, "LINEOUT", a, 2, context ) streams = Streams( context ) stream = streams~resolve( StreamName( a ), .False, .True ) Call MethodStreamArgs a, "-P" data = .Nil If a~hasIndex(2) Then data = a[2] stream~opArgs = a~section( 2 ) r = stream~lineoutOp( context, name, data, a~hasIndex(3), a[3] ) -- LINEOUT(name) closes the stream: it is forgotten. If \ a~hasIndex(2), \ a~hasIndex(3), StreamName( a ) \== "" Then Do streams~remove( StreamName( a ) ) Call SecureForget StreamName( a ), context End Return r -- LINES(name, 'N'), the default, is 1 or 0; LINES(name, 'C') counts. ::Routine BIF.LINES Use Strict Arg name, args, context a = CheckArgs( name, args, context, "oSTREAM oSTR" ) option = "N" -- The option's first character, C or N (40.904 with the whole option). If a~hasIndex(2) Then Do option = Upper( Left( a[2], 1 ) ) If option \== "C", option \== "N" Then Call BifError "40.904", name, 2, "CN", a[2] End -- QUEUE: is .STDQUE's QUEUED (straight when no one could tell). If IsQueueName( a ), context~queueTarget \== .Nil Then Do If option == "N" Then post = "LINESN" Else post = "" Return .RVM.BifSend~new( context~queueTarget, "QUEUED", .Array~new, post ) End If IsQueueName( a ) Then count = context~queued Else If LocalStream( a, .True, context ) \== .Nil Then Do If option == "N" Then post = "LINESN" Else post = "" Return LocalSend( LocalStream( a, .True, context ), "LINES", a, 2, context, post ) End Else If SecureStream( a, context ) \== .Nil Then Do If option == "N" Then post = "LINESN" Else post = "" Return LocalSend( SecureStream( a, context ), "LINES", a, 2, context, post ) End Else Do stream = Streams( context )~resolve( StreamName( a ), .True, .True ) If a~hasIndex(2) Then stream~opArgs = .Array~of( a[2] ) Else stream~opArgs = .Array~of( "NORMAL" ) count = stream~linesOp( context, name, option == "N" ) End If option == "N", count \= 0 Then Return 1 Return count + 0 -- STREAM(name [, 'S' | 'D' | 'C', command]): the state, its description, or -- (option C) the result of a stream command. ::Routine BIF.STREAM Use Strict Arg name, args, context a = CheckArgs( name, args, context, "rSTREAM oSTR oANY" ) If a[1] == "" Then Call BifError 40.27, name, a[1] option = "S" -- The option's first character, one of SDC (40.904 with the whole option). If a~hasIndex(2) Then Do option = Upper( Left( a[2], 1 ) ) If option == "" | Pos( option, "SDC" ) == 0 | a[2] == "" Then Call BifError "40.904", name, 2, "SDC", a[2] End If option \== "C", args~last > 2 Then Call BifError 40.4, name, 2 If option == "C", args~last < 3 Then Call BifError 40.3, name, 3 target = LocalStream( a, .True, context ) If target == .Nil Then Do add = .False If option == "C" Then Do w = Upper( a[3] ) add = WordPos( "OPEN", w ) + WordPos( "CLOSE", w ) + WordPos( "SEEK", w ) + - WordPos( "POSITION", w ) > 0 End target = SecureStream( a, context, add ) End If target \== .Nil Then Select Case option When "S" Then Return LocalSend( target, "STATE", a, 99, context ) When "D" Then Return LocalSend( target, "DESCRIPTION", a, 99, context ) Otherwise Return LocalSend( target, "COMMAND", a, 3, context ) End Select Case option When "S" Then Return Streams( context )~resolve( a[1], .True, .False )~state When "D" Then Return Streams( context )~resolve( a[1], .True, .False )~description Otherwise Nop End -- A command. OPEN and CLOSE, SEEK and POSITION work on the stream kept for -- the name (made if needed); a failed OPEN and a CLOSE forget it. streams = Streams( context ) command = a[3] commandUpper = Upper( command ) Select When WordPos( "OPEN", commandUpper ) > 0 Then Do r = streams~resolve( a[1], .True, .True )~commandOp( context, name, command ) If r \== "READY:" Then Do streams~remove( a[1] ) Call SecureForget a[1], context End Return r End When WordPos( "CLOSE", commandUpper ) > 0 Then Do r = streams~resolve( a[1], .True, .True )~commandOp( context, name, command ) streams~remove( a[1] ) Call SecureForget a[1], context Return r End When WordPos( "SEEK", commandUpper ) > 0 | WordPos( "POSITION", commandUpper ) > 0 Then Return streams~resolve( a[1], .True, .True )~commandOp( context, name, command ) Otherwise Return streams~resolve( a[1], .True, .False )~commandOp( context, name, command ) End /* QUALIFY(name) -- the name a stream is known by: absolute, with "~", "." */ /* and ".." resolved, whether it exists or not ("" for the null name). */ ::Routine BIF.QUALIFY Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return .RVM.FileSystem~qualify( str( a[1] ) ) /******************************************************************************/ /* */ /* FILESPEC(option, filespec) -- a part of a file specification: D(rive), */ /* L(ocation: drive and path), P(ath), N(ame), E(xtension, without the dot). */ /* The path ends at the last path separator; the drive (where the platform */ /* has drives) runs up to the first colon. The extension is what follows the */ /* last dot of the name ("" when the name has none). As in ooRexx, the */ /* specification is read as a C string: up to its first NUL. */ /* */ /******************************************************************************/ ::Routine BIF.FILESPEC Use Strict Arg name, args, context -- ooRexx runs it as a native routine (InternalPackage.cpp's sysFilespec, -- two CSTRINGs): 88.9xx; an unknown option is 40.904 with its first -- character. a = RoutineArgs( args, "rSTR rSTR" ) first = Left( a[1], Min( Length( a[1] ), 1 ) ) option = Upper( first ) If option == "" | Pos( option, "DELNP" ) == 0 Then Call BifError "40.904", name, 1, "DELNP", first a[1] = option spec = a[2] fs = .RVM.FileSystem pathStart = 1 If fs~hasDrives Then pathStart = Pos( ":", spec ) + 1 lastSep = 0 Do c Over fs~pathSeparators~makeArray( "" ) lastSep = Max( lastSep, LastPos( c, spec ) ) End If lastSep == 0 Then pathEnd = pathStart -- just past the path Else pathEnd = lastSep + 1 Select Case a[1] When "D" Then Return Left( spec, pathStart - 1 ) When "L" Then Return Left( spec, pathEnd - 1 ) When "P" Then Return SubStr( spec, pathStart, Max( pathEnd - pathStart, 0 ) ) When "N" Then Return SubStr( spec, pathEnd ) Otherwise Do -- E dot = LastPos( ".", spec ) If dot >= pathEnd, dot > 0 Then Return SubStr( spec, dot + 1 ) Return "" End End /******************************************************************************/ /* */ /* The process: DIRECTORY USERID BEEP GC SETLOCAL ENDLOCAL (see */ /* RVM.SystemHost). */ /* */ /******************************************************************************/ /* DIRECTORY([dir]) -- change to dir (qualified first), then the current */ /* directory; "" when dir cannot be made current. */ ::Routine BIF.DIRECTORY Use Strict Arg name, args, context -- ooRexx runs it as a native routine (sysDirectory, an OPTIONAL_CSTRING). a = RoutineArgs( args, "oSTR" ) If a~hasIndex(1) Then Do dir = .RVM.FileSystem~qualify( str( a[1] ) ) If dir == "" Then Return "" If \ .RVM.SystemHost~changeDirectory( dir ) Then Return "" End Return .RVM.SystemHost~currentDirectory /* RXFUNCQUERY(name) -- 0 when an external function of that name is there, */ /* else 1 (ooRexx's PackageManager~queryRegisteredRoutine: the routines of */ /* the packages it has loaded, REXXUTIL among them, then those RXFUNCADD */ /* registered: see RXFUNCADD). Any case. */ ::Routine BIF.RXFUNCQUERY Use Strict Arg name, args, context a = CheckArgs( name, args, context ) If RexxUtilRoutine( str( a[1] ) ) \== .Nil Then Return "0" If context~world~libraryRoutine( str( a[1] ) ) \== .Nil Then Return "0" If .RVM.RexxUtil~registered~hasIndex( Upper( str( a[1] ) ) ) Then Return "0" Return "1" /* RXFUNCADD(name, module [, procedure]) -- 0 when the function can be */ /* called now, else 1 (ooRexx's PackageManager~addRegisteredRoutine). A */ /* routine already there (REXXUTIL's, a library's loaded): 0. A library of */ /* the RVM (RVMLibrary): loaded, as ::REQUIRES ... LIBRARY; 0 when it has a */ /* routine of that name (the procedure is not used, as ooRexx's for a library */ /* package), else 1. Any other module is a classic library the RVM cannot */ /* load: the name is registered (RXFUNCQUERY sees it; RXFUNCDROP drops it, */ /* once for each time it was registered, as rxapi), and 1. A call finds */ /* nothing in it (43.1, as ooRexx when it cannot resolve the function). The */ /* registration lasts as long as the process (ooRexx's is rxapi's: until it */ /* is dropped). */ ::Routine BIF.RXFUNCADD Use Strict Arg name, args, context a = CheckArgs( name, args, context ) fname = Upper( str( a[1] ) ) module = str( a[2] ) world = context~world If RexxUtilRoutine( fname ) \== .Nil Then Return "0" If world~libraryRoutine( fname ) \== .Nil Then Return "0" table = RVMLibrary( module ) If table \== .Nil Then Do world~loadLibrary( module, table ) If world~libraryRoutine( fname ) == .Nil Then Return "1" Return "0" End -- rxapi keeps every registration: as many drops as times registered. reg = .RVM.RexxUtil~registered If reg~hasIndex( fname ) Then reg[ fname ] = reg[ fname ] + 1 Else reg[ fname ] = 1 Return "1" /* RXFUNCDROP(name) -- 0 when RXFUNCADD had registered it (it is dropped), */ /* else 1: a routine of a library is not registered (ooRexx's */ /* PackageManager~dropRegisteredRoutine, rxapi's RexxDeregisterFunction). */ ::Routine BIF.RXFUNCDROP Use Strict Arg name, args, context a = CheckArgs( name, args, context ) reg = .RVM.RexxUtil~registered fname = Upper( str( a[1] ) ) If \ reg~hasIndex( fname ) Then Return "1" If reg[ fname ] > 1 Then reg[ fname ] = reg[ fname ] - 1 Else reg~remove( fname ) Return "0" /* USERID() -- the name of the user running the program. */ ::Routine BIF.USERID Use Strict Arg name, args, context a = CheckArgs( name, args, context ) Return .RVM.SystemHost~userid /* BEEP(frequency, duration) -- a sound: 37 to 32767 Hz, 0 to 60000 ms. */ /* ooRexx runs it as a native routine (InternalPackage.cpp's sysBeep, with */ /* two wholenumber_t): its errors are the routine's (88.9xx), not 40.x. */ ::Routine BIF.BEEP Use Strict Arg name, args, context a = RoutineArgs( args, "rWHOLE rWHOLE" ) If a[1] < 37 | a[1] > 32767 Then Raise Syntax 88.907 Array( "frequency", 37, 32767, a[1] ) If a[2] < 0 | a[2] > 60000 Then Raise Syntax 88.907 Array( "duration", 0, 60000, a[2] ) .RVM.SystemHost~beep( a[1], a[2] ) Return "" /* RoutineArgs(args, signature) : the arguments of a function that ooRexx */ /* runs as a native routine (BEEP, FILESPEC), converted as the API converts */ /* them (NativeActivation::processArguments), in order: an omitted required */ /* one is 88.901; rWHOLE/oWHOLE a wholenumber_t (88.907); rSTR/oSTR a */ /* CSTRING (up to its first "00"x). Too many arguments, 88.922, at the end. */ ::Routine RoutineArgs Use Strict Arg args, signature out = .Array~new n = args~last If n == .Nil Then n = 0 words = signature~makeArray( " " ) Do i = 1 To words~items word = words[i] If \ args~hasIndex( i ) Then Do If Left( word, 1 ) == "r" Then Raise Syntax 88.901 Array( i ) Iterate End v = args[i] Select Case SubStr( word, 2 ) When "WHOLE" Then Do w = .Nil If Upper( v~class~id ) \== "RVM.OBJ" Then w = nativeWhole( v ) If w == .Nil Then Raise Syntax 88.907 Array( i, "-999999999999999999", "999999999999999999", str( v ) ) out[i] = w End When "STR" Then out[i] = CString( str( v ) ) End End If n > words~items Then Raise Syntax 88.922 Array( words~items ) Return out /* GC(['F']) -- 1 when a garbage collection ran (only when forced), else 0. */ ::Routine BIF.GC Use Strict Arg name, args, context a = CheckArgs( name, args, context, "oSTR" ) If a~hasIndex(1), Pos( Left( a[1], 1 ), "fF" ) == 0 | a[1] == "" Then Call BifError "40.904", name, 1, '"force", "Force", "f", "F"', a[1] Return .RVM.SystemHost~gc( a~hasIndex(1) ) + 0 /* SETLOCAL() -- save the current directory and environment variables: 1 */ /* (0 where the platform cannot). ENDLOCAL() -- go back to the latest save: */ /* 1, or 0 when there is none. */ ::Routine BIF.SETLOCAL Use Strict Arg name, args, context a = CheckArgs( name, args, context ) If \ .RVM.SystemHost~hasLocalEnvironments Then Return 0 .RVM.SystemHost~pushLocal Return 1 ::Routine BIF.ENDLOCAL Use Strict Arg name, args, context a = CheckArgs( name, args, context ) If \ .RVM.SystemHost~hasLocalEnvironments Then Return 0 Return .RVM.SystemHost~popLocal + 0 /* TRACE([setting]) -- the current TRACE setting; with a setting, change it */ /* as the TRACE instruction does (see RVM.BaseContext~setTrace). */ ::Routine BIF.TRACE Use Strict Arg name, args, context a = CheckArgs( name, args, context, "oSTR" ) -- Checked as the instruction's setting (ooRexx's parseTraceSetting): any -- number of '?', then one of the letters (24.1 names the character). If a~hasIndex(1) Then Do letter = Strip( a[1], "L", "?" ) letter = Left( letter, Min( Length( letter ), 1 ) ) If letter \== "", Pos( Upper( letter ), "ACEFILNOR" ) == 0 Then Raise Syntax 24.1 Array( letter ) End old = context~traceSetting If a~hasIndex(1) Then context~setTrace( a[1] ) Return old