Skip to the content.

Writing Argon

Argon is a dynamically typed scripting language. Chloride (argon) is its interpreter and Isotope (isotope) is its package manager. It looks like Python/JavaScript, but many details differ. Don’t assume Python or JS semantics. Check the rules below, and always run the code.

Describes Chloride v4.1.0 (check with argon --version; see “If you’re on v4.0.3 or older” below) and Isotope 1.0.0. Full docs: the README.md tree in the Argon docs repository. For the stdlib and Isotope, read reference/stdlib.md and reference/isotope.md.

Workflow

  1. Write the code to a .ar file.
  2. Run it with argon file.ar (the .ar is optional). Uncaught errors print ERROR! <Type>: <message> with the file:line:column to stderr and exit with status 1.
  3. Fix and rerun. For quick experiments, pipe code in: echo 'term.log(1 + 1)' | argon.
  4. Never name a file after a stdlib module you import (json.ar, build.ar, path.ar…). Local files shadow the stdlib, and a file importing its own name throws ImportError.

Core syntax

# comments start with #
let name = "world"                       # declare with let; redeclaring in the same scope is an error
let a = 1, b = 2                         # several declarations
term.log(`Hello, $(name)!`)             # print; template strings interpolate $( expr )

let add(a, b) = a + b                    # single-expression function
let greet(who, greeting = "Hi") = do     # block body: `do` at END of line, body indented
    let message = `$(greeting), $(who)`
    return message                       # no return => null

let square = (x) = x * x                 # anonymous function
term.log(add(1, 2), greet("Ada"), greet("Ada", greeting = "Yo"), square(4))

if (a > b) do                            # condition always in parentheses
    term.log("a is bigger")
else if (a == b) term.log("equal")       # single-statement bodies need no `do`
else term.log("b is bigger")

for (i in 0 until 3) term.log(i)         # 0 1 2 (until = exclusive)
for (i in 1 to 3) term.log(i)            # 1 2 3 (to = inclusive)
for ([key, value] in {x: 1, y: 2}) term.log(key, value)

let n = 0
while (n < 3) n += 1

Blocks and indentation

let run(f) = f()
let result = run(() = do
    let total = 0
    for (i in 1 to 4) total += i
    return total
)
term.log(result)   # 10

Python/JS habits that are WRONG in Argon

Don’t write Write instead Why
2 ** 3 2 ^ 3 ^ is exponent
x ** y ** z x ^ y ^ z ^ is right-associative and binds tighter than unary minus (-2 ^ 2 == -4)
if (items) to test non-empty if (items.length) [] and {} are truthy; only false, null, 0, "" are falsy
"n=" + 5 `n=$(5)` or "n=" + string(5) + doesn’t convert types
s.strip() s.strip(" \t\n\r") strip requires the set of chars
arr.sort() arr.sort((a, b) = a - b) comparator is required; it sorts in place and returns the array
", ".join(arr) arr.join(", ") array method; strings only
len(x) x.length property; dictionaries have none, so use array(d).length
type(x) == "number" type(x) == number or type(x).__name__ == "number" type() returns a class
isinstance is_instance(x, number)  
d["missing"] expecting null d.value_get("missing", default) or "k" in d missing keys throw AttributeError
[1] == [1] expecting true compare element-wise == on arrays and dictionaries is identity
*args used as an array array(args) *args is a tuple (immutable)
def f(x=[]) style defaults let f(x = null) + create inside defaults are evaluated once, at definition
tuple([1, 2]) to convert tuple.of([1, 2]) tuple(a, b) takes the items as arguments
print(...) / console.log term.log(a, b, sep=", ", end="\n")  
term.error("text") term.error(exception_object) to write raw text to stderr use file.stderr (binary, takes a buffer)
try ... finally catch, clean up, rethrow no finally
catch (e) catch (Exception as e), catch (Exception) or bare catch bare catch doesn’t catch StopIteration/KeyboardInterrupt
while True: forever do or while (true) do  
float rounding like 0.1 + 0.2 != 0.3   numbers are exact rationals: 0.1 + 0.2 == 0.3

More facts that differ:

Values and built-ins

Destructuring

let [first, *rest] = [1, 2, 3]
let [x, [y, z]] = [1, [2, 3]]
let {name, version: v} = {name: "argon", version: 4}
term.log(first, rest, x, y, z, name, v)    # 1 [2, 3] 1 2 3 argon 4
for ({name} in [{name: "a"}, {name: "b"}]) term.log(name)

Functions

let f(x, label?, scale = 1, *args, **kwargs) = do   # label? defaults to null
    return [x * scale, label, args, kwargs]

term.log(f(2))                         # [2, null, tuple(), {}]
term.log(f(2, "l", 3, 4, 5, k = 6))    # [6, "l", tuple(4, 5), {"k": 6}]
term.log(f(*[1, "a"], **{scale: 10}))  # spread at call site

Order: required, then defaults/optional, then *args, then **kwargs.

Classes

class Shape do
    this.count = 0                                  # class attribute
    let secret = "private"                          # private to the class body
    this.__init__(self, name) = do
        self.name = name                            # instance attribute
        Shape.count += 1
    this.area(self) = 0
    this.__string__(self) = `$(self.name) with area $(self.area())`
    this.describe() = `$(this.count) shapes`        # no self => static, call on the class

class Square(Shape) do                              # inheritance
    this.__init__(self, side) = do
        Shape.__init__(self, "square")              # call the parent explicitly
        self.side = side
    this.area(self) = self.side ^ 2
    this.get_perimeter(self) = self.side * 4        # property: sq.perimeter

let sq = Square(3)
term.log(sq, sq.perimeter, Shape.describe(), is_instance(sq, Shape))

Errors

class AppError(Exception) null

let risky(n) = do
    if (n < 0) throw AppError(`negative: $(n)`)
    return n

try do
    risky(-1)
catch (AppError as e) do
    term.log(type(e).__name__, e.message)    # AppError negative: -1

Built-ins: Exception > RuntimeError, ValueError, TypeError, IndexError, NameError > AttributeError, MathsError > ZeroDivisionError, FileError > PathError, ImportError, .... Module exceptions live on the module (file.FileNotFoundError, regex.RegexError, network.SocketError). e.stack_trace is an array of tuple(file, line, col, len).

Modules

import "json" as json                     # module as a dictionary
import "file" expose open, is_file        # pull names into scope
import "./helpers" expose helper as h     # rename; .ar and /init.ar are implied
if (program.main) main()                  # only when run directly

Resolution order: relative to the importing file, then argon_modules/ in that directory and each parent directory, then the installation’s stdlib and global argon_modules. Every top-level let is exported. Modules run once and are cached. Compiled bytecode goes in __arcache__/ (gitignore it).

Known issues

If you’re on v4.0.3 or older

If argon --version reports a version before v4.1.0, these differ: