The Quarz standard library
Classes and modules
ArgumentErrorAn argument with the right type but a wrong value: a malformed text for Integer or Float, rand(0), an exclusive range for Comparable#clamp, an invalid radix.ArrayAn ordered, immutable sequence of Ts: [1, 2, 3], %w[a b], Array[Int].new.Array::BuilderA mutable array: Ruby's destructive Array API, for building an array step by step. Its methods change it in place and most return the builder itself, so calls chain (b << 1 << 2).AtomA shared cell holding an immutable value, which any task can read and replace atomically. The replacement for shared mutable state: an update computes a new value from the old one and swaps it in.BoolThe class of true and false.BytesAn immutable sequence of bytes: binary data, which a String (always UTF-8) does not hold.Bytes::BuilderA mutable buffer of bytes, for building Bytes piece by piece.Bytes::MatchDataA match in Bytes: as MatchData, with Bytes and byte offsets.ChannelA typed queue between tasks: all communication and synchronization between tasks goes through channels.Channel::ClosedRaised by sending on a closed channel and by Channel#receive on one that is closed and empty.ComparableThe comparison operators, between? and clamp, for a class that includes it and defines <=>. T is the type compared with, usually the class itself (include Comparable[Version]).DeadlockErrorEvery task is blocked (on a channel, on another task) and none can make progress. A fatal error, as Ruby's fatal and Go's "all goroutines are asleep": the runtime reports it with the blocked tasks and stops the program with status 1, without raising it where a rescue could catch it or an ensure run.DirDirectories, and the current directory. Operating-system failures raise SystemCallError. The operations that read or change the file system run on a helper thread: only the calling task waits.DslScopeA marker for DSL receivers: inside a block whose receiver includes it, the receivers of enclosing blocks that include it are not implicit (a call must name them), so nested builders do not leak into each other. The enclosing method's self stays implicit.DurationA span of time, kept as a signed 64-bit count of nanoseconds: about 292 years either way. Made by Int#ms, Int#seconds, Float#minutes and the like; sleep and timeouts take one.EOFErrorReading past the end of the input: gets, readline and IO#readline at the end of the file (gets? returns nil instead).EnumerableA module of collection methods built on each. A class that includes Enumerable[T] and defines each gets every other method here: mapping and filtering (#map, #select, #filter_map, #flat_map), folding (#reduce, #sum, #count, #tally), searching (#find, #include?, #any?), slicing (#first, #take_while, #each_slice), grouping (#group_by, #partition, #chunk_while) and ordering (#sort_by, #min_by). #sort, #min, #max, minmax, min(n) and max(n) need either a comparator block or elements that are Comparable, and #sum without a block needs Int, Float or Integer elements.EnumeratorAn external iterator over what a method yields: xs.each, xs.map, xs.each_with_index, xs.each_slice(n), range.step(n) without a block return one. It is Enumerable, so xs.each_with_index.map { } works, and #with_index collects with an index (xs.map.with_index).ExceptionThe root of the exception classes. raise takes an instance of one (raise ArgumentError, "bad size" makes it), and rescue without a class catches StandardError and its subclasses only: the direct subclasses of Exception are for what a program does not usually handle (SystemStackError, Task::Cancelled).FileFiles, by path. Operating-system failures (a missing file, say) raise SystemCallError; File.open with a block closes the file afterwards.FloatA double-precision (IEEE 754 binary64) floating-point number.FloatDomainErrorA Float that has no integer: NaN or an infinity converted to an Int (Float#to_i, floor, round, ...), as in Ruby. A RangeError. Math functions return NaN instead.FrozenErrorAn attempt to change a frozen value. Declared for compatibility with Ruby: built-in values are immutable and have no methods that change them, so the runtime does not raise it.HTTPHTTP: require "http". An HTTP/1.1 server for use behind a reverse proxy (docs/11-http.md): a handler takes a Request and returns a Response; the server runs a task per connection.HTTP::BadRequestA malformed request or body: answered 400.HTTP::BodyA request body, read from the connection as the handler asks for it.HTTP::BodyWriterGiven to a Stream body's procedure: each write is a chunk.HTTP::ErrorAnswered with its status (and its message as a text body) when a handler raises it; the parser raises the subclasses.HTTP::FieldOne header field, its name lowercased.HTTP::HandlerWhat serves requests: a Router, a procedure (HTTP.handler) or a class or data of one's own. Handlers are Shareable, since every connection's task calls them: state shared between requests lives in an Atom or a Channel. Middleware is a handler holding the next.HTTP::HeadersHeader fields in order, names lowercased; a name may repeat. Names are case-insensitive, and written out in the conventional form (Content-Type). Immutable: put, add and delete return new headers.HTTP::HeadersTooLargeA request line and headers over the server's max_header_bytes: answered 431.HTTP::OptionsA server's settings, as Server.new takes them.HTTP::PayloadTooLargeA body over the server's max_body_bytes (Body#read): answered 413.HTTP::ProxiesTrusted proxies: addresses or networks (10.0.0.0/8, fd00::/8).HTTP::RequestA request, as the server read it or as a test builds it (HTTP::Request.get). A data value: with makes a changed copy. It is not Shareable, since its Body is not: copy the fields a task needs out of it before spawning one.HTTP::ResponseWhat a handler returns. A data value: #header and with make changed copies. When it sends one, the server adds the framing (Content-Length or Transfer-Encoding) and a Date header.HTTP::ResponseBodyThe body of a Response. The server adds the framing it implies: Content-Length for all but ResponseBody::Stream, which is sent chunked.HTTP::RouterRoutes by method and path pattern (/users/{id}, /files/{path...}): the most specific match wins; a path that only other methods have is answered 405.HTTP::RouterBuilderCollects routes for Router.build. A pattern is a path whose segments may be {name} (one segment) or, last, {name...} (the rest of the path, possibly empty, slashes included); a trailing slash is significant.HTTP::ServerAn HTTP/1.1 server: a task per connection, requests on one connection served in order. Shareable, so that a Signal.trap block or another task can shut it down.HashAn immutable map from keys to values, kept in insertion order.Hash::BuilderA mutable hash, for building a Hash in place.IOA stream: the standard streams and open files. At the end of the stream, gets, readline and read(length) raise EOFError, gets? and read?(length) return nil, and read and read? (the rest of the stream) return "".IOErrorAn operation on a stream that cannot do it: writing to a closed stream or to one not opened for writing, rewinding a socket.IndexErrorAn index out of range: Array#[] and the indexing methods that do not return nil (the ? forms do) raise it.IntA 64-bit integer: arithmetic that leaves the range raises OverflowError. Integer is the integer of any size.IntegerAn integer of any size: arithmetic with an Int gives an Integer (an Int becomes one only by to_integer, or as a literal where an Integer is expected, or too large for an Int).JSONJSON: parsing into JSON::Value and generation from any value.JSON::GeneratorErrorRaised by JSON.generate on a value JSON cannot represent, such as a Float infinity or NaN.JSON::ParseErrorRaised by JSON.parse on malformed input; the message gives the line and column.JSON::ValueA parsed JSON document, its variants named as Rust's serde_json names them. A Number holds any number: an Int, an Integer when too large for an Int (kept exact), or a Float when it has a fraction or an exponent. Inside the enum the names are the variants: the types are ::Bool, ::String and so on.KernelThe program's functions (puts, gets, rand, exit, ...), included in Object: private, so they are called without a receiver, as in Ruby.KeyErrorA key that is not there: Hash#[] with a missing key, as fetch does in Ruby (Hash#[]? returns nil instead).MatchDataA match of a Regexp in a string: the matched text, its groups and where they are. Positions are character indices. Made by String#match, String#matches, Regexp#match and given to the blocks of String#sub, String#gsub and String#scan.MathFloating-point functions, as Ruby's Math: angles are in radians.MetaWhat a static def sees of the program at compile time (docs/14). Meta::ClassDef exists at compile time only; the data types are ordinary values.Meta::ClassDefThe class being declared, as a static statement and the static class method it calls see it through self: a Type[T] (the class as a value, with its class methods and the reflection) that will also take the members a static def generates. At run time, in a static def that is not compile-time only, self is the class value itself.Meta::FieldA field of a class: its name, declared type (type arguments erased), whether it is var, and whether it has a default.Meta::MethodSigA method's signature: no body is visible.Meta::ParamA parameter of a method signature.Meta::ParamKindHow a parameter is passed.NilThe class of nil, the absence of a value. A type T? is T or Nil.NoMatchingPatternErrorA case/in whose patterns all fail to match, without an else. The compiler warns about such a case when it can tell the patterns do not cover the type.NoMemoryErrorDeclared for compatibility with Ruby. The runtime does not raise it: an allocation that fails aborts the process.NotImplementedErrorA method with no implementation: a native method the runtime does not provide, or an abstract method reached at run time. Programs raise it for what they leave unimplemented.ObjectThe root of the class hierarchy: every value is an Object, and the methods here apply to all of them. It includes Kernel, whose private functions (puts, rand, exit) are called without a receiver.OverflowErrorAn Int operation whose result does not fit in 64 bits. Integer holds integers of any size.ProcA block or a lambda as a value, of a type (A, B) -> R: called with call, () or [].ProcessThe running program and the child processes it runs.Process::OutputWhat a child process produced: Process.run("ls", "-l"), Process.sh("ls | wc -l").RandomA pseudo-random number generator with its own state; Random.rand and Kernel#rand draw from a default generator that srand seeds.RangeThe values from begin to end: 1..3 includes 3, 1...3 excludes it. Either bound may be left out: (1..) is endless and (..3) beginless; their missing bound is nil.RangeErrorA value out of the range an operation accepts: converting NaN or an infinity to an Int (Float#to_i), a Time out of range. Its subclass OverflowError is for Int arithmetic.RegexpA regular expression: a literal /.../imx or .new. Searches go through String's methods (String#match, String#scan, String#gsub, ...) or this class's match, match? and =~; positions are character indices. Bytes are searched with the same patterns, byte by byte.ResultThe result of an operation that can fail, as a value instead of an exception: Ok with the value or Err with the error. Make one with Result.ok and Result.err, take it apart with case/in, or chain it with map and and_then (a for comprehension desugars to flat_map). Result.capture turns an exception into an Err, and get raises an Err's exception again; ok and Result.ok_or go to and from T?.RuntimeErrorA generic error: what raise "message" raises (a String given to raise without a class), and what Result#unwrap raises on a Result::Err.ScopeThe scope a Task.scope block is given: the tasks started with #spawn are waited for when the block ends.SelectorWhat a Channel.select or Channel.select_loop block registers its operations on. Each method only registers an operation and its block; the chosen operation's block runs after the Channel.select block returns.SetAn immutable set: each value at most once, compared with == and hash.Set::BuilderA mutable set, for building a Set in place.ShareableA marker: values of the class can be shared between tasks. Derived automatically for user classes; the built-in classes declare it.SignalSignals: Signal.trap(:TERM) { } runs the block on a task of its own when the signal arrives (the signal handler only notes it).SocketSockets: require "socket". Every operation that would block suspends only the calling task; Task.timeout and cancel interrupt it. Addresses are Socket::Addresses; Socket has the ways to connect and serve, and the classes TCPSocket, TCPServer, UDPSocket, UNIXSocket and UNIXServer the connections.Socket::AddressA numeric address, IPv4 or IPv6, and a port.SocketErrorA host name that does not resolve.StandardErrorThe exceptions a program is expected to handle: a rescue without a class rescues these (and their subclasses) only. Define an application's errors under it.StopIterationThe end of an external iteration: Enumerator#next past the last element. loop rescues it and ends the loop.StringA sequence of characters, always valid UTF-8. Immutable: methods that change a string (#upcase, #sub, #insert) return a new one, and String::Builder is the mutable buffer to build one piece by piece.String::BuilderA mutable buffer of text, to build a String in pieces without copying at each step. to_s (and freeze) hand the contents over without copying and leave the builder empty; snapshot copies. Indices count characters, as a string's do. A builder is Unshareable: it stays in the task that made it.SymbolA name, written :name (or :"any text"): interned, so equal symbols are the same value and compare in constant time. Used for hash keys, options and enum-like values.SystemCallErrorA call to the operating system that failed, with its message: opening a file that does not exist, a refused connection.SystemExitRaised by exit and abort to end the program, as in Ruby. Outside StandardError, so a plain rescue lets it through: the ensure clauses it leaves run, and one nothing rescues ends the program with #status (from any task) after the at_exit blocks. rescue SystemExit (or Exception) catches it; exit! ends the program without it.SystemStackErrorA recursion too deep for the task's stack ("stack level too deep"). Outside StandardError: only rescue SystemStackError (or rescue Exception) catches it.TCPServerA listening TCP socket: Socket.tcp_server and Socket.tcp_server_loop make one, or TCPServer.new.TCPSocketA TCP connection: Socket.tcp(host, port) makes one.TaskA lightweight thread, running a block concurrently with the others, and the handle to its result T.Task::CancelledRaised in a cancelled task (Task#cancel, Scope#cancel, a failing Task.scope). A direct subclass of Exception: rescue => e does not catch it, and ensure runs as usual.Task::TimeoutRaised by Task.timeout when the block has not finished in time.TestTests: require "test", run by quarz test (docs/12-testing.md). A test is a test_* method of a class that inherits Test::Case, and the compiler finds them and generates the runner.Test::AssertionFailedA failed assertion. Not a StandardError, so that rescue => e in the code under test does not swallow it.Test::AssertionsThe assertions, for Test::Case and for a module of tests or helpers that test classes include (module Sizes; include Test::Assertions).Test::CaseThe base class of test cases: an instance is made for each test. quarz test runs every public test_* method of a class that inherits it (docs/12-testing.md); a field with an initializer is a fixture, fresh for each test.Test::Omittedomit: the test does not apply here.Test::Pendingpend: the test is known not to pass yet.Test::UnitA module that gives Test::Case its Test::Unit name, Test::Unit::TestCase, for tests moved from Ruby.TimeA point in time, to the nanosecond, with the UTC offset it is shown in. Immutable.TypeA class as a value, as x.class returns it and is_a? takes it: Int written in an expression is a Type[Int], Array[Int] a Type[Array[Int]], and x.class a Type[Object], also written Class. A Type of a subclass is a Type of its superclass (Type[StandardError] is a Type[Exception]). A class is constructed with new only where it is written (Array[Int].new, or new in a class method): a Type[T] value may hold a subclass whose initialize takes other arguments. At run time a class value carries no type arguments: Array[Int] and Array[String] are the same value.TypeErrorA value of the wrong type at run time: a failed cast with as (x.as(String) on an Int), or a JSON value of another kind than the accessor asked for.UDPSocketA UDP socket, sending and receiving datagrams.UNIXServerA listening UNIX domain socket: Socket.unix_server(path) makes one.UNIXSocketA connection to a UNIX domain socket: Socket.unix(path) makes one.UnshareableA marker: the builders, which no other task may see.ZeroDivisionErrorAn integer division or modulo by zero (Int#/, Int#%). A Float division by zero is not an error: it gives an infinity or NaN.
Constants
ARGV: Array[String]
The command-line arguments given to the program, without the program's
name (Process.argv).
<prelude>:6916
ENV: Hash[String, String]
The environment variables when the program started, as an immutable
Hash (Process.env).
<prelude>:6919
STDERR: IO
Standard error (Process.stderr): what warn writes to.
<prelude>:6925
STDIN: IO
Standard input (Process.stdin).
<prelude>:6921
STDOUT: IO
Standard output (Process.stdout): what puts and print write to.
<prelude>:6923