module yeti.lang.io
Standard input/output functions.
Exceptions thrown
java.io.IOException | - | Can be thrown for IO errors by any function in this module. |
typedef input_handle = {}
close is () → (),
Closes the input stream.
contents is () → string,
Reads full contents of the stream as a single string.
lines is () → list<string>,
Returns a lazy list representing lines from the stream.
Description
The stream will be read as the returned list is consumed. If the close method is called, the whole list will be forced to be read.If the stream is forced to close with rawClose method and the returned list was not fully consumed, then consuming that list further results in IO exception.A line is considered to be terminated by "\r", "\n" or "\r\n" character sequence.rawClose is () → (),
Closes the input stream without forcing pending reads.
read maxLength is number → string,
Reads at most maxLength characters from the stream.
maxLength | - | maximum number of characters to be read |
Description
Blocks until some input is available, then reads at most maxLength characters as long as it won't cause blocking again. Returns the read characters as a string. If applied at the end of stream, a undef_str is returned.Examples
Copy standard input to standard output:(str = stdin.read 8192; print str; defined? str) loop;The defined? function is used to test for undef_str marking the end of stream.
readln is () → string
Reads a line from the stream. Returns the line, or undef_str
if applied at the end of stream.
Notes
A line is considered to be terminated by "\r", "\n" or "\r\n" character sequence.typedef output_handle = {}
close is () → (),
Closes the output stream (flushing any buffers first).
flush is () → (),
Flushes any buffers to the output stream.
write string is string → (),
Writes the given string to the output stream.
string | - | a string to write |
writeln string is string → ()
Writes the string and system line separator to the output stream.
string | - | a string to write |
Notes
The line separator is defined by the system line.separator property.typedef bin_input_handle = {}
.close is () → (),
Closes the input stream.
.read buffer offset is byte[] → number → number
Reads some bytes from the input stream and stores them into the
buffer (after the start offset). Returns the number of bytes actually
read, or -1 if applied at the end of stream.
buffer | - | a byte array |
offset | - | starting offset in the buffer for storing data |
Notes
The binReadAll function can be used to ensure reading a given number of bytes (or all bytes until the end of stream).Module signature
{
}
Binary IO: binInputHandle binOutputHandle binReadAll binReadFile binWriteFile
Filesystem operations: createPath deleteFile listDirectory
Reading text: getContents getLines inputHandle openInFile readFile readerHandle readln stdin
Writing text: eprintln openOutFile outputHandle print println putLines trace writeFile writerHandle
Miscellaneous functions: _argv fetchURL runThread runnable sleep sysExit threadExit withHandle
Filesystem operations: createPath deleteFile listDirectory
Reading text: getContents getLines inputHandle openInFile readFile readerHandle readln stdin
Writing text: eprintln openOutFile outputHandle print println putLines trace writeFile writerHandle
Miscellaneous functions: _argv fetchURL runThread runnable sleep sysExit threadExit withHandle
Binary IO
binInputHandle input is ~java.io.InputStream → bin_input_handle, Creates binary handle object for the given input stream.
input | - | java.io.InputStream instance to be used |
binOutputHandle output is ,
~java.io.OutputStream →
{}
close is () → (),
Closes the output stream (calls output#close()).
flush is () → (),
Flushes the output stream (calls output#flush()).
write list is list?<number> → ()
Writes bytes from the given list to the output stream.
If numbers out of the range -128 to 255 are present in
the list, then the result is undefined.
list | - | list of bytes to write to the output stream |
Creates binary handle object for the given output stream.
output | - | java.io.OutputStream instance to be used |
binReadAll limit handle is number → bin_input_handle → list<number>,
Reads up to limit bytes from input handle and returns a list of
the read bytes.
limit | - | Maximum number of bytes to read (<= 0 means unlimited). |
handle | - | Binary input stream handle. |
Examples
A contents of file could be copied in the following way:data = binReadFile "test" (binReadAll 0); binWriteFile "test2" (data |>);
binReadFile file block is string → (bin_input_handle → 'a) → 'a,
Applies the given block to binary input handle opened for
specified file. The input handle will be automatically closed
afterwards (even when exception was thrown by the block).
Returns the value returned by the block.
file | - | path to the file to be read |
block | - | a function to be applied to the opened input object |
binWriteFile file block is string → ((list?<number> → ()) → 'b) → 'b,
Applies the given block to function writing to the file
and returns the value returned by the block.
file | - | path to the file to be written |
block | - | a function to be applied to the write function |
Description
Creates the specified file and applies the given block to function writing to the file. The file will be automatically closed afterwards (even when exception was thrown by the block). If the file existed before, it will be truncated to zero length before appling the block.The write function is same as .write field in the handle object returned by the binOutputHandle function, taking as argument a byte list to be written. It may be called as many times as needed, with each call writing additional bytes to the given file.Examples
Write 4 bytes representing ASCII string 'TEST' to file 'testfile':binWriteFile 'testfile' do f: f [84, 69, 83, 84] done
Filesystem operations
createPath path is string → (), Creates the specified directory path, if it doesn't already exist.
Missing parent directories are created as needed.
path | - | path of the directory to create |
deleteFile path is string → boolean,
Deletes a file or empty directory with the specified path name.
Returns true if deleting succeeded, and false if the path didn't exist,
was a non-empty directory, or couldn't be deleted for some other reason.
path | - | directory or file name |
listDirectory hidden directory is ,
boolean →
string →
list<{}>
directory? is boolean,
Whether this entry denotes a directory.
file? is boolean,
Whether this entry denotes a normal file.
name is string,
Name without any preceding path.
path is string
Path to the file or directory.
Lists files in given directory.
hidden | - | Include hidden file/directory entries |
directory | - | Path to the directory to list |
Reading text
getContents handle is {.contents is () → 'e} → 'e, Applies the given handle.contents field to () and returns the result.
handle | - | a handle object having a contents function field |
Examples
Can be used together with IO functions expecting a block.str = readFile 'example.txt' '' getContents;Reads whole contents from a file named 'example.txt' into the str string.
getLines handle is {.lines is () → 'f} → 'f,
Applies the given handle.lines field to () and returns the result.
handle | - | a handle object having a lines function field |
Examples
Can be used together with IO functions expecting a block.lines = readFile 'example.txt' '' getLines;Reads all lines into a string list from a file named 'example.txt'.
inputHandle stream encoding is ~java.io.InputStream → string → input_handle,
Create a text input handle object from a Java InputStream instance.
The bytes read from the stream will be converted to text according
to the specified encoding. If encoding is empty string, system default
charset is used.
stream | - | a java.io.InputStream instance to be used |
encoding | - | name of the charset used in the given stream |
openInFile file encoding is string → string → input_handle,
Open text file and create an input handle object for it.
The bytes read from the file will be converted to text according
to the specified encoding.
file | - | path to the file to be opened |
encoding | - | name of the charset used in the given stream (empty string means system default charset) |
readFile file encoding block is string → string → (input_handle → 'j) → 'j,
Applies the given block to text input handle opened for specified
file. The input handle will be automatically closed afterwards
(even when exception was thrown by the block).
Returns the value returned by the block.
file | - | path to the file to be read |
encoding | - | name of the charset used in the given stream (empty string means system default charset) |
block | - | a function to be applied to the opened input object |
readerHandle reader is ~java.io.BufferedReader → input_handle,
Create a text input handle object wrapping a Java BufferedReader instance.
reader | - | a java.io.BufferedReader instance to be used |
readln is () → string,
Reads a single line from the stdin and returns as a string.
The undef_str value is returned at the end of stream.
Notes
It causes the stdin to create a java.io.BufferedReader wrapping the System.in, which means that readln may cause more data to be read from System.in to the stdin buffer, than the returned line.stdin is input_handle,
Standard input handle.
Description
This module field (stdin) is implemented as read-only property. When accessed first time, a java.io.BufferedReader instance wrapping System.in is created internally. This means, that reading stdin can cause data read from System.in to be in the stdin specific reader buffer.Examples
Read from standard input and print all non-empty lines.for (filter (!= '') (stdin.lines ())) println;This uses stdin.lines and filter working lazily, so whole stdin stream contents never needs to be hold in memory at once.
Writing text
eprintln value is 'c → (), Prints string representation of the given value and system line separator
to the standard error output, and flushes the error printer buffers.
value | - | a value to print |
Description
The given value is formatted the same way as the string function would do. The resulting string and system line separator (usually '\n') are sent to the standard error stream and buffers are flushed.Using (eprintln value) should be always equivalent to (eprintln (string value)), the exact formatting rules are described in the string function documentation.openOutFile file encoding is string → string → output_handle,
Open text file and create an output handle object for it.
The text written to the file will be encoded to bytes according
to the specified encoding.
file | - | path to the file to be opened |
encoding | - | name of the charset to use for the given stream (empty string means system default charset) |
outputHandle stream encoding is ~java.io.OutputStream → string → output_handle,
Create a text output handle object from a Java OutputStream instance.
The text written to the file will be encoded to bytes according
to the specified encoding. If encoding is empty string, system default
charset is used.
stream | - | a java.io.InputStream instance to be used |
encoding | - | name of the charset used in the given stream |
print value is 'g → (),
Prints string representation of the given value to standard output
and flushes the output buffers.
value | - | a value to print |
Description
The given value is formatted the same way as the string function would do. The resulting string is sent to the standard output stream and buffers are flushed.Using (print value) should always be equivalent to (print (string value)), the exact formatting rules are described in the string function documentation.println value is 'h → (),
Prints string representation of the given value and system line separator
to the standard output, and flushes the error printer buffers.
value | - | a value to print |
Description
The given value is formatted the same way as the string function would do. The resulting string and system line separator (usually '\n') are sent to the standard output stream and buffers are flushed.Using (println value) should always be equivalent to (println (string value)), the exact formatting rules are described in the string function documentation.putLines handle lines is {.writeln is 'i → ()} → list?<'i> → (),
Applies the given handle.writeln field to each element in the
lines list.
handle | - | a handle object having a writeln function field |
lines | - | list of strings to written as separate lines |
Description
The canonical implementation is following:putLines handle lines = for lines handle.writeln;
Examples
lines = ['orange', 'apple', 'mouse']; writeFile 'test.txt' '' (`putLines` lines);Writes the lines list to the test.txt file as separate lines.
trace message result is 'm → 'n → 'n,
Prints trace message (formatted like the string function would do it)
to standard error stream and returns the given result value. Useful for
inserting debug printing into expressions.
message | - | a value to print |
result | - | a value to return |
writeFile file encoding block is string → string → (output_handle → 'p) → 'p,
Applies the given block to text output handle opened for specified
file. The output handle will be automatically closed afterwards
(even when exception was thrown by the block).
Returns the value returned by the block.
file | - | path to the file to be written |
encoding | - | name of the charset to use for the given stream (empty string means system default charset) |
block | - | a function to be applied to the opened output object |
writerHandle writer is ~java.io.BufferedWriter → output_handle,
Create a text output handle object wrapping a Java BufferedWriter instance.
writer | - | a java.io.WriterReader instance to be used |
Miscellaneous functions
var _argv is array<string>, Program command line arguments. It is thread-local.
fetchURL options result url is ,
list?<> →
CharSet. (string → string) |
Callback to determine response body charset.
Argument is charset from the Content-Type response header.
Delete. () |
Send DELETE request.
Disconnect. (number → boolean) |
Disconnect sets predicate function that determines whether
to disconnect for given status code.
Default is to always disconnect, but this disables
connection reuse via keep-alive for JDK.
DisconnectOnError. () |
Disconnect on HTTP 408 and 5xx errors.
Expires. (number → ()) |
Callback to be called for expiration time
in milliseconds from epoch.
Head. () |
Send HEAD request.
Header. (string → string → ()) |
Callback to be called on each response header
(with header name and value as arguments).
Post. string |
Send POST request with the given body.
Put. string |
Send PUT request with the given body.
SetHeader. {.name is string, .value is string} |
Set request header.
Status. (number → string → ()) |
Callback to be called for the status code and message.
If not set, then HTTP error response causes IOException.
Timeout. number |
Set timeout in seconds.
UseCaches. boolean
Set using caches.
() →
Binary. (bin_input_handle → 'd) |
Apply given function to bin_input_handle
reading from the response body.
Handle. (input_handle → 'd) |
Apply given function to input_handle
reading from the response body.
Stream. (~java.io.InputStream → 'd)
Apply given function to InputStream
reading from the response body.
string →
'd
Fetches given url, mostly useful for making HTTP GET or POST requests.
options | - | option list |
result | - | block to read the response body |
url | - | URL to fetch |
Examples
Fetch URL as string and print it:str = fetchURL [] (Handle getContents) 'http://example.com/'; println str;Fetch as binary data and write to file:
data = fetchURL [] (Binary (binReadAll 0)) 'http://example.com/'; binWriteFile 'example.html' (data |>);
runThread options block is ,
list?<> →
ClassLoader. ~java.lang.ClassLoader |
Set the threads context class loader.
Daemon. ()
Mark the thread a daemon thread. The JVM exits when last
non-daemon thread has stopped.
(() → ()) →
~java.lang.Thread
Starts a new thread, which will start execution by invoking
the given block. Returns java.lang.Thread object corresponding
to the created thread.
options | - | options for the new thread |
block | - | a function invoked by the new thread |
runnable function is (() → ()) → ~java.lang.Runnable,
Create java.lang.Runnable instance that applies the given function
to (), when its run method is invoked.
function | - | function to apply, when run method is invoked |
sleep seconds is number → (),
Puts the current thread to sleep for given number of seconds.
seconds | - | how long to sleep (with 1/1000 second precision) |
sysExit status is number → 'k,
Terminates the Java virtual machine process with given exit status
(by calling System#exit(status)).
status | - | exit status code to be returned from the JVM process |
threadExit status is number → 'l,
Terminates the current thread. If it is a main thread, the whole
Java virtual machine will quit with the given exit status.
status | - | exit status code to be used when main thread is terminated |
Notes
The implementation works by throwing yeti.lang.ExitError, which is catched by the Yeti compiler generated main function.withHandle handle block is {.close is () → ()} → ({.close is () → ()} → 'o) → 'o
Applies block to the given handle, after that applies handle.close field
to () value, even when exception was thrown by the block (the exception
will be passed to caller of withHandle in that case). Returns the value
returned by the block.
handle | - | object with close field |
block | - | a function to be applied to the given handle |