Pikoc

Coming from TypeScript

You already know
most of Pikoc.

Pikoc reads like TypeScript and ships JavaScript's library: arrays, Map and Set, strings, JSON, RegExp, promises, fetch, streams and console. Most code ports by adding types where Pikoc can't infer them. This page is about the rest: what is deliberately different, and the Pikoc way to write it.

shapes.pi
interface Shape { area(): number }

class Circle implements Shape {
  constructor(public r: number) {}
  public area(): number { Math.PI * r * r }
}
class Rect implements Shape {
  constructor(public w: number, public h: number) {}
  public area(): number { w * h }
}

const shapes: Shape[] = [new Circle(1.0), new Rect(2.0, 3.0)]
const total = shapes.map(s => s.area()).reduce((a, b) => a + b, 0.0)
println(`total area: ${total.toFixed(2)}`)
$ pikoc run shapes.pi
total area: 9.14

What works as in TypeScript

These keep JavaScript's semantics, so ported code keeps its meaning.

  • Number(x), String(x), parseFloat, isNaN, the Number statics, and toFixed, toPrecision and toString(radix), rounded as JavaScript rounds them.
  • Array callbacks get (x, i, xs), and all of Array.prototype is there, with Array.from, Array.of and Array.isArray.
  • Map and Set with live iterators, Object.keys/values/entries/fromEntries/assign.
  • JSON.parse with a reviver, JSON.stringify with a replacer and indent, and JSON.parse<T> for typed data.
  • Error.stack, new Error(msg, { cause }), AggregateError, and RangeError or TypeError where JavaScript throws them.
  • console.log and friends, addEventListener(type, f, { once, signal }), Promise.withResolvers(), ===, for (k in o), export default.
const xs = [3, 1, 2]
xs.sort((a, b) => a - b)
println(xs.map((x, i) => x * i))               // callbacks get (x, i, xs)

const counts = new Map<string, int>()
for (const w of "a b a".split(" ")) counts.set(w, (counts.get(w) ?? 0) + 1)
println(Object.fromEntries(counts))

println(JSON.stringify({ name: "Ann", tags: ["x", "y"] }))
println((0.1 + 0.2).toFixed(2))
println(`${xs}`)                               // 1,2,3

Types are sound and nominal

TypeScript compares types by shape and lets any switch the checker off. Pikoc compares them by name, has no any, and what type-checks holds at run time.

TypeScript
interface Named { name(): string }

class Robot {
  name() { return "R2-D2" }
}

function hello(x: Named) {
  console.log(`Hello, ${x.name()}`)
}
hello(new Robot())   // fine: the shape matches
Pikoc
interface Named { name(): string }

class Dog implements Named {         // conforms only through `implements`
  public name(): string { "Rex" }
}
class Robot {                        // the same shape, but not a Named
  public name(): string { "R2-D2" }
}

function hello(x: Named) { println(`Hello, ${x.name()}`) }
hello(new Dog())
// hello(new Robot())                // error E0308: expected `Named`, found `Robot`
Nullability
function greet(name: string?): string {
  if (name == null) return "Hello, stranger"
  `Hello, ${name.toUpperCase()}`     // narrowed to string
}
println(greet(null))
println(greet("ann"))

const port: int? = int.parse("8080")
println(port! + 1)                   // `!` asserts non-null, panics on null
const label: string? = null
println(label?.length ?? 0)
unknown instead of any
function describe(u: unknown): string {
  match (u) {                        // unknown has to be narrowed before use
    n: int => `an int: ${n + 1}`,
    s: string => `a string of ${s.length}`,
    _ => "something else",
  }
}
println(describe(41))
println(describe("hi"))

Integers and floats are different types

An integer literal is an int (64-bit), and number is a 64-bit float. Sized types (i8 to u64, f32) are there when you need them.

TypeScriptPikocWhy
every number is a doubleint and number are separate; an integer literal is an intexact integers past 253, fast integer code
7 / 2 is 3.57 / 2 is 3; write 7.0 / 2.0integer division for integers
overflow loses precisionoverflow panicssilent wraparound hides bugs
1 / 0 is Infinityinteger / 0 panics; 1.0 / 0.0 is Infinityas above
parseInt("x") is NaNparseInt returns int and panics without digitsan int has no NaN; use int.parse(s) for int?
typeof 1 is "number"typeof 1 is "i64"types are more precise; narrow with is int or is number

Mixing int and number needs an explicit as: n as number, or x as int, which truncates.

println(7 / 2)                  // 3: both sides are int
println(7.0 / 2.0)              // 3.5
const ratio: number = 7 / 2.0   // 3.5: the expected type makes 7 a number
const n = 10
println((n as number) / 4.0)    // 2.5: mixing int and number needs `as`
println(3.9 as int)             // 3: truncates
println(typeof 1)               // i64
println(2 ** 62)                // 4611686018427387904, exact
println(int.parse("x") ?? -1)   // -1: null instead of NaN

Conditions take only booleans

if (str), if (count) and x || "default" on non-booleans don't compile. Write what you mean; Boolean(x) gives JavaScript's truthiness as a value when you need it.

TypeScript
const name: string | undefined = undefined
if (name) console.log(name)
const label = name || "anonymous"
console.log(label)
const items: number[] = []
if (items.length) console.log(items[0])
Pikoc
const name: string? = null
if (name != null && name.length > 0) println(name)
const label = name ?? "anonymous"      // instead of name || "anonymous"
println(label)
const items: int[] = []
if (items.length > 0) println(items[0])   // not `if (items.length)`
println(Boolean(""))                      // JavaScript truthiness, as a value

Strings count code points

  • Strings are UTF-8, and lengths and indices count code points: "🙂".length is 1, not 2.
  • s[i] is a char, and an index past the end panics instead of giving undefined.
  • toUpperCase and toLowerCase cover ASCII letters, and trim removes ASCII white space.
