new create(x: U32, y: U32) =>
_x = x
_y = y

// Define a + function
fun add(other: Pair): Pair =>
Pair(_x + other._x, _y + other._y)

// Now let's use it
class Foo
fun foo() =>
var x = Pair(1, 2)
var y = Pair(3, 4)
var z = x + y
```

It is possible to overload infix operators to some degree using union types or f-bounded polymorphism, but this is beyond the scope of this tutorial. See the Pony standard library for further information.

You do not have to worry about any of this if you don't want to. You can simply use the existing infix operators for numbers just like any other language and not provide them for your own types.


U8 val

u16¶
[Source]
fun box u16()
: U16 val

Returns¶

U16 val

u32¶
[Source]
fun box u32()
: U32 val

Returns¶


I16 val

i32¶
[Source]
fun box i32()
: I32 val

Returns¶

I32 val

i64¶
[Source]
fun box i64()
: I64 val

Returns¶


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351


fun box release(
auth: ApplyReleaseBackpressureAuth val)
: None val

Parameters¶

auth: ApplyReleaseBackpressureAuth val

Returns¶

None val

eq¶
[Source]
fun box eq(
that: Backpressure val)
: Bool val

Parameters¶


str: Pointer[U8 val] box
len: USize val

Returns¶

String ref^

copy_cstring¶
[Source]
Create a string by copying a null-terminated C string. Note that
the scan is unbounded; the pointed to data must be null-terminated
within the allocated array to preserve memory safety. If a null
pointer is given then an empty string is returned.
new ref copy_cstring(
str: Pointer[U8 val] box)
: String ref^

Parameters¶


fun ref int[N: (Unsigned val & Real[N] val) = U64](n: N): N =>
"""
A random integer in [0, n)

Uses fixed-point inversion if platform supports native 128 bit operations
otherwise uses floating-point multiplication.
"""
ifdef native128 then
// TODO: once we have specialized generic functions, chose smaller int
// types for smaller N.
N.from[U64](((next().u128() * n.u128()) >> 64).u64())
else
int_fp_mult[N](n)
end

fun ref int_unbiased[N: (Unsigned val & Real[N] val) = U64](n: N): N =>
"""
A random integer in [0, n)


Public Functions¶
value¶
[Source]
fun box value()
: U32 val

Returns¶

U32 val

eq¶
[Source]
fun box eq(
that: FileSync val)
: Bool val

Parameters¶


fun ref _process_opts() =>
"""
Process our command line options.
All command line arguments given must be recognised and make sense.
State for specified options is stored in object fields.
We don't use the options package because we aren't already dependencies.
"""
var exe_name = ""

for arg in _env.args.values() do
if exe_name == "" then
exe_name = arg
continue
end

if arg == "--sequential" then
_sequential = true
elseif arg == "--verbose" then
_verbose = true


872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891


fun box rds_info_send_messages()
: I32 val

Returns¶

I32 val

rds_info_sockets¶
[Source]
fun box rds_info_sockets()
: I32 val

Returns¶

I32 val

rds_info_tcp_sockets¶
[Source]


y: U16 val

Returns¶

U16 val

modc¶
[Source]
fun box modc(
y: U16 val)
: (U16 val , Bool val)

Parameters¶

y: U16 val

Returns¶


u8¶
[Source]
fun ref u8()
: U8 val

Returns¶

U8 val

u16¶
[Source]
fun ref u16()
: U16 val

Returns¶

U16 val


# Create

To create an object you need to specify the type and call a constructor. Pony allows you to miss out the constructor and will insert a call to `create()` for you. So:

```pony
var foo = Foo
```

becomes:

```pony
var foo = Foo.create()
```

Normally types are not valid things to appear in expressions, so omitting the constructor call is not ambiguous. Remember that you can easily spot that a name is a type because it will start with a capital letter.

If arguments are needed for `create` these can be provided as if calling the type. Default and named arguments can be used as normal.

```pony
var foo = Foo(x, 37 where crash = false)


descriptors or reading limited global system state. Access to global name
spaces, such as file system or IPC name spaces, is prevented.
"""
ifdef freebsd or "capsicum" then
@cap_enter() == 0
else
false
end

fun read(): U64 => _id(0, 1 << 0)
fun write(): U64 => _id(0, 1 << 1)
fun seek_tell(): U64 => _id(0, 1 << 2)
fun seek(): U64 => _id(0, 1 << 3) or seek_tell()
fun pread(): U64 => seek() or read()
fun pwrite(): U64 => seek() or write()

fun mmap(): U64 => _id(0, 1 << 4)
fun mmap_r(): U64 => mmap() or seek() or read()
fun mmap_w(): U64 => mmap() or seek() or write()
fun mmap_x(): U64 => mmap() or seek() or _id(0, 1 << 5)


232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251


Remove all instances of s from the string. Returns the count of removed
instances.
fun ref remove(
s: String box)
: USize val

Parameters¶

s: String box

Returns¶

USize val

replace¶
[Source]
Replace up to n occurrences of from in this with to. If n is 0, all
occurrences will be replaced. Returns the count of replaced occurrences.
fun ref replace(


fun box so_listenincqlen()
: I32 val

Returns¶

I32 val

so_listenqlen¶
[Source]
fun box so_listenqlen()
: I32 val

Returns¶

I32 val

so_listenqlimit¶
[Source]


primitive _StillRunning

type _WaitResult is (ProcessExitStatus | WaitpidError | _StillRunning)

interface _Process
fun kill()
fun ref wait(): _WaitResult
"""
Only polls, does not actually wait for the process to finish,
in order to not block a scheduler thread.
"""

class _ProcessNone is _Process
fun kill() => None
fun ref wait(): _WaitResult => Exited(255)

class _ProcessPosix is _Process


Env¶
[Source]
An environment holds the command line and other values injected into the
program by default by the runtime.
class val Env

Constructors¶
create¶
[Source]
Build an artificial environment. A root capability must be supplied.
new val create(
root': AmbientAuth val,
input': InputStream tag,


SerialiseAuth¶
[Source]
This is a capability that allows the holder to serialise objects. It does not
allow the holder to examine serialised data or to deserialise objects.
primitive val SerialiseAuth

Constructors¶
create¶
[Source]
new val create(
auth: AmbientAuth val)
: SerialiseAuth val^


[Source]
fun ref u32()
: U32 val

Returns¶

U32 val

u64¶
[Source]
fun ref u64()
: U64 val

Returns¶

U64 val

u128¶


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


fun box so_upcallclosewait()
: I32 val

Returns¶

I32 val

so_update_accept_context¶
[Source]
fun box so_update_accept_context()
: I32 val

Returns¶

I32 val

so_useloopback¶
[Source]


## Reading from a `val` variable

A `val` origin is deeply and globally immutable, so all of its fields are also `val`. The only exception is a `tag` field. Since we can't read from it, we also can't guarantee that nobody can write to it, so it stays `tag`.


else
// Couldn't SIGTERM, as a last resort SIGKILL
@kill(pid, Sig.kill())
end
end
end

fun ref wait(): _WaitResult =>
"""Only polls, does not block."""
if pid > 0 then
var wstatus: I32 = 0
let options: I32 = 0 or _WNOHANG()
// poll, do not block
match @waitpid(pid, addressof wstatus, options)
| let err: I32 if err < 0 =>
// one could possibly do at some point:
//let wpe = WaitPidError(@pony_os_errno())
WaitpidError
| let exited_pid: I32 if exited_pid == pid => // our process changed state
if _WaitPidStatus.exited(wstatus) then


y: U32 val

Returns¶

U32 val

mul¶
[Source]
fun box mul(
y: U32 val)
: U32 val

Parameters¶

y: U32 val

Returns¶


_read_again()
return
end
end
else
_close()
end
end

fun ref _complete_reads(len: U32) =>
"""
The OS has informed as that len bytes of pending reads have completed.
This occurs only with IOCP on Windows.
"""
ifdef windows then
if _read_buf.space() == 0 then
// Socket has been closed
_readable = false
_close()
return


fun box so_reuseport()
: I32 val

Returns¶

I32 val

so_reuseshareuid¶
[Source]
fun box so_reuseshareuid()
: I32 val

Returns¶

I32 val

so_rfcomm_fc_info¶
[Source]


Returns¶

F64 val

cos¶
[Source]
fun box cos()
: F64 val

Returns¶

F64 val

sin¶
[Source]
fun box sin()
: F64 val


932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


fun generate(rnd: Randomness): I16^ =>
rnd.i16(min, max)

fun shrink(i: I16): ValueAndShrink[I16] =>
that._int_shrink[I16](consume i, min)
end)

fun i32(
min: I32 = I32.min_value(),
max: I32 = I32.max_value())
: Generator[I32]
=>
"""
Create a generator for I32 values.
"""
let that = this
Generator[I32](
object is GenObj[I32]
fun generate(rnd: Randomness): I32^ =>
rnd.i32(min, max)


572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591


u32_unsafe¶
fun box u32_unsafe()
: U32 val

Returns¶

U32 val

u64_unsafe¶
fun box u64_unsafe()
: U64 val

Returns¶

U64 val

ulong_unsafe¶
fun box ulong_unsafe()


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351


match _timers
| let ts: Timers =>
ts.dispose()
_timers = None
end

fun ref _setup_windows_timers() =>
let timers = _ensure_timers()
let pm: ProcessMonitor tag = this
let tn =
object iso is TimerNotify
fun ref apply(timer: Timer, count: U64): Bool =>
pm.timer_notify()
true
end
let timer = Timer(consume tn, 50_000_000, 10_000_000)
timers(consume timer)

fun ref _try_shutdown() =>
"""


greatest_common_divisor.pony

1
2
3
4
5
6
7
8
9
10
11


412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431


fun has_next(): Bool =>
"""
True if it believes there are remaining entries. May not be right if values
were added or removed from the map.
"""
_count < _map.size()

fun ref next(): M->V ? =>
"""
Returns the next value, or raises an error if there isn't one. If values
are added during iteration, this may not return all values.
"""
_i = _map.next_index(_i)?
_count = _count + 1
_map.index(_i)?._2

