/******************************************************************************/ /* */ /* RVM.Stream.cls - Streams (the RVM's runtime) */ /* ============================================ */ /* */ /* An RVM.Stream is a named stream as the stream built-in functions see it */ /* (CHARIN, CHAROUT, CHARS, LINEIN, LINEOUT, LINES, STREAM): a read position */ /* and a write position (each a character position and, while known, a line */ /* position), an open mode, and a state (READY, NOTREADY, ERROR, UNKNOWN). */ /* It opens itself on first use when it has not been opened explicitly, and */ /* it raises the NOTREADY condition when an operation cannot be completed. */ /* STREAM(name, 'C', command) opens, closes, flushes, positions and queries */ /* it (see commandOp). */ /* */ /* Underneath there is a file (an RVM.HostFile, the platform part) that */ /* only knows bytes at offsets. On top of it, this class keeps the model of */ /* an operating-system file: ONE current offset shared by reads and writes, */ /* an end-of-file flag that stays set once an attempt to read past the end */ /* has failed, and the system error number of the last failure. */ /* */ /* RVM.StreamTable maps names to streams. As in ooRexx, the program and */ /* each method activation have a table of their own, and every other */ /* activation uses its caller's (RVM.BaseContext~activeStreams); all the */ /* tables of a run share the standard streams (see */ /* doc/13-io-and-commands.md). The null name and STDIN / STDOUT / STDERR */ /* (with or without a trailing colon, in any case) are the standard */ /* streams; every other name is qualified (see RVM.FileSystem) and that */ /* qualified name is the key. */ /* */ /* This file is part of the RVM, the Rexx Virtual Machine */ /* [See https://rexx.epbcn.com/rexx-parser/] */ /* */ /* This file is derived from the ooRexx interpreter: the streams and the */ /* methods of Stream (StreamNative.cpp, StreamCommandParser.cpp). It is */ /* therefore distributed under the Common Public License v1.0, not under the */ /* Apache License 2.0 that covers the rest of the RVM (see NOTICE). */ /* */ /* Copyright (c) 1995, 2004 IBM Corporation. All rights reserved. */ /* Copyright (c) 2005-2026 Rexx Language Association. All rights reserved. */ /* Copyright (c) 2026 Josep Maria Blasco */ /* */ /* This program and the accompanying materials are made available under the */ /* terms of the Common Public License v1.0 which accompanies this */ /* distribution. A copy is also available at the following address: */ /* https://www.oorexx.org/license.html */ /* */ /******************************************************************************/ ::Requires "RVM.Host.cls" ::Requires "RVM.BaseContext.cls" /******************************************************************************/ /* RVM.StreamTable */ /******************************************************************************/ ::Class RVM.StreamTable Public -- A new table. Its standard streams are those of 'from' (another table) -- when given: there is one STDIN, one STDOUT and one STDERR per run. ::Method init Expose table stdin stdout stderr Use Strict Arg from = .Nil table = .StringTable~new If from \== .Nil Then Do std = from~standard stdin = std[1] stdout = std[2] stderr = std[3] Return End -- The standard streams are open from the start. stdin = .RVM.Stream~new( "STDIN" )~~openStandard stdout = .RVM.Stream~new( "STDOUT" )~~openStandard stderr = .RVM.Stream~new( "STDERR" )~~openStandard -- The standard streams: an Array (STDIN, STDOUT, STDERR). ::Method standard Expose stdin stdout stderr Return .Array~of( stdin, stdout, stderr ) -- The stream a function works on. The null name is the default input stream -- (when 'input' is true) or the default output stream. A file stream seen -- for the first time is remembered only when 'add' is true. ::Method resolve Expose table stdin stdout stderr Use Strict Arg name, input, add If name == "" Then Do If input Then Return stdin Return stdout End Select Case Upper( name ) When "STDIN", "STDIN:" Then Return stdin When "STDOUT", "STDOUT:" Then Return stdout When "STDERR", "STDERR:" Then Return stderr Otherwise Nop End key = self~keyOf( name ) stream = table[ key ] If stream == .Nil Then Do stream = .RVM.Stream~new( name ) If add Then table[ key ] = stream End Return stream -- Forget a stream (after it has been closed, or when an explicit open fails). ::Method remove Expose table Use Strict Arg name table~remove( self~keyOf( name ) ) ::Method keyOf Private Use Strict Arg name key = .RVM.FileSystem~qualify( name ) If .RVM.FileSystem~caseless Then key = Upper( key ) Return key /******************************************************************************/ /* RVM.Stream */ /******************************************************************************/ ::Class RVM.Stream Public ::Constant CTRL_Z "1a"x -- an end-of-file mark, overwritten on writes ::Constant EACCES 13 ::Constant EINVAL 22 ::Constant CHUNK 4096 -- bytes read ahead from a persistent file ::Attribute name Get -- the name the stream was first used with -- The Stream object (of the REXX package) whose stream this is: made by -- RVM.World~streamObject when someone needs it (the ADDITIONAL of a -- NOTREADY, the receiver of its frames), or the one whose INIT made it. ::Attribute rexxObject -- The arguments of the Stream method a function stands for (its frame's, -- in a NOTREADY): set by the function before the operation. ::Attribute opArgs ::Method init Expose name state errorInfo errorText file thrownResult rexxObject opArgs - commandText Use Strict Arg name rexxObject = .Nil opArgs = .Array~new commandText = "" file = .Nil self~resetFields If WordPos( Upper( name ), "STDIN STDIN: STDOUT STDOUT: STDERR STDERR:" ) > 0 - Then self~setStandard state = "UNKNOWN" errorInfo = 0 errorText = "" thrownResult = "" ::Method setStandard Private Expose stdstream stdstream = .True -- A read of standard input (a terminal or a pipe: kind LINE, CHARS of -- 'count' bytes, or ALL) that would block, when the machine lets its -- activity wait (RVM.StdinReader~gate is the context, which this takes): -- an RVM.StdinNeed, and the activity waits for it while the others run (the -- operation runs again then). .Nil: the operation runs now. ::Method inputNeed Private Expose name stdstream Use Strict Arg context, kind, setPosition, count If .RVM.StdinReader~gate \== context Then Return .Nil .RVM.StdinReader~gate = .Nil If \ stdstream | setPosition | count = 0 Then Return .Nil If WordPos( Upper( name ), "STDIN STDIN:" ) == 0 Then Return .Nil If \ .RVM.StdinReader~transient Then Return .Nil If .RVM.StdinReader~has( kind, count ) Then Return .Nil Return .RVM.StdinNeed~new( kind, count ) /*----------------------------------------------------------------------------*/ /* The operations the built-in functions call. Each one takes the context */ /* (for the NOTREADY condition), the function name (for errors) and the value */ /* to return when the operation ends early with a NOTREADY condition. */ /*----------------------------------------------------------------------------*/ ::Method charinOp Expose thrownResult Use Strict Arg context, bif, setPosition, position, count need = self~inputNeed( context, "CHARS", setPosition, count ) If need \== .Nil Then Return need self~setContext( context, bif, "", "CHARIN" ) Signal On Syntax Name Thrown Return self~charin( setPosition, position, count ) Thrown: If \ IsThrow( Condition( "O" ) ) Then Raise Propagate Return thrownResult ::Method charoutOp Expose thrownResult Use Strict Arg context, bif, data, setPosition, position self~setContext( context, bif, 0, "CHAROUT" ) Signal On Syntax Name Thrown Return self~charout( data, setPosition, position ) Thrown: If \ IsThrow( Condition( "O" ) ) Then Raise Propagate Return thrownResult ::Method charsOp Expose thrownResult Use Strict Arg context, bif self~setContext( context, bif, 0, "CHARS" ) Signal On Syntax Name Thrown Return self~chars Thrown: If \ IsThrow( Condition( "O" ) ) Then Raise Propagate Return thrownResult ::Method lineinOp Expose thrownResult Use Strict Arg context, bif, setPosition, position, count need = self~inputNeed( context, "LINE", setPosition, count ) If need \== .Nil Then Return need self~setContext( context, bif, "", "LINEIN" ) Signal On Syntax Name Thrown Return self~linein( setPosition, position, count ) Thrown: If \ IsThrow( Condition( "O" ) ) Then Raise Propagate Return thrownResult ::Method lineoutOp Expose thrownResult Use Strict Arg context, bif, data, setPosition, position self~setContext( context, bif, 1, "LINEOUT" ) Signal On Syntax Name Thrown Return self~lineout( data, setPosition, position ) Thrown: If \ IsThrow( Condition( "O" ) ) Then Raise Propagate Return thrownResult ::Method linesOp Expose thrownResult Use Strict Arg context, bif, quick self~setContext( context, bif, 0, "LINES" ) Signal On Syntax Name Thrown Return self~lines( quick ) Thrown: If \ IsThrow( Condition( "O" ) ) Then Raise Propagate Return thrownResult -- STREAM(name, 'C', command): CLOSE, FLUSH, OPEN, POSITION / SEEK, QUERY. -- Each command word may be abbreviated to its first letters. ::Method commandOp Expose thrownResult opArgs commandText Use Strict Arg context, bif, command self~setContext( context, bif, "" ) Signal On Syntax Name Thrown commandText = command Parse Var command word parms opArgs = .Array~of( Upper( parms ) ) -- (CLOSE and FLUSH: none) word = Expand( Upper( word ), "CLOSE FLUSH OPEN POSITION QUERY SEEK" ) Select Case word When "CLOSE" Then Do If parms \== "" Then self~badCommand( "CLOSE takes no options", parms ) self~setOperation( "CLOSE", 259 ) opArgs = .Array~new Return self~streamClose End When "FLUSH" Then Do If parms \== "" Then self~badCommand( "FLUSH takes no options", parms ) self~setOperation( "FLUSH", 265 ) opArgs = .Array~new Return self~streamFlush End When "OPEN" Then Do self~setOperation( "OPEN", 270 ) Return self~streamOpen( parms ) End When "POSITION", "SEEK" Then Do self~setContext( context, bif, 0 ) If word == "SEEK" Then self~setOperation( "POSITION", 279 ) Else self~setOperation( "POSITION", 273 ) Return self~streamPosition( parms, word ) End When "QUERY" Then Return self~query( parms ) -- (Stream's COMMAND method: 93.914.) Otherwise Do Parse Var command original . Raise Syntax 93.914 Array( 1, "CLOSE FLUSH OPEN POSITION QUERY SEEK", original ) End End Thrown: If \ IsThrow( Condition( "O" ) ) Then Raise Propagate Return thrownResult /*----------------------------------------------------------------------------*/ /* The methods of Stream (ooRexx's StreamNative.cpp: stream_charin...): the */ /* operations of the functions, without a function (bif is .Nil): an error */ /* is a method's (see error), and a NOTREADY has no lines of its own (the */ /* method's line is the machine's). */ /*----------------------------------------------------------------------------*/ ::Method methodOp Expose thrownResult Use Strict Arg context, what, default, a1 = .Nil, a2 = .Nil, a3 = .Nil Select Case what When "CHARIN" Then need = self~inputNeed( context, "CHARS", a1, a3 ) When "LINEIN" Then need = self~inputNeed( context, "LINE", a1, a3 ) When "ARRAYIN" Then need = self~inputNeed( context, "ALL", .False, 1 ) Otherwise need = .Nil End If need \== .Nil Then Return need self~setContext( context, .Nil, default ) Signal On Syntax Name Thrown Select Case what When "CHARIN" Then Return self~charin( a1, a2, a3 ) When "CHAROUT" Then Return self~charout( a1, a2, a3 ) When "LINEIN" Then Return self~linein( a1, a2, a3 ) When "ARRAYIN" Then Return self~arrayin( a1 ) When "LINEOUT" Then Return self~lineout( a1, a2, a3 ) When "LINES" Then Return self~lines( a1 ) When "CHARS" Then Return self~chars When "CLOSE" Then Return self~streamClose When "FLUSH" Then Return self~streamFlush When "OPEN" Then Return self~streamOpen( a1 ) When "POSITION" Then Return self~streamPosition( a1, "POSITION" ) When "QUERYPOSITION" Then Return self~queryStreamPosition( a1, "POSITION" ) When "EXISTS" Then Return self~streamExists When "HANDLE" Then Return self~queryHandle When "SIZE" Then Return self~getStreamSize When "TYPE" Then Return self~getStreamType When "TIME" Then Return self~getTimeStamp When "QUALIFY" Then Do self~resolveStreamName Return self~qualifiedName End End Thrown: If \ IsThrow( Condition( "O" ) ) Then Raise Propagate Return thrownResult ::Method qualifiedName Private Expose qname Return qname -- !STD_SET: a standard stream (by name). ::Method setStandardStream self~setStandard -- A malformed command (40.900 says what is wrong; the error is 93.0). ::Method badCommand Private Use Strict Arg what, found = .Nil If found \== .Nil Then what = what'; found "'found'"' self~error( 40.900, "argument 3:" what ) -- 'operation': the ooRexx method of Stream that does it (.Nil: none), and -- 'commandLine' the line of the COMMAND method that calls it (a STREAM -- command); they are the traceback lines of a NOTREADY (see raiseNotready). ::Method setContext Private Expose context bif defaultResult operation commandLine saidSeen Use Strict Arg context, bif, defaultResult, operation = .Nil commandLine = .Nil If Var( "saidSeen" ), self~sharedOffset Then self~absorbSaid -- The lines SAY wrote straight since this stream last looked are its own -- lines (ooRexx's SAY is a LINEOUT of it): they move the line position. -- Only the standard output of the stream table (.OUTPUT's) has saidSeen. ::Method absorbSaid Private Expose file saidSeen lineWritePosition n = file~saidLines If n = saidSeen Then Return If lineWritePosition > 0 Then lineWritePosition += n - saidSeen saidSeen = n ::Method setOperation Private Expose operation commandLine Use Strict Arg operation, commandLine /*----------------------------------------------------------------------------*/ /* State */ /*----------------------------------------------------------------------------*/ ::Method state Expose state Select Case state When "UNKNOWN" Then Return "UNKNOWN" When "NOTREADY", "EOF" Then Return "NOTREADY" When "ERROR" Then Return "ERROR" Otherwise Return "READY" End ::Method description Expose state errorInfo errorText Select Case state When "UNKNOWN" Then Return "UNKNOWN:" When "EOF" Then Return "NOTREADY:EOF" When "READY" Then Return "READY:" Otherwise Do text = state":"errorInfo If errorInfo \= 0 Then text = text errorText Return text End End /*----------------------------------------------------------------------------*/ /* Conditions and errors */ /*----------------------------------------------------------------------------*/ -- An error: the stream goes to the ERROR state, NOTREADY is raised, and the -- operation ends, returning 'result' (by default, the operation's default). ::Method notreadyError Private Expose state errorInfo errorText sysErrno sysErrtext defaultResult Use Arg code = ( sysErrno ), result = ( defaultResult ) If Arg( 1, "E" ), code \= sysErrno Then text = .RVM.FileSystem~errorText( code ) Else text = sysErrtext state = "ERROR" errorInfo = code errorText = text sysErrno = 0 -- the file's error is now the stream's sysErrtext = "" self~raiseNotready( result ) -- The end of the stream: NOTREADY, and the operation ends returning 'result'. ::Method eof Private Expose state defaultResult Use Arg result = ( defaultResult ) state = "EOF" self~raiseNotready( result ) ::Method raiseNotready Private Expose context name thrownResult operation commandLine stdstream opArgs - commandText Use Strict Arg result thrownResult = result info = .RVM.ConditionInfo~new( "NOTREADY", name ) info~objResult = result -- the RESULT of the condition object info~additional = self -- the Stream object (made when asked) -- (after using 'result': a message instruction sets RESULT) -- ooRexx raises it in a method of Stream: the lines of its traceback, and -- its frames (the method, the Stream object, the arguments). A STREAM -- command runs in the COMMAND method (CLOSE and FLUSH, nested deeper -- there); a function on a standard stream sends its message to the -- stream's monitor (.INPUT, .OUTPUT...), whose UNKNOWN gets the name and -- the arguments. If operation \== .Nil Then Do lines = .Array~of( ' *-* Compiled method "'operation'" with scope "Stream".' ) frames = .Array~of( .Array~of( "STREAM", operation, self, opArgs, .Nil ) ) If commandLine \== .Nil Then Do If WordPos( operation, "CLOSE FLUSH" ) > 0 Then pad = 11 Else pad = 7 lines~append( Right( commandLine, 6 ) "*-*" || Copies( " ", pad ) || - 'Method COMMAND with scope "Stream" in package "REXX" (no source available).' ) frames~append( .Array~of( "STREAM", "COMMAND", self, .Array~of( commandText ), commandLine ) ) End Else If stdstream == .True Then Do lines~append( " 1457 *-* Method UNKNOWN with scope" - '"Monitor" in package "REXX" (no source available).' ) Select Case Left( Upper( name ), 4 ) When "STDI" Then monitor = "INPUT" When "STDO" Then monitor = "OUTPUT" Otherwise monitor = "ERROR" End frames~append( .Array~of( "MONITOR", "UNKNOWN", .Array~of( "LOCAL", monitor ), - .Array~of( operation, opArgs~copy ), 1457 ) ) End info~nativeStack = lines info~nativeFrames = frames End -- ::OPTIONS NOTREADY SYNTAX (ooRexx's Activity::raiseCondition; not in a -- STREAM command: ooRexx's COMMAND method is Rexx, and RAISEs it). If commandLine == .Nil, context~isSyntaxCond( "NOTREADY" ) Then Raise Syntax 98.974 Array( name ) context~raiseCondition( info ) Raise Syntax 98.900 Array( "stream" ) Description "RVM.StreamThrow" -- At the end of the file, the end-of-stream NOTREADY; otherwise an error. ::Method checkEof Private If self~sysAtEof Then self~eof self~notreadyError -- An error of the stream (it does not return): a method's, also for a -- function (ooRexx's functions send the stream the method: see RVM.BIFs): a -- transient stream cannot be positioned (93.958); the rest are ooRexx's -- Rexx_Error_Incorrect_method (93). ('code' says what went wrong.) ::Method error Private Use Arg code If code == 40.42 Then Raise Syntax 93.958 Raise Syntax 93.000 /*----------------------------------------------------------------------------*/ /* Opening and closing */ /*----------------------------------------------------------------------------*/ -- Back to the state of a stream that has never been opened (the name and -- the standard-stream mark stay). ::Method resetFields Private Expose qname file streamLineSize binaryRecordLength - readOnly writeOnly readWrite append openedAsHandle - charReadPosition charWritePosition lineReadPosition lineWritePosition - lineReadCharPosition lineWriteCharPosition nobuffer lastOpWasRead - transient recordBased isopen stdstream - fp fileeof buffered sysAppend sysErrno sysErrtext cacheStart cacheData qname = "" If file \== .Nil Then file~close file = .Nil streamLineSize = 0 binaryRecordLength = 0 readOnly = .False writeOnly = .False readWrite = .False If \ Var( "stdstream" ) Then stdstream = .False append = .False openedAsHandle = .False charReadPosition = 1 charWritePosition = 1 lineReadPosition = 1 lineWritePosition = 1 lineReadCharPosition = 1 lineWriteCharPosition = 1 nobuffer = .False lastOpWasRead = .True transient = .False recordBased = .False isopen = .False -- The operating-system file. fp = 0 fileeof = .False buffered = .True sysAppend = .False sysErrno = 0 sysErrtext = "" cacheStart = 0 cacheData = "" -- The qualified name, worked out once. ::Method resolveStreamName Private Expose qname name If qname == "" Then qname = .RVM.FileSystem~qualify( name ) -- A standard stream, opened as it is when a program starts (one of the -- stream table's: SAY writes to its standard output). ::Method openStandard Expose saidSeen file self~openStd saidSeen = file~saidLines -- A standard stream is always there: opening it only records the mode. ::Method openStd Private Expose name qname stdstream readOnly append nobuffer isopen state transient - file buffered Use Strict Arg options = "" Select Case Upper( name ) When "STDIN", "STDIN:" Then Do file = .RVM.HostFile~standard( "STDIN" ) readOnly = .True End When "STDOUT", "STDOUT:" Then Do file = .RVM.HostFile~standard( "STDOUT" ) append = .True End Otherwise Do file = .RVM.HostFile~standard( "STDERR" ) append = .True End End nobuffer = Pos( "NOBUFFER", Upper( options ) ) > 0 qname = name isopen = .True state = "READY" transient = file~transient buffered = .False Return "READY:" -- Open on first use: for reading and writing if possible (creating the file -- unless 'type' is "NOCREATE"), else write-only (type "WRITE") or read-only. ::Method implicitOpen Private Expose stdstream openedAsHandle readWrite writeOnly readOnly isopen state - defaultResult charWritePosition lineWritePosition lineWriteCharPosition - sysErrno file Use Strict Arg type If stdstream Then Do self~openStd Return End self~resetFields self~resolveStreamName readWrite = .True opened = self~sysOpen( "READWRITE", type \== "NOCREATE", .False, .False ) If \ opened Then Do readWrite = .False self~sysClearErrors If type == "WRITE" Then Do opened = self~sysOpen( "WRITE", .False, .False, .False ) writeOnly = .True End Else Do opened = self~sysOpen( "READ", .False, .False, .False ) readOnly = .True End If \ opened Then Do If defaultResult == .Nil Then defaultResult = "ERROR:"sysErrno self~notreadyError End End isopen = .True If \ file~transient, \ readOnly Then Do self~positionAfterData lineWritePosition = 0 lineWriteCharPosition = 0 End state = "READY" self~checkStreamType -- A stream opened for writing writes after the existing data; a final -- end-of-file mark (Ctrl-Z) is overwritten. ::Method positionAfterData Private Expose charWritePosition writeOnly size = self~sysSize If size <= 0 Then Return charWritePosition = self~setPosition( size ) c = self~sysRead( 1 ) If c == .Nil | c == "" Then Do If \ writeOnly Then self~notreadyError c = " " End If c \== self~CTRL_Z Then charWritePosition = self~setPosition( charWritePosition + 1 ) -- Transient streams have no positions; fixed-length records need a length. -- BINARY with no RECLENGTH on an empty stream: an error (ooRexx's 93; from -- the BIF, the RVM's 40.900, as its other STREAM errors). ooRexx leaves the -- stream open with records of length 0, and its next LINEOUT divides by zero -- (SIGFPE): here, the stream is closed again. ::Method checkStreamType Private Expose transient file recordBased binaryRecordLength isopen state transient = .False If \ file~transient Then Do If recordBased, binaryRecordLength = 0 Then Do binaryRecordLength = self~sysSize If binaryRecordLength = 0 Then Do self~sysClose isopen = .False state = "UNKNOWN" self~error( 40.900, "argument 3: BINARY on an empty stream requires RECLENGTH" ) End End End Else Do transient = .True If recordBased, binaryRecordLength = 0 Then binaryRecordLength = 1 End ::Method close Private Expose isopen state defaultResult closed = self~sysClose If \ closed Then Do defaultResult = self~sysErrnoValue self~notreadyError End isopen = .False state = "UNKNOWN" ::Method sysErrnoValue Private Expose sysErrno Return sysErrno -- CLOSE: "" when it was not open. ::Method streamClose Expose isopen state If \ isopen Then Do state = "UNKNOWN" Return "" End self~close Return "READY:" /*----------------------------------------------------------------------------*/ /* Positions */ /*----------------------------------------------------------------------------*/ -- Ready to read: opened (never creating the file), in the READY state, and -- the file at the read position. ::Method readSetup Private Expose isopen state file charReadPosition fp If \ isopen Then self~implicitOpen( "NOCREATE" ) state = "READY" If \ file~transient Then Do If charReadPosition - 1 \= fp Then charReadPosition = self~setPosition( charReadPosition ) End -- Ready to write: opened (creating the file), not read-only, READY, and the -- file at the write position (unless appending). ::Method writeSetup Private Expose isopen readOnly state file charWritePosition fp append If \ isopen Then self~implicitOpen( "WRITE" ) If readOnly Then self~notreadyError( self~EACCES ) state = "READY" self~sysTell If \ file~transient, charWritePosition - 1 \= fp, \ append Then charWritePosition = self~setPosition( charWritePosition ) -- Move the file to a 1-based position; returns the new 1-based position. ::Method setPosition Private Expose isopen Use Strict Arg position If \ isopen Then self~implicitOpen( "NOCREATE" ) new = self~sysSeek( position - 1, "SET" ) If new == .Nil Then self~checkEof Return new + 1 -- The same, relative to the start ("SET"), the current position ("CUR") or -- the end ("END"). ::Method setPositionFrom Private Use Strict Arg offset, style If style == "SET" Then offset = offset - 1 new = self~sysSeek( offset, style ) If new == .Nil Then self~checkEof Return new + 1 -- CHARIN's position: within the data, or the end-of-stream NOTREADY. ::Method setCharReadPosition Private Expose transient charReadPosition name Use Strict Arg position If transient Then self~error( 40.42, name ) self~checkPositive( position ) If self~sysSize >= position Then charReadPosition = self~setPosition( position ) Else self~eof -- CHAROUT's position: anywhere (writing past the end leaves zeros between). ::Method setCharWritePosition Private Expose transient charWritePosition name Use Strict Arg position If transient Then self~error( 40.42, name ) self~checkPositive( position ) charWritePosition = self~setPosition( position ) -- A position must be positive (93.907: ooRexx names argument 1, whichever -- it is). ::Method checkPositive Private Use Strict Arg position If position < 1 Then Raise Syntax 93.907 Array( 1, position ) -- A character operation makes the line positions unknown. ::Method resetLinePositions Private Expose lineReadCharPosition lineReadPosition streamLineSize lineReadCharPosition = 0 lineReadPosition = 0 streamLineSize = 0 /*----------------------------------------------------------------------------*/ /* Characters */ /*----------------------------------------------------------------------------*/ -- Read 'length' bytes (or fewer, at the end); anything but data read is an -- error NOTREADY (even hitting the end with nothing read). ::Method readBuffer Private Expose charReadPosition Use Strict Arg length data = self~sysRead( length ) If data == .Nil | ( data == "" & length > 0 ) Then self~notreadyError charReadPosition = charReadPosition + Length( data ) Return data -- Write bytes; the write position follows the file (except on a transient -- stream). ::Method writeBuffer Private Expose transient charWritePosition fp Use Strict Arg data If \ self~sysWrite( data ) Then self~notreadyError If \ transient Then charWritePosition = fp + 1 -- 'count' blanks (the rest of a fixed-length record). ::Method writeBlanks Private Use Strict Arg count If count > 0 Then self~writeBuffer( Copies( " ", count ) ) ::Method charin Private Use Strict Arg setPosition, position, count self~readSetup If setPosition Then self~setCharReadPosition( position ) If count = 0 Then Return "" data = self~readBuffer( count ) self~resetLinePositions If Length( data ) < count Then self~eof( data ) Return data -- CHAROUT: no data closes the stream (or, with a position, just moves the -- write position). Returns the count of characters NOT written. ::Method charout Private Expose readOnly defaultResult Use Strict Arg data, setPosition, position If data == .Nil Then Do If readOnly, \ setPosition Then self~close self~writeSetup If \ setPosition Then self~close Else self~setCharWritePosition( position ) Return 0 End defaultResult = Length( data ) self~writeSetup If setPosition Then self~setCharWritePosition( position ) If data \== "" Then self~writeBuffer( data ) self~resetLinePositions Return 0 -- CHARS: characters left to read (a transient stream: 1 or 0; a stream open -- only for writing: 0). ::Method chars Private Expose isopen file readOnly readWrite charReadPosition If \ isopen Then self~implicitOpen( "NOCREATE" ) If file~transient Then Return self~sysHasData If \ readOnly, \ readWrite Then Return 0 remainder = self~sysSize - ( charReadPosition - 1 ) Return Max( remainder, 0 ) /*----------------------------------------------------------------------------*/ /* Lines */ /* */ /* A line ends at a line feed; a carriage return just before it is part of */ /* the line end, any other carriage return is data. The last line may have no */ /* line end. Line positions are known only while nothing but line operations */ /* have been done (0 means "unknown"); the number of lines, once counted, is */ /* remembered (streamLineSize) until something may have changed it. */ /*----------------------------------------------------------------------------*/ -- After a line has been read: the read position follows the file. ::Method lineReadIncrement Private Expose transient charReadPosition fp lineReadPosition lineReadCharPosition - lastOpWasRead If transient Then Return charReadPosition = fp + 1 If lineReadPosition \= 0 Then lineReadPosition = lineReadPosition + 1 lineReadCharPosition = charReadPosition lastOpWasRead = .True -- One line, without its line end; at the end of the stream, NOTREADY. ::Method readVariableLine Private line = self~sysGets If line == .Nil Then self~checkEof self~lineReadIncrement If Right( line, 1 ) == "0a"x Then Return Left( line, Length( line ) - 1 ) Return line ::Method linein Private Expose recordBased binaryRecordLength charReadPosition Use Strict Arg setPosition, position, count If count \= 0, count \= 1 Then self~error( 40.39, count ) self~readSetup If setPosition Then self~setLineReadPosition( position ) If count = 0 Then Return "" If recordBased Then Do -- The rest of the current record. length = binaryRecordLength - ( charReadPosition - 1 ) // binaryRecordLength data = self~readBuffer( length ) If Length( data ) < length Then self~eof( data ) Return data End Return self~readVariableLine -- ARRAYIN (ooRexx's StreamInfo::arrayin): the lines left, appended to -- 'array' (a host Array) until the end-of-stream NOTREADY, which ends it -- (what was appended stays). Fixed-length records: the rest of the current -- one, then whole ones; the last may be short (readBuffer: the NOTREADY -- comes with the read that gets nothing). ::Method arrayin Private Expose recordBased binaryRecordLength charReadPosition Use Strict Arg array self~readSetup If recordBased Then Do length = binaryRecordLength - ( charReadPosition - 1 ) // binaryRecordLength Loop array~append( self~readBuffer( length ) ) length = binaryRecordLength End End Loop array~append( self~readVariableLine ) End -- LINEOUT: no data closes the stream (or, with a position, just moves the -- write position). Returns 0 (1 when the line could not be written). ::Method lineout Private Expose readOnly streamLineSize append charWritePosition lineWritePosition - lineWriteCharPosition recordBased binaryRecordLength Use Strict Arg data, setPosition, position If data == .Nil Then Do If readOnly, \ setPosition Then self~close self~writeSetup -- A record written in part is completed with blanks. If recordBased Then self~writeBlanks( binaryRecordLength - ( charWritePosition - 1 ) // binaryRecordLength ) If \ setPosition Then self~close Else self~setLineWritePosition( position ) Return 0 End self~writeSetup If setPosition Then self~setLineWritePosition( position ) If recordBased Then Do -- The line, and what may have been written of the record, must fit. used = ( charWritePosition - 1 ) // binaryRecordLength If binaryRecordLength < Length( data ) + used Then self~error( 40.900, "argument 2 does not fit in the record length ("binaryRecordLength")" ) self~writeBuffer( data ) self~writeBlanks( binaryRecordLength - used - Length( data ) ) Return 0 End If streamLineSize > 0 Then Do If append | charWritePosition = self~sysSize Then streamLineSize = streamLineSize + 1 Else streamLineSize = 0 End self~writeBuffer( data || .RVM.FileSystem~lineEnd ) If lineWritePosition > 0 Then Do lineWritePosition = lineWritePosition + 1 lineWriteCharPosition = charWritePosition End Return 0 -- LINES: 1 or 0 when 'quick', else the number of lines left to read. ::Method lines Private Expose isopen file readOnly readWrite charReadPosition streamLineSize - lineReadPosition recordBased binaryRecordLength Use Strict Arg quick If \ isopen Then self~implicitOpen( "NOCREATE" ) If file~transient Then Return self~sysHasData If \ readOnly, \ readWrite Then Return 0 If recordBased Then Do size = self~sysSize If charReadPosition > size Then Return 0 Return CeilDiv( size, binaryRecordLength ) - ( charReadPosition - 1 ) % binaryRecordLength End If charReadPosition > self~sysSize Then Return 0 If quick Then Return 1 If streamLineSize > 0, lineReadPosition > 0 Then Return streamLineSize - lineReadPosition + 1 self~readSetup Return self~countStreamLines( lineReadPosition, charReadPosition ) -- The lines from a position to the end; the total is remembered. ::Method countStreamLines Private Expose streamLineSize Use Strict Arg currentLinePosition, currentPosition If streamLineSize > 0 Then Return streamLineSize self~setPosition( currentPosition ) count = self~sysCountLines streamLineSize = count + currentLinePosition - 1 Return count -- LINEIN's position. ::Method setLineReadPosition Private Expose transient name lineReadPosition lineReadCharPosition charReadPosition Use Strict Arg position If transient Then self~error( 40.42, name ) self~checkPositive( position ) Parse Value self~setLinePosition( position, lineReadPosition, lineReadCharPosition ) - With lineReadPosition lineReadCharPosition charReadPosition = self~setPosition( lineReadCharPosition ) -- LINEOUT's position. ::Method setLineWritePosition Private Expose transient name lineWritePosition lineWriteCharPosition charWritePosition Use Strict Arg position If transient Then self~error( 40.42, name ) self~checkPositive( position ) Parse Value self~setLinePosition( position, lineWritePosition, lineWriteCharPosition ) - With lineWritePosition lineWriteCharPosition charWritePosition = self~setPosition( lineWriteCharPosition ) -- Where line 'newLine' starts, from a known (line, position) pair: returns -- "line position" (the line may be less than asked for, at the end). ::Method setLinePosition Private Expose recordBased binaryRecordLength Use Strict Arg newLine, currentLine, currentPosition If newLine <= 1 Then Return "1 1" If recordBased Then Return newLine ( binaryRecordLength * ( newLine - 1 ) + 1 ) Return self~seekToVariableLine( newLine, currentLine, currentPosition ) ::Method seekToVariableLine Private Use Strict Arg target, currentLine, currentPosition If currentLine = target Then Return currentLine currentPosition -- Only forwards: from the start when the target is behind or unknown. If currentLine > target | currentLine <= 0 Then Do currentLine = 1 currentPosition = 1 End Return self~readForwardByLine( target - currentLine, currentLine, currentPosition ) ::Method readForwardByLine Private Expose streamLineSize Use Strict Arg offset, currentLine, currentPosition self~readSetup currentPosition = self~setPosition( currentPosition ) Parse Value self~sysSeekForwardLines( currentPosition - 1, offset ) With endPosition left currentPosition = endPosition + 1 currentLine = currentLine + offset - left If left \= 0 Then streamLineSize = currentLine Return currentLine currentPosition /*----------------------------------------------------------------------------*/ /* Commands */ /*----------------------------------------------------------------------------*/ -- OPEN [READ | WRITE | BOTH] [APPEND | REPLACE] [NOBUFFER] -- [BINARY [RECLENGTH n]] [SHARED | SHAREREAD | SHAREWRITE] -- (the default is BOTH, positioned for writing after the existing data). -- Opening an open stream closes it first. A file opened for READ must -- exist; WRITE is read-write when the file can be read, write-only if not. ::Method streamOpen Private Expose isopen stdstream readOnly writeOnly readWrite append nobuffer - recordBased binaryRecordLength qname charWritePosition - lineWritePosition lineWriteCharPosition sysErrno buffered file state Use Strict Arg options If isopen Then self~close If stdstream Then Return self~openStd( options ) self~resetFields table = .Array~of( - .Array~of( "READ", 3, "MEB readOnly;MEB readWrite;MEB writeOnly;MEB append;ME oflag TRUNC;SETB readOnly" ), - .Array~of( "WRITE", 1, "MEB readOnly;MEB readWrite;MEB writeOnly;SETB writeOnly;OR oflag WRONLY CREAT" ), - .Array~of( "BOTH", 2, "MEB readOnly;MEB readWrite;MEB writeOnly;SETB readWrite;OR oflag RDWR CREAT" ), - .Array~of( "APPEND", 2, "MEB readOnly;MEB append;ME oflag TRUNC;SETB append;OR oflag APPEND" ), - .Array~of( "REPLACE", 3, "MEB readOnly;MEB append;ME oflag TRUNC;OR oflag TRUNC" ), - .Array~of( "NOBUFFER", 3, "MEB nobuffer;SETB nobuffer" ), - .Array~of( "BINARY", 2, "MEB recordBased;SETB recordBased" ), - .Array~of( "RECLENGTH", 3, "MIB recordBased;RECLENGTH" ), - .Array~of( "SHARED", 6, "MEB shared;SETB shared" ), - .Array~of( "SHAREREAD", 6, "MEB shared;SETB shared" ), - .Array~of( "SHAREWRITE", 6, "MEB shared;SETB shared" ) ) o = self~parseOptions( options, table, "FAIL", "OPEN" ) readOnly = o~readOnly writeOnly = o~writeOnly readWrite = o~readWrite append = o~append nobuffer = o~nobuffer recordBased = o~recordBased binaryRecordLength = o~reclength oflag = o~oflag self~resolveStreamName If recordBased, WordPos( "TRUNC", oflag ) > 0, binaryRecordLength = 0 Then self~badCommand( "BINARY REPLACE requires RECLENGTH" ) -- Neither READ nor WRITE nor BOTH: BOTH. If \ HasAny( oflag, "WRONLY RDWR CREAT" ), \ readOnly Then Do oflag = oflag "RDWR CREAT" readWrite = .True If WordPos( "APPEND", oflag ) > 0 Then append = .True End If readOnly Then Do If \ .RVM.FileSystem~isFile( qname ) Then self~notreadyError( 2, "ERROR:2" ) charWritePosition = 0 lineWritePosition = 0 lineWriteCharPosition = 0 End -- WRITE: try read-write first. If WordPos( "WRONLY", oflag ) > 0 Then Do readWrite = .True writeOnly = .True oflag = Space( ChangeStr( "WRONLY", oflag, "" ) ) "RDWR CREAT" End If \ self~sysOpenFlags( oflag ) Then Do If writeOnly Then Do If \ self~sysOpen( "WRITE", .True, .False, .False ) Then self~notreadyError( sysErrno, "ERROR:"sysErrno ) readWrite = .False writeOnly = .True End Else self~notreadyError( sysErrno, "ERROR:"sysErrno ) End If nobuffer Then buffered = .False isopen = .True If \ file~transient, HasAny( oflag, "WRONLY RDWR CREAT" ) Then Do self~positionAfterData lineWritePosition = 0 lineWriteCharPosition = 0 End state = "READY" self~checkStreamType Return "READY:" -- Open with a set of flags: RDWR or WRONLY (else read-only), CREAT, TRUNC, -- APPEND. ::Method sysOpenFlags Private Use Strict Arg oflag Select When WordPos( "RDWR", oflag ) > 0 Then access = "READWRITE" When WordPos( "WRONLY", oflag ) > 0 Then access = "WRITE" Otherwise access = "READ" End Return self~sysOpen( access, WordPos( "CREAT", oflag ) > 0, - WordPos( "TRUNC", oflag ) > 0, WordPos( "APPEND", oflag ) > 0 ) -- FLUSH: what could not be written is an error NOTREADY ("ERROR:n"). ::Method streamFlush Private Expose file isopen -- (Not open, its OPEN failed too: nothing to write, READY:, as native's -- SysFile::flush with no handle.) If file == .Nil | \ isopen Then Return "READY:" If \ file~flush Then self~notreadyError( file~errno, "ERROR:"file~errno ) Return "READY:" -- SEEK / POSITION [= | < | + | -] offset [READ | WRITE] [CHAR | LINE]: -- from the start (the default), from the end, forwards or backwards from -- the current position of the file. Without READ or WRITE, the positions -- the stream was opened for (both, for a read-write stream, which then -- first takes the read positions as the write positions too). Returns the -- new position. ::Method streamPosition Private Expose bif transient name readOnly writeOnly readWrite lastOpWasRead - charReadPosition charWritePosition lineReadPosition lineWritePosition - lineReadCharPosition lineWriteCharPosition isopen streamLineSize state Use Strict Arg options, word table = .Array~of( - .Array~of( "=", 1, "MEB styleSet;SETI style SET;SETB styleSet" ), - .Array~of( "<", 1, "MEB styleSet;SETI style END;SETB styleSet" ), - .Array~of( "+", 1, "MEB styleSet;SETI style CUR;SETB styleSet" ), - .Array~of( "-", 1, "MEB styleSet;SETI style CUR;SETB seekBack;SETB styleSet" ), - .Array~of( "READ", 1, "ME flags READ;ME flags WRITE;OR flags READ" ), - .Array~of( "WRITE", 1, "ME flags READ;ME flags WRITE;OR flags WRITE" ), - .Array~of( "CHAR", 1, "ME flags LINE;ME flags CHAR;OR flags CHAR" ), - .Array~of( "LINE", 1, "ME flags LINE;ME flags CHAR;OR flags LINE" ) ) o = self~parseOptions( options, table, "OFFSET", word ) If transient Then self~error( 40.42, name ) If o~offset == -1 Then Raise Syntax 93.903 Array( "SEEK", "offset" ) offset = o~offset style = o~style flags = o~flags state = "READY" If \ HasAny( flags, "READ WRITE" ) Then Do If readOnly Then flags = flags "READ" Else If writeOnly Then flags = flags "WRITE" Else Do flags = flags "READ WRITE" If lastOpWasRead Then Do charWritePosition = charReadPosition lineWritePosition = lineReadPosition End Else Do charReadPosition = charWritePosition lineReadPosition = lineWritePosition End End End If \ isopen Then self~implicitOpen( "NOCREATE" ) If WordPos( "READ", flags ) > 0 Then streamLineSize = 0 If \ HasAny( flags, "CHAR LINE" ) Then flags = flags "CHAR" If o~seekBack Then offset = -offset If WordPos( "CHAR", flags ) > 0 Then Do self~resetLinePositions If WordPos( "READ", flags ) > 0 Then Do charReadPosition = self~setPositionFrom( offset, style ) If WordPos( "WRITE", flags ) > 0 Then charWritePosition = charReadPosition Return charReadPosition End charWritePosition = self~setPositionFrom( offset, style ) Return charWritePosition End -- By lines: not for a stream open only for writing. If \ ( readWrite | readOnly ) Then Return 0 If WordPos( "READ", flags ) > 0 Then Do charReadPosition = self~setPosition( charReadPosition ) Parse Value self~seekLinePosition( offset, style, lineReadPosition, lineReadCharPosition ) - With lineReadPosition lineReadCharPosition charReadPosition = lineReadCharPosition If WordPos( "WRITE", flags ) > 0 Then Do charWritePosition = charReadPosition lineWriteCharPosition = lineReadCharPosition lineWritePosition = lineReadPosition End Return lineReadPosition End charWritePosition = self~setPosition( charWritePosition ) Parse Value self~seekLinePosition( offset, style, lineWritePosition, lineWriteCharPosition ) - With lineWritePosition lineWriteCharPosition charWritePosition = lineWriteCharPosition Return lineWritePosition -- A line position from the start, the end (counting the lines), or the -- current line (which may be unknown, 0); never before line 1. ::Method seekLinePosition Private Use Strict Arg offset, style, currentLine, currentPosition Select Case style When "END" Then newLine = self~getLineSize - offset When "SET" Then newLine = offset Otherwise newLine = offset + currentLine End If newLine < 1 Then newLine = 1 Return self~setLinePosition( newLine, currentLine, currentPosition ) -- The number of lines (records, or counted from the start). ::Method getLineSize Private Expose recordBased binaryRecordLength If recordBased Then Return CeilDiv( self~sysSize, binaryRecordLength ) Return self~countStreamLines( 1, 1 ) -- QUERY DATETIME | EXISTS | HANDLE | POSITION (or SEEK) [...] | SIZE | -- STREAMTYPE | TIMESTAMP. A NOTREADY returns the stream's description. ::Method query Private Expose defaultResult Use Strict Arg parms Parse Var parms sub parms original = sub sub = Expand( Upper( sub ), "DATETIME EXISTS HANDLE POSITION SEEK SIZE STREAMTYPE TIMESTAMP" ) If sub == "" Then Do self~error( 40.904, 3, "DATETIME EXISTS HANDLE POSITION SEEK SIZE STREAMTYPE TIMESTAMP", original ) End If parms \== "", sub \== "POSITION", sub \== "SEEK" Then self~badCommand( "QUERY" sub "takes no options", parms ) defaultResult = self~description Select Case sub When "DATETIME", "TIMESTAMP" Then Do If self~getStreamType == "TRANSIENT" Then Return "" stamp = self~getTimeStamp If stamp == "" Then Return "" If sub == "TIMESTAMP" Then Return stamp Parse Var stamp yyyy "-" mm "-" dd time Return mm"-"dd"-"Right( yyyy, 2 ) time End When "EXISTS" Then Return self~streamExists When "HANDLE" Then Return self~queryHandle When "SIZE" Then Return self~getStreamSize When "STREAMTYPE" Then Return self~getStreamType Otherwise Return self~queryStreamPosition( parms, sub ) End -- QUERY HANDLE: the system's handle of the file ("" when not open: ooRexx's -- queryHandle). ::Method queryHandle Private Expose isopen file If \ isopen Then Return "" Return file~handle -- QUERY POSITION [SYS | [READ | WRITE] [CHAR | LINE]]: "" when not open, 1 -- for a transient stream; SYS is the file's own 0-based position. ::Method queryStreamPosition Private Expose isopen transient fp writeOnly charReadPosition charWritePosition file Use Strict Arg options, sub table = .Array~of( - .Array~of( "SYS", 1, "ME flags SYS;ME flags READ;ME flags WRITE;ME flags CHAR;ME flags LINE;OR flags SYS" ), - .Array~of( "READ", 1, "ME flags SYS;ME flags READ;ME flags WRITE;OR flags READ" ), - .Array~of( "WRITE", 1, "ME flags SYS;ME flags READ;ME flags WRITE;OR flags WRITE" ), - .Array~of( "CHAR", 1, "ME flags SYS;ME flags CHAR;ME flags LINE;OR flags CHAR" ), - .Array~of( "LINE", 1, "ME flags SYS;ME flags CHAR;ME flags LINE;OR flags LINE" ) ) flags = self~parseOptions( options, table, "FAIL", "QUERY" sub )~flags If \ isopen Then Return "" If transient Then Return 1 -- (SAY writes there too, straight: where the last write ended.) If self~sharedOffset Then charWritePosition = file~writePosition If WordPos( "SYS", flags ) > 0 Then Return fp If \ HasAny( flags, "READ WRITE" ) Then Do If writeOnly Then flags = flags "WRITE" Else flags = flags "READ" End If WordPos( "WRITE", flags ) > 0 Then Do If WordPos( "LINE", flags ) > 0 Then Return self~getLineWritePosition Return charWritePosition End If WordPos( "LINE", flags ) > 0 Then Return self~getLineReadPosition Return charReadPosition ::Method getLineReadPosition Private Expose recordBased binaryRecordLength charReadPosition lineReadPosition - lineReadCharPosition If recordBased Then Return ( charReadPosition - 1 ) % binaryRecordLength + 1 If lineReadPosition = 0 Then lineReadPosition = self~queryLinePosition( charReadPosition ) lineReadCharPosition = charReadPosition Return lineReadPosition ::Method getLineWritePosition Private Expose recordBased binaryRecordLength charWritePosition lineWritePosition - lineWriteCharPosition If recordBased Then Return CeilDiv( charWritePosition, binaryRecordLength ) If lineWritePosition = 0 Then lineWritePosition = self~queryLinePosition( charWritePosition ) + 1 lineWriteCharPosition = charWritePosition Return lineWritePosition -- The line a character position is in (lines counted from the start). ::Method queryLinePosition Private Use Strict Arg position If position = 0 Then position = 1 Return self~sysCountLinesTo( position - 1 ) -- EXISTS: the qualified name ("" when there is no such file); an open device -- answers with its own name. ::Method streamExists Private Expose isopen file name qname If isopen Then Do If file~device Then Return name Return qname End self~resolveStreamName If .RVM.FileSystem~isFile( qname ) Then Return qname Return "" ::Method getStreamType Private Expose isopen transient If \ isopen Then Return "UNKNOWN" If transient Then Return "TRANSIENT" Return "PERSISTENT" -- SIZE: of the open file, or of whatever has that name ("" when nothing). ::Method getStreamSize Private Expose isopen qname If isopen Then Return self~sysSize self~resolveStreamName Return .RVM.FileSystem~size( qname ) -- The modification time, "yyyy-mm-dd hh:mm:ss", or "". ::Method getTimeStamp Private Expose qname self~resolveStreamName Return .RVM.FileSystem~timeStamp( qname ) /*----------------------------------------------------------------------------*/ /* Command options */ /* */ /* Options are words separated by blanks; "=", "+", "-" and "<" are words on */ /* their own. A word is a keyword when it is an abbreviation of one, as long */ /* as the keyword's minimum; the first keyword of the table that it */ /* abbreviates is the one. Each keyword carries actions: */ /* MEB x x must not be set yet MIB x x must be set */ /* ME f w word w must not be in f OR f ws add the words to f */ /* SETB x set x SETI x v x becomes v */ /* RECLENGTH a record length may follow (a whole number above 0) */ /* A word that is no keyword is an error, or (OFFSET) the offset, once. */ /*----------------------------------------------------------------------------*/ ::Method parseOptions Private Use Strict Arg options, table, unknown, command o = .Directory~new Do x Over "readOnly writeOnly readWrite append nobuffer recordBased shared styleSet seekBack"~makeArray(" ") o[ Upper( x ) ] = .False End o~oflag = "" o~flags = "" o~style = "SET" o~reclength = 0 o~offset = -1 tokens = Tokens( options ) i = 1 Do While i <= tokens~items token = tokens[ i ] i = i + 1 entry = .Nil Do e Over table If Length( token ) <= Length( e[1] ), Abbrev( e[1], Upper( token ) ) Then Do entry = e Leave End End If entry == .Nil Then Do If unknown == "OFFSET", o~offset == -1, IsOffset( token ) Then o~offset = token + 0 Else self~badCommand( "incorrect" command "options", options ) Iterate End If Length( token ) < entry[2] Then self~badCommand( "incorrect" command "options", options ) Do action Over entry[3]~makeArray(";") Parse Var action verb target values target = Upper( target ) Select Case verb When "MEB" Then bad = o[ target ] When "MIB" Then bad = \ o[ target ] When "ME" Then bad = WordPos( values, o[ target ] ) > 0 When "OR" Then Do o[ target ] = Space( o[ target ] values ) bad = .False End When "SETB" Then Do o[ target ] = .True bad = .False End When "SETI" Then Do o[ target ] = values bad = .False End Otherwise Do -- RECLENGTH [n] bad = .False If i <= tokens~items, o~reclength = 0 Then Do n = RecLength( tokens[ i ] ) i = i + 1 If n == "" Then bad = .True Else If n = 0 Then bad = .True Else o~reclength = n End End End If bad Then self~badCommand( "incorrect" command "options", options ) End End Return o /*----------------------------------------------------------------------------*/ /* The operating-system file */ /* */ /* One 0-based offset 'fp' for reads and writes. A read that finds nothing */ /* sets 'fileeof', which stays set until the file is opened again. Seeking */ /* relative to the end counts backwards on a buffered file and forwards on */ /* an unbuffered one (NOBUFFER). Appending writes always land at the end. */ /* Bytes read from a persistent file are read ahead in chunks, invisibly. */ /*----------------------------------------------------------------------------*/ ::Method sysOpen Private Expose file qname fp fileeof sysAppend sysErrno sysErrtext buffered cacheData Use Strict Arg access, create, truncate, appendMode file = .RVM.HostFile~new( qname ) If \ file~open( access, create, truncate ) Then Do sysErrno = file~errno sysErrtext = file~errtext Return .False End fp = 0 fileeof = .False sysAppend = appendMode buffered = \ file~device cacheData = "" If appendMode Then fp = file~size Return .True ::Method sysClose Private Expose file cacheData sysErrno sysErrtext cacheData = "" If file == .Nil Then Return .True ok = file~close If \ ok Then Do sysErrno = file~errno sysErrtext = file~errtext End Return ok ::Method sysClearErrors Private Expose sysErrno sysErrtext sysErrno = 0 sysErrtext = "" ::Method sysSize Private Expose file Return file~size -- Up to 'length' bytes from fp: the data ("" when nothing is left, which also -- sets fileeof), or .Nil for an error. ::Method sysRead Private Expose file fp fileeof cacheStart cacheData sysErrno sysErrtext Use Strict Arg length If length = 0 Then Return "" If file~transient Then Do data = file~readAt( fp, length ) If data == .Nil Then Return self~sysFailed If data == "" Then fileeof = .True Return data End out = "" Do While length > 0 cacheEnd = cacheStart + Length( cacheData ) If fp < cacheStart | fp >= cacheEnd Then Do chunk = file~readAt( fp, Max( length, self~CHUNK ) ) If chunk == .Nil Then Return self~sysFailed If chunk == "" Then Do fileeof = .True -- even after a short read Leave End cacheStart = fp cacheData = chunk cacheEnd = fp + Length( chunk ) End take = Min( length, cacheEnd - fp ) out = out || SubStr( cacheData, fp - cacheStart + 1, take ) fp = fp + take length = length - take End Return out ::Method sysFailed Private Expose file sysErrno sysErrtext sysErrno = file~errno sysErrtext = file~errtext Return .Nil ::Method sysWrite Private Expose file fp sysAppend cacheData sysErrno sysErrtext Use Strict Arg data If data == "" Then Return .True cacheData = "" If sysAppend, \ file~transient Then fp = file~size If \ file~writeAt( fp, data ) Then Do sysErrno = file~errno sysErrtext = file~errtext Return .False End If \ file~transient Then fp = fp + Length( data ) Return .True -- One line from fp, with its line feed if it has one (a carriage return + -- line feed becomes a line feed); .Nil when there is nothing left. ::Method sysGets Private Expose file fileeof line = "" If file~transient Then Do -- one byte at a time: no read-ahead Do Forever c = file~readAt( 0, 1 ) If c == .Nil Then Return self~sysFailed If c == "" Then Do fileeof = .True Leave End line = line || c If c == "0a"x Then Leave End End Else Do Forever chunk = self~sysPeekChunk If chunk == .Nil Then Return .Nil If chunk == "" Then Leave p = Pos( "0a"x, chunk ) If p > 0 Then Do line = line || self~sysRead( p ) Leave End line = line || self~sysRead( Length( chunk ) ) End If line == "" Then Return .Nil If Right( line, 2 ) == "0d0a"x Then line = Left( line, Length( line ) - 2 ) || "0a"x Return line -- What can be read from fp without moving it: the rest of the current chunk -- ("" at the end, which sets fileeof; .Nil for an error). ::Method sysPeekChunk Private Expose file fp fileeof cacheStart cacheData cacheEnd = cacheStart + Length( cacheData ) If fp < cacheStart | fp >= cacheEnd Then Do chunk = file~readAt( fp, self~CHUNK ) -- (persistent files only) If chunk == .Nil Then Return self~sysFailed If chunk == "" Then Do fileeof = .True Return "" End cacheStart = fp cacheData = chunk cacheEnd = fp + Length( chunk ) End Return SubStr( cacheData, fp - cacheStart + 1 ) -- The lines from fp to the end (a last line without a line end counts). ::Method sysCountLines Private count = 0 Do Forever line = self~sysGets If line == .Nil Then Return count count = count + 1 End -- The line (counted from the start) that the 0-based offset 'end' is in; -- all the lines when it is past the end. ::Method sysCountLinesTo Private Expose fp Use Strict Arg end self~sysSeek( 0, "SET" ) count = 0 Do Forever If self~sysGets == .Nil Then Return count count = count + 1 If fp > end Then Return count End -- Move past 'lineCount' line feeds from the 0-based offset 'start': returns -- "end left", the offset after the last line feed found and how many were -- still missing when the end was reached. fp is left wherever the search -- stopped reading. ::Method sysSeekForwardLines Private Use Strict Arg start, lineCount Do Forever self~sysSeek( start, "SET" ) data = self~sysRead( 512 ) If data == .Nil | data == "" Then Return start lineCount offset = 0 Do Forever p = Pos( "0a"x, data, offset + 1 ) If p == 0 Then Leave lineCount = lineCount - 1 If lineCount = 0 Then Return start + p lineCount offset = p End start = start + Length( data ) End -- Seek: the new 0-based offset, or .Nil (a negative offset is EINVAL). ::Method sysSeek Private Expose file fp buffered sysErrno sysErrtext Use Strict Arg offset, style Select Case style When "SET" Then new = offset When "CUR" Then Do self~sysTell new = fp + offset End Otherwise Do If buffered Then new = file~size - offset Else new = file~size + offset End End If new < 0 Then Do sysErrno = self~EINVAL sysErrtext = .RVM.FileSystem~errorText( self~EINVAL ) Return .Nil End fp = new If self~sharedOffset Then file~seek( fp ) Return fp -- A standard output or error stream redirected to a file shares its offset -- with the commands the program runs (ooRexx writes where the descriptor -- is: getPosition): fp follows it. Standard input does not (the stream -- reads ahead, as ooRexx's does). ::Method sharedOffset Private Expose stdstream file readOnly If file == .Nil Then Return .False Return stdstream & \ file~transient & \ readOnly ::Method sysTell Private Expose file fp If self~sharedOffset Then fp = file~tell -- Is there something to read? Once the end has been seen, never again. ::Method sysHasData Private Expose file fp fileeof If fileeof Then Return .False If file~transient Then Return file~hasData If fp < file~size Then Return .True fileeof = .True Return .False ::Method sysAtEof Private Return \ self~sysHasData /******************************************************************************/ /* Helpers */ /******************************************************************************/ -- Is this condition object the internal unwinding of a stream operation? ::Routine IsThrow Use Strict Arg co description = co~description If \ description~isA( .String ) Then Return .False Return description == "RVM.StreamThrow" -- The keyword of 'list' that 'word' starts (" " + word must be found in the -- list: the null word is the first keyword); "" when none. ::Routine Expand Use Strict Arg word, list p = Pos( " "word, " "list ) If p == 0 Then Return "" Return Word( SubStr( " "list, p + 1 ), 1 ) -- Does 'flags' hold any of the words of 'these'? ::Routine HasAny Use Strict Arg flags, these Do w Over these~makeArray(" ") If WordPos( w, flags ) > 0 Then Return .True End Return .False -- The option words: blank-separated, "=", "+", "-" and "<" on their own. ::Routine Tokens Use Strict Arg s tokens = .Array~new i = 1 n = Length( s ) Do While i <= n c = SubStr( s, i, 1 ) If c == " " Then Do i = i + 1 Iterate End If Pos( c, "=+-<" ) > 0 Then Do tokens~append( c ) i = i + 1 Iterate End j = i Do While j <= n, Pos( SubStr( s, j, 1 ), "=+-< " ) == 0 j = j + 1 End tokens~append( SubStr( s, i, j - i ) ) i = j End Return tokens -- Digits only, and not beyond a 64-bit number. -- A record length (ooRexx's StreamToken::toNumber(size_t), its overflow -- check as it is: 64 bits without sign that wrap; up to 2**64-1): the -- number, or "" when it is not one. ::Routine RecLength Use Strict Arg s Numeric Digits 40 If Verify( s, "0123456789" ) > 0 Then Return "" off = 0 Do k = 1 To Length( s ) next = ( off * 10 + SubStr( s, k, 1 ) ) // 18446744073709551616 If off > next Then Return "" off = next End Return off ::Routine IsOffset Use Strict Arg s Numeric Digits 30 If s == "" | Verify( s, "0123456789" ) > 0 Then Return .False Return s <= 9223372036854775807 -- a / b, rounded up (whole numbers, b > 0). ::Routine CeilDiv Use Strict Arg a, b q = a % b If a // b > 0 Then q = q + 1 Return q /******************************************************************************/ /* RVM.StdinNeed -- what a read of standard input that must wait needs (see */ /* RVM.Stream~inputNeed): the machine makes its activity wait for it */ /* (RVM.StdinWait) and runs the operation again when it is there. */ /******************************************************************************/ ::Class RVM.StdinNeed Public ::Attribute kind ::Attribute count ::Method init Expose kind count Use Strict Arg kind, count