const s = "zażółć 🙂"
println(s.length)                            // 8: code points
println(new TextEncoder().encode(s).length)  // 15: UTF-8 bytes
println(s[7])                                // 🙂: a char

Classes, structs and values

Classes look the same, with a few rules TypeScript doesn't have, and struct adds value types.

Classes
class Account {
  balance: int = 0                       // private: members are private by default
  constructor(public owner: string) {}   // a public parameter property
  public deposit(amount: int) { balance += amount }   // no `this.` needed
  public get total(): int { balance }
}

const acc = new Account("Ann")
acc.deposit(50)
println(`${acc.owner}: ${acc.total}`)
class Counter {
  count: int = 0
  public tick() { count++ }
  public get value(): int { count }
}
const counter = new Counter()
const tick = counter.tick      // a method used as a value stays bound
tick()
tick()
println(counter.value)         // 2
Structs
struct Point { x: int; y: int }

let a = Point { x: 1, y: 2 }
let b = a                          // a copy, not a reference
b.x = 10
println(a.x)                       // 1
println(a == Point { x: 1, y: 2 }) // true: compared field by field

const seen = new Set<Point>()
seen.add(Point { x: 1, y: 2 })
println(seen.has(Point { x: 1, y: 2 }))   // true: equal structs are the same key
class Box { constructor(public value: int) {} }

const a = new Box(1)
const b = new Box(1)
println(a == b)          // false: classes compare by identity unless they define equals()
const c = a
c.value = 2
println(a.value)         // 2: classes are shared references

Exceptions are checked

A function declares what it throws with throws, and callers either handle it or declare it in turn. The compiler reports an error that is neither as E0336.

  • Top-level functions infer their throws; methods and exported functions declare it. Higher-order functions are polymorphic: map throws whatever its callback throws.
  • try is an expression. try? turns an error into null, and try! turns it into a panic.
  • Errors JavaScript can throw almost anywhere stay unchecked, such as a RangeError from typed-array access.
  • Panics (an index out of bounds, overflow, x! on null, a failed as, assert) aren't exceptions: catch doesn't see them. They run finally blocks and end the program, because they're bugs.
class ParseError extends Error {}

function parsePort(s: string): int throws ParseError {
  const n = int.parse(s)
  if (n == null) throw new ParseError(`not a port: ${s}`)
  n
}

class Server {
  public start(arg: string): void throws ParseError {   // drop `throws` here: E0336
    println(`listening on ${parsePort(arg)}`)
  }
}

try {
  new Server().start("http")
} catch (e: ParseError) {
  println(e.message)
}

const port = try parsePort("x") catch (e: ParseError) 8080   // try is an expression
const maybe = try? parsePort("x")                              // int?: null on error
const sure = try! parsePort("443")                             // an error becomes a panic
println(`${port} ${maybe ?? -1} ${sure}`)
pikoc explain E0336            # the long-form help for any error code

I/O is async only

There's no readFileSync, and there won't be. Use await: top-level await works in the entry module, and promises are the JavaScript ones.

TypeScript (Node)
import { readFileSync } from "node:fs"

const text = readFileSync("notes.txt", "utf8")
console.log(text.split("\n").length)
Pikoc
import { readText, writeText } from "std/fs"

await writeText("notes.txt", "# one\ntext\n# two\n")   // top-level await
const text = await readText("notes.txt")
println(text.split("\n").filter(l => l.startsWith("#")).length)

function delay(ms: int): Promise<string> {
  new Promise((resolve) => setTimeout(() => resolve(`waited ${ms} ms`), ms))
}
const [a, b] = await Promise.all([delay(10), delay(20)])
println(`${a}, ${b}`)

An iterator's next() returns T?, with null meaning done, rather than { value, done }.

Syntax differences

  • Semicolons are optional, but there's no JavaScript-style automatic semicolon insertion. A line starting with (, [, - or a template literal starts a new statement, so end the previous line with an operator to continue it. A leading ., && or ?? continues it.
  • Everything is an expression: if, match and blocks produce values, and a block body returns its last expression. A trailing ; makes it void.
  • Arrays have no holes, and they don't grow by assigning past the end: use push.
const total = [1, 2, 3]
  .map(x => x * 2)               // a leading `.` continues the expression
  .reduce((a, b) => a + b, 0)

const ok = total > 10 &&
  total < 20                     // so does a trailing operator

const sign = if (total > 0) "positive" else "not positive"   // if is an expression
const twice = (x: int) => { x * 2 }   // a block returns its last expression
println(`${total} ${ok} ${sign} ${twice(21)}`)

Native code and the browser

Pikoc compiles to native executables, so it can call C directly. For the browser it compiles to WebAssembly and talks to JavaScript.

  • Declare C functions in an extern "C" block (or import a header with import * as m from "c:math.h"). Calls that take and return only primitives are safe; anything returning a pointer needs unsafe.
  • In browser builds, 64-bit integers cross to JavaScript as numbers, structs and enums as copies, and classes as handles that keep their object alive until free().
  • A Pikoc array reaches JavaScript as a live Proxy; a JavaScript array passed in is copied, then written back when the call returns.
extern "C" {
  function abs(x: c_int): c_int
  function getpid(): c_int
}

println(abs(-42))                    // 42: plain C calls need no wrapper
println(getpid() > 0)

Get started

Download pikoc from the home page (one archive: the compiler, clang, lld, the runtime and the standard library), then save any example above as a .pi file.

pikoc run shapes.pi            # compile and run
pikoc run --interp shapes.pi   # skip the native build
pikoc init                     # a project: project.json and src/main.pi
pikoc test                     # every *.test.pi
pikoc explain E0308            # long-form error help