bound to a new mapping that contains just the fields for which that did not
match a field-match-pattern
.
For every match pattern, there is a set of shapes that the pattern matches. The
type corresponding to the match pattern is the type containing these shapes. The
value matches the pattern if and only if it looks like the type. A mutable value
thus can match the pattern without belonging to the corresponding type. However,
an immutable value that matches the pattern will always belong to the type.
In particular, for the match of an error-match-pattern
with an
error-type-reference
against an error value to succeed, the
error value must belong to the referenced error type.
This section uses the read-only intersection between two types, which is defined analogously to the read-only difference used for conditional variable type narrowing as follows. We use the notation T &ro S for the read-only intersection of T and S. T &ro S is computed separately for each uniform type. Let TU be the subset of T belonging to uniform type U, i.e. the intersection of T and U. For a uniform type U that is immutable, TU &ro SU is the same as TU & SU; for a uniform type U that is mutable, TU &ro SU is empty if TU & SU is empty, and TU otherwise. T &ro S is the union for every uniform type U of TU &ro SU. Note that the read-only intersection operation is not commutative.
A match-clause
is defined to be unguarded if it does not
have a match-guard
or if the static type of the expression in the
match-guard
is singleton true.
For each match-clause
C, we can compute a type L that the target
value must look like if the statement-block
of C is
executed. L is computed as the difference of a positive type P and negative type
N, where
match-pattern-list
of C, andmatch-pattern-list
of every unguarded match-clause
that precedes C.
Let T be the static type of the match-target
. If the intersection
of T and L is empty, then it is not possible for the
match-pattern-list
of C to match, and accordingly the statements in
the statement-block of C are not reachable. If the match-target
is
a variable-reference
, then the type of the referenced variable is
narrowed to T &ro L within the match-guard
, if any,
and the statement-block
of C. If there is a
match-guard
, then the type narrowing described in Conditional variable type
narrowing is in addition applied to the statement-block
A match-stmt
is exhaustive if and only if the static type
of the match-target
is a subtype of union of the type corresponding
to the match patterns of the match-pattern-list
of every unguarded
match clause. A match-stmt
that is exhaustive can complete normally
only if at least one of its statement-block
s can complete normally.
foreach-stmt :=foreach
typed-binding-patternin
action-or-expr statement-block
A foreach statement iterates over an iterable value, executing a statement block once for each value in the iterable value's iteration sequence. The static type of action-or-expr must be an iterable type with an iteration completion type of nil.
The scope of any variables created in typed-binding-pattern is statement-block. These variables are implicitly final.
In more detail, a foreach statement executes as follows:
In step 2, the compiler will give an error if the static type of expression is not suitable for 2a or 2b.
In step 5, the typed-binding-pattern is used unconditionally, and the compiler
will check that the static types guarantee that the match will succeed. If the
typed-binding-pattern uses var, then the type will be inferred from the type of
action-or-expr
.
while-stmt := while
expression statement-block
A while statement repeatedly executes a statement block so long as a boolean-valued expression evaluates to true.
In more detail, a while statement executes as follows:
The static type of expression
must be a subtype of boolean.
continue-stmt :=continue
;
A continue statement is only allowed if it is lexically within a while-stmt or a foreach-stmt. Execution a continue statement results in a transfer of control that causes the execution of the outermost statement-block in the nearest enclosing while-stmt or foreach-stmt to complete normally.
break-stmt :=break
;
A break statement is only allowed if it is lexically within a while-stmt or a foreach-stmt. Execution of a break statement results in a transfer of control that causes the execution of nearest enclosing while-stmt or foreach-stmt to complete normally.
lock-stmt := lock
statement-block
A lock-stmt executing in the context of some strand must execute its statement-block in such a way that the effect on the state of the program is consistent with the execution of the statement-block not being interleaved with the execution of a lock-stmt on any other strand.
A naive implementation can simply acquire a single, program-wide, recursive mutex before executing a lock statement, and release the mutex after completing the execution of the lock statement. A more sophisticated implementation can perform compile-time analysis to infer a more fine-grained locking strategy that will have the same effects as the naive implementation.
It is not allowed to start a new strand within a lock. More precisely, when a strand has started but not yet completed the execution of a lock-stmt, the execution of a named-worker-decl or a start-action on that strand will result in a panic. It is a compile-time error for a named-worker-decl or start-action to occur lexically within a lock-stmt. The compiler may also give a compile-time error if a function definition contains a named-worker-decl or start-action, and there is a function call lexically within the lock-stmt that might result directly or indirectly in a call to that defined function.
There are two cases where a variable is restricted to be used only within a lock statement:
self
within an isolated object and
self
occurs in a field-access-expr self.x
,
unless the field x
is isolated; since non-isolated
fields are required to be private, this restriction applies only to the object's
methods.When a lock statement contains one of the above two cases of restricted variable usage, the lock statement is subject to the following additional requirements, which maintain the invariant that the restricted variable is an isolated root.
self
behaves like a
parameter.
The execution of a statement can fail either as the result of check
expression or action, or from an explicit fail
statement. When
execution of a statement fails, control flow transfers to the nearest lexically
enclosing failure-handling statement. The failure handling statements are
stmt-with-on-fail, retry-stmt, transaction-stmt and retry-transaction-stmt. If
there is no such statement, it terminates the current worker normally. Note that
failure is completely distinct from panic.
When execution fails there is an associated error value, which is passed to the failure-handling statement if there is one. If there is no failure-handling statement, then the error value becomes the return value of the worker. The possible failure control flows are known at compile-time, as are the types of the associated error values. For every statement, the type of the error value associated with a failure causing control to transfer out of the block is determined at compile-time. This is in contrast with panics, for which the type of associated error value is not known at compile-time.
fail-stmt :=fail
expression;
Executing a fail-stmt will cause control flow to transfer to the nearest lexically enclosing failure handling statement.
The static type of the expression must be a subtype of error. Execution of the fail-stmt evaluates the expression; the resulting error value is passed to the failure handling statement or becomes the termination value of the current worker.
stmt-with-on-fail := regular-compound-stmt on-fail-clause on-fail-clause :=on
fail
[typed-binding-pattern] statement-block
A stmt-with-on-fail
is executed by executing the
regular-compound-stmt
. A check
expression or action,
or a fail
statement may cause control to transfer to the
on-fail-cause
. If so, the statement-block
is executed;
otherwise the statement-block
is not executed.
If there is a typed-binding-pattern
, then it is matched to the
associated error value, binding the variables occurring within the
typed-binding-pattern
; the statement-block
is executed
with these bindings in scope. The static type of the associated error value is
determined from the static type of the relevant check
expressions
and actions, and fail
statements. It is a compile error unless the
match of the typed-binding-pattern
with the associated error value
is guaranteed to succeed by the static type of the associated error value.
retry-stmt :=retry
retry-spec statement-block retry-spec := [type-parameter] [(
arg-list)
]
The type-parameter in a retry-spec specifies a class, which must be a subtype of
RetryManager<F>, where F is the failure type of the statement-block; this
implies that the parameter type of the class's shouldRetry method must be a
supertype of F. The arg-list in a retry-spec specifies parameters to be passed
to the class's init
method; as with new
, the arg-list
can be omitted if the class's init
method has no required
arguments.
A retry-stmt is executed as follows:
new T(A)
,
where T and A are the type-descriptor in the type-parameter and the arg-list
respectively.r.shouldRetry(e)
. If the result is true, go back to the previous
step. If the result is false, then continue with the fail.
If the type-parameter is omitted, it defaults to
DefaultRetryManager
defined in langlib error module.
Ballerina provides language support for distributed transactions. A global transaction consists of one or more transaction branches, where a branch corresponds to work done by a single strand of a Ballerina program that is part of the global transaction. Every transaction branch is uniquely identified by an XID, which consists of an identifier of the global transaction and an identifier of a branch with the global transaction.
At runtime, there is a mapping from each strand to a transaction stack, which is a stack of transaction branches. A strand is in transaction mode, if its transaction stack is non-empty; the top of a strand's transaction stack is the current transaction branch for that strand.
Static checking is based on the idea of a transactional scope: this is a lexical
region of the program where it is known that at runtime the strand executing the
region will always be in transactional mode. A function with the
transactional
qualifier can only be called in a transactional
scope; this includes function calls using start
.
A running instance of a Ballerina program includes a transaction manager. This may run in the same process as the Ballerina program or in a separate process. It should not be connected over an unreliable network. The transaction manager of a program is responsible for managing the transaction branches of all the program's strands.
When a global transaction involves multiple Ballerina programs, there must be a
network protocol that allows that transaction managers for each Ballerina
program to communicate. The protocol must also allow a remote method or resource
method on a service object to be informed of the global transaction, if any, to
which it belongs. When a listener object determines that a remote method or
resource method of a service object is to be a part of a global transaction
manager, then it will create a new transaction branch, join it to the global
transaction and push that on the transaction stack for the strand on which the
method is called; if the method is declared as transactional
, the
listener will not call the method unless it can do this. Similarly, the protocol
must allow a remote method on a client object that is called in transaction mode
to send information about the global transaction of which it is part; if the
method is declared as transactional
, then as usual the method can
only be called in transaction mode; it also implies that the client object
implementation is transaction-aware, and that the recipient of the message sent
by the remote method must join the global transaction. A global transaction can
combine Ballerina programs with programs written in other programming languages
provided they agree on this network protocol.
A strand in transaction mode can register commit or rollback handlers with the transaction manager; the handlers are functions which will be called by the transaction manager when the decision has been made whether to commit or rollback the global transaction to which the current transaction branch belongs.
Note that internal storage in Ballerina is not transactional. Rolling back a transaction does not automatically restore the mutable values are variables to their state when the transaction started. It is up to the programmer to do this using commit or rollback handlers.
When a new strand is created by a named-worker-decl that includes a
transactional
qualifier or by using start
to call a
function with a transactional
qualifier, a new transaction branch
will be created and joined to the global transaction; this transaction branch
will be pushed onto transaction stack for the newly created strand.
Ballerina also has the concept that a transaction may be part of a sequence of retries, where the last transaction can complete with either a rollback or commit, and the preceding transactions all completed with a rollback.
The semantics of Ballerina's transactional language features are defined in terms of the following abstract operations on the transaction manager. These operations cover only the interface between the application and the transaction manager, not the interface between the resource manager and the application. These operations are all performed by a Ballerina program in the context of a strand. The transaction manager supports additional operations, which are defined in the langlib transaction module.
The Begin operation starts a global transaction and pushes a transaction branch for the new global transaction onto the current strand's transaction stack. This transaction branch is the initiating branch of the global transaction. The current strand will be in transaction mode.
The Begin operation has an optional parameter that contains information about the previous transactions in a sequence of retries.
The Commit operation is only called in transaction mode, and when the current transaction branch is the initiating branch of a global transaction. The Commit operation always removes the topmost transaction branch from the strand's transaction stack. The Commit operation initiates a commit of the global transaction that the current transaction branch belongs to.
When the commit is initiated, the transaction manager runs a two-phase commit protocol if necessary. First, it requests each participant to prepare to commit and waits for the participants to respond. There are two possibilities. If it receives a response from each participant that it is prepared to commit, then the transaction manager will make a decision to commit. If it receives a response from any participant that it cannot commit or it gives up waiting for a response from any participant, then the transaction manager will make a decision to rollback; in this case, it will create an error value for the cause of the rollback.
Once the transaction manager has made a decision whether to commit, it calls the handlers that were registered with it for for the branches of the global transaction that it is managing; the commit handlers are called if the decision was to commit and the rollback handlers are called if the decision was to rollback. The error value for the cause of the rollback will be passed as an argument to the call of each rollback handler. At this point, the Commit operation can return. The transaction manager will also communicate its decision to the transaction's participants, which will result in them running commit or rollback handlers for their branches.
The Commit operation has an optional parameter which is a RetryManager object or nil, which defaults to nil. If this parameter is non-nil and the decision is to rollback, then the transaction manager will call the RetryManager object's shouldRetry method, record the result and then pass it as the willRetry parameter to any rollback handlers.
If the transaction manager decided to rollback, then the Commit operation returns the error value for the reason for the rollback. Otherwise, it returns nil.
The Rollback operation is only called in transaction mode, and when the current transaction branch is the initiating branch of a global transaction. The Rollback operation always removes the topmost transaction from the strand's transaction stack. The Rollback operations initiates a commit of the global transaction that the current transaction branch belongs to. The transaction manager calls the rollback handlers that were registered with it for the branches of the global transaction that it is managing. The Rollback operation has a parameter which is either an error value or nil; this is passed as an argument to any rollback handlers.
The Rollback operation also has an optional parameter which is a RetryManager object or nil, which defaults to nil. If this parameter is non-nil, then the transaction manager will call the RetryManager object's shouldRetry method, record the result and then pass it as the willRetry parameter to any rollback handlers.
A transaction is performed using a transaction statement. The semantics of the transaction statement guarantees that every transaction manager Begin operation will be paired with a Rollback or Commit operation.
transaction-stmt := transaction
statement-block
The statement-block must contain at least one commit-action. In addition, the compiler must be able to verify that any exit out of the statement-block that is neither a panic nor a fail will have executed a commit-action or rollback-stmt.
A transaction-stmt is executed as follows:
The statement-block of a transaction-stmt is a transactional scope, except for any statements that could potentially be executed after the execution of a commit-action or rollback-stmt.
It is an error for a transactional-stmt to appear in a transactional scope. However, it is not an error if the current strand is in transaction mode when a transaction-stmt is executed: in this case, the Begin() operation performed by the transaction-stmt will, as usual, start a new transaction, which will be completely independent of any existing transactions.
retry-transaction-stmt := retry
retry-spec transaction-stmt
A retry-transaction-stmt is the same as a retry-stmt containing a transaction-stmt, except as follows.
commit-action := commit
A commit-action
is only allowed if it is lexically within the
statement-block
of a transaction-stmt.
Evaluating the commit-action
performs the transaction manager
Commit() operation; the result of this operation is the result of the
commit-action
. The type of the result is
transaction:Error?
. Note that the commit action does not alter the
flow of control.
rollback-stmt :=rollback
[expression];
A rollback-stmt
is only allowed if it is lexically within the
statement-block
of a transaction-stmt.
The rollback-stmt
performs the transaction manager Rollback(e)
operation, where e is the result of executing the expression
, if
present, and nil otherwise. Note that like the commit action, the rollback
statement does not alter the flow of control.
panic-stmt :=panic
expression;
A panic statement terminates the current worker abnormally. The result of
evaluating expression
provides the termination value of the worker.
The static type of expression
must be a subtype of error.
return-stmt :=return
[ action-or-expr ];
A return statement terminates the current worker normally.The result of evaluating the action-or-expr provides the termination value of the worker. If action-or-expr is omitted, then the termination value is nil.
Each source part in a Ballerina module must match the production
module-part
.
The import declarations must come before other declarations; apart from this, the order of the definitions and declarations at the top-level of a module is not constrained.
module-part := import-decl* other-decl* other-decl := listener-decl | service-decl | function-defn | module-type-defn | module-class-defn | module-var-decl | module-const-decl | module-enum-decl | module-xmlns-decl | annotation-decl
import-decl :=import
[org-name/
] module-name [as
import-prefix];
import-prefix := module-prefix |_
module-prefix := identifier | predeclared-prefix org-name := import-identifier module-name := import-identifier (.
import-identifier)* import-identifier := RestrictedIdentifier qualified-identifier := module-prefix NoSpaceColon identifier
If org-name is omitted, it is defaulted from the organization of the importing module.
A module-prefix
is a name that is used locally within the source of
a module to refer to another module. A module-prefix
in a
qualified-identifier must refer to a module-prefix
specified in an
import-declaration in the same source part.
An import-prefix of _
causes the module to be imported without
making its symbols available via a module-prefix. In this case, the effect of
importing the module will be just to cause the module to be included in the
program and initialized. It is an error for a source-part to import a module
using a module-prefix and then not to use that module-prefix.
A module-prefix
declared by an import-decl
is in the
same symbol space as a xmlns-namespace-prefix
declared by an
xmlns-decl
. This symbol space is distinct from a module's main
symbol space used by other declarations.
It is an error for a module to directly or indirectly import itself. In other words, the directed graph of module imports must be acyclic.
predeclared-prefix :=boolean
|decimal
|error
|float
|function
|future
|int
|map
|object
|stream
|string
|table
|transaction
|typedesc
|xml
A reserved keyword t
that is a predeclared-prefix is
predeclared as referring to the lang.t
lang library
module, but this can be overridden by an import-decl that imports a module using
that prefix. A predeclared-prefix can be used as a module-prefix without using a
QuotedIdentifier.
A Ballerina program consists of one or more modules; one of these modules is distinguished as the root module. The source code for a module uses import declarations to identify the modules on which it depends directly. At compile-time, a root module is specified, and the modules comprising the program are inferred to be those that the root module imports directly or indirectly. The directed graph of module imports must be acyclic.
Program execution may terminate successfully or unsuccessfully. Unsuccessful program termination returns an error value. Program execution consists of two consecutive phases: an initialization phase and a listening phase.
Module initialization is performed by calling an initialization function, which is synthesized by the compiler for each module. Module initialization can fail, in which case the initialization function returns an error value. The initialization phase of program execution consists of initializing each of the program's modules. If the initialization of a module is unsuccessful, then program execution immediately terminates unsuccessfully, returning the error value returned by the initialization function.
The initialization of a program's modules is ordered so that a module will not be initialized until all of the modules on which it depends have been initialized. (Such an ordering will always be possible, since the graph of module imports is required to be acyclic.) The order in which modules are initialized follows the order in which modules are imported so far as is consistent with the previous constraint.
A module's initialization function performs expression evaluation so as to
initialize the identifiers declared in the module's declarations; if evaluation
of an expression completes abruptly, then the module initialization function
immediately returns the error value associated with the abrupt completion. If a
module defines a function named init
, then a module's
initialization function will end by calling this function; if it terminates
abruptly or returns an error, then the module's initialization function will
return an error value. Note that the init
function of the root
module will be the last function called during a program's initialization phase.
This specification does not define any mechanism for processing the program
command-line arguments typically provided by an operating system. The Ballerina
standard library provides a function to retrieve these command-line arguments.
In addition, the Ballerina platform provides a convenient mechanism for
processing these arguments. This works by generating a new command-line
processing module from the specified root module. The init
function of the generated module retrieves the command-line arguments, parses
them, and calls a public function of the specified root module (typically the
main
function). The parsing of the command-line arguments is
controlled by the declared parameter types, annotations and names of the public
functions. The generated module, which imports the specified root module,
becomes the new root module.
A configuration is supplied as input to program execution. A
configuration consists of mapping from names of configurable
module-level variables to values. The values in a configuration always belong to
the type anydata&readonly
. The value for a variable in the
configuration is used during module initialization to initialize the variable
instead of the value specified in the module. A configurable module-level
variable may require that a configuration include a value for it. Except for
this requirement, a configuration may be empty. Before initializing any module,
the initialization phase must check that there is a value of the correct type
supplied for every configurable module-level variable that requires
configuration. If not, the module initialization phase terminates unsuccessfull.
If the initialization phase of program execution completes successfully, then execution proceeds to the listening phase, which is described in the next section. The termination of the listening phase, which may be successful or unsuccessful, terminates the program execution.
Service objects support network interaction using remote methods and resource methods. Listeners provide the interface between the network and service objects. A listener object receives network messages from a remote process according to some protocol and translates the received messages into remote methods calls or resource accesses of service objects that have been attached to the listener object. It is up to the listener object to determine how this translation happens. A resource path segment may correspond to something that at the protocol level is not a string. For example, in HTTP a path segment is natively a sequence of bytes. In this case, the listener should be able to convert this native representation into a string, for example, by using UTF-8 decoding. The type of the listener object constrains the type of a service that can be attached to the listener. (This constraint cannot yet be fully expressed by Ballerina's type system.)
A service object's remote or resource method uses its return value to indicate to the listener what further handling of the network message is needed. An error return value is used to indicate that the method encountered some sort of error in handling the network message. When a service object is returned, it means that the listener should use that service object to further handle the network message. When no further handling is needed, the return value should be nil.
The return value can also be used to supply a response to the network message. This has the limitation that the method cannot control what happens if there is an error in sending a response. It also has the limitation that it cannot handle complex message exchange patterns, although returning multiple responses to a single request can be modelled by returning a stream. A listener object can avoid these limitations by passing a client object as a parameter to the service object's remote or resource method; the service object then makes calls on the remote methods of the client object in order to send a response back to the client.
The methods defined by the Listener object type allow for the management of the lifecycle of a listener object and its attached services. A listener declaration registers a listener object with a module, so that it can be managed by the module. The runtime state of each module includes a list of listener objects that have been registered with the module. A listener object that has been registered with a module is called a module listener
If at the start of the listening phase of program execution there are no module
listeners, then the listening phase immediately terminates successfully.
Otherwise, the start
method of each module listener is called; if
any of these calls returns an error value, then the listening phase terminates
unsuccessfully with this error value as its return value.
The listening phase of program execution continues until either the program
explicitly exits, by calling a standard library function, or the user explicitly
requests the termination of the program using an implementation-dependent
operating system facility (such as a signal on a POSIX system). In the latter
case, the gracefulStop
or immediateStop
method of
each registered listener will be called before termination.
listener-decl := metadata [public
]listener
[type-descriptor] variable-name=
expression;
A listener-decl
declares a module listener. A module listener
declares a variable in a similar way to a final variable declaration, but the
type of the variable is always a subtype of the Listener object type,
and it has the additional semantic of registering the variable's value with the
module as a listener. As with a variable declared in a final variable
declaration, the variable can be referenced by a variable-reference, but cannot
be assigned to. A module may have multiple multiple listeners.
When a listener-decl is initialized as part of module initialization, its expression is evaluated. If expression evaluation completes abruptly or the result of the expression is an error, then module initialization fails. Otherwise the variable is initialized with the result of the evaluation.
If the type-descriptor is present, it specifies the static type of the variable.
The static type of expression
must be equivalent to a union L|E,
where L is a listener object type and E is subtype of error, which may be
never
; if the type-descriptor is not present, then L is used as the
static type of the variable.
service-decl := metadata [isolated-qual]service
[type-descriptor] [attach-point]on
expression-list object-constructor-block attach-point := absolute-resource-path | string-literal absolute-resource-path := root-resource-path | (/
resource-path-segment-name)+ root-resource-path :=/
expression-list := expression (,
expression)*
A service-decl
creates a service object and attaches it to one or more
listeners.
The static type S for the constructed service object is specified by the
type-descriptor if present, and otherwise is the union of a type inferred from
each expression in the expression list as follows. Each expression in the
expression-list must have a type Listener<T,A>|E where T is a subtype of
service object {}
, A is a subtype of
string[]|string|()
and E is a subtype of error
; the
inferred type is T. The object-constructor-block has the same semantics as in an
object-constructor-expr with a service
qualifier and a
type-reference that refers to S. If the service-decl includes
isolated
, then it is equivalent to an object-constructor-expr with
an isolated
qualifier as well as a service
qualifier.
The attach-point
determines the second argument passed to the
attach
method: if the attach-point
is absent, then the
argument is nil; if it is a string-literal
, then the argument is a
string; otherwise, it is an absolute-resource-path
and the argument
is an array of strings, with one string for each
resource-path-segment-name
. Attaching service objects
s1,...,sn with absolute
resource paths p1,...,pn
is equivalent to attaching a single service object with n
get
resource methods to /
, where the i-th
resource method has a path pi (an
absolute-resource-path
is turned into a
relative-resource-path
with the same
resource-path-segment-name
s) and returns
si.
A service-decl is initialized as part of module initialization as follows. The
object-constructor-block is evaluated as in an object-constructor-expr resulting
in a service object s
. Then for each expression in
expression-list:
obj
belonging to a listener object type;obj
is registered as a module listener
(registering the same object multiple times is the same as registering it
once);s
is then attached to obj
using obj
's attach
method;attach
fails, then module initialization
fails.A listener object can use the isolated bit of a service object and of a service object's remote method to determine whether it is safe to make concurrent calls to the remote object or the remote method.
The compiler may infer that a service object or a service object's remote method
is isolated even it is not explicitly declared as such. In doing so, it analyzes
a module to determine whether there is a set of declarations and definitions in
the module, where each of them is a service-decl
,
module-var-decl
, module-class-defn
function-defn
or method-defn
, and none of them
explicitly specified an isolated
qualifier, such that if all them
explicitly specified an isolated
qualifier, then they all would
meet the requirements for isolated functions
and isolated objects. If so, then the isolated bit of values resulting from them
is set in the same way as if isolated
qualifiers had been
explicitly specified. The analysis should not infer a function or method to be
isolated
if that would be inconsistent with an annotion supported
by the implementation that provides control over which thread is used for a strand
created for named-worker-decl or start-action.
This inference is purely an optimization to improve service concurrency and is
subject to two constraints. First, any inferences do not affect the static types
visible to other modules. Second, anything explicitly declared as
isolated
must satisfy the requirements of this specification
without without relying on inference.
function-defn := metadata [public
] function-qualsfunction
identifier function-signature function-defn-body function-defn-body := block-function-body | expr-function-body;
| external-function-body;
If a module has a function-defn with an identifier of init
, it is
called called automatically by the system at the end of the initialization of
that module; if this call returns an error, then initialization of the module
fails. The following special requirements apply to the init
function of a module: it must not be declared public
; its return
type must both be a subtype of error?
and contain ()
;
it must have no parameters.
If the function-quals includes transactional
, then
expr-function-body and the block-function-body are transactional scopes.
module-type-defn := metadata [public
]type
identifier type-descriptor;
A module-type-defn binds the identifier to the specified type descriptor. The binding is in the main symbol space. The type-descriptor is resolved as part of module initialization.
A class is a type descriptor that in addition to describing an object type also defines a way to construct an object belonging to the type; in particular, it provides the method definitions that are associated with the object when it is constructed.
module-class-defn := metadata [public
] class-type-qualsclass
identifier{
class-member*}
class-type-quals := (distinct
|readonly
| isolated-qual | object-network-qual)* class-member := object-field | method-defn | remote-method-defn | resource-method-defn | object-type-inclusion
It is an error for a keyword to appear more than once in
class-type-quals
.
As in an object constructor expression, a visibility qualifier of
private
can be used within a class definition; this means that the
visibility region consists of all method definitions in the class definition. If
class has private fields or methods, then it is not possible to define another
object type descriptor that is a subtype of the class's type.
If class-type-quals
contains readonly
, then an object
constructed using the class will have its read-only bit set; the effective type
of each field is thus the intersection of the specified type and
readonly
; furthermore, an object shape belongs to the class's type
only if its read-only bit is set.
If class-type-quals
contains isolated
, then the
defined object type is an isolated type, and an object constructed using the
type will have its isolated bit set. An object-field
or
method-defn
occurring as a class-member
in an isolated
class is subject to same requirements as when it occurs as an
object-member
in an object-constructor-expr
that is
explicitly isolated.
If an object-type-inclusion
references a type-descriptor that is a
class, then only the type of the class is included: the definitions of the
methods and any initializers for the fields are not included. If a class uses an
object-type-inclusion to include an object type T, then each method declared in
T must be defined in the class using a method-defn
with the same
visibility. If T has a method or field with module-level visibility, then C must
be in the same module. If the class is readonly (i.e.
class-type-quals
includes readonly
), then an
object-type-inclusion
in the class is allowed to directly or
indirectly reference a readonly
class or readonly
type
descriptor.
If class-type-quals
contains distinct
, then the
primary type-id of the class will the type-id of that occurrence of
distinct
, and the secondary type-ids will be the union of the
type-ids of the included object types. If class-type-quals
does not
contain distinct
, then the type-ids of the class come from the
included object types in the same way as with an object type descriptor.
An object of a class is initialized by:
init
method, if there is one
The parameter list of an init
method within an
module-class-defn
is not required to be empty, unlike within an
object-constructor-expr
.
module-var-decl := module-init-var-decl | module-no-init-var-decl
A module-var-decl declares a variable. The scope of variables declared in a
module-var-decl is the entire module. The variable may be initialized in the
declaration or within the module's init
function. If
final
is specified, then it is not allowed to assign to the
variable after it is initialized.
module-init-var-decl := metadata [public
] module-init-var-quals typed-binding-pattern=
module-var-init;
module-init-var-quals := (final
| isolated-qual)* |configurable
module-var-init := expression |?
A module-init-var-decl declares and initializes a variable. It is an error for a
keyword to appear more than once in module-init-var-quals
. If the
typed-binding-pattern uses var
, then the type of the variables is
inferred from the static type of expression
; if the module-var-decl
includes final
or configurable
, the precise type is
used, and otherwise the broad type is used. If the typed-binding-pattern
specifies a type-descriptor, then that type-descriptor provides the contextually
expected type for action-or-expr.
If the module-init-var-decl includes public
, then the
typed-binding-pattern must not use var
.
If a module-init-var-decl includes an isolated-qual, then the variable declared
is isolated. In this case, public
must not be specified, the
binding-pattern in the typed-binding-pattern must be just a variable-name, and
the expression must be an isolated expression. A variable declared as an
isolated variable can be accessed only within a lock-stmt. When an isolated-qual
occurs in a position where the grammar would allow it to be parsed as part of
module-init-var-quals or typed-binding-pattern, the former parse is used.
If configurable
is specified, then the initializer specified in the
module-var-init may be overridden at the time of module initialization by a
value supplied when the program is run. If such a value is supplied, then the
expression in the module-var-init is not evaluated and the variable is
initialized with the supplied value instead. A module-var-init of ?
is allowed only when configurable
is specified and means that a
configurable value must be supplied for this variable. If
configurable
is specified, then the typed-binding-pattern must use
an explicit type-descriptor rather than var
and the binding-pattern
must be just a variable-name. The type specified by the type-descriptor must be
a subtype of anydata
. A variable declared as
configurable
is implicitly final, and cannot be assigned to outside
the declaration. The static type of a variable declared as
configurable
is implicitly readonly
: the type
specified in the type-descriptor is intersected with readonly
. A
configurable variable can thus always be referenced within an isolated function.
module-no-init-var-decl := metadata [public
] [final
] type-descriptor variable-name;
A module variable declared with module-no-init-var-decl
must be
initialized in the module's init
function. It must be definitely
assigned at each point that the variable is referenced. If final
is
specified, then the variable must not be assigned more than once. The
type-descriptor
must not be never
.
module-const-decl := metadata [public
]const
[type-descriptor] identifier=
const-expr;
A module-const-decl declares a compile-time constant. A compile-time constant is an named immutable value, known at compile-time. A compile-time constant can be used like a variable, and can also be referenced in contexts that require a value that is known at compile-time, such as in a type-descriptor or in a match-pattern.
The type of the constant is the intersection of readonly
and the
singleton type containing just the shape of the value named by the constant. The
type of the constant determines the static type of a variable-reference-expr
that references this constant.
If type-descriptor is present, then it provides the contextually expected type
for the interpretation of const-expr. It is a compile-time error if the static
type of const-expr is not a subtype of that type. The type-descriptor must
specify a type that is a subtype of anydata and must not be never
.
Note that the type-descriptor does not specify the type of the constant,
although the type of the constant will all be a subtype of the type specified by
the type-descriptor.
module-enum-decl := metadata [public
]enum
identifier{
enum-member (,
enum-member)*}
enum-member := metadata identifier [=
const-expr]
A module-enum-decl provides a convenient syntax for declaring a union of string constants.
Each enum-member is defined as compile-time constant in the same way as if it had been defined using a module-const-decl. The result of evaluating the const-expr must be a string. If the const-expr is omitted, it defaults to be the same as the identifier.
The identifier is defined as a type in the same was as if it had been defined by a module-type-defn, with the type-descriptor being the union of the constants defined by the members.
If the module-enum-decl is public, then both the type and the constants are public.
So for example:
public enum Color { RED, GREEN, BLUE }
is exactly equivalent to:
public const RED = "RED"; public const GREEN = "GREEN"; public const BLUE = "BLUE"; public type Color RED|GREEN|BLUE;
module-xmlns-decl := xmlns-decl
A module-xmlns-decl
declares an XML namespace prefix with module
scope. It applies only to the source part in which it occurs, as with an
import-decl.
The semantics of xmlns-decl are described in the XML namespace declaration statement section.
Ballerina allows metadata to be attached to a construct by specifying the metadata before the construct.
metadata := [DocumentationString] [annots]
There are two forms of metadata: documentation and annotations.
annots := annotation+
annotation := @
annot-tag-reference annot-value
Annotations provide structured metadata about a particular construct. Multiple annotations can be applied to a single construct. An annotation consists of a tag and a value.
annotation-decl := metadata [public
] [const
]annotation
[type-descriptor] annot-tag [on
annot-attach-points];
annot-tag := identifier
An annotation-decl declares an annotation tag. Annotations tags are in a separate symbol space and cannot conflict with other module level declarations and definitions. The annotation tag symbol space is also distinct from the symbol space used by module prefixes and XML namespace prefixes.
The type-descriptor specifies the type of the annotation tag. The type must be a
subtype of one of the following three types: true
,
map<value:Cloneable>
,
map<value:Cloneable>[]
. If the type-descriptor is omitted,
then the type is true
.
annot-tag-reference := qualified-identifier | identifier annot-value := [mapping-constructor-expr]
An annot-tag-reference in an annotation must refer to an annot-tag declared in an annotation declaration. When an annot-tag-reference is a qualified-identifier, then the module-prefix of the qualified-identifier is resolved using import declarations into a reference to a module, and that module must contain an annotation-decl with the same identifier. An annot-tag-reference that is an identifier rather than a qualified-identifier does not refer to an annotation defined within the same module. Rather the compilation environment determines which identifiers can occur as an annotation-tag-reference, and for each such identifier which module defines that annotation tag.
Each annotation has a value. For every construct that has an annotation with a particular tag, there is also an effective value for that annotation tag, which is constructed from the values of all annotations with that tag that were attached to that construct. The effective value belongs to the type declared for the annotation tag. The type of the annotation tag determines the type of the annotation value and whether multiple annotations with the same tag on a single construct are allowed. For an annotation tag declared with type T, if T is M[] for some type mapping type M, then the type of the annotation value is M, multiple annotations are allowed, and the effective value is an array of the values for each annotation; otherwise the type of the annotation value is T, multiple annotations are not allowed, the effective value is the value of the single annotation.
If the type of the annotation value is true
, then a
mapping-constructor-expr is not allowed, and the annotation value is
true
. Otherwise the type of the annotation value must be a mapping
type M; if a mapping-constructor-expr is not specified, then it defaults to
{ }
; the mapping-constructor-expr must have static type M and the
annotation value is the result of evaluating the mapping-constructor-expr with M
as the contextually expected type.
If the annotation-decl for a tag specifies const
, then a
mapping-constructor-expr in annotations with that tag must be a const-expr and
is evaluated at compile-time with the semantics of a const-expr. Otherwise, the
mapping-constructor-expr is evaluated when the annotation is evaluated and the
ImmutableClone abstract operation is applied to the result.
An annotation applied to a module-level declaration is evaluated when the module is initialized. An annotation applied to a service constructor is evaluated when the service constructor is evaluated. An annotation occurring within a type descriptor is evaluated when the type descriptor is resolved.
annot-attach-points := annot-attach-point (,
annot-attach-point)* annot-attach-point := dual-attach-point | source-only-attach-point dual-attach-point := [source
] dual-attach-point-ident dual-attach-point-ident :=type
|class
| [object
|service
remote
]function
|parameter
|return
|service
| [object
|record
]field
source-only-attach-point :=source
source-only-attach-point-ident source-only-attach-point-ident :=annotation
|external
|var
|const
|listener
|worker
The annot-attach-points
specify the constructs to which an
annotation can be attached.
When an attachment point is prefixed with source
, then the
annotation is attached to a fragment of the source rather than to any runtime
value, and thus is not available at runtime. If any of the attachment points
specify source
, the annotation-decl must specify
const
.
When an attachment point is not prefixed with source, then the annotation is accessible at runtime by applying the annotation access operator to a typedesc value.
The available attachment points are described in the following table.
| Attachment point name | Syntactic attachment point(s) | Attached to which type descriptor at runtime |
| type | module-type-defn, module-enum-decl, type-cast-expr | defined type |
| class | module-class-defn | defined type (which will be type of objects constructed using this class) |
| function | function-defn, method-decl, method-defn, anonymous-function-expr | type of function |
| object function | method-decl, method-defn | type of function |
| service remote function | method-defn with remote qualifier on service object | type of function, on service value |
| return | return-type-descriptor | indirectly to type of function |
| parameter | required-param, defaultable-param, included-record-param, rest-param | indirectly to type of function |
| service | service-decl, object-constructor-expr with service qualifier | type of service |
| field | individual-field-descriptor, member-type-descriptor, object-field-descriptor | type of mapping, list or object |
| object field | object-field-descriptor, object-field | type of object |
| record field | individual-field-descriptor | type of mapping |
| listener | listener-decl | none |
| var | module-var-decl, local-var-decl-stmt, let-var-decl | none |
| const | module-const-decl, enum-member | none |
| annotation | annotation-decl | none |
| external | external-function-body | none |
| worker | named-worker-decl, start-action | none |
A documentation string is an item of metadata that can be associated with module-level Ballerina constructs and with method declarations. The purpose of the documentation strings for a module is to enable a programmer to use the module. Information not useful for this purpose should be provided in in comments.
A documentation string has the format of one or more lines each of which has a
#
optionally preceded by blank space.
The documentation statement is used to document various Ballerina constructs.
DocumentationString := DocumentationLine +
DocumentationLine := BlankSpace* #
[Space] DocumentationContent
DocumentationContent := (^ 0xA)* 0xA
BlankSpace := Tab | Space
Space := 0x20
Tab := 0x9
A DocumentationString
is recognized only at the beginning of a
line. The content of a documentation string is the concatenation of the
DocumentationContent
of each DocumentationLine
in the
DocumentationString
. Note that a single space following the # is
not treated as part of the DocumentationContent.
The content of a DocumentationString
is parsed as Ballerina
Flavored Markdown (BFM). BFM is also used for a separate per-module
documentation file, conventionally called Module.md
.
Ballerina Flavored Markdown is GitHub Flavored Markdown, with some additional conventions.
In the documentation string attached to a function or method, there must be
documentation for each parameter, and for the return value if the return value
is not nil. The documentation for the parameters and a return value must consist
of a Markdown list, where each list item must have the form ident -
doc
, where ident is either the parameter name or return, and doc is the
documentation of that parameter or of the return value.
The documentation for an object must contain a list of fields rather than parameters. Private fields should not be included in the list.
BFM also provides conventions for referring to Ballerina-defined names from
within documentation strings in a source file. An identifier in backticks
`X`
, when preceded by one of the following words:
type
service
variable
var
annotation
module
function
parameter
is assumed to be a reference to a Ballerina-defined name of the type indicated
by the word. In the case of parameter
, the name must be unqualified
and be the name of a parameter of the function to which the documentation string
is attached. For other cases, if the name is unqualified it must refer to a
public name of the appropriate type in the source file's module; if it is a
qualified name M:X, then the source file must have imported M, and X must refer
to a public name of an appropriate type in M. BFM also recognizes
`f()`
as an alternative to function `f`
. In both
cases, f can have any of the following forms (where `m` is a module import, `x` is a
function name, `T` is an object type name, and `y` is a method name):
x() m:x() T.y() m:T.y()
Example
# Adds parameter `x` and parameter `y` # + x - one thing to be added # + y - another thing to be added # + return - the sum of them function add (int x, int y) returns int { return x + y; }
The Ballerina platform may define additional conventions, in particular relating
to headings with particular content. For example, a heading with a content of
Deprecated
can be used to provide information about the deprecation
of the name to which the documentation string is attached.
Modules in the ballerina
organization with a module name starting
with lang.
are reserved for use by this specification. These
modules are called the lang library.
Modules in the lang library can make use generic typing. Since generic typing
has not yet been added to Ballerina, the source code for the modules use an
annotation to describe generic typing as follows. When a module type definition
has a @typeParam
annotation, it means that this type serves as a
type parameter when it is used in a function definition: all uses of the type
parameter in a function definition refer to the same type; the definition of the
type is an upper bound on the type parameter. A parameter of a function
definition can be annotated with an @isolatedParam
annotation; this
is allowed when the function is declared as isolated and the type of the
parameter is a function type; the meaning is that when the function is called in
a context that requires it to be isolated, then the argument supplied for the
parameter must also be isolated. In effect, the function is parameterized with
the isolated qualifier.
Note We plan to provide full support for generic types in a future version of this specification.
A module in the lang library can provide types that are built-in in the
sense that their meaning is defined by this specification. Each such built-in
type is a subtype of a single basic type; a built-in type that is a subtype of a
basic type B
is provided by the module
lang.B
.
The built-types provided by lang library modules are described in the following table.
| Basic type | Type name | Criteria for v to belong to type |
|---|---|---|
| int | Unsigned8 | 0 ≤ v ≤ 255 |
| Signed8 | -128 ≤ v ≤ 127 | |
| Unsigned16 | 0 ≤ v ≤ 65,535 | |
| Signed16 | -32,768 ≤ v ≤ 32,767 | |
| Unsigned32 | 0 ≤ v ≤ 4,294,967,295 | |
| Signed32 | -2,147,483,648 ≤ v ≤ 2,147,483,647 | |
| string | Char | v has length 1 |
| xml | Element | v is an element singleton |
| ProcessingInstruction | v is a processing instruction singleton | |
| Comment | v is a comment singleton | |
| Text | v is either the empty xml value or a text singleton |
Each built-in type has a type definition in the module that provides it. The
type descriptor of the type definition is the corresponding basic type. The type
definition has a @builtinSubtype
annotation, which indicates that
the meaning of the type name is built-in, as specified in the above table,
rather than coming from its type descriptor. It is an error to use the
@builtinSubtype
annotation except in a lang library module.
So, for example, the lang.int
module would include the definition:
@builtinSubtype type Signed32 int;
Semantically, these types behave like a predefined type that can be referenced
by an unqualified name, such as byte
. Syntactically, these types
are referenced by a type-reference
in the same way as if their
definitions were not built-in. A built-in type T
which is a subtype
of basic type B
can be referenced by a type-reference
M:T
, where M
is a module-prefix referring to module
ballerina/lang.B
.
For convenience, this specification refers to the built-in subtype T provided by
the module for basic type B as B:T. For example, in this specification
int:Signed32
refers to the Signed32
built-in subtype
of int
, which is provided by the lang.int
module.
The int:Unsigned8
type is equivalent to the predefined
byte
type.
The lang library consists of the following modules. With the exception of the
lang.value
, lang.transaction
and
lang.runtime
modules, each corresponds to a basic type.
lang.array
moduleThe lang.array
module corresponds to basic type list.
# A type parameter that is a subtype of `any|error`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type Type any|error; # A type parameter that is a subtype of `any|error`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type Type1 any|error; # A type parameter that is a subtype of `anydata|error`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type AnydataType anydata; # Returns the number of members of an array. # # + arr - the array # + return - number of members in `arr` public isolated function length((any|error)[] arr) returns int = external; # Returns an iterator over an array. # # + arr - the array # + return - a new iterator object that will iterate over the members of `arr`. public isolated function iterator(Type[] arr) returns object { public isolated function next() returns record {| Type value; |}?; } = external; # Returns a new array consisting of index and member pairs. # # + arr - the array # + return - array of index, member pairs public isolated function enumerate(Type[] arr) returns [int, Type][] = external; # Applies a function to each member of an array and returns an array of the results. # # + arr - the array # + func - a function to apply to each member # + return - new array containing result of applying `func` to each member of `arr` in order public isolated function 'map(Type[] arr, @isolatedParam function(Type val) returns Type1 func) returns Type1[] = external; # Applies a function to each member of an array. # The function `func` is applied to each member of array `arr` in order. # # + arr - the array # + func - a function to apply to each member public isolated function forEach(Type[] arr, @isolatedParam function(Type val) returns () func) returns () = external; # Selects the members from an array for which a function returns true. # # + arr - the array # + func - a predicate to apply to each member to test whether it should be selected # + return - new array only containing members of `arr` for which `func` evaluates to true public isolated function filter(Type[] arr, @isolatedParam function(Type val) returns boolean func) returns Type[] = external; # Combines the members of an array using a combining function. # The combining function takes the combined value so far and a member of the array, # and returns a new combined value. # # + arr - the array # + func - combining function # + initial - initial value for the first argument of combining function `func` # + return - result of combining the members of `arr` using `func` # # For example # ``` # reduce([1, 2, 3], function (int total, int n) returns int { return total + n; }, 0) # ``` # is the same as `sum(1, 2, 3)`. public isolated function reduce(Type[] arr, @isolatedParam function(Type1 accum, Type val) returns Type1 func, Type1 initial) returns Type1 = external; # Tests whether a function returns true for some member of an array. # `func` is called for each member of `arr` in order unless and until a call returns true. # When the array is empty, returns false. # # + arr - the array # + func - function to apply to each member # + return - true if func returns true for some member of `arr`; otherwise, false # public isolated function some(Type[] arr, @isolatedParam function(Type val) returns boolean func) returns boolean = external; # Tests whether a function returns true for every member of an array. # `func` is called for each member of `arr` in order unless and until a call returns false. # When the array is empty, returns true. # # + arr - the array # + func - function to apply to each member # + return - true if func returns true for every member of `arr`; otherwise, false # public isolated function every(Type[] arr, @isolatedParam function(Type val) returns boolean func) returns boolean = external; # Returns a slice of an array. # # + arr - the array # + startIndex - index of first member to include in the slice # + endIndex - index of first member not to include in the slice # + return - new array containing members of `arr` with index >= `startIndex` and < `endIndex` public isolated function slice(Type[] arr, int startIndex, int endIndex = arr.length()) returns Type[] = external; # Removes a member of an array. # # + arr - the array # + index - index of member to be removed from `arr` # + return - the member of `arr` that was at `index` # This removes the member of `arr` with index `index` and returns it. # It panics if there is no such member. public isolated function remove(Type[] arr, int index) returns Type = external; # Removes all members of an array. # + arr - the array # Panics if any member cannot be removed. public isolated function removeAll((any|error)[] arr) returns () = external; # Changes the length of an array. # # + arr - the array of which to change the length # + length - new length # `setLength(arr, 0)` is equivalent to `removeAll(arr)`. public isolated function setLength((any|error)[] arr, int length) returns () = external; # Returns the index of first member of `arr` that is equal to `val` if there is one. # Returns `()` if not found. # Equality is tested using `==`. # # + arr - the array # + val - member to search for # + startIndex - index to start the search from # + return - index of the member if found, else `()` public isolated function indexOf(AnydataType[] arr, AnydataType val, int startIndex = 0) returns int? = external; # Returns the index of last member of `arr` that is equal to `val` if there is one. # Returns `()` if not found. # Equality is tested using `==`. # # + arr - the array # + val - member to search for # + startIndex - index to start searching backwards from # + return - index of the member if found, else `()` public isolated function lastIndexOf(AnydataType[] arr, AnydataType val, int startIndex = arr.length() - 1) returns int? = external; # Reverses the order of the members of an array. # # + arr - the array to be reversed # + return - new array with the members of `arr` in reverse order public isolated function reverse(Type[] arr) returns Type[] = external; # Direction for `sort` function. public enum SortDirection { ASCENDING = "ascending", DESCENDING = "descending" } # A type of which any ordered type must be a subtype. # Whether a type is an ordered type cannot be defined in # terms of being a subtype of a type, so being a subtype # of `OrderedType` is a necessary but not sufficient condition # for a type to be an ordered type. public type OrderedType ()|boolean|int|float|decimal|string|OrderedType[]; # Sorts an array. # If the member type of the array is not sorted, then the `key` function # must be specified. # Sorting works the same as with the `sort` clause of query expressions. # # + arr - the array to be sorted; # + direction - direction in which to sort # + key - function that returns a key to use to sort the members # + return - new array consisting of the members of `arr` in sorted order public isolated function sort(Type[] arr, SortDirection direction = ASCENDING, (isolated function(Type val) returns OrderedType)? key = ()) returns Type[] = external; # Removes and returns the last member of an array. # The array must not be empty. # # + arr - the array # + return - removed member public isolated function pop(Type[] arr) returns Type = external; # Adds values to the end of an array. # # + arr - the array # + vals - values to add to the end of the array public isolated function push(Type[] arr, Type... vals) returns () = external; # Removes and returns first member of an array. # The array must not be empty. # # + arr - the array # + return - the value that was the first member of the array public isolated function shift(Type[] arr) returns Type = external; # Adds values to the start of an array. # The values newly added to the array will be in the same order # as they are in `vals`. # # + arr - the array # + vals - values to add to the start of the array public isolated function unshift(Type[] arr, Type... vals) returns () = external; # Returns the string that is the Base64 representation of an array of bytes. # The representation is the same as used by a Ballerina Base64Literal. # The result will contain only characters `A..Z`, `a..z`, `0..9`, `+`, `/` and `=`. # There will be no whitespace in the returned string. # # + arr - the array # + return - Base64 string representation public isolated function toBase64(byte[] arr) returns string = external; # Returns the byte array that a string represents in Base64. # `str` must consist of the characters `A..Z`, `a..z`, `0..9`, `+`, `/`, `=` # and whitespace as allowed by a Ballerina Base64Literal. # # + str - Base64 string representation # + return - the byte array or error public isolated function fromBase64(string str) returns byte[]|error = external; # Returns the string that is the Base16 representation of an array of bytes. # The representation is the same as used by a Ballerina Base16Literal. # The result will contain only characters `0..9`, `a..f`. # There will be no whitespace in the returned string. # # + arr - the array # + return - Base16 string representation public isolated function toBase16(byte[] arr) returns string = external; # Returns the byte array that a string represents in Base16. # `str` must consist of the characters `0..9`, `A..F`, `a..f` # and whitespace as allowed by a Ballerina Base16Literal. # # + str - Base16 string representation # + return - the byte array or error public isolated function fromBase16(string str) returns byte[]|error = external; # Returns a stream of the members of an array. # # + arr - the array # + returns - stream of members of the array # The returned stream will use an iterator over `arr` and # will therefore handle mutation of `arr` in the same way # as an iterator does. # Theutation of the `arr` public isolated function toStream(T[] arr) returns stream<T,()> = external;
lang.boolean
moduleThe lang.boolean
module corresponds to basic type boolean.
# Converts a string to a boolean. # Returns the boolean of which `s` is a string representation. # The accepted representations are `true`, `false` # (in any combination of lower- and upper-case), # and also `1` for true and `0` for `false`. # This is the inverse of `value:toString` applied to a `boolean`. # # + s - string representing a boolean value # + return - boolean that `s` represents, or an error if there is no such boolean public isolated function fromString(string s) returns boolean|error = external;
lang.decimal
moduleThe lang.decimal
module corresponds to basic type decimal.
# Sum of zero or more decimal values. # # + xs - decimal values to sum # + return - sum of all the `xs`; 0 if `xs` is empty public isolated function sum(decimal... xs) returns decimal = external; # Maximum of one or more decimal values. # # + x - first decimal value # + xs - other decimal values # + return - maximum value of `x` and all the `xs` public isolated function max(decimal x, decimal... xs) returns decimal = external; # Minimum of one or more decimal values # # + x - first decimal value # + xs - other decimal values # + return - minimum value of `x` and all the `xs`. public isolated function min(decimal x, decimal... xs) returns decimal = external; # IEEE abs operation. # # + x - decimal value to operate on # + return - absolute value of `x` public isolated function abs(decimal x) returns decimal = external; # Round a decimal to a specified number of digits. # Returns the decimal value that has an exponent of `-fractionDigits` # and is closest to `x`. # If there are two such values, returns the one whose final digit is even # (this is the round-to-nearest rounding mode, which is the default for IEEE # and for Ballerina). # A value of `fractionDigits` greater than 0 thus corresponds to the number of digits after the decimal # point being `fractionDigits`; a value of 0 for `fractionDigits` rounds to an integer. # Note that IEEE 754 roundToIntegralTiesToEven operation differs from `round` with `fractionDigits` as 0, # in that roundToIntegralTiesToEven will return a value with a positive exponent when the operand has a positive exponent. # Note that `<int>x` is the same as `<int>x.round(0)`. # # + x - decimal value to operate on # + fractionDigits - the number of digits after the decimal point # + return - closest decimal value to `x` that is an integral multiple of 10 raised to the power of `-fractionDigits` public isolated function round(decimal x, int fractionDigits = 0) returns decimal = external; # Return a decimal with a specified value and exponent. # Return a decimal value that has the same value (except for rounding) as the first # argument, and the same exponent as the second argument. # This is the IEEE quantize operation. # + x - decimal value to operate on # + y - decimal value from which to get the quantum # + return - `x` with the quantum of `y` public isolated function quantize(decimal x, decimal y) returns decimal = external; # Rounds a decimal down to the closest integral value. # # + x - decimal value to operate on # + return - largest (closest to +∞) decimal value not greater than `x` that is a mathematical integer. public isolated function floor(decimal x) returns decimal = external; # Rounds a decimal up to the closest integral value. # # + x - decimal value to operate on # + return - smallest (closest to -∞) decimal value not less than `x` that is a mathematical integer public isolated function ceiling(decimal x) returns decimal = external; # Return the decimal value represented by `s`. # `s` must follow the syntax of DecimalFloatingPointNumber as defined by the Ballerina specification # with the following modifications # - the DecimalFloatingPointLiteral may have a leading `+` or `-` sign # - a FloatingPointTypeSuffix is not allowed # This is the inverse of `value:toString` applied to an `decimal`. # # + s - string representation of a decimal # + return - decimal representation of the argument or error public isolated function fromString(string s) returns decimal|error = external;
lang.error
moduleThe lang.error
module corresponds to basic type error.
# Type for value that can be cloned. # This is the same as in lang.value, but is copied here to avoid a dependency. public type Cloneable readonly|xml|Cloneable[]|map<Cloneable>|table<map<Cloneable>>; # The type to which error detail records must belong. public type Detail record {| Cloneable...; |}; # A type parameter that is a subtype of error `Detail` record type. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type DetailType Detail; # Returns the error's message. # # + e - the error value # + return - error message public isolated function message(error e) returns string = external; # Returns the error's cause. # # + e - the error value # + return - error cause public isolated function cause(error e) returns error? = external; # Returns the error's detail record. # The returned value will be immutable. # + e - the error value # + return - error detail value public isolated function detail(error<DetailType> e) returns readonly & DetailType = external; # Type representing a stack frame. # A call stack is represented as an array of stack frames. # This type is also present in lang.runtime to avoid a dependency. public type StackFrame readonly & object { # Returns a string representing this StackFrame. # This must not contain any newline characters. # + return - a string public isolated function toString() returns string; }; # Returns an array representing an error's stack trace. # # + e - the error value # + return - an array representing the stack trace of the error value # The first member of the array represents the top of the call stack. public isolated function stackTrace(error e) returns StackFrame[] = external; # Converts an error to a string. # # + e - the error to be converted to a string # + return - a string resulting from the conversion # # The details of the conversion are specified by the ToString abstract operation # defined in the Ballerina Language Specification, using the direct style. public isolated function toString(error e) returns string = external; # Converts an error to a string that describes the value in Ballerina syntax. # + e - the error to be converted to a string # + return - a string resulting from the conversion # # The details of the conversion are specified by the ToString abstract operation # defined in the Ballerina Language Specification, using the expression style. public isolated function toBalString(error e) returns string = external; # A type of error which can be retried. public type Retriable distinct error; # The RetryManager used by default. public class DefaultRetryManager { private int count; public function init(int count = 3) { this.count = count; } public function shouldRetry(error e) returns boolean { if e is Retriable && count > 0 { count -= 1; return true; } else { return false; } } }
lang.float
moduleThe lang.float
module corresponds to basic type float.
# The number π public const float PI = 3.141592653589793; # Euler's number public const float E = 2.718281828459045; # IEEE not-a-number value public const float NaN = 0.0/0.0; # IEEE positive infinity public const float Infinity = 1.0/0.0; # Tests whether a float is finite. # Exactly one of isFinite, isInfinite and IsNaN will be true for any float value # # + x - the float to be tested # + return - true if `x` is finite, i.e. neither NaN nor +∞ nor -∞ public isolated function isFinite(float x) returns boolean = external; # Tests whether a float is infinite. # Exactly one of isFinite, isInfinite and IsNaN will be true for any float value # # + x - the float to be tested # + return - true if `x` is either +∞ or -∞ public isolated function isInfinite(float x) returns boolean = external; # Tests whether a float is NaN. # Exactly one of isFinite, isInfinite and IsNaN will be true for any float value. # # + x - the float to be tested # + return - true if `x` is NaN public isolated function isNaN(float x) returns boolean = external; # Sum of zero or more float values. # Result is NaN if any arg is NaN # # + xs - float values to sum # + return - sum of all the `xs`, +0.0 if `xs` is empty public isolated function sum(float... xs) returns float = external; # Maximum of zero or more float values. # Result is -∞ if no args # NaN if any arg is NaN # # + xs - float values to operate on # + return - maximum value of all the `xs` public isolated function max(float... xs) returns float = external; # Minimum of zero or more float values. # Result is +∞ if no args # Result is NaN if any arg is NaN # # + xs - float values to operate on # + return - minimum value of all the `xs` public isolated function min(float... xs) returns float = external; # IEEE abs operation. # # + x - float value to operate on # + return - absolute value of `x` public isolated function abs(float x) returns float = external; # Round a float value to a specified number of digits. # Returns the float value that is an integral multiple of 10 raised to the power of `-fractionDigits` and closest to `x`. # If there are two such values, choose the one whose final digit is even # (this is the round-to-nearest rounding mode, which is the default for IEEE and for Ballerina). # A value of `fractionDigits` greater than 0 thus corresponds to the number of digits after the decimal # point being `fractionDigits`; a value of 0 for `fractionDigits` rounds to an integer. # If `x` is NaN, +0, -0, +∞ or -∞, then the result is `x``. # When `fractionDigits` is 0, this is # the same as Java Math.rint method, .NET Math.Round method and # IEEE roundToIntegralTiesToEven operation # Note that `<int>x` is the same as `<int>x.round(0)`. # # + x - float value to operate on # + fractionDigits - the number of digits after the decimal point # + return - float value closest to `x` that is an integral multiple of 10 raised to the power of `-fractionDigits` public isolated function round(float x, int fractionDigits = 0) returns float = external; # Rounds a float down to the closest integral value. # # + x - float value to operate on # + return - largest (closest to +∞) float value not greater than `x` that is a mathematical integer. public isolated function floor(float x) returns float = external; # Rounds a float up to the closest integral value. # # + x - float value to operate on # + return - smallest (closest to -∞) decimal value not less than `x` that is a mathematical integer public isolated function ceiling(float x) returns float = external; # Returns the square root of a float value. # Corresponds to IEEE squareRoot operation. # # + x - float value to operate on # + return - square root of `x` public isolated function sqrt(float x) returns float = external; # Returns the cube root of a float value. # Corresponds to IEEE rootn(x, 3) operation. # # + x - float value to operate on # + return - cube root of `x` public isolated function cbrt(float x) returns float = external; # Raises one float value to the power of another float values. # Corresponds to IEEE pow(x, y) operation. # # + x - base value # + y - the exponent # + return - `x` raised to the power of `y` public isolated function pow(float x, float y) returns float = external; # Returns the natural logarithm of a float value # Corresponds to IEEE log operation. # # + x - float value to operate on # + return - natural logarithm of `x` public isolated function log(float x) returns float = external; # Returns the base 10 logarithm of a float value. # Corresponds to IEEE log10 operation. # # + x - float value to operate on # + return - base 10 logarithm of `x` public isolated function log10(float x) returns float = external; # Raises Euler's number to a power. # Corresponds to IEEE exp operation. # # + x - float value to operate on # + return - Euler's number raised to the power `x` public isolated function exp(float x) returns float = external; # Returns the sine of a float value. # Corresponds to IEEE sin operation. # # + x - float value, specifying an angle in radians # + return - the sine of `x` public isolated function sin(float x) returns float = external; # Returns the cosine of a float value. # Corresponds to IEEE cos operation. # # + x - float value, specifying an angle in radians # + return - the cosine of `x` public isolated function cos(float x) returns float = external; # Returns the tangent of a float value. # Corresponds to IEEE tan operation # # + x - float value, specifying an angle in radians # + return - the tangent of `x` public isolated function tan(float x) returns float = external; # Returns the arccosine of a float value. # Corresponds to IEEE acos operation # # + x - float value to operate on # + return - the arccosine of `x` in radians public isolated function acos(float x) returns float = external; # Returns the arctangent of a float value. # Corresponds to IEEE atan operation. # # + x - float value to operate on # + return - the arctangent of `x` in radians public isolated function atan(float x) returns float = external; # Returns the arcsine of a float value. # Corresponds to IEEE asin operation. # # + x - float value to operate on # + return - the arcsine of `x` in radians public isolated function asin(float x) returns float = external; # Performs the 2-argument arctangent operation. # Corresponds IEEE atan2(y, x) operation. # # + y - the y-coordinate # + x - the x-coordinate # + return - the angle in radians from the positive x-axis to the point # whose Cartesian coordinates are `(x, y)` public isolated function atan2(float y, float x) returns float = external; # Returns the hyperbolic sine of a float value. # Corresponds to IEEE sinh operation. # # + x - float value to operate on # + return - hyperbolic sine of `x` public isolated function sinh(float x) returns float = external; # Returns the hyperbolic cosine of a float value. # Corresponds to IEEE cosh operation. # # + x - float value to operate on # + return - hyperbolic cosine of `x` public isolated function cosh(float x) returns float = external; # Returns the hyperbolic tangent of a float value. # Corresponds to IEEE tanh operation. # # + x - float value to operate on # + return - hyperbolic tangent of `x` public isolated function tanh(float x) returns float = external; # Return the float value represented by `s`. # `s` must follow the syntax of DecimalFloatingPointNumber as defined by the Ballerina specification # with the following modifications # - the DecimalFloatingPointNumber may have a leading `+` or `-` sign # - `NaN` is allowed # - `Infinity` is allowed with an optional leading `+` or `-` sign # - a FloatingPointTypeSuffix is not allowed # This is the inverse of `value:toString` applied to an `float`. # # + s - string representation of a float # + return - float value or error public isolated function fromString(string s) returns float|error = external; # Returns a string that represents `x` as a hexadecimal floating point number. # The returned string will comply to the grammar of HexFloatingPointLiteral # in the Ballerina spec with the following modifications: # - it will have a leading `-` sign if negative # - positive infinity will be represented by `Infinity` # - negative infinity will be represented by `-Infinity` # - NaN will be represented by `NaN` # The representation includes `0x` for finite numbers. # # + x - float value # + return - hexadecimal floating point hex string representation public isolated function toHexString(float x) returns string = external; # Return the float value represented by `s`. # `s` must follow the syntax of HexFloatingPointLiteral as defined by the Ballerina specification # with the following modifications # - the HexFloatingPointLiteral may have a leading `+` or `-` sign # - `NaN` is allowed # - `Infinity` is allowed with an optional leading `+` or `-` sign # # + s - hexadecimal floating point hex string representation # + return - float value or error public isolated function fromHexString(string s) returns float|error = external; # Returns IEEE 64-bit binary floating point format representation of `x` as an int. # # + x - float value # + return - `x` bit pattern as an int public isolated function toBitsInt(float x) returns int = external; # Returns the float that is represented in IEEE 64-bit floating point by `x`. # All bit patterns that IEEE defines to be NaNs will all be mapped to the single float NaN value. # # + x - int value # + return - `x` bit pattern as a float public isolated function fromBitsInt(int x) returns float = external; # Returns a string that represents `x` using fixed-point notation. # The returned string will be in the same format used by `value:toString`, # except that it will not include an exponent. # If `x` is NaN or infinite, the result will be the same as `value:toString`. # This will panic if `fractionDigits`` is less than 0. # If `fractionDigits`` is zero, there will be no decimal point. # Any necessary rounding will use the roundTiesToEven rounding direction. # # + x - float value # + fractionDigits - number of digits following the decimal point; `()` means to use # the minimum number of digits required to accurately represent the value # + return - string representation of `x` in fixed-point notation public isolated function toFixedString(float x, int? fractionDigits) returns string = external; # Returns a string that represents `x` using scientific notation. # The returned string will be in the same format used by `value:toString`, # except that it will always include an exponent and there will be exactly # one digit before the decimal point. # But if `x` is NaN or infinite, the result will be the same as `value:toString`. # The digit before the decimal point will be zero only if all other digits # are zero. # This will panic if fractionDigits is less than 0. # If `fractionDigits` is zero, there will be no decimal point. # Any necessary rounding will use the roundTiesToEven rounding direction. # The exponent in the result uses lower-case `e`, followed by a `+` or `-` sign, # followed by at least two digits, and only as many more digits as are needed # to represent the result. If `x` is zero, the exponent is zero. A zero exponent # is represented with a `+` sign. # # + x - float value # + fractionDigits - number of digits following the decimal point; `()` means to use # the minimum number of digits required to accurately represent the value # + return - string representation of `x` in scientific notation public isolated function toExpString(float x, int? fractionDigits) returns string = external;
lang.function
moduleThe lang.function
module corresponds to basic type function.
# Calls a function dynamically. # If the arguments specified in `args` are not of the type required by `func`, # then this will panic. # # + func - the function to be called # + args - the arguments to be passed to the function # + return - the return value of the call to the function public isolated function call(@isolatedParam function func, any|error... args) returns any|error = external;
lang.future
moduleThe lang.future
module corresponds to basic type future.
# Requests cancellation of a future. # + f - the future to be cancelled # This sets the cancellation flag in the strand corresponding to `f`. # Each time that a strand yields, it will check the cancellation flag # and terminate abnormally if the flag is set. public isolated function cancel(future f) returns () = external;
lang.int
moduleThe lang.int
module corresponds to basic type int.
# Built-in subtype that allows signed integers that can be represented in 32 bits using two's complement. # This allows an int between -2^31 and 2^31 - 1 inclusive. # i.e. between -2,147,483,648 and 2,147,483,647 inclusive. @builtinSubtype public type Signed32 int; # Built-in subtype that allows non-negative integers that can be represented in 16 bits using two's complement. # This allows an int between -2^15 and 2^15 - 1 inclusive. # i.e. between -32,768 and 32,767 inclusive. @builtinSubtype public type Signed16 int; # Built-in subtype that allows non-negative integers that can be represented in 8 bits using two's complement. # This allows an int between -2^7 and 2^7 - 1 inclusive. # i.e. between -128 and 127 inclusive. @builtinSubtype public type Signed8 int; # Built-in subtype that allows non-negative integers that can be represented in 32 bits. # This allows an int between 0 and 2^32 - 1 inclusive, # i.e. between 0 and 4,294,967,295 inclusive. @builtinSubtype public type Unsigned32 int; # Built-in subtype that allows non-negative integers that can be represented in 16 bits. # This allows an int between 0 and 2^16 - 1 inclusive, # i.e. between 0 and 65,535 inclusive. @builtinSubtype public type Unsigned16 int; # Built-in subtype that allows non-negative integers that can be represented in 8 bits. # This allows an int between 0 and 2^8 - 1 inclusive, # i.e. between 0 and 255 inclusive. # This is the same as `byte`. @builtinSubtype public type Unsigned8 int; # Maximum value of type `int`. public const MAX_VALUE =<PHONE_NUMBER>854775807; # Minimum value of type `int`. public const MIN_VALUE = -9223372036854775807 - 1; // -9223372036854775808 would overflow # Maximum value of type `Signed32`. public const SIGNED32_MAX_VALUE =<PHONE_NUMBER>; # Minimum value of type `Signed32`. public const SIGNED32_MIN_VALUE = -2147483648; # Maximum value of type `Signed16`. public const SIGNED16_MAX_VALUE = 32767; # Minimum value of type `Signed16`. public const SIGNED16_MIN_VALUE = -32768; # Maximum value of type `Signed8`. public const SIGNED8_MAX_VALUE = 127; # Minimum value of type `Signed8`. public const SIGNED8_MIN_VALUE = -128; # Maximum value of type `Unsigned32`. public const UNSIGNED32_MAX_VALUE =<PHONE_NUMBER>; # Maximum value of type `Unsigned16`. public const UNSIGNED16_MAX_VALUE = 65535; # Maximum value of type `Unsigned8`. public const UNSIGNED8_MAX_VALUE = 255; # Returns absolute value of an int. # # + n - int value to be operated on # + return - absolute value of `n` public isolated function abs(int n) returns int = external; # Returns sum of zero or more int values. # # + ns - int values to sum # + return - sum of all the `ns`; 0 is `ns` is empty public isolated function sum(int... ns) returns int = external; # Maximum of one or more int values. # # + n - first int value # + ns - other int values # + return - maximum value of value of `x` and all the `xs` public isolated function max(int n, int... ns) returns int = external; # Minimum of one or more int values # # + n - first int value # + ns - other int values # + return - minimum value of `n` and all the `ns` public isolated function min(int n, int... ns) returns int = external; # Returns the integer that `s` represents in decimal. # Returns error if `s` is not the decimal representation of an integer. # The first character may be `+` or `-`. # This is the inverse of `value:toString` applied to an `int`. # # + s - string representation of a integer value # + return - int representation of the argument or error public isolated function fromString(string s) returns int|error = external; # Returns representation of `n` as hexdecimal string. # There is no `0x` prefix. Lowercase letters a-f are used. # Negative numbers will have a `-` prefix. No sign for # non-negative numbers. # # + n - int value # + return - hexadecimal string representation of int value public isolated function toHexString(int n) returns string = external; # Returns the integer that `s` represents in hexadecimal. # Both uppercase A-F and lowercase a-f are allowed. # It may start with an optional `+` or `-` sign. # No `0x` or `0X` prefix is allowed. # Returns an error if the `s` is not in an allowed format. # # + s - hexadecimal string representation of int value # + return - int value or error public isolated function fromHexString(string s) returns int|error = external;
lang.map
moduleThe lang.map
module corresponds to basic type mapping.
# A type parameter that is a subtype of `any|error`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type Type any|error; # A type parameter that is a subtype of `any|error`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type Type1 any|error; # Returns number of members of a map. # # + m - the map # + return - number of members in `m` public isolated function length(map<any|error> m) returns int = external; # Returns an iterator over a map. # The iterator will iterate over the members of the map not the keys. # The `entries` function can be used to iterate over the keys and members together. # The `keys` function can be used to iterator over just the keys. # # + m - the map # + return - a new iterator object that will iterate over the members of `m` public isolated function iterator(map<Type> m) returns object { public isolated function next() returns record {| Type value; |}?; } = external; # Returns the member of map `m` with key `k`. # This for use in a case where it is known that the map has a specific key, # and accordingly panics if `m` does not have a member with key `k`. # # + m - the map # + k - the key # + return - member with key `k` public isolated function get(map<Type> m, string k) returns Type = external; # Returns a map containing [key, member] pair as the value for each key. # # + m - the map # + return - a new map of [key, member] pairs public isolated function entries(map<Type> m) returns map<[string, Type]> = external; # Applies a function each member of a map and returns a map of the result. # The resulting map will have the same keys as the argument map. # # + m - the map # + func - a function to apply to each member # + return - new map containing result of applying function `func` to each member public isolated function 'map(map<Type> m, @isolatedParam function(Type val) returns Type1 func) returns map<Type1> = external; # Applies a function to each member of a map. # The function `func` is applied to each member of `m`. # # + m - the map # + func - a function to apply to each member public isolated function forEach(map<Type> m, @isolatedParam function(Type val) returns () func) returns () = external; # Selects the members from a map for which a function returns true. # # + m - the map # + func - a predicate to apply to each element to test whether it should be included # + return - new map containing members for which `func` evaluates to true public isolated function filter(map<Type> m, @isolatedParam function(Type val) returns boolean func) returns map<Type> = external; # Combines the members of a map using a combining function. # The combining function takes the combined value so far and a member of the map, # and returns a new combined value. # # + m - the map # + func - combining function # + initial - initial value for the first argument of combining function `func` # + return - result of combining the members of `m` using `func` public isolated function reduce(map<Type> m, @isolatedParam function(Type1 accum, Type val) returns Type1 func, Type1 initial) returns Type1 = external; # Removes a member of a map. # # + m - the map # + k - the key # + return - the member of `m` that had key `k` # This removes the member of `m` with key `k` and returns it. # It panics if there is no such member. public isolated function remove(map<Type> m, string k) returns Type = external; # Removes a member of a map with a given key, if the map has member with the key. # # + m - the map # + k - the key # + return - the member of `m` that had key `k`, or `()` if `m` does not have a key `k` # If `m` has a member with key `k`, it removes and returns it; # otherwise it returns `()`. public isolated function removeIfHasKey(map<Type> m, string k) returns Type? = external; # Removes all members of a map. # This panics if any member cannot be removed. # # + m - the map public isolated function removeAll(map<any|error> m) returns () = external; # Tests whether m has a member with key `k`. # # + m - the map # + k - the key # + return - true if m has a member with key `k` public isolated function hasKey(map<Type> m, string k) returns boolean = external; # Returns a list of all the keys of map `m`. # # + m - the map # + return - a new list of all keys public isolated function keys(map<any|error> m) returns string[] = external; # Returns a list of all the members of a map. # # + m - the map # + return - an array whose members are the members of `m` public isolated function toArray(map<Type> m) returns Type[] = external;
lang.object
moduleThe lang.object
module corresponds to basic type object.
# Distinct Iterable type. # An object can make itself iterable by using `*object:Iterable;`, # and then defining an `iterator` method. public type Iterable distinct object { # Create a new iterator. # # + return - a new iterator object public function iterator() returns object { public function next() returns record {| any|error value; |}|error?; }; }; # Distinct RawTemplate type. # A raw template expression constructs an object belonging to this type. public type RawTemplate distinct object { # An array of the strings containing the characters in BacktickString # outside of interpolations, split at the interpolation points. # The length of this array is one greater than # the length of the `insertions` array. public (readonly & string[]) strings; # An array containing the results of evaluating the # interpolations in the BacktickString. public (any|error)[] insertions; };
lang.stream
moduleThe lang.stream
module corresponds to basic type stream.
# A type parameter that is a subtype of `any|error`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type Type any|error; # A type parameter that is a subtype of `error`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type ErrorType error; # A type parameter that is a subtype of `error?`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. # This represents the result type of an iterator. @typeParam type CompletionType error?; # A type parameter that is a subtype of `any|error`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type Type1 any|error; # Returns an iterator over a stream. # # + stm - the stream # + return - a new iterator object that will iterate over the members of `stm`. public isolated function iterator(stream<Type,CompletionType> stm) returns object { public isolated function next() returns record {| Type value; |}|CompletionType; } = external; # Returns the next member of the stream. # # + stm - the stream # + return - a record containing the next member of the stream, if there is one, or, # otherwise, the completion value public isolated function next(stream<Type,CompletionType> stm) returns record {| Type value; |}|CompletionType = external; # Closes a stream. # This releases any system resources being used by the stream. # Closing a stream that has already been closed has no effect and returns `()`. # # + stm - the stream to close # + return - () if the close completed successfully, otherwise an error public isolated function close(stream<Type,CompletionType> stm) returns CompletionType? = external; # Applies a function to each member of a stream and returns a stream of the results. # # + stm - the stream # + func - a function to apply to each member # + return - new stream containing result of applying `func` to each member of `stm` in order public isolated function 'map(stream<Type,CompletionType> stm, @isolatedParam function(Type val) returns Type1 func) returns stream<Type1,CompletionType> = external; # Applies a function to each member of a stream. # The function `func` is applied to each member of stream `stm` in order. # # + stm - the stream # + func - a function to apply to each member public isolated function forEach(stream<Type,CompletionType> stm, @isolatedParam function(Type val) returns () func) returns CompletionType = external; # Selects the members from a stream for which a function returns true. # # + stm - the stream # + func - a predicate to apply to each member to test whether it should be selected # + return - new stream only containing members of `stm` for which `func` evaluates to true public isolated function filter(stream<Type,CompletionType> stm, @isolatedParam function(Type val) returns boolean func) returns stream<Type,CompletionType> = external; # Combines the members of a stream using a combining function. # The combining function takes the combined value so far and a member of the stream, # and returns a new combined value. # # + stm - the stream # + func - combining function # + initial - initial value for the first argument of combining function `func` # + return - result of combining the members of `stm` using `func` public isolated function reduce(stream<Type,ErrorType?> stm, @isolatedParam function(Type1 accum, Type val) returns Type1 func, Type1 initial) returns Type1|ErrorType = external;
lang.string
moduleThe lang.string
module corresponds to basic type string.
# Built-in subtype of string containing strings of length 1. @builtinSubtype type Char string; # Returns the length of the string. # # + str - the string # + return - the number of characters (code points) in `str` public isolated function length(string str) returns int = external; # Returns an iterator over the string. # The iterator will yield the substrings of length 1 in order. # # + str - the string to be iterated over # + return - a new iterator object public isolated function iterator(string str) returns object { public isolated function next() returns record {| Char value; |}?; } = external; # Concatenates zero or more strings. # # + strs - strings to be concatenated # + return - concatenation of all of the `strs`; empty string if `strs` is empty public isolated function concat(string... strs) returns string = external; # Returns the code point of a character in a string. # # + str - the string # + index - an index in `str` # + return - the Unicode code point of the character at `index` in `str` public isolated function getCodePoint(string str, int index) returns int = external; # Returns a substring of a string. # # + str - source string. # + startIndex - the starting index, inclusive # + endIndex - the ending index, exclusive # + return - substring consisting of characters with index >= startIndex and < endIndex public isolated function substring(string str, int startIndex, int endIndex = str.length()) returns string = external; # Lexicographically compares strings using their Unicode code points. # This orders strings in a consistent and well-defined way, # but the ordering will often not be consistent with cultural expectations # for sorted order. # # + str1 - the first string to be compared # + str2 - the second string to be compared # + return - an int that is less than, equal to or greater than zero, # according as `str1` is less than, equal to or greater than `str2` public isolated function codePointCompare(string str1, string str2) returns int = external; # Joins zero or more strings together with a separator. # # + separator - separator string # + strs - strings to be joined # + return - a string consisting of all of `strs` concatenated in order # with `separator` in between them public isolated function 'join(string separator, string... strs) returns string = external; # Finds the first occurrence of one string in another string. # # + str - the string in which to search # + substr - the string to search for # + startIndex - index to start searching from # + return - index of the first occurrence of `substr` in `str` that is >= `startIndex`, # or `()` if there is no such occurrence public isolated function indexOf(string str, string substr, int startIndex = 0) returns int? = external; # Finds the last occurrence of one string in another string. # # + str - the string in which to search # + substr - the string to search for # + startIndex - index to start searching backwards from # + return - index of the last occurrence of `substr` in `str` that is <= `startIndex`, # or `()` if there is no such occurrence public isolated function lastIndexOf(string str, string substr, int startIndex = str.length() - substr.length()) returns int? = external; # Tests whether a string includes another string. # # + str - the string in which to search # + substr - the string to search for # + startIndex - index to start searching from # + return - `true` if there is an occurrence of `substr` in `str` at an index >= `startIndex`, # or `false` otherwise public isolated function includes(string str, string substr, int startIndex = 0) returns boolean = external; # Tests whether a string starts with another string. # # + str - the string to be tested # + substr - the starting string # + return - true if `str` starts with `substr`; false otherwise public isolated function startsWith(string str, string substr) returns boolean = external; # Tests whether a string ends with another string. # # + str - the string to be tested # + substr - the ending string # + return - true if `str` ends with `substr`; false otherwise public isolated function endsWith(string str, string substr) returns boolean = external; # Converts occurrences of A-Z to a-z. # Other characters are left unchanged. # # + str - the string to be converted # + return - `str` with any occurrences of A-Z converted to a-z public isolated function toLowerAscii(string str) returns string = external; # Converts occurrences of a-z to A-Z. # Other characters are left unchanged. # # + str - the string to be converted # + return - `str` with any occurrences of a-z converted to A-Z public isolated function toUpperAscii(string str) returns string = external; # Tests whether two strings are the same, ignoring the case of ASCII characters. # A character in the range a-z is treated the same as the corresponding character in the range A-Z. # # + str1 - the first string to be compared # + str2 - the second string to be compared # + return - true if `str1` is the same as `str2`, treating upper-case and lower-case # ASCII letters as the same; false, otherwise public isolated function equalsIgnoreCaseAscii(string str1, string str2) returns boolean = external; # Removes ASCII white space characters from the start and end of a string. # The ASCII white space characters are 0x9...0xD, 0x20. # # + str - the string # + return - `str` with leading or trailing ASCII white space characters removed public isolated function trim(string str) returns string = external; # Represents `str` as an array of bytes using UTF-8. # # + str - the string # + return - UTF-8 byte array public isolated function toBytes(string str) returns byte[] = external; # Constructs a string from its UTF-8 representation in `bytes`. # # + bytes - UTF-8 byte array # + return - `bytes` converted to string or error public isolated function fromBytes(byte[] bytes) returns string|error = external; # Converts a string to an array of code points. # # + str - the string # + return - an array with a code point for each character of `str` public isolated function toCodePointInts(string str) returns int[] = external; # Converts a single character string to a code point. # # + ch - a single character string # + return - the code point of `ch` public isolated function toCodePointInt(Char ch) returns int = external; # Constructs a string from an array of code points. # An int is a valid code point if it is in the range 0 to 0x10FFFF inclusive, # but not in the range 0xD800 or 0xDFFF inclusive. # # + codePoints - an array of ints, each specifying a code point # + return - a string with a character for each code point in `codePoints`; or an error # if any member of `codePoints` is not a valid code point public isolated function fromCodePointInts(int[] codePoints) returns string|error = external; # Constructs a single character string from a code point. # An int is a valid code point if it is in the range 0 to 0x10FFFF inclusive, # but not in the range 0xD800 or 0xDFFF inclusive. # # + codePoint - an int specifying a code point # + return - a single character string whose code point is `codePoint`; or an error # if `codePoint` is not a valid code point public isolated function fromCodePointInt(int codePoint) returns Char|error = external; # Adds padding to the start of a string. # Adds sufficient `padChar` characters at the start of `str` to make its length be `len`. # If the length of `str` is >= `len`, returns `str`. # # + str - the string to pad # + len - the length of the string to be returned # + padChar - the character to use for padding `str`; defaults to a space character # + return - `str` padded with `padChar` public isolated function padStart(string str, int len, Char padChar = " ") returns string = external; # Adds padding to the end of a string. # Adds sufficient `padChar` characters to the end of `str` to make its length be `len`. # If the length of `str` is >= `len`, returns `str`. # # + str - the string to pad # + len - the length of the string to be returned # + padChar - the character to use for padding `str`; defaults to a space character # + return - `str` padded with `padChar` public isolated function padEnd(string str, int len, Char padChar = " ") returns string = external; # Pads a string with zeros. # The zeros are added at the start of the string, after a `+` or `-` sign if there is one. # Sufficient zero characters are added to `str` to make its length be `len`. # If the length of `str` is >= `len`, returns `str`. # # + str - the string to pad # + len - the length of the string to be returned # + zeroChar - the character to use for the zero; defaults to ASCII zero `0` # + return - `str` padded with zeros public isolated function padZero(string str, int len, Char zeroChar = "0") returns string = external;
lang.table
moduleThe lang.table
module corresponds to basic type table.
# A type parameter that is a subtype of `any|error`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type Type any|error; # A type parameter that is a subtype of `map<any|error>`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type MapType map<any|error>; # A type parameter that is a subtype of `map<any|error>`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type MapType1 map<any|error>; # A type parameter that is a subtype of `anydata`. # Has the special semantic that when used in a declaration # all uses in the declaration must refer to same type. @typeParam type KeyType anydata; # Returns number of members of a table. # # + t - the table # + return - number of members in `t` public isolated function length(table<map<any|error>> t) returns int = external; # Returns an iterator over a table. # The iterator will iterate over the members of the table not the keys. # The `entries` function can be used to iterate over the keys and members together. # The `keys` function can be used to iterator over just the keys. # # + t - the table # + return - a new iterator object that will iterate over the members of `t` public isolated function iterator(table<MapType> t) returns object { public isolated function next() returns record {| MapType value; |}?; } = external; # Returns the member of table `t` with key `k`. # This for use in a case where it is known that the table has a specific key, # and accordingly panics if `t` does not have a member with key `k`. # # + t - the table # + k - the key # + return - member with key `k` public isolated function get(table<MapType> key<KeyType> t, KeyType k) returns MapType = external; # Adds a member `val` to table `t`, replacing any member with the same key value. # If `val` replaces an existing member, it will have the same position # in the order of the members as the existing member; # otherwise, it will be added as the last member. # It panics if `val` is inconsistent with the inherent type of `t`. public isolated function put(table<MapType> t, MapType val) = external; # Adds a member `val` to table `t`. # It will be added as the last member. # It panics if `val` has the same key as an existing member of `t`, # or if `val` is inconsistent with the inherent type of `t`. public isolated function add(table<MapType> t, MapType val) = external; # Applies a function each member of a table and returns a table of the result. # # + t - the table # + func - a function to apply to each member # + return - new table containing result of applying function `func` to each member public isolated function map(table<MapType> t, @isolatedParam function(MapType val) returns MapType1 func) returns table<MapType1> key<never> = external; # Applies a function to each member of a table. # The function `func` is applied to each member of `t`. # # + t - the table # + func - a function to apply to each member public isolated function forEach(table<MapType> t, @isolatedParam function(MapType val) returns () func) returns () = external; # Selects the members from a table for which a function returns true. # The resulting table will have the same keys as the argument table. # # + t - the table # + func - a predicate to apply to each member to test whether it should be included # + return - new table containing members for which `func` evaluates to true public isolated function filter(table<MapType> key<KeyType> t, @isolatedParam function(MapType val) returns boolean func) returns table<MapType> key<KeyType> = external; # Combines the members of a table using a combining function. # The combining function takes the combined value so far and a member of the table, # and returns a new combined value. # # + t - the table # + func - combining function # + initial - initial value for the first argument of combining function `func` # + return - result of combining the members of `t` using `func` public isolated function reduce(table<MapType> t, @isolatedParam function(Type accum, MapType val) returns Type func, Type initial) returns Type = external; # Removes a member of a table. # # + t - the table # + k - the key # + return - the member of `t` that had key `k` # This removed the member of `t` with key `k` and returns it. # It panics if there is no such member. public isolated function remove(table<MapType> key<KeyType> t, KeyType k) returns MapType = external; # Removes a member of a table with a given key, if the table has member with the key. # # + t - the table # + k - the key # + return - the member of `t` that had key `k`, or `()` if `t` does not have a key `k` # If `t` has a member with key `k`, it removes and returns it; # otherwise it returns `()`. public isolated function removeIfHasKey(table<MapType> key<KeyType> t, KeyType k) returns MapType? = external; # Removes all members of a table. # This panics if any member cannot be removed. # # + t - the table public isolated function removeAll(table<map<any|error>> t) returns () = external; # Tests whether `t` has a member with key `k`. # # + t - the table # + k - the key # + return - true if `t` has a member with key `k` public isolated function hasKey(table<MapType> key<KeyType> t, KeyType k) returns boolean = external; # Returns a list of all the keys of table `t`. # # + t - the table # + return - a new list of all keys public isolated function keys(table<map<any|error>> key<KeyType> t) returns KeyType[] = external; # Returns a list of all the members of a table. # # + t - the table # + return - an array whose members are the members of `t` public isolated function toArray(table<MapType> t) returns MapType[] = external; # Returns the next available integer key. # + t - the table with a key of type int # + return - an integer not yet used as a key # This is maximum used key value + 1, or 0 if no key used # XXX should it be 0, if the maximum used key value is < 0? # Provides similar functionality to auto-increment public isolated function nextKey(table<map<any|error>> key<int> t) returns int = external;
lang.typedesc
moduleThe lang.typedesc
module corresponds to basic type typedesc.
# A record representing an identifier for a module. # This uniquely identifies a module within a program. public type ModuleId readonly & record {| # the organization string organization; # the module name string name; # platform-specified parts of the identifier string[] platformParts; |}; # A record representing a type-id. # A type-id uniquely identifies an occurrence of a distinct type descriptor # within a program. public type TypeId readonly & record {| # An identifier for the module. ModuleId moduleId; # An identifier within the module identified by `moduleId`. # If it is a string, then it is the name of a type defined in the module. # If it is an integer, then it is compiler-generated. (string|int) localId; |}; # Returns the type-ids induced by a typedesc value. # + t - the typedesc # + primaryOnly - if true, only the primary type-ids will be returned; otherwise, all type-ids will be returned # + return - an array containing the type-ids induced by `t` or nil if `t` is not definite public isolated function typeIds(typedesc t, boolean primaryOnly = false) returns readonly & TypeId[]? = external;
lang.xml
moduleThe lang.xml
module corresponds to basic type xml.