class MapPairs[K, V, H: HashFunction[K] val, M: HashMap[K, V, H] #read] is
Iterator[(M->K, M->V)]
"""
An iterator over the keys and values in a map.


return
end

var index = _records.size()
_records.push(_TestRecord(_env, name))

var group = _find_group(test.exclusion_group())
group(_TestRunner(this, index, consume test, group, _verbose, _env,
_timers))

fun ref _find_group(group_name: String): _Group =>
"""
Find the group to use for the given group name, subject to the
--sequential flag.
"""
var name = group_name

if _sequential then
// Use the same group for all tests.
name = "all"


Bool val

min¶
[Source]
fun box min(
y: A)
: A

Parameters¶

y: A

Returns¶

A

max¶
[Source]


y: A

Returns¶

A

div¶
[Source]
fun box div(
y: A)
: A

Parameters¶

y: A

Returns¶

A


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


timeout¶
[Source]
Reject the promise after the given expiration in nanoseconds.
fun tag timeout(
expiration: U64 val)
: None val

Parameters¶

expiration: U64 val

Returns¶

None val


```c
/* In C */
int option_value = 4455;
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &option_value, 4);

/* In Pony */
var option: I32 = 4455;
@setsockopt[I32](fd, OSSockOpt.sol_socket(), OSSockOpt.so_rcvbuf(),
addressof option, I32(4))
```
"""

/* Constants are from
*   macOS Sierra 10.12.6
*   Ubuntu Linux Xenial/16.04 LTS + kernel 4.4.0-109-generic
*   FreeBSD 11.1-RELEASE
*   Windows Winsock function reference for getsockopt & setsockopt:
*     https://msdn.microsoft.com/en-us/library/windows/desktop/ms738544(v=vs.85).aspx
*     https://msdn.microsoft.com/en-us/library/windows/desktop/ms740476(v=vs.85).aspx


_paused = false
_accept()
end

fun ref _accept(ns: U32 = 0) =>
"""
Accept connections as long as we have spawned fewer than our limit.
"""
ifdef windows then
if ns == -1 then
// Unsubscribe when we get an invalid socket in the event.
@pony_asio_event_unsubscribe(_event)
return
end

if ns > 0 then
if _closed then
@pony_os_socket_close(ns)
return
end


| _PathSep =>
state = _PathDot
| _PathDot =>
state = _PathDot2
| _PathDot2 =>
backtrack = s.size().isize()
s.append("...")
state = _PathOther
| _PathOther =>
s.append(".")
end
else
match state
| _PathSep =>
backtrack = s.size().isize()
| _PathDot =>
backtrack = s.size().isize()
s.append(".")
| _PathDot2 =>
backtrack = s.size().isize()


fun box ne(
that: FileEOF val)
: Bool val

Parameters¶

that: FileEOF val

Returns¶

Bool val


next¶
[Source]
Returns the next line in the file.
fun ref next()
: String iso^ ?

Returns¶

String iso^ ?


fun box ipv6_flowinfo_priority()
: I32 val

Returns¶

I32 val

ipv6_flowinfo_send¶
[Source]
fun box ipv6_flowinfo_send()
: I32 val

Returns¶

I32 val

ipv6_flowlabel_mgr¶
[Source]


and (this._port == that._port)
and (host_eq(that))
and (this._scope == that._scope)

fun host_eq(that: NetAddress box): Bool =>
if ip4() then
this._addr == that._addr
else
(this._addr1 == that._addr1)
and (this._addr2 == that._addr2)
and (this._addr3 == that._addr3)
and (this._addr4 == that._addr4)
end

fun length() : U8 =>
"""
For platforms (OSX/FreeBSD) with `length` field as part of
its `struct sockaddr` definition, returns the `length`.
Else (Linux/Windows) returns the size of `sockaddr_in` or `sockaddr_in6`.
"""


new val create()
: FormatHex val^

Returns¶

FormatHex val^

Public Functions¶
eq¶
[Source]
fun box eq(
that: FormatHex val)
: Bool val

Parameters¶

that: FormatHex val

Returns¶


"""
Grey text.
"""
"\x1B[90m"

fun white(): String =>
"""
White text.
"""
"\x1B[97m"

fun bright_red(): String =>
"""
Bright red text.
"""
"\x1B[91m"

fun bright_green(): String =>
"""
Bright green text.


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


TCPListenAuth¶
[Source]
primitive val TCPListenAuth

Constructors¶
create¶
[Source]
new val create(
from: (AmbientAuth val | NetAuth val | TCPAuth val))
: TCPListenAuth val^

Parameters¶


ReadlineNotify¶
[Source]
Notifier for readline.
interface ref ReadlineNotify

Public Functions¶
apply¶
[Source]
Receives finished lines. The next prompt is set by fulfilling the promise.
If the promise is rejected, readline will stop handling input.
fun ref apply(
line: String val,
prompt: Promise[String val] tag)


Parameters¶

gen1: Generator[T1] box
gen2: Generator[T2] box
gen3: Generator[T3] box
gen4: Generator[T4] box
fn: {(T1, T2, T3, T4): T5^}[T1, T2, T3, T4, T5] ref

Returns¶

Generator[T5] box

bool¶
[Source]
Create a generator of bool values.
fun box bool()
: Generator[Bool val] box

Returns¶


fun box f64_unsafe()
: F64 val

Returns¶

F64 val

compare¶
[Source]
fun box compare(
that: U16 val)
: (Less val | Equal val | Greater val)

Parameters¶

that: U16 val

Returns¶


"""
if _index >= _n() then
_populate()
end

try
var x = _state(_index)?
_index = _index + 1

x = x xor ((x >> 29) and 0x5555555555555555)
x = x xor ((x << 17) and 0x71d67fffeda60000)
x = x xor ((x << 37) and 0xfff7eee000000000)
x xor (x >> 43)
else
0
end

fun ref _populate() =>
"""
Repopulates the state array.


Parameters¶

y: ILong val

Returns¶

(ILong val , ILong val) ?

fld_partial¶
[Source]
fun box fld_partial(
y: ILong val)
: ILong val ?

Parameters¶

y: ILong val

Returns¶


format_spec.pony

1
2
3
4
5
6
7
8
9
10
11


fun box rem_unsafe(
y: U8 val)
: U8 val

Parameters¶

y: U8 val

Returns¶

U8 val

neg_unsafe¶
[Source]
fun box neg_unsafe()
: U8 val

Returns¶


new min_value() => 0
new max_value() => 0xFFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF_FFFF

fun next_pow2(): U128 =>
let x = (this - 1).clz()
1 << (if x == 0 then 0 else bitwidth() - x end)

fun abs(): U128 => this
fun bit_reverse(): U128 => @"llvm.bitreverse.i128"(this)
fun bswap(): U128 => @"llvm.bswap.i128"(this)
fun popcount(): U128 => @"llvm.ctpop.i128"(this)
fun clz(): U128 => @"llvm.ctlz.i128"(this, false)
fun ctz(): U128 => @"llvm.cttz.i128"(this, false)

fun clz_unsafe(): U128 =>
"""
Unsafe operation.
If this is 0, the result is undefined.
"""


Parameters¶

data: ByteSeqIter val

writev¶
[Source]
Write an iterable collection of ByteSeqs.
be writev(
data: ByteSeqIter val)

Parameters¶

data: ByteSeqIter val

flush¶
[Source]
Flush the stream.


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


(Cons[A] val | Nil[A] val)

map[B: B]¶
[Source]
Builds a new list by applying a function to every member of the list.
fun val map[B: B](
f: {(val->A): val->B}[A, B] box)
: (Cons[B] val | Nil[B] val)

Parameters¶

f: {(val->A): val->B}[A, B] box

Returns¶

(Cons[B] val | Nil[B] val)

flat_map[B: B]¶


// Overlong encoding.
((c == 0xF0) and (c2 < 0x90)) or
// UTF32 would be > 0x10FFFF.
((c == 0xF4) and (c2 >= 0x90))
then
err
else
(((c.u32() << 18) +
(c2.u32() << 12) +
(c3.u32() << 6) +
c4.u32()) - 0x3C82080, 4)
end
end
else
// UTF32 would be > 0x10FFFF.
err
end

fun apply(i: USize): U8 ? =>
"""


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171


Public Functions¶
has_next¶
[Source]
fun ref has_next()
: Bool val

Returns¶

Bool val

next¶
[Source]
fun ref next()
: T

Returns¶

T


USize val

ctz¶
[Source]
fun box ctz()
: USize val

Returns¶

USize val

clz_unsafe¶
[Source]
fun box clz_unsafe()
: USize val

Returns¶


uid: U32 val,
gid: U32 val)
: Bool val

Parameters¶

uid: U32 val
gid: U32 val

Returns¶

Bool val

touch¶
[Source]
Set the last access and modification times of the directory to now.
fun box touch()
: Bool val


(USize val , Bool val)

mod_partial¶
[Source]
fun box mod_partial(
y: USize val)
: USize val ?

Parameters¶

y: USize val

Returns¶

USize val ?

mod_unsafe¶
[Source]


Persistent Collections Package¶
List - A persistent list with functional transformations.
Map - A persistent map based on the Compressed Hash Array Mapped Prefix-tree
from 'Optimizing Hash-Array Mapped Tries for Fast and Lean Immutable JVM
Collections' by Michael J. Steindorfer and Jurgen J. Vinju.
Set - A persistent set implemented as a persistent map of an alias of a type
to itself.
Vec - A persistent vector based on the Hash Array Mapped Trie from 'Ideal Hash
Trees' by Phil Bagwell.
Public Types¶

class Cons
class HashMap


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


Returns¶

String val

eq¶
[Source]
fun box eq(
that: ANSI val)
: Bool val

Parameters¶

that: ANSI val

Returns¶

Bool val


@"llvm.bswap.i32"(this.u32()).isize()
else
@"llvm.bswap.i64"(this.u64()).isize()
end

fun popcount(): USize =>
ifdef ilp32 then
@"llvm.ctpop.i32"(this.u32()).usize()
else
@"llvm.ctpop.i64"(this.u64()).usize()
end

fun clz(): USize =>
ifdef ilp32 then
@"llvm.ctlz.i32"(this.u32(), false).usize()
else
@"llvm.ctlz.i64"(this.u64(), false).usize()
end

fun ctz(): USize =>


end

fun _has_short(sh: U8): Bool =>
match _short
| let ss: U8 => sh == ss
else
false
end

fun help_string(): String =>
"""
Returns a formated help string for this option.
"""
let s =
match _short
| let ss: U8 => "-" + String.from_utf32(ss.u32()) + ", "
else
"    "
end
s + "--" + _name +


compact¶
[Source]
Minimise the memory used for the map.
fun ref compact()
: None val

Returns¶

None val

clone[optional H2: HashFunction[this->K!] val]¶
[Source]
Create a clone. The key and value types may be different due to aliasing
and viewpoint adaptation.
fun box clone[optional H2: HashFunction[this->K!] val]()
: HashMap[this->K!, this->V!, H2] ref^


fun ref reverse_in_place() =>
"""
Reverse the array in place.
"""
if _size > 1 then
var i: USize = 0
var j = _size - 1

while i < j do
let x = _ptr._apply(i)
_ptr._update(i, _ptr._apply(j))
_ptr._update(j, x)
i = i + 1
j = j - 1
end
end

fun ref swap_elements(i: USize, j: USize) ? =>
"""
Swap the element at index i with the element at index j.


[Source]
Divide this integer by y and return the result and a flag indicating overflow or division by zero.
fun box divc(
y: A)
: (A , Bool val)

Parameters¶

y: A

Returns¶

(A , Bool val)

remc¶
[Source]
Calculate the remainder of this number divided by y and return the result and a flag indicating division by zero or overflow.
The result will have the sign of the dividend.
fun box remc(


fun box rotr(
y: U8 val)
: U8 val

Parameters¶

y: U8 val

Returns¶

U8 val

string¶
[Source]
fun box string()
: String iso^

Returns¶


peek_u32_le(offset)?.u64() or (peek_u32_le(offset + 4)?.u64() << 32)

fun peek_i64_be(offset: USize = 0): I64 ? =>
"""
Peek at a big-endian I64.
"""
peek_u64_be(offset)?.i64()

fun peek_i64_le(offset: USize = 0): I64 ? =>
"""
Peek at a little-endian I64.
"""
peek_u64_le(offset)?.i64()

fun peek_u128_be(offset: USize = 0): U128 ? =>
"""
Peek at a big-endian U128.
"""
(peek_u64_be(offset)?.u128() << 64) or peek_u64_be(offset + 8)?.u128()


Returns¶

Generator[HashSet[T, HashEq[T] val] ref] box

set_is_of[T: T]¶
[Source]
Create a generator for SetIs filled with values
of the given generator gen.
The returned SetIs will have a size up to max,
but tend to have fewer entries
depending on the source generator gen.
E.g. if the given generator is for U8 values and max is set to 1024
the set will only ever be of size 256 max.
Also for efficiency purposes and to not loop forever,
this generator will only try to add at most max values to the set.
If there are duplicates, the set won't grow.
fun box set_is_of[T: T](
gen: Generator[T] box,
max: USize val = 100)


_SignedUnsafeArithmetic.mod_unsafe[ILong, ULong](this, y)

fun hash(): USize => ulong().hash()

fun addc(y: ILong): (ILong, Bool) =>
ifdef ilp32 or llp64 then
(let r, let o) =
@"llvm.sadd.with.overflow.i32"(this.i32(), y.i32())
(r.ilong(), o)
else
(let r, let o) =
@"llvm.sadd.with.overflow.i64"(this.i64(), y.i64())
(r.ilong(), o)
end

fun subc(y: ILong): (ILong, Bool) =>
ifdef ilp32 or llp64 then
(let r, let o) =
@"llvm.ssub.with.overflow.i32"(this.i32(), y.i32())
(r.ilong(), o)


U128 val

clz_unsafe¶
[Source]
Unsafe operation.
If this is 0, the result is undefined.
fun box clz_unsafe()
: U128 val

Returns¶

U128 val

ctz_unsafe¶
[Source]
Unsafe operation.
If this is 0, the result is undefined.


fun box f64()
: F64 val

Returns¶

F64 val

i8_unsafe¶
[Source]
fun box i8_unsafe()
: I8 val

Returns¶

I8 val

i16_unsafe¶
[Source]


fun box bitwidth()
: U32 val

Returns¶

U32 val

bytewidth¶
[Source]
fun box bytewidth()
: USize val

Returns¶

USize val

min¶
[Source]


232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251


new create(c: String iso) =>
_c = consume c

fun get(): this->String iso => _c

fun ref set(c: String iso) => _c = consume c

actor Main
new create(env:Env) =>
let a = Foo(recover iso String end)
env.out.print(a.get().string())
a.set(recover iso String end)
env.out.print(a.get().string())
```


_make_heap()

fun ref concat(iter: Iterator[A^], offset: USize = 0, len: USize = -1) =>
"""
Add len iterated elements, starting from the given offset.
"""
_data.concat(iter, offset, len)
_make_heap()

fun values(): ArrayValues[A, this->Array[A]]^ =>
"""
Return an iterator for the elements in the heap. The order of elements is
arbitrary.
"""
_data.values()

fun ref _make_heap() =>
let n = size()
if n < 2 then return end
var i = (n / 2)


fun box ip_bind_address_no_port()
: I32 val

Returns¶

I32 val

ip_block_source¶
[Source]
fun box ip_block_source()
: I32 val

Returns¶

I32 val

ip_bound_if¶
[Source]


532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411


fun eq(that: Flags[A, B] box): Bool =>
"""
Returns true if this has the same flags set as that.
"""
_value == that._value

fun lt(that: Flags[A, B] box): Bool =>
"""
Returns true if the flags set on this are a strict subset of the flags set
on that. Flags is only partially ordered, so lt is not the opposite of ge.
"""
(_value != that._value) and ((_value and not that._value) == 0)

fun le(that: Flags[A, B] box): Bool =>
"""
Returns true if the flags set on this are a subset of the flags set on
that or they are the same. Flags is only partially ordered, so le is not
the opposite of te.
"""
((_value and not that._value) == 0)


fun sinh(): F32 => @sinhf(this)
fun tanh(): F32 => @tanhf(this)

fun acos(): F32 => @acosf(this)
fun asin(): F32 => @asinf(this)
fun atan(): F32 => @atanf(this)
fun atan2(y: F32): F32 => @atan2f(this, y)

fun acosh(): F32 => @acoshf(this)
fun asinh(): F32 => @asinhf(this)
fun atanh(): F32 => @atanhf(this)

fun copysign(sign: F32): F32 => @"llvm.copysign.f32"(this, sign)

fun hash(): USize => bits().hash()
fun hash64(): U64 => bits().hash64()

fun i128(): I128 => f64().i128()
fun u128(): U128 => f64().u128()


I128 val

neg¶
[Source]
fun box neg()
: I128 val

Returns¶

I128 val

eq¶
[Source]
fun box eq(
y: I128 val)
: Bool val

Parameters¶


auth: InputSerialisedAuth val,
data: Array[U8 val] val)
: Serialised ref^

Parameters¶

auth: InputSerialisedAuth val
data: Array[U8 val] val

Returns¶

Serialised ref^

Public Functions¶
apply¶
[Source]
A caller with DeserialiseAuth can create an object graph from serialised
data.
fun box apply(


"1.19208e-07".f32()? == F32(1.19208e-07)
"NaN".f32()?.nan() == true

fun box f32(
offset: ISize val = 0)
: F32 val ?

Parameters¶

offset: ISize val = 0

Returns¶

F32 val ?

f64¶
[Source]
Convert this string starting at the given offset
to a 64-bit floating point number (F64).


852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871


fun remc(y: I64): (I64, Bool) =>
_SignedCheckedArithmetic.rem_checked[I64, U64](this, y)

fun fldc(y: I64): (I64, Bool) =>
_SignedCheckedArithmetic.fld_checked[I64, U64](this, y)

fun modc(y: I64): (I64, Bool) =>
_SignedCheckedArithmetic.mod_checked[I64, U64](this, y)

fun add_partial(y: I64): I64 ? =>
_SignedPartialArithmetic.add_partial[I64](this, y)?

fun sub_partial(y: I64): I64 ? =>
_SignedPartialArithmetic.sub_partial[I64](this, y)?

fun mul_partial(y: I64): I64 ? =>
_SignedPartialArithmetic.mul_partial[I64](this, y)?

fun div_partial(y: I64): I64 ? =>


FormatGeneralLarge¶
[Source]
primitive val FormatGeneralLarge is
FormatSpec val

Implements¶

FormatSpec val

Constructors¶
create¶
[Source]


Create a generator for Set filled with values
of the given generator gen.
The returned sets will have a size up to max,
but tend to have fewer than max
depending on the source generator gen.
E.g. if the given generator is for U8 values and max is set to 1024,
the set will only ever be of size 256 max.
Also for efficiency purposes and to not loop forever,
this generator will only try to add at most max values to the set.
If there are duplicates, the set won't grow.
fun box set_of[T: (Hashable #read & Equatable[T] #read)](
gen: Generator[T] box,
max: USize val = 100)
: Generator[HashSet[T, HashEq[T] val] ref] box

Parameters¶

gen: Generator[T] box
max: USize val = 100


Example:
let original: String = "Hello!"
let delimiter: String = "><"
let split_array: Array[String] = original.split_by(delimiter)
env.out.print("OUTPUT:")
for value in split_array.values() do
env.out.print(value)
end

// OUTPUT:
// Hello!

Adjacent delimiters result in a zero length entry in the array. For
example, "1CutCut2".split_by("Cut") => ["1", "", "2"].
An empty delimiter results in an array that contains a single element equal
to the whole string.
If you want to split the string with each individual character of delim,
use split.


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831


432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451


Returns¶

Iterator[T^] ref

value_and_shrink_iter¶
[Source]
fun box value_and_shrink_iter(
rnd: Randomness ref)
: Iterator[(T^ , Iterator[T^] ref)] ref

Parameters¶

rnd: Randomness ref

Returns¶

Iterator[(T^ , Iterator[T^] ref)] ref


### Example

```pony
Iter[I64]([1; 2; 3; 4; 5; 6].values())
.take_while({(x) => x < 4 })
```
`1 2 3`
"""
Iter[A!](
object
var _done: Bool = false
var _next: (A! | None) = None

fun ref has_next(): Bool =>
if _next isnt None then true
else _try_next()
end

fun ref next(): A! ? =>
if (_next isnt None) or _try_next() then


492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511


Parameters¶

predicate: {(T): (T^, Bool)}[T] box

Returns¶

Generator[T] box

map[U: U]¶
[Source]
Apply fn to each value of this iterator
and yield the results.
Example:
let single_code_point_string_gen =
Generators.u32()
.map[String]({(u) => String.from_utf32(u) })

fun box map[U: U](
fn: {(T): U^}[T, U] box)


## `nosupertype`

Recognised on objects(`actor`, `class`, `primitive`, `struct`). A type annotated with `nosupertype` will not be a subtype of any other type (except _), even if the type structurally provides an interface. If a `nosupertype` type has a provides list, a compiler error is reported. As a result, a `nosupertype` type is excluded from both nominal and structural subtyping.

Here's an example of how `nosupertype` can be important:

```pony
class Empty

class Foo
fun foo[A: Any](a: (A | Empty val)) =>
match consume a
| let a': A => None
end
```

The above code won't compile because you could supply `Empty ref`. Doing so results in a compiler error about an unsafe match because we would need to distinguish between `Empty val` and `Empty ref` at runtime.

By adding `nosupertype` to the definition of `Empty`, we declare that `Empty` is not a subtype of `Any` and thereby allow the code to compile as there is no longer an unsafe match.


: Iter[A!] ref^

Parameters¶

f: {(A!): Bool ?}[A] box

Returns¶

Iter[A!] ref^

step_by¶
[Source]
Return an iterator that yields every nth element of the
original iterator. n == 0 is treated like n == 1 rather than an error.
Example¶
Iter[USize](Range(0, 10))
.step_by(2)

1 3 5 7 9


end

fun ref left(ctrl: Bool = false, alt: Bool = false, shift: Bool = false) =>
"""
Move left.
"""
if _cur_pos == 0 then
return
end

try
repeat
_cur_pos = _cur_pos - 1
until
(_cur_pos == 0) or
((_edit.at_offset(_cur_pos)? and 0xC0) != 0x80)
end

_refresh_line()
end


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


(ULong val , Bool val)

add_partial¶
[Source]
fun box add_partial(
y: ULong val)
: ULong val ?

Parameters¶

y: ULong val

Returns¶

ULong val ?

sub_partial¶
[Source]


1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171


WeightedGenerator[T: T]¶
[Source]
A generator with an associated weight, used in Generators.frequency.
type WeightedGenerator[T: T] is
(USize val , Generator[T] box)

Type Alias For¶

(USize val , Generator[T] box)


fun ref exec()
: None val

Returns¶

None val

shared¶
[Source]
Set the write flag for everyone to the same as owner_write.
fun ref shared()
: None val

Returns¶

None val

group¶


Constructors¶
create¶
[Source]
new val create()
: HashByteSeq val^

Returns¶

HashByteSeq val^

Public Functions¶
hash¶
[Source]
fun box hash(
x: (String box | Array[U8 val] box))
: USize val

Parameters¶


Parameters¶

key: K
value: V

Returns¶

(V^ | None val)

upsert¶
[Source]
Combines a provided value with the current value for the provided key
using the provided function. If the provided key has not been added to
the map yet, it sets its value to the provided value and ignores the
provided function.
As a simple example, say we had a map with I64 values and we wanted to
add 4 to the current value for key "test", which let's say is currently 2.
We call


(I16 val , Bool val)

subc¶
[Source]
fun box subc(
y: I16 val)
: (I16 val , Bool val)

Parameters¶

y: I16 val

Returns¶

(I16 val , Bool val)

mulc¶
[Source]


512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531


fun box ip_drop_source_membership()
: I32 val

Returns¶

I32 val

ip_dummynet3¶
[Source]
fun box ip_dummynet3()
: I32 val

Returns¶

I32 val

ip_dummynet_configure¶
[Source]


"""
None

fun ref throttled(conn: TCPConnection ref) =>
"""
Called when the connection starts experiencing TCP backpressure. You should
respond to this by pausing additional calls to `write` and `writev` until
you are informed that pressure has been released. Failure to respond to
the `throttled` notification will result in outgoing data queuing in the
connection and increasing memory usage.
"""
None

fun ref unthrottled(conn: TCPConnection ref) =>
"""
Called when the connection stops experiencing TCP backpressure. Upon
receiving this notification, you should feel free to start making calls to
`write` and `writev` again.
"""
None


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351


[Source]
A random integer in [-2^127, 2^127)
fun ref i128()
: I128 val

Returns¶

I128 val

ilong¶
[Source]
A random integer in [ILong.min_value(), ILong.max_value()]
fun ref ilong()
: ILong val

Returns¶

ILong val


| `*?`     | `mul_partial()?` | Partial Multiplication        |
| `/?`     | `div_partial()?` | Partial Division              |
| `%?`     | `rem_partial()?` | Partial Remainder             |
| `%%?`    | `mod_partial()?` | Partial Modulo                | Starting with version `0.26.1` |

---


672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691


Since bare methods have no receiver, they cannot reference the `this` identifier in their body (either explicitly or implicitly through field access), cannot use `this` viewpoint adapted types, and cannot specify a receiver capability.


that: DNS val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: DNS val)
: Bool val

Parameters¶

that: DNS val

Returns¶

Bool val


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311


"""
53

fun tag precision10(): U8 =>
"""
Mantissa precision in decimal digits.
"""
15

fun tag min_exp2(): I16 =>
"""
Minimum exponent value such that (2^exponent) - 1 is representable at full
precision (ie a normalised number).
"""
-1021

fun tag min_exp10(): I16 =>
"""
Minimum exponent value such that (10^exponent) - 1 is representable at full
precision (ie a normalised number).


312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331


Returns¶

None val

has_prev¶
[Source]
Return true if there is a previous node.
fun box has_prev()
: Bool val

Returns¶

Bool val

has_next¶
[Source]
Return true if there is a next node.


752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771


fun box ne(
that: AlignLeft val)
: Bool val

Parameters¶

that: AlignLeft val

Returns¶

Bool val


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


If any input or output of the operation is +/- infinity or NaN, the result
is undefined.
The operation isn't required to fully comply to IEEE 754 semantics.
fun box mod_unsafe(
y: A)
: A

Parameters¶

y: A

Returns¶

A

neg_unsafe¶
[Source]
Unsafe operation.
If any input or output of the operation is +/- infinity or NaN, the result


while len > 0 do
(let iov_p, let iov_s) =
ifdef windows then
(let tmp_s, let tmp_p) = _pending_writev_windows(num_sent)?
(tmp_p, tmp_s)
else
_pending_writev_posix(num_sent)?
end
if iov_s <= len then
num_sent = num_sent + 1
len = len - iov_s
_pending_writev_total = _pending_writev_total - iov_s
else
ifdef windows then
_pending_writev_windows(num_sent)? = (iov_s-len, iov_p.offset(len))
else
_pending_writev_posix(num_sent)? = (iov_p.offset(len), iov_s-len)
end
_pending_writev_total = _pending_writev_total - len
len = 0


Bool val

ne¶
[Source]
fun box ne(
that: FormatHexSmallBare val)
: Bool val

Parameters¶

that: FormatHexSmallBare val

Returns¶

Bool val


1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051


512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531


fun box ip_nat_xxx()
: I32 val

Returns¶

I32 val

ip_nodefrag¶
[Source]
fun box ip_nodefrag()
: I32 val

Returns¶

I32 val

ip_old_fw_add¶
[Source]


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171


# The code

Then, create a file in that directory called `main.pony`.

__Does the name of the file matter?__ Not to the compiler, no. Pony doesn't care about filenames other than that they end in `.pony`. But it might matter to you! By giving files good names, it can be easier to find the code you're looking for later.

In your file, put the following code:

```pony
actor Main
new create(env: Env) =>
env.out.print("Hello, world!")
```


create¶
[Source]
new val create()
: HashIs[A] val^

Returns¶

HashIs[A] val^

Public Functions¶
hash¶
[Source]
Hash the identity rather than the contents.
fun box hash(
x: box->A!)
: USize val

Parameters¶


fun box ctz_unsafe()
: U8 val

Returns¶

U8 val

bitwidth¶
[Source]
fun box bitwidth()
: U8 val

Returns¶

U8 val

bytewidth¶
[Source]


new val create()
: Greater val^

Returns¶

Greater val^

Public Functions¶
string¶
[Source]
fun box string()
: String iso^

Returns¶

String iso^

eq¶


USize val

f32¶
[Source]
fun box f32()
: F32 val

Returns¶

F32 val

f64¶
[Source]
fun box f64()
: F64 val

Returns¶


fun box sctp_ss_fair_bandwith()
: I32 val

Returns¶

I32 val

sctp_ss_first_come¶
[Source]
fun box sctp_ss_first_come()
: I32 val

Returns¶

I32 val

sctp_ss_priority¶
[Source]


Bool val


## Isolated data is safe

If a block of data has only one reference to it then we call it __isolated__. Since there is only one reference to it, isolated data cannot be __shared__ by multiple threads, so there are no concurrency problems. Isolated data can be passed between multiple threads. As long as only one of them has a reference to it at a time then the data is still safe from concurrency problems.


fun box tipc_top_srv()
: I32 val

Returns¶

I32 val

tipc_wait_forever¶
[Source]
fun box tipc_wait_forever()
: I32 val

Returns¶

I32 val

tipc_withdrawn¶
[Source]


fun box sctp_shutdown_received()
: I32 val

Returns¶

I32 val

sctp_shutdown_sent¶
[Source]
fun box sctp_shutdown_sent()
: I32 val

Returns¶

I32 val

sctp_smallest_pmtu¶
[Source]


: Bool
=>
"""
Assert that the 2 given expressions are equal.
"""
if expect != actual then
_fail(_fmt_msg(loc,  "Assert eq failed. " + msg
+ " Expected (" + expect.string() + ") == (" + actual.string() + ")"))
return false
end

_runner.log(_fmt_msg(loc, "Assert eq passed. " + msg
+ " Got (" + expect.string() + ") == (" + actual.string() + ")"),
true)
true

fun assert_ne[A: (Equatable[A] #read & Stringable #read)](
not_expect: A,
actual: A,
msg: String = "",


fun box ip_pktinfo()
: I32 val

Returns¶

I32 val

ip_pktoptions¶
[Source]
fun box ip_pktoptions()
: I32 val

Returns¶

I32 val

ip_pmtudisc_do¶
[Source]


(Less val | Equal val | Greater val)


-0x8000_0000
else
-0x8000_0000_0000_0000
end

new max_value() =>
ifdef ilp32 or llp64 then
0x7FFF_FFFF
else
0x7FFF_FFFF_FFFF_FFFF
end

fun abs(): ULong => if this < 0 then (-this).ulong() else this.ulong() end

fun bit_reverse(): ILong =>
ifdef ilp32 or llp64 then
@"llvm.bitreverse.i32"(this.u32()).ilong()
else
@"llvm.bitreverse.i64"(this.u64()).ilong()
end


fun box ge(
y: U16 val)
: Bool val

Parameters¶

y: U16 val

Returns¶

Bool val

gt¶
[Source]
fun box gt(
y: U16 val)
: Bool val

Parameters¶


fun box icmp_net_ano()
: I32 val

Returns¶

I32 val

icmp_net_unknown¶
[Source]
fun box icmp_net_unknown()
: I32 val

Returns¶

I32 val

icmp_net_unreach¶
[Source]


Align¶
[Source]
type Align is
(AlignLeft val | AlignRight val | AlignCenter val)

Type Alias For¶

(AlignLeft val | AlignRight val | AlignCenter val)


// f(x) = x + (2^-5 * x^2)
T.from[F64](_subtract = _subtract + (0.03125 * _subtract * _subtract))

fun ref has_next(): Bool =>
match relation
| Less => (_cur < min) and not _overflow
| Equal => false
| Greater => (_cur > min) and not _overflow
end

fun ref next(): T^ ? =>
match relation
| Less =>
let minuend: T = _next_minuend()
let old = _cur
_cur = _cur + minuend
if old > _cur then
_overflow = true
end
old


Returns¶

I128 val ?

ilong¶
[Source]
fun box ilong(
base: U8 val = 0)
: ILong val ?

Parameters¶

base: U8 val = 0

Returns¶

ILong val ?


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411


fun box add_unsafe(
y: U128 val)
: U128 val

Parameters¶

y: U128 val

Returns¶

U128 val

sub_unsafe¶
[Source]
fun box sub_unsafe(
y: U128 val)
: U128 val

Parameters¶


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211


[Source]
fun box overhead()
: MicroBenchmark iso^

Returns¶

MicroBenchmark iso^

before¶
[Source]
fun ref before()
: None val ?

Returns¶

None val ?

before_iteration¶


ULong val | USize val) & Integer[T] val)](
x: T,
y: T,
h: PropertyHelper val)
: None val ?

Parameters¶

x: T
y: T
h: PropertyHelper val

Returns¶

None val ?

name¶
fun box name()
: String val


primitive _StepExecve
fun apply(): U8 => 2

primitive _WNOHANG
fun apply(): I32 =>
ifdef posix then
@ponyint_wnohang()
else
compile_error "no clue what WNOHANG is on this platform."
end

class val Exited is (Stringable & Equatable[ProcessExitStatus])
"""
Process exit status: Process exited with an exit code.
"""
let _exit_code: I32

new val create(code: I32) =>
_exit_code = code


for_all.pony

1
2
3
4
5
6
7
8
9
10
11


fun box tcp_keepidle()
: I32 val

Returns¶

I32 val

tcp_keepinit¶
[Source]
fun box tcp_keepinit()
: I32 val

Returns¶

I32 val

tcp_keepintvl¶
[Source]


new val create()
: FormatUTF32 val^

Returns¶

FormatUTF32 val^

Public Functions¶
eq¶
[Source]
fun box eq(
that: FormatUTF32 val)
: Bool val

Parameters¶

that: FormatUTF32 val

Returns¶


Public Functions¶
string¶
[Source]
fun box string()
: String iso^

Returns¶

String iso^

eq¶
[Source]
fun box eq(
that: ForkError val)
: Bool val

Parameters¶


652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671


try _map.remove(value)? end

fun ref extract(value: box->A!): A^ ? =>
"""
Remove a value from the set and return it. Raises an error if the value
wasn't in the set.
"""
_map.remove(value)?._2

fun ref union(that: Iterator[A^]) =>
"""
Add everything in that to the set.
"""
for value in that do
set(consume value)
end

fun ref intersect[K: HashFunction[box->A!] val = H](
that: HashSet[box->A!, K])
=>


fun box so_peersec()
: I32 val

Returns¶

I32 val

so_port_scalability¶
[Source]
fun box so_port_scalability()
: I32 val

Returns¶

I32 val

so_priority¶
[Source]


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351


Otherwise we would end up with
an alias for T which is T!.
(e.g. String iso would be returned as String iso!,
which aliases as a String tag).
Example:
Generators.repeatedly[Writer]({(): Writer^ =>
let writer = Writer.>write("consume me, please")
consume writer
})

fun box repeatedly[T: T](
f: {(): T^ ?}[T] box)
: Generator[T] box

Parameters¶

f: {(): T^ ?}[T] box

Returns¶


else
while value != 0 do
let index = ((value = value / base) - (value * base))
s.push(table(index.usize())?)
end
end
end

_extend_digits(s, prec')
s.append(typestring)
s.append(prestring)
_pad(s, width, align, fill)
s
end
```

That's from `format/_FormatInt`. It creates a `String ref`, does a bunch of stuff with it, and finally returns it as a `String iso`.

You can also give an explicit reference capability:


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


: None val

Parameters¶

data: (String box | Array[U8 val] box)

Returns¶

None val

queuev¶
[Source]
Queue an iterable collection of ByteSeqs to be written
NOTE: Queue'd data will always be written before normal print/write
requested data
fun ref queuev(
data: ByteSeqIter box)
: None val


fun box div_partial(
y: U8 val)
: U8 val ?

Parameters¶

y: U8 val

Returns¶

U8 val ?

rem_partial¶
[Source]
fun box rem_partial(
y: U8 val)
: U8 val ?

Parameters¶


list_size - the number of items in the following list of items
as a big-endian 32-bit integer
zero or more items of the following data:
a big-endian 64-bit floating point number
a string that starts with a big-endian 32-bit integer that
specifies the length of the string, followed by a number of
bytes that represent the string

A message would be something like this:
[message_length][list_size][float1][string1][float2][string2]...

The following program uses a Reader to decode a message of
this type and print them:
use "buffered"
use "collections"

class Notify is InputNotify
let _env: Env
new create(env: Env) =>
_env = env


fun so_acceptconn():I32 => @pony_os_sockopt_option(I32(802))
fun so_acceptfilter():I32 => @pony_os_sockopt_option(I32(803))
fun so_atmpvc():I32 => @pony_os_sockopt_option(I32(804))
fun so_atmqos():I32 => @pony_os_sockopt_option(I32(805))
fun so_atmsap():I32 => @pony_os_sockopt_option(I32(806))
fun so_attach_bpf():I32 => @pony_os_sockopt_option(I32(807))
fun so_attach_filter():I32 => @pony_os_sockopt_option(I32(808))
fun so_bindtodevice():I32 => @pony_os_sockopt_option(I32(809))
fun so_bintime():I32 => @pony_os_sockopt_option(I32(810))
fun so_bpf_extensions():I32 => @pony_os_sockopt_option(I32(811))
fun so_broadcast():I32 => @pony_os_sockopt_option(I32(812))
fun so_bsdcompat():I32 => @pony_os_sockopt_option(I32(813))
fun so_bsp_state():I32 => @pony_os_sockopt_option(I32(814))
fun so_busy_poll():I32 => @pony_os_sockopt_option(I32(815))
fun so_conaccess():I32 => @pony_os_sockopt_option(I32(816))
fun so_condata():I32 => @pony_os_sockopt_option(I32(817))
fun so_conditional_accept():I32 => @pony_os_sockopt_option(I32(818))
fun so_connect_time():I32 => @pony_os_sockopt_option(I32(819))
fun so_debug():I32 => @pony_os_sockopt_option(I32(820))
fun so_detach_bpf():I32 => @pony_os_sockopt_option(I32(821))


```

Variables only exist from when they are defined until the end of the current scope. For our variable `x` this is the `end` at the end of the then expression: after that, it cannot be used.


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291


212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231


FileExists¶
[Source]
primitive val FileExists

Constructors¶
create¶
[Source]
new val create()
: FileExists val^

Returns¶

FileExists val^


### `packed`

Recognised on a `struct` declaration. Removes padding in the associated `struct`, making it ABI-compatible with a packed C structure with compatible members (declared with the `__attribute__((packed))` extension or the `#pragma pack` preprocessor directive in many C compilers).

```pony
struct \packed\ MyPackedStruct
var x: U8
var y: U32
```


1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231


(F32 val , U32 val)

log¶
[Source]
fun box log()
: F32 val

Returns¶

F32 val

log2¶
[Source]
fun box log2()
: F32 val

Returns¶


new min_normalised() =>
"""
Minimum positive value representable at full precision (ie a normalised
number).
"""
from_bits(0x00800000)

new epsilon() =>
"""
Minimum positive value such that (1 + epsilon) != 1.
"""
from_bits(0x34000000)

fun tag radix(): U8 =>
"""
Exponent radix.
"""
2


fun box ipv6_2292pktinfo()
: I32 val

Returns¶

I32 val

ipv6_2292pktoptions¶
[Source]
fun box ipv6_2292pktoptions()
: I32 val

Returns¶

I32 val

ipv6_2292rthdr¶
[Source]


# Pony-ORCA characteristics

1. An actor may perform garbage collection concurrently with other actors while they are executing any kind of behaviour.

2. An actor may decide whether to garbage collect an object solely based on its own local state, without consultation with or inspecting the state of any other actor.

3. No synchronization between actors is required during garbage collection, other than potential message sends.

4. An actor may garbage collect between its normal behaviours, i.e. it need not wait until its message queue is empty.

5. Pony-ORCA can be applied to several other programming languages, provided that they satisfy the following two requirements:

* **Actor behaviours are atomic**.

* **Message delivery is causal**. [Causal](https://www.google.com/search?q=causal+definition): messages arrive before any messages they may have caused if they have the same destination. So there needs to be some kind of causal ordering guarantee, but fewer requirements than with comparable concurrent, fast garbage collectors.


U8 val ?

mul_partial¶
[Source]
fun box mul_partial(
y: U8 val)
: U8 val ?

Parameters¶

y: U8 val

Returns¶

U8 val ?

div_partial¶
[Source]


U16 val

bswap¶
[Source]
fun box bswap()
: U16 val

Returns¶

U16 val

popcount¶
[Source]
fun box popcount()
: U16 val

Returns¶


ILong val

isize¶
[Source]
fun box isize()
: ISize val

Returns¶

ISize val

u8¶
[Source]
fun box u8()
: U8 val

Returns¶


(I128 val , Bool val)

mulc¶
[Source]
fun box mulc(
y: I128 val)
: (I128 val , Bool val)

Parameters¶

y: I128 val

Returns¶

(I128 val , Bool val)

divc¶
[Source]


772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791


"""
Write an I16 to the buffer in big-endian byte order.
"""
u16_be(data.u16())

fun ref u32_le(data: U32) =>
"""
Write a U32 to the buffer in little-endian byte order.
"""
let num_bytes = U32(0).bytewidth()
ifdef littleendian then
_current.push_u32(data)
else
_current.push_u32(data.bswap())
end
_size = _size + num_bytes

fun ref u32_be(data: U32) =>
"""
Write a U32 to the buffer in big-endian byte order.


if n <= 1 then
"\x1B[A"
else
"\x1B[" + n.string() + "A"
end

fun down(n: U32 = 0): String =>
"""
Move the cursor down n lines. 0 is the same as 1.
"""
if n <= 1 then
"\x1B[B"
else
"\x1B[" + n.string() + "B"
end

fun right(n: U32 = 0): String =>
"""
Move the cursor right n columns. 0 is the same as 1.
"""


U32 val

u64¶
[Source]
fun box u64()
: U64 val

Returns¶

U64 val

u128¶
[Source]
fun box u128()
: U128 val

Returns¶


U32 val

u64_unsafe¶
[Source]
fun box u64_unsafe()
: U64 val

Returns¶

U64 val

u128_unsafe¶
[Source]
fun box u128_unsafe()
: U128 val

Returns¶


new val create(
value: F64 val = 0)
: F64 val^

Parameters¶

value: F64 val = 0

Returns¶

F64 val^

pi¶
[Source]
new val pi()
: F64 val^

Returns¶


be prompt(value: String) =>
"""
Pass a prompt along to the notifier.
"""
_notify.prompt(this, value)

be size() =>
_size()

fun ref _size() =>
"""
Pass the window size to the notifier.
"""
let ws: _TermSize = _TermSize
ifdef posix then
@ioctl(0, _TIOCGWINSZ(), ws) // do error handling
_notify.size(ws.row, ws.col)
end


cur.push(_ptr._apply(i))
i = i + 1
end

result.push(consume cur)
end

consume result

fun ref strip(s: String box = " \t\v\f\r\n") =>
"""
Remove all leading and trailing characters from the string that are in s.
"""
this .> lstrip(s) .> rstrip(s)

fun ref rstrip(s: String box = " \t\v\f\r\n") =>
"""
Remove all trailing characters within the string that are in s. By default,
trailing whitespace is removed.
"""


end

fun tag _n(): USize => 312
fun tag _m(): USize => 156
fun tag _n1(): USize => _n() - 1

fun tag _mask(x: U64, y: U64): U64 =>
(x and 0xffffffff80000000) or (y and 0x000000007fffffff)

fun tag _matrix(x: U64): U64 => (x and 1) * 0xb5026f5aa96619e9

fun tag _mix(x: U64, y: U64): U64 =>
let z = _mask(x, y)
(z >> 1) xor _matrix(z)

fun ref _lower(i: USize, x: U64): U64 ? =>
let y = _state(i + 1)?
_state(i)? = _state(i + _m())? xor _mix(x, y)
y


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


52
53
54interface ProcessNotify
"""
Notifications for Process connections.
"""

fun ref created(process: ProcessMonitor ref) =>
"""
ProcessMonitor calls this when it is created.
"""

fun ref stdout(process: ProcessMonitor ref, data: Array[U8] iso) =>
"""
ProcessMonitor calls this when new data is received on STDOUT of the
forked process
"""

fun ref stderr(process: ProcessMonitor ref, data: Array[U8] iso) =>
"""


<cmd> true
to yield an arg value like
cmd.arg("opt").bool() == true.
new val bool(
name': String val,
descr': String val = "",
default': (Bool val | None val) = reference)
: ArgSpec val^

Parameters¶

name': String val
descr': String val = ""
default': (Bool val | None val) = reference

Returns¶

ArgSpec val^


612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631


532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551


ctrl: Bool val = false
alt: Bool val = false
shift: Bool val = false

Returns¶

None val

end_key¶
[Source]
End of the line.
fun ref end_key(
ctrl: Bool val = false,
alt: Bool val = false,
shift: Bool val = false)
: None val

Parameters¶


Constructors¶
create¶
[Source]
new val create(
value: A)
: Real[A] val^

Parameters¶

value: A

Returns¶

Real[A] val^

from[B: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[B] val)]¶
[Source]
new val from[B: ((I8 val | I16 val | I32 val |


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


commands': Array[CommandSpec] box = Array[CommandSpec]()) ?
=>
"""
Creates a command spec that can accept options and child commands, but not
arguments.
"""
_type = _CommandSpecParent
_name = _assertName(name')?
_descr = descr'
for o in options'.values() do
_options.update(o.name(), o)
end
for c in commands'.values() do
_commands.update(c.name(), c)
end

new leaf(
name': String,
descr': String = "",
options': Array[OptionSpec] box = Array[OptionSpec](),


I16 val

i32¶
[Source]
fun box i32()
: I32 val

Returns¶

I32 val

i64¶
[Source]
fun box i64()
: I64 val

Returns¶


y: U64 val

Returns¶

U64 val

rotr¶
[Source]
fun box rotr(
y: U64 val)
: U64 val

Parameters¶

y: U64 val

Returns¶


fun box head()
: val->A

Returns¶

val->A

tail¶
[Source]
Returns the tail of the list.
fun box tail()
: (Cons[A] val | Nil[A] val)

Returns¶

(Cons[A] val | Nil[A] val)

reverse¶


U32 val

clz¶
[Source]
fun box clz()
: U32 val

Returns¶

U32 val

ctz¶
[Source]
fun box ctz()
: U32 val

Returns¶


fun box map[B: B](
f: {(val->A): val->B}[A, B] box)
: Nil[B] val

Parameters¶

f: {(val->A): val->B}[A, B] box

Returns¶

Nil[B] val

flat_map[B: B]¶
[Source]
Flatmapping a function from A to B over the empty list yields the
empty list of Bs.
fun box flat_map[B: B](
f: {(val->A): List[B]}[A, B] box)
: Nil[B] val


y: I128 val

Returns¶

I128 val

fld¶
[Source]
fun box fld(
y: I128 val)
: I128 val

Parameters¶

y: I128 val

Returns¶


page_up¶
[Source]
fun ref page_up(
ctrl: Bool val,
alt: Bool val,
shift: Bool val)
: None val

Parameters¶

ctrl: Bool val
alt: Bool val
shift: Bool val

Returns¶

None val


divrem¶
[Source]
fun box divrem(
y: A)
: (A , A)

Parameters¶

y: A

Returns¶

(A , A)

rem¶
[Source]
fun box rem(


A

fld¶
[Source]
fun box fld(
y: A)
: A

Parameters¶

y: A

Returns¶

A

mod¶
[Source]


# Alias types

Occasionally we'll want to talk about the type of an alias generically. An alias type is a way of saying "whatever we can safely alias this thing as". We'll discuss generic types later, which will put this to use, but for now it will help us talk about aliases of capabilities in the future.

We indicate an alias type by putting a `!` at the end. Here's an example:

```pony
fun test(a: A) =>
var b: A! = a
```

Here, we're using `A` as a __type variable__, which we'll cover later. So `A!` means "an alias of whatever type `A` is". We can also use it to talk about capabilities: we could have written the statements about `iso` and `trn` as just `iso!` = `tag` and `trn!` = `box`.


Registrar¶
[Source]
A Registrar keeps a map of lookup string to anything. Generally, this is used
to keep a directory of long-lived service-providing actors that can be
looked up name.
actor tag Registrar

Constructors¶
create¶
[Source]
new tag create()
: Registrar tag^


FileSeek¶
[Source]
primitive val FileSeek

Constructors¶
create¶
[Source]
new val create()
: FileSeek val^

Returns¶

FileSeek val^


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206"""


[Source]
A random integer in [0, 2^64)
fun ref next()
: U64 val

Returns¶

U64 val

has_next¶
[Source]
fun tag has_next()
: Bool val

Returns¶

Bool val


I64 val

op_xor¶
[Source]
fun box op_xor(
y: I64 val)
: I64 val

Parameters¶

y: I64 val

Returns¶

I64 val

op_not¶
[Source]


use @kill[I32](pid_t: I32, sig: U32)
use @waitpid[I32](pid: I32, stat_loc: Pointer[I32] tag, opts: I32)
use @_exit[None](status: I32)

// for Windows System Error Codes see: https://docs.microsoft.com/de-de/windows/desktop/Debug/system-error-codes
primitive _ERRORBADEXEFORMAT
fun apply(): U32 =>
"""
ERROR_BAD_EXE_FORMAT
%1 is not a valid Win32 application.
"""
193 // 0xC1

primitive _ERRORDIRECTORY
fun apply(): U32 =>
"""
The directory name is invalid.
"""
267 // 0x10B


"""
if (x <= 1) and (y <= 1) then
"\x1B[H"
else
"\x1B[" + y.string() + ";" + x.string() + "H"
end

fun clear(): String =>
"""
Clear the screen and move the cursor to the top left corner.
"""
"\x1B[H\x1B[2J"

fun erase(direction: _EraseDirection = EraseRight): String =>
"""
Erases content. The direction to erase is dictated by the `direction`
parameter. Use `EraseLeft` to erase everything from the cursor to the
beginning of the line. Use `EraseLine` to erase the entire line. Use
`EraseRight` to erase everything from the cursor to the end of the line.
The default direction is `EraseRight`.


end

fun filter(f: {(this->A!): Bool} box): List[this->A!]^ =>
"""
Builds a new `List` with those elements that satisfy the predicate.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
let other_list = my_list.filter( {(s: String): Bool => s == "b" } )  // other_list is ["b"]
```
"""
try
_filter(head()?, f, List[this->A!])
else
List[this->A!]
end

fun _filter(
ln: this->ListNode[A],
f: {(this->A!): Bool} box,


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291


class Foo
fun foo(str: String): Hashable iso^ =>
object iso is Hashable
let s: String = str
fun apply(): String => s
fun hash(): USize => s.hash()
end
```

We can also implicitly capture values from the lexical scope by using them in the object literal. Sometimes values that aren't local variables, aren't fields, and aren't parameters of a function are called _free variables_. By using them in a function, we are _closing over_ them - that is, capturing them. The code above could be written without the field `s`:

```pony
use "collections"

class Foo
fun foo(str: String): Hashable iso^ =>
object iso is Hashable
fun apply(): String => str
fun hash(): USize => str.hash()
end


fun val slice(
from: USize val = 0,
to: USize val = call,
step: USize val = 1)
: Vec[A] val

Parameters¶

from: USize val = 0
to: USize val = call
step: USize val = 1

Returns¶

Vec[A] val

reverse¶
[Source]
Return a vector with the elements in reverse order.


172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191


fun box bindat()
: U64 val

Returns¶

U64 val

connectat¶
[Source]
fun box connectat()
: U64 val

Returns¶

U64 val

sock_client¶
[Source]


U8 val

u16¶
[Source]
fun box u16()
: U16 val

Returns¶

U16 val

u32¶
[Source]
fun box u32()
: U32 val

Returns¶


use @pony_asio_event_fd[U32](event: AsioEventID)
use @pony_asio_event_resubscribe_read[None](event: AsioEventID)
use @pony_asio_event_resubscribe_write[None](event: AsioEventID)
use @pony_asio_event_get_disposable[Bool](event: AsioEventID)
use @pony_asio_event_set_writeable[None](event: AsioEventID, writeable: Bool)
use @pony_asio_event_set_readable[None](event: AsioEventID, readable: Bool)
use @pony_os_recv[USize](event: AsioEventID, buffer: Pointer[U8] tag,
size: USize) ?
use @pony_os_writev[USize](ev: AsioEventID, wsa: Pointer[(USize, Pointer[U8] tag)] tag,
wsacnt: I32) ? if windows
use @pony_os_writev[USize](ev: AsioEventID, iov: Pointer[(Pointer[U8] tag, USize)] tag,
iovcnt: I32) ? if not windows
use @pony_os_writev_max[I32]()
use @pony_os_keepalive[None](fd: U32, secs: U32)
use @pony_os_socket_close[None](fd: U32)
use @pony_os_socket_shutdown[None](fd: U32)
use @pony_os_connect_tcp[U32](owner: AsioEventNotify, host: Pointer[U8] tag,
service: Pointer[U8] tag, from: Pointer[U8] tag, flags: U32)
use @pony_os_connect_tcp4[U32](owner: AsioEventNotify, host: Pointer[U8] tag,
service: Pointer[U8] tag, from: Pointer[U8] tag, flags: U32)


custodian.pony

1
2
3
4
5
6
7
8
9
10
11


fun box tcp_maxburst()
: I32 val

Returns¶

I32 val

tcp_maxhlen¶
[Source]
fun box tcp_maxhlen()
: I32 val

Returns¶

I32 val

tcp_maxolen¶
[Source]


452
453
454
455
456
457
458
459
460
461
462
463
464
465interface val _PropertyRunNotify
"""
Simple callback for notifying the runner
that a run completed.
"""
fun apply(round: _Round, success: Bool)


Unsigned¶
[Source]
type Unsigned is
(U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val)

Type Alias For¶

(U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val)


and (_read_buf_offset > 0) do
// get data to be distributed and update `_read_buf_offset`
let chop_at = if _expect == 0 then _read_buf_offset else _expect end
(let data, _read_buf) = (consume _read_buf).chop(chop_at)
_read_buf_offset = _read_buf_offset - chop_at

_notify.received(this, consume data, 1)
_read_buf_size()
end

_queue_read()
end

fun ref _read_buf_size() =>
"""
Resize the read buffer if it is empty or smaller than the next payload size
"""
if _read_buf.size() <= _expect then
_read_buf.undefined(_read_buffer_size)
end


Generator[box->T] box

none[T: None val]¶
[Source]
fun box none[T: None val]()
: Generator[(T | None val)] box

Returns¶

Generator[(T | None val)] box

repeatedly[T: T]¶
[Source]
Generate values by calling the lambda f repeatedly,
once for every invocation of generate.
f needs to return an ephemeral type T^, that means
in most cases it needs to consume its returned value.


List[B] ref^

filter¶
[Source]
Builds a new List with those elements that satisfy the predicate.
let my_list = List[String].from(["a"; "b"; "c"])
let other_list = my_list.filter( {(s: String): Bool => s == "b" } )  // other_list is ["b"]

fun box filter(
f: {(this->A!): Bool}[A] box)
: List[this->A!] ref^

Parameters¶

f: {(this->A!): Bool}[A] box

Returns¶


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351


data: U8 val

Returns¶

None val

u16_le¶
[Source]
Write a U16 to the buffer in little-endian byte order.
fun ref u16_le(
data: U16 val)
: None val

Parameters¶

data: U16 val

Returns¶


None val

head¶
[Source]
Show the head of the list, raising an error if the head is empty.
let my_list = List[String].from(["a"; "b"; "c"])
try my_list.head()? end // Returns a ListNode[String] containing "a"

fun box head()
: this->ListNode[A] ref ?

Returns¶

this->ListNode[A] ref ?

tail¶
[Source]
Show the tail of the list, raising an error if the tail is empty.


USize val

i8_unsafe¶
[Source]
fun box i8_unsafe()
: I8 val

Returns¶

I8 val

i16_unsafe¶
[Source]
fun box i16_unsafe()
: I16 val

Returns¶


fun tcpolen_window():I32 => @pony_os_sockopt_option(I32(962))
fun tcpopt_cc():I32 => @pony_os_sockopt_option(I32(963))
fun tcpopt_ccecho():I32 => @pony_os_sockopt_option(I32(964))
fun tcpopt_ccnew():I32 => @pony_os_sockopt_option(I32(965))
fun tcpopt_eol():I32 => @pony_os_sockopt_option(I32(966))
fun tcpopt_fastopen():I32 => @pony_os_sockopt_option(I32(967))
fun tcpopt_fast_open():I32 => @pony_os_sockopt_option(I32(968))
fun tcpopt_maxseg():I32 => @pony_os_sockopt_option(I32(969))
fun tcpopt_multipath():I32 => @pony_os_sockopt_option(I32(970))
fun tcpopt_nop():I32 => @pony_os_sockopt_option(I32(971))
fun tcpopt_pad():I32 => @pony_os_sockopt_option(I32(972))
fun tcpopt_sack():I32 => @pony_os_sockopt_option(I32(973))
fun tcpopt_sack_hdr():I32 => @pony_os_sockopt_option(I32(974))
fun tcpopt_sack_permitted():I32 => @pony_os_sockopt_option(I32(975))
fun tcpopt_sack_permit_hdr():I32 => @pony_os_sockopt_option(I32(976))
fun tcpopt_signature():I32 => @pony_os_sockopt_option(I32(977))
fun tcpopt_timestamp():I32 => @pony_os_sockopt_option(I32(978))
fun tcpopt_tstamp_hdr():I32 => @pony_os_sockopt_option(I32(979))
fun tcpopt_window():I32 => @pony_os_sockopt_option(I32(980))
fun tcp_ca_name_max():I32 => @pony_os_sockopt_option(I32(981))


```pony
class \nosupertype\ Empty

class Foo
fun foo[A: Any](a: (A | Empty val)) =>
match consume a
| let a': A => None
end
```

`nosupertype` is particularly valuable when constructing generic classes like collections that need a marker class to describe "lack of an item".


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


## Arrays and References

Constructing an array with a literal creates new references to its elements. Thus, to be 100% technically correct, array literal elements are inferred to be the alias of the actual element type. If all elements are of type `T` the array literal will be inferred as `Array[T!] ref` that is as an array of aliases of the type `T`.

It is thus necessary to use elements that can have more than one reference of the same type (e.g. types with `val` or `ref` capability) or use ephemeral types for other capabilities (as returned from [constructors](/types/classes.md#constructors) or the [consume expression](/reference-capabilities/consume-and-destructive-read.md)).


if ret == 0 then
return false
end

// get current process pseudo-handle
let handle = @GetCurrentProcess()
if handle == 0 then
return false
end

// get security token
var token: USize = 0
let rights: U32 = 0x0020 // TOKEN_ADJUST_PRIVILEGES
ret = @OpenProcessToken(handle, rights, addressof token)
if ret == 0 then
return false
end

// try to turn on SE_CREATE_SYMBOLIC_LINK privilege
// this won't work unless we are administrator or have Developer Mode on


not_expect: A,
actual: A,
msg: String val = "",
loc: SourceLoc val = __loc)
: Bool val

Parameters¶

not_expect: A
actual: A
msg: String val = ""
loc: SourceLoc val = __loc

Returns¶

Bool val

assert_array_eq[A: (Equatable[A] #read & Stringable #read)]¶
[Source]


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


that: Cap val

Returns¶

Bool val


F32 val

sqrt_unsafe¶
[Source]
Unsafe operation.
If this is negative, the result is undefined.
fun box sqrt_unsafe()
: F32 val

Returns¶

F32 val

cbrt¶
[Source]
fun box cbrt()
: F32 val


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


U8 val

bswap¶
[Source]
fun box bswap()
: U8 val

Returns¶

U8 val

popcount¶
[Source]
fun box popcount()
: U8 val

Returns¶


Fact¶
[Source]
This is an assertion that is always enabled. If the test is false, it will
print any supplied error message to stderr and raise an error.
primitive val Fact

Constructors¶
create¶
[Source]
new val create()
: Fact val^

Returns¶


fun box tcpci_opt_timestamps()
: I32 val

Returns¶

I32 val

tcpci_opt_wscale¶
[Source]
fun box tcpci_opt_wscale()
: I32 val

Returns¶

I32 val

tcpf_ca_cwr¶
[Source]


fun box ipv6_priority_uncharacterized()
: I32 val

Returns¶

I32 val

ipv6_recvdstopts¶
[Source]
fun box ipv6_recvdstopts()
: I32 val

Returns¶

I32 val

ipv6_recverr¶
[Source]


Delete a value from the map and return it. Raises an error if there was no
value for the given key.
"""
try
(let i, let found) = _search(key)

if found then
_size = _size - 1

match _array(i)? = _MapDeleted
| (let k: K, let v: V) =>
return (consume k, consume v)
end
end
end
error

fun get_or_else(key: box->K!, alt: this->V): this->V =>
"""
Get the value associated with provided key if present. Otherwise,


Public Functions¶
apply¶
[Source]
Attempt to get the value corresponding to k.
fun val apply(
k: K)
: val->V ?

Parameters¶

k: K

Returns¶

val->V ?

size¶
[Source]


Iter[A: A]¶
[Source]
Wrapper class containing methods to modify iterators.
class ref Iter[A: A] is
Iterator[A] ref

Implements¶

Iterator[A] ref

Constructors¶
create¶


F32 val

f64¶
[Source]
fun box f64()
: F64 val

Returns¶

F64 val

i8_unsafe¶
[Source]
fun box i8_unsafe()
: I8 val

Returns¶


fun box ipv6_fl_s_user()
: I32 val

Returns¶

I32 val

ipv6_hoplimit¶
[Source]
fun box ipv6_hoplimit()
: I32 val

Returns¶

I32 val

ipv6_hopopts¶
[Source]


312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331


1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391


fun box add(
y: USize val)
: USize val

Parameters¶

y: USize val

Returns¶

USize val

sub¶
[Source]
fun box sub(
y: USize val)
: USize val

Parameters¶


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291


fun box mod_partial(
y: I16 val)
: I16 val ?

Parameters¶

y: I16 val

Returns¶

I16 val ?

shl¶
[Source]
fun box shl(
y: U16 val)
: I16 val

Parameters¶


Parameters¶

y: Bool val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
y: Bool val)
: Bool val

Parameters¶

y: Bool val

Returns¶


Note how in `b` above, the arguments were given out of order by using `where` followed using the name of the arguments.

__Should I specify `where` for each named argument?__ No. There must be only one `where` in a method call.

Named and positional arguments can be used together in a single call. Just start with the positional arguments you want to specify, then a `where` and finally the named arguments. But be careful, each argument must be specified only once.

Default arguments can also be used in combination with positional and named arguments - just miss out any for which you want to use the default.

```pony
class Foo
fun f(a: U32 = 1, b: U32 = 2, c: U32 = 3, d: U32 = 4, e: U32 = 5): U32  =>
0

fun g() =>
f(6, 7 where d = 8)
// Equivalent to:
f(6, 7, 3, 8, 5)
```


: U64 val

Returns¶

U64 val

f64¶
[Source]
Returns the option value as an F64, defaulting to 0.0.
fun box f64()
: F64 val

Returns¶

F64 val

string_seq¶
[Source]


352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371


None val ?

tear_down¶
fun ref tear_down(
h: TestHelper val)
: None val

Parameters¶

h: TestHelper val

Returns¶

None val

label¶
fun box label()


U32 val

max¶
[Source]
fun box max(
y: U32 val)
: U32 val

Parameters¶

y: U32 val

Returns¶

U32 val

addc¶
[Source]


Returns¶

U32 val

chld¶
[Source]
fun box chld()
: U32 val

Returns¶

U32 val

ttin¶
[Source]
fun box ttin()
: U32 val


Why is flatten_next valuable given that next could take a B that is of
a type like Promise[String]? Let's start with some code to demonstrate the
problem that arises when returning Promise[Promise[B]] from next.
Let's say we have a library for accessing the GitHub REST API:
class GitHub
new create(personal_access_token: String)

fun get_repo(repo: String): Promise[Repository]

class Repository
fun get_issue(number: I64): Promise[Issue]

class Issue
fun title(): String

And we want to use this promise based API to look up the title of an issue.
Without flatten_next, we could attempt to do the following using next:
actor Main
new create(env: Env) =>
let repo: Promise[Repository] =


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


offset: USize val
value: U8 val

Returns¶

U8 val ?

update_u16[optional B: (A & Real[B] val & U8 val)]¶
[Source]
Write a U16 at offset. This is only allowed for an array of U8s.
fun ref update_u16[optional B: (A & Real[B] val & U8 val)](
offset: USize val,
value: U16 val)
: U16 val ?

Parameters¶

offset: USize val
value: U16 val


_esc_flush()
end
| _EscapeCSI =>
match c
| 'A' => _up()
| 'B' => _down()
| 'C' => _right()
| 'D' => _left()
| 'H' => _home()
| 'F' => _end()
| '~' => _keypad()
| ';' =>
_escape = _EscapeMod
| if (c >= '0') and (c <= '9') =>
// Escape number.
_esc_num = (_esc_num * 10) + (c - '0')
_esc_buf.push(c)
else
_esc_flush()
end


Parameters¶

that: DoNotOptimise val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: DoNotOptimise val)
: Bool val

Parameters¶

that: DoNotOptimise val

Returns¶


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411


let _hawk: Hawk = Hawk
```

This is explained later, in more detail in the [sugar](/expressions/sugar.md) section.


// _iter might be empty, get next value from other
if _iter.has_next() then
_iter.next()?
else
other.next()?
end
else
_use_original = not _use_original

// other might be empty, get next value from _iter
if other.has_next() then
other.next()?
else
_iter.next()?
end
end
end)

fun ref interleave_shortest(other: Iterator[A]): Iter[A!] =>
"""


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311


Called if name resolution succeeded for a TCPConnection and we are now
waiting for a connection to the server to succeed. The count is the number
of connections we're trying. The notifier will be informed each time the
count changes, until a connection is made or connect_failed() is called.
"""
None

fun ref connected(conn: TCPConnection ref) =>
"""
Called when we have successfully connected to the server.
"""
None

fun ref connect_failed(conn: TCPConnection ref)
"""
Called when we have failed to connect to all possible addresses for the
server. At this point, the connection will never be established.

It is expected to implement proper error handling. You need to opt in to
ignoring errors, which can be implemented like this:


foo(x, 37 where crash = false)
```

becomes:

```pony
var foo = Foo.create()
foo.apply(x, 37 where crash = false)
```

__Do I still need to provide the arguments to apply?__ Yes, only the `apply` will be added for you, the correct number and type of arguments must be supplied. Default and named arguments can be used as normal.

__How do I call a function foo if apply is added?__ The `apply` sugar is only added when calling an object, not when calling a method. The compiler can tell the difference and only adds the `apply` when appropriate.


: U32 val

Returns¶

U32 val

u64¶
[Source]
fun ref u64()
: U64 val

Returns¶

U64 val

u128¶
[Source]
fun ref u128()


Public Functions¶
eq¶
[Source]
fun box eq(
that: FileOK val)
: Bool val

Parameters¶

that: FileOK val

Returns¶

Bool val

ne¶
[Source]


String iso^

insert_in_place¶
[Source]
Inserts the given string at the given offset. Appends the string if the
offset is out of bounds.
fun ref insert_in_place(
offset: ISize val,
that: String box)
: None val

Parameters¶

offset: ISize val
that: String box

Returns¶

None val


352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371


"""
consume acc

fun every(f: {(val->A): Bool} box): Bool =>
"""
Any predicate is true of every member of the empty list.
"""
true

fun exists(f: {(val->A): Bool} box): Bool =>
"""
For any predicate, there is no element that satisfies it in the empty
list.
"""
false

fun partition(f: {(val->A): Bool} box): (Nil[A], Nil[A]) =>
"""
The only partition of the empty list is two empty lists.
"""


that: ASCIINonPrintable val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: ASCIINonPrintable val)
: Bool val

Parameters¶

that: ASCIINonPrintable val

Returns¶


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391


# Shadowing

Some programming languages let you declare a variable with the same name as an existing variable, and then there are rules about which one you get. This is called _shadowing_, and it's a source of bugs. If you accidentally shadow a variable in Pony, the compiler will complain.

If you need a variable with _nearly_ the same name, you can use a prime `'`.


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


timer_notify.pony

1
2
3
4
5
6
7
8
9
10
11


[Source]
Bright grey text.
fun box bright_grey()
: String val

Returns¶

String val

black_bg¶
[Source]
Black background.
fun box black_bg()
: String val

Returns¶

String val


"""
Handles ANSI escape codes from stdin.
"""
let _timers: Timers
var _timer: (Timer tag | None) = None
let _notify: ANSINotify
let _source: DisposableActor
var _escape: _EscapeState = _EscapeNone
var _esc_num: U8 = 0
var _esc_mod: U8 = 0
embed _esc_buf: Array[U8] = Array[U8]
var _closed: Bool = false

new create(
notify: ANSINotify iso,
source: DisposableActor,
timers: Timers = Timers)
=>
"""
Create a new ANSI term.


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491


min: USize = 0,
max: USize = 100)
: Generator[S]
=>
"""
Create a `Seq` from the values of the given Generator with an optional
minimum and maximum size.

Defaults are 0 and 100, respectively.
"""

Generator[S](
object is GenObj[S]
let _gen: GenObj[T] = gen
fun generate(rnd: Randomness): GenerateResult[S] =>
let size = rnd.usize(min, max)

let result: S =
Iter[T^](_gen.value_iter(rnd))
.take(size)


312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


i32_be¶
[Source]
Write an I32 to the buffer in big-endian byte order.
fun ref i32_be(
data: I32 val)
: None val

Parameters¶

data: I32 val

Returns¶

None val

f32_le¶
[Source]
Write an F32 to the buffer in little-endian byte order.
fun ref f32_le(


fun box u8_unsafe()
: U8 val

Returns¶

U8 val

u16_unsafe¶
[Source]
fun box u16_unsafe()
: U16 val

Returns¶

U16 val

u32_unsafe¶
[Source]


672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691


fun box u128_unsafe()
: U128 val

Returns¶

U128 val

ulong_unsafe¶
[Source]
fun box ulong_unsafe()
: ULong val

Returns¶

ULong val

usize_unsafe¶
[Source]


fun box atanh()
: A

Returns¶

A

copysign¶
[Source]
fun box copysign(
sign: A)
: A

Parameters¶

sign: A

Returns¶


nullable_pointer.pony

1
2
3
4
5
6
7
8
9
10
11


"""
_timers = timers
_notify = consume notify
_source = source

ifdef not windows then
SignalHandler(recover _TermResizeNotify(this) end, Sig.winch())
end

_size()

be apply(data: Array[U8] iso) =>
"""
Receives input from stdin.
"""
if _closed then
return
end

for c in (consume data).values() do


1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311


for entry in directory.entries()?.values() do
if not join(entry)?.remove() then
return false
end
end
end

ifdef windows then
// _unlink() on Windows can't remove readonly files
// so we change mode to _S_IWRITE just in case
@_chmod(path.cstring(), U32(0x0080))
if info.directory and not info.symlink then
0 == @_rmdir(path.cstring())
else
0 == @_unlink(path.cstring())
end
else
if info.directory and not info.symlink then
0 == @rmdir(path.cstring())


Returns¶

None val

after¶
[Source]
fun ref after(
c: AsyncBenchContinue val)
: None val

Parameters¶

c: AsyncBenchContinue val

Returns¶

None val


new min_value() => 0

new max_value() =>
ifdef ilp32 then
0xFFFF_FFFF
else
0xFFFF_FFFF_FFFF_FFFF
end

fun next_pow2(): USize =>
let x = (this - 1).clz()
1 << (if x == 0 then 0 else bitwidth() - x end)

fun abs(): USize => this

fun bit_reverse(): USize =>
ifdef ilp32 then
@"llvm.bitreverse.i32"(this.u32()).usize()
else


Parameters¶

y: A

Returns¶

A ?

divrem_partial¶
[Source]
fun box divrem_partial(
y: A)
: (A , A) ?

Parameters¶

y: A

Returns¶


472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491


elseif arg == "--noprog" then
_no_prog = true
elseif arg == "--list" then
_list_only = true
elseif arg.compare_sub("--exclude=", 10) is Equal then
_exclude = arg.substring(10)
elseif arg.compare_sub("--label=", 8) is Equal then
_label = arg.substring(8)
elseif arg.compare_sub("--only=", 7) is Equal then
_only = arg.substring(7)
else
_env.out.print("Unrecognised argument \"" + arg + "\"")
_env.out.print("")
_env.out.print("Usage:")
_env.out.print("  " + exe_name + " [options]")
_env.out.print("")
_env.out.print("Options:")
_env.out.print("  --exclude=prefix  - Don't run tests whose names "
+ "start with the given prefix.")
_env.out.print("  --only=prefix     - Only run tests whose names "


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


String iso^ ?

u8¶
[Source]
Get a U8. Raise an error if there isn't enough data.
fun ref u8()
: U8 val ?

Returns¶

U8 val ?

i8¶
[Source]
Get an I8.
fun ref i8()
: I8 val ?


__Do I have to provide default values for all of my arguments?__ No, you can provide defaults for as many, or as few, as you like.


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211


72
73
74
75
76
77
78
79class XorOshiro128Plus is Random
"""
This is an implementation of xoroshiro128+, as detailed at:

http://xoroshiro.di.unimi.it

This is currently the default Rand implementation.
"""
// state
var _x: U64
var _y: U64

new from_u64(x: U64 = 5489) =>


if not os.required() then
options.update(os.name(), Option(os, os._default_p()))
end
end
end
end

// Check for missing options and error if any exist.
for os in _spec.options().values() do
if not options.contains(os.name()) then
if os.required() then
return SyntaxError(os.name(), "missing value for required option")
end
end
end

// Check for missing args and error if found.
while arg_pos < _spec.args().size() do
try
let ars = _spec.args()(arg_pos)?


end
true
else
// No notifier. Stop reading.
_close_event()
false
end

fun ref _close_event() =>
"""
Close the event.
"""
if not _event.is_null() then
@pony_asio_event_unsubscribe(_event)
_event = AsioEvent.none()
end


552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571


that: Format val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: Format val)
: Bool val

Parameters¶

that: Format val

Returns¶


Returns¶

None val

swap_elements¶
[Source]
Swap the element at index i with the element at index j.
If either i or j are out of bounds, an error is raised.
fun ref swap_elements(
i: USize val,
j: USize val)
: None val ?

Parameters¶

i: USize val
j: USize val

Returns¶


# Bare functions

Classic Pony functions have a receiver, which acts as an implicit argument to the function. Because of this, classic functions can't be used as callbacks with many C APIs. Instead, you can use _bare functions_, which are functions with no receiver.

You can define a bare function by prefixing the function name with the @ symbol.

```pony
class C
fun @callback() =>
...
```

The function can then be passed as a callback to a C API with the `addressof` operator.

```pony
@setup_callback(addressof C.callback)
```

Note that it is possible to use an object reference instead of a type as the left-hand side of the method access.


fun box lt(
that: HashSet[A, H] box)
: Bool val

Parameters¶

that: HashSet[A, H] box

Returns¶

Bool val

le¶
[Source]
Returns true if every element in this is also in that.
fun box le(
that: HashSet[A, H] box)
: Bool val


Indicate that this is a long running test that may continue after the
test function exits.
Once this function is called, complete() must be called to finish the test,
unless a timeout occurs.
The timeout is specified in nanseconds.
fun box long_test(
timeout: U64 val)
: None val

Parameters¶

timeout: U64 val

Returns¶

None val

complete¶
[Source]


fun ip_recvpktinfo():I32 => @pony_os_sockopt_option(I32(322))
fun ip_recvretopts():I32 => @pony_os_sockopt_option(I32(323))
fun ip_recvrssbucketid():I32 => @pony_os_sockopt_option(I32(324))
fun ip_recvtos():I32 => @pony_os_sockopt_option(I32(325))
fun ip_recvttl():I32 => @pony_os_sockopt_option(I32(326))
fun ip_retopts():I32 => @pony_os_sockopt_option(I32(327))
fun ip_router_alert():I32 => @pony_os_sockopt_option(I32(328))
fun ip_rssbucketid():I32 => @pony_os_sockopt_option(I32(329))
fun ip_rss_listen_bucket():I32 => @pony_os_sockopt_option(I32(330))
fun ip_rsvp_off():I32 => @pony_os_sockopt_option(I32(331))
fun ip_rsvp_on():I32 => @pony_os_sockopt_option(I32(332))
fun ip_rsvp_vif_off():I32 => @pony_os_sockopt_option(I32(333))
fun ip_rsvp_vif_on():I32 => @pony_os_sockopt_option(I32(334))
fun ip_sendsrcaddr():I32 => @pony_os_sockopt_option(I32(335))
fun ip_striphdr():I32 => @pony_os_sockopt_option(I32(336))
fun ip_tos():I32 => @pony_os_sockopt_option(I32(337))
fun ip_traffic_mgt_background():I32 => @pony_os_sockopt_option(I32(338))
fun ip_transparent():I32 => @pony_os_sockopt_option(I32(339))
fun ip_ttl():I32 => @pony_os_sockopt_option(I32(340))
fun ip_unblock_source():I32 => @pony_os_sockopt_option(I32(341))


```pony
// listening() is a callback function for class UDPNotify
fun ref listening(sock: UDPSocket ref) =>
match sock.getsockopt(OSSockOpt.sol_socket(), OSSockOpt.so_rcvbuf(), 4)
| (0, let gbytes: Array[U8] iso) =>
try
let br = Reader.create().>append(consume gbytes)
ifdef littleendian then
let buffer_size = br.u32_le()?
else
let buffer_size = br.u32_be()?
end
end
| (let errno: U32, _) =>
// System call failed
end
```
"""
_OSSocket.getsockopt(_fd, level, option_name, option_max_size)


try
let path' = FilePath.from(path, target, path.caps)?

ifdef linux or bsd then
0 == @fchmodat(_fd, target.cstring(), mode.u32(), I32(0))
else
path'.chmod(mode)
end
else
false
end

fun chownat(target: String, uid: U32, gid: U32): Bool =>
"""
Set the FileMode for some path relative to this directory.
"""
if
not path.caps(FileChown)
or not path.caps(FileLookup)
or (_fd == -1)


F64 val

fld¶
[Source]
fun box fld(
y: F64 val)
: F64 val

Parameters¶

y: F64 val

Returns¶

F64 val

fld_unsafe¶
[Source]


addr1-4 fields are the IPv6 address, or invalid for an IPv4 address. The
scope field is the IPv6 scope, or invalid for an IPv4 address.

This class is modelled after the C data structure for holding socket
addresses for both IPv4 and IPv6 `sockaddr_storage`.

Use the `name` method to obtain address/hostname and port/service as Strings.
"""
let _family: U16 = 0

let _port: U16 = 0
"""
Port number in network byte order.
"""

let _addr: U32 = 0
"""
IPv4 address in network byte order.
Will be `0` for IPv6 addresses. Check with `ipv4()` and `ipv6()`.
"""


descr': String val = ""
options': Array[OptionSpec val] box = call
args': Array[ArgSpec val] box = call

Returns¶

CommandSpec ref^ ?

Public Functions¶
add_command¶
[Source]
Adds an additional child command to this parent command.
fun ref add_command(
cmd: CommandSpec box)
: None val ?

Parameters¶

cmd: CommandSpec box


: Array[NetAddress] iso^
=>
"""
Gets all IPv4 addresses for a host and service.
"""
_resolve(auth, 1, host, service)

fun ip6(auth: DNSAuth, host: String, service: String)
: Array[NetAddress] iso^
=>
"""
Gets all IPv6 addresses for a host and service.
"""
_resolve(auth, 2, host, service)

fun broadcast_ip4(auth: DNSAuth, service: String)
: Array[NetAddress] iso^
=>
"""
Link-local IP4 broadcast address.


492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511


The Path primitive can be used to do path-related operations on
strings and characters.
Example program¶
This program opens the files that are given as command line arguments
and prints their contents.
use "files"

actor Main
new create(env: Env) =>
for file_name in env.args.slice(1).values() do
let path = FilePath(FileAuth(env.root), file_name)
match OpenFile(path)
| let file: File =>
while file.errno() is FileOK do
env.out.write(file.read(1024))
end
else
env.err.print("Error opening file '" + file_name + "'")
end
end


"""

fun eq(x: box->A!, y: box->A!): Bool
"""
Determine equality between two keys with the same hash. This is done with
viewpoint adapted aliases to allow data structures to determine equality
in a box fun without consuming keys.
"""

interface val HashFunction64[A]
"""
A pluggable hash function with 64-bit hashes.
"""
new val create()
"""
Data structures create instances internally. Use a primitive if possible.
"""

fun hash64(x: box->A!): U64
"""


U8 val

u16¶
[Source]
fun box u16()
: U16 val

Returns¶

U16 val

u32¶
[Source]
fun box u32()
: U32 val

Returns¶


let g = this
match g.generate(rnd)?
| let t: T => consume t
| (let t: T, _) => consume t
end

fun generate_and_shrink(rnd: Randomness): ValueAndShrink[T] ? =>
"""
Generate a value and also return a shrink result,
even if the generator does not return any when calling `generate`.
"""
let g = this
match g.generate(rnd)?
| let t: T => g.shrink(consume t)
| (let t: T, let shrinks: Iterator[T^])=> (consume t, shrinks)
end

fun iter(rnd: Randomness): Iterator[GenerateResult[T]]^ =>
let that: GenObj[T] = this


new iso create(
p4: Property4[T1, T2, T3, T4] iso,
name': (String val | None val) = reference)
: Property4UnitTest[T1, T2, T3, T4] iso^

Parameters¶

p4: Property4[T1, T2, T3, T4] iso
name': (String val | None val) = reference

Returns¶

Property4UnitTest[T1, T2, T3, T4] iso^

Public Functions¶
name¶
[Source]
fun box name()
: String val


452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131


Return a new path relative to this one.
fun val join(
path': String val,
caps': Flags[(FileCreate val | FileChmod val | FileChown val | FileLink val | FileLookup val | FileMkdir val | FileRead val | FileRemove val | FileRename val | FileSeek val | FileStat val | FileSync val | FileTime val | FileTruncate val | FileWrite val | FileExec val), U32 val] val = recover)
: FilePath val ?

Parameters¶

path': String val
caps': Flags[(FileCreate val | FileChmod val | FileChown val | FileLink val | FileLookup val | FileMkdir val | FileRead val | FileRemove val | FileRename val | FileSeek val | FileStat val | FileSync val | FileTime val | FileTruncate val | FileWrite val | FileExec val), U32 val] val = recover

Returns¶

FilePath val ?

walk¶
[Source]
Walks a directory structure starting at this.
handler(dir_path, dir_entries) will be called for each directory


type Align is
( AlignLeft
| AlignRight
| AlignCenter )


fun box rds_get_mr()
: I32 val

Returns¶

I32 val

rds_get_mr_for_dest¶
[Source]
fun box rds_get_mr_for_dest()
: I32 val

Returns¶

I32 val

rds_ib_abi_version¶
[Source]


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


Property2UnitTest[T1: T1, T2: T2]¶
[Source]
class iso Property2UnitTest[T1: T1, T2: T2] is
UnitTest ref

Implements¶

UnitTest ref

Constructors¶
create¶
[Source]


PropertyHelper¶
[Source]
Helper for PonyCheck properties.
Mirrors the TestHelper API as closely as possible.
Contains assertion functions and functions for completing asynchronous
properties, for expecting and completing or failing actions.
Internally a new PropertyHelper will be created for each call to
a property with a new sample and also for every shrink run.
So don't assume anything about the identity of the PropertyHelper inside of
your Properties.
This class is val by default so it can be safely passed around to other
actors.
It exposes the process Env as public env field in order to


612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631


else
error
end

fun ref update(key: K, value: V): (V^ | None) =>
"""
Sets a value in the map. Returns the old value if there was one, otherwise
returns None. If there was no previous value, this may trigger a resize.
"""
try
(let i, let found) = _search(key)

match _array(i)? = (consume key, consume value)
| (_, let v: V) =>
return consume v
else
_size = _size + 1

if (_size * 4) > (_array.size() * 3) then
_resize(_array.size() * 2)


ValueAndShrink[T1: T1]¶
[Source]
Possible return type for
Generator.generate.
Represents a generated value and an Iterator of shrunken values.
type ValueAndShrink[T1: T1] is
(T1^ , Iterator[T1^] ref)

Type Alias For¶

(T1^ , Iterator[T1^] ref)


772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791


fun tcp_notsent_lowat():I32 => @pony_os_sockopt_option(I32(1022))
fun tcp_pcap_in():I32 => @pony_os_sockopt_option(I32(1023))
fun tcp_pcap_out():I32 => @pony_os_sockopt_option(I32(1024))
fun tcp_queue_seq():I32 => @pony_os_sockopt_option(I32(1025))
fun tcp_quickack():I32 => @pony_os_sockopt_option(I32(1026))
fun tcp_repair():I32 => @pony_os_sockopt_option(I32(1027))
fun tcp_repair_options():I32 => @pony_os_sockopt_option(I32(1028))
fun tcp_repair_queue():I32 => @pony_os_sockopt_option(I32(1029))
fun tcp_rxt_conndroptime():I32 => @pony_os_sockopt_option(I32(1030))
fun tcp_rxt_findrop():I32 => @pony_os_sockopt_option(I32(1031))
fun tcp_saved_syn():I32 => @pony_os_sockopt_option(I32(1032))
fun tcp_save_syn():I32 => @pony_os_sockopt_option(I32(1033))
fun tcp_sendmoreacks():I32 => @pony_os_sockopt_option(I32(1034))
fun tcp_syncnt():I32 => @pony_os_sockopt_option(I32(1035))
fun tcp_s_data_in():I32 => @pony_os_sockopt_option(I32(1036))
fun tcp_s_data_out():I32 => @pony_os_sockopt_option(I32(1037))
fun tcp_thin_dupack():I32 => @pony_os_sockopt_option(I32(1038))
fun tcp_thin_linear_timeouts():I32 => @pony_os_sockopt_option(I32(1039))
fun tcp_timestamp():I32 => @pony_os_sockopt_option(I32(1040))
fun tcp_user_timeout():I32 => @pony_os_sockopt_option(I32(1041))


U64 val

bit_reverse¶
[Source]
fun box bit_reverse()
: I64 val

Returns¶

I64 val

bswap¶
[Source]
fun box bswap()
: I64 val

Returns¶


fun box ipproto_leaf2()
: I32 val

Returns¶

I32 val

ipproto_max¶
[Source]
fun box ipproto_max()
: I32 val

Returns¶

I32 val

ipproto_maxid¶
[Source]


Returns¶

String iso^

add¶
fun box add(
y: F32 val)
: F32 val

Parameters¶

y: F32 val

Returns¶

F32 val

sub¶


"""
Minimum exponent value such that (10^exponent) - 1 is representable at full
precision (ie a normalised number).
"""
-37

fun tag max_exp2(): I16 =>
"""
Maximum exponent value such that (2^exponent) - 1 is representable.
"""
128

fun tag max_exp10(): I16 =>
"""
Maximum exponent value such that (10^exponent) - 1 is representable.
"""
38

fun abs(): F32 => @"llvm.fabs.f32"(this)
fun ceil(): F32 => @"llvm.ceil.f32"(this)


U128 val

ulong_unsafe¶
[Source]
fun box ulong_unsafe()
: ULong val

Returns¶

ULong val

usize_unsafe¶
[Source]
fun box usize_unsafe()
: USize val

Returns¶


USize val

rotl¶
[Source]
fun box rotl(
y: USize val)
: USize val

Parameters¶

y: USize val

Returns¶

USize val

rotr¶
[Source]


932
933
934
935
936
937
938
939
940use @"llvm.sadd.with.overflow.i8"[(I8, Bool)](a: I8, b: I8)
use @"llvm.sadd.with.overflow.i16"[(I16, Bool)](a: I16, b: I16)
use @"llvm.sadd.with.overflow.i32"[(I32, Bool)](a: I32, b: I32)
use @"llvm.sadd.with.overflow.i64"[(I64, Bool)](a: I64, b: I64)
use @"llvm.sadd.with.overflow.i128"[(I128, Bool)](a: I128, b: I128)
use @"llvm.ssub.with.overflow.i8"[(I8, Bool)](a: I8, b: I8)
use @"llvm.ssub.with.overflow.i16"[(I16, Bool)](a: I16, b: I16)
use @"llvm.ssub.with.overflow.i32"[(I32, Bool)](a: I32, b: I32)
use @"llvm.ssub.with.overflow.i64"[(I64, Bool)](a: I64, b: I64)
use @"llvm.ssub.with.overflow.i128"[(I128, Bool)](a: I128, b: I128)
use @"llvm.smul.with.overflow.i8"[(I8, Bool)](a: I8, b: I8)
use @"llvm.smul.with.overflow.i16"[(I16, Bool)](a: I16, b: I16)


F64 val) & Real[A] val)](
a: A)
: USize val^

Parameters¶

a: A

Returns¶

USize val^

min_value¶
[Source]
new val min_value()
: USize val^

Returns¶


fun box ipx_receive_broadcast()
: I32 val

Returns¶

I32 val

ipx_recvhdr¶
[Source]
fun box ipx_recvhdr()
: I32 val

Returns¶

I32 val

ipx_reripnetnumber¶
[Source]


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171


fun box divrem_partial(
y: I64 val)
: (I64 val , I64 val) ?

Parameters¶

y: I64 val

Returns¶

(I64 val , I64 val) ?

fld_partial¶
[Source]
fun box fld_partial(
y: I64 val)
: I64 val ?

Parameters¶


input = Stdin._create(@pony_os_stdin_setup())
out = StdStream._out()
err = StdStream._err()

args = _strings_from_pointers(argv, argc.usize())
vars = _strings_from_pointers(envp, _count_strings(envp))

exitcode = {(code: I32) => @pony_exitcode(code) }

new val create(
root': AmbientAuth,
input': InputStream, out': OutStream,
err': OutStream, args': Array[String] val,
vars': Array[String] val,
exitcode': {(I32)} val)
=>
"""
Build an artificial environment. A root capability must be supplied.
"""
root = root'


fun box eq(
y: I32 val)
: Bool val

Parameters¶

y: I32 val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
y: I32 val)
: Bool val

Parameters¶


that: Debug val

Returns¶

Bool val


_unsynced_metadata = true
end
for d in Range[USize](0, num_written, 1) do
_pending_writev.shift()?
end
end
return result
else
// TODO: error recovery? EINTR?

// check error
_errno = _get_error()

dispose()
return false
end

fun _write_to_disk(): (Bool, USize, USize) ? =>
"""
Write pending data.


class _ListReverseProperties is UnitTest
fun name(): String => "list/properties"

fun apply(h: TestHelper) ? =>
let gen1 = Generators.seq_of[USize, Array[USize]](Generators.usize())
PonyCheck.for_all[Array[USize]](gen1, h)({
(arg1: Array[USize], ph: PropertyHelper) =>
ph.assert_array_eq[USize](arg1, arg1.reverse().reverse())
})
let gen2 = Generators.seq_of[USize, Array[USize]](1, Generators.usize())
PonyCheck.for_all[Array[USize]](gen2, h)({
(arg1: Array[USize], ph: PropertyHelper) =>
ph.assert_array_eq[USize](arg1, arg1.reverse())
})
```


[Source]
Returns the last error code set for this File
fun box errno()
: (FileOK val | FileError val | FileEOF val |
FileBadFileNumber val | FileExists val | FilePermissionDenied val)

Returns¶

(FileOK val | FileError val | FileEOF val |
FileBadFileNumber val | FileExists val | FilePermissionDenied val)

clear_errno¶
[Source]
Clears the last error code set for this File.
Clears the error indicator for the stream.
fun ref clear_errno()
: None val

Returns¶


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


: Bool
=>
"""
Check that the 2 given expressions are not equal.
"""
if not_expect == actual then
fail(_format_loc(loc) + "Assert " + check + " failed. " + msg
+ " Expected (" + not_expect.string() + ") != (" + actual.string()
+ ")")
return false
end

log(
_format_loc(loc) + "Assert " + check + " passed. " + msg
+ " Got (" + not_expect.string() + ") != (" + actual.string() + ")",
true)
true

fun assert_array_eq[A: (Equatable[A] #read & Stringable #read)](
expect: ReadSeq[A],


# Proxy support

Using the `proxy_via` callback in a `TCPConnectionNotify` it is possible
to implement proxies. The function takes the intended destination host
and service as parameters and returns a 2-tuple of the proxy host and
service.

The proxy `TCPConnectionNotify` should decorate another implementation of
`TCPConnectionNotify` passing relevent data through.


expect_action¶
[Source]
Can be called in a long test to set up expectations for one or more actions
that, when all completed, will complete the test.
This pattern is useful for cases where you have multiple things that need
to happen to complete your test, but don't want to have to collect them
all yourself into a single actor that calls the complete method.
The order of calls to expect_action don't matter - the actions may be
completed in any other order to complete the test.
fun box expect_action(
name: String val)
: None val

Parameters¶

name: String val

Returns¶


that: box->A

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: box->A)
: Bool val

Parameters¶

that: box->A

Returns¶


"""
"\x1B[92m"

fun bright_yellow(): String =>
"""
Bright yellow text.
"""
"\x1B[93m"

fun bright_blue(): String =>
"""
Bright blue text.
"""
"\x1B[94m"

fun bright_magenta(): String =>
"""
Bright magenta text.
"""
"\x1B[95m"


F64 val) & Real[A] val)](
a: A)
: U32 val^

Parameters¶

a: A

Returns¶

U32 val^

min_value¶
[Source]
new val min_value()
: U32 val^

Returns¶


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


A

floor¶
[Source]
fun box floor()
: A

Returns¶

A

round¶
[Source]
fun box round()
: A

Returns¶


// to the provided value. The old map is unchanged.
let m2 = m1("a") = 5 // {a: 5}
let m3 = m2("b") = 10 // {a: 5, b: 10}
let m4 = m3.remove("a")? // {b: 10}
// You can create a new map from key value pairs.
let m5 = Map[String, U32].concat([("a", 2); ("b", 3)].values()) // {a: 2, b: 3}
end

class val HashMap[K: Any #share, V: Any #share, H: HashFunction[K] val]

Constructors¶
create¶
[Source]
new val create()
: HashMap[K, V, H] val^

Returns¶

HashMap[K, V, H] val^