Last updated: 2026-11-21

U
Undergraduate level

PatLang Showcase: Watching, Secrets and Specifications

For new readers

Three small programs, each pairing two of PatLang's paradigms: a long job that another program can find and question while it works, a key exchange whose timing the compiler checks, and a currency converter whose specification runs as its tests. Each sits beside the same program in Python. The other showcase pages are the first four pairs and bounds, streams, worlds and parallel sums.specs as tests is BDD

The code shown is the file in the PatLang repository's showcase/ directory, and the output is what PatLang's test gates check it against, on the interpreter and as native builds for Windows and Linux. Each Python version runs in the same gates and must print the same lines.

A long job you can ask about while it works

Signals and concurrency. A job counts primes a slice at a time, each slice at most 20 ms of work, and between slices it answers any signals that have arrived. It announces itself under the name prime_counter with the requests it accepts, so a monitor that knows only that name can find its port, ask for its status twice, see that the second answer shows more work than the first, and tell it to stop. The monitor here is a thread of the same program; another program on the same machine could do the same with no change to the job. Its output depends only on whether the job made progress, so it prints the same however fast the machine is.the 20 ms slice is a time budget

# A long job you can ask about while it works.
#
# Paradigms: signals and concurrency (budgeted slices, a monitoring thread).
#
# The job counts primes, a slice at a time: each slice runs for at most 20 ms
# of work (budgeted), and between slices the job answers any signals that
# have arrived. It announces itself by name, so a monitor that knows only the
# name "prime_counter" can find its port, ask for its status as it goes, and
# tell it to stop. Here the monitor is a thread of the same program; it could
# as well be another program on the same machine, with no change to the job.
#
# Output does not depend on timing: the monitor checks that the answers it
# got show progress, not what the counts were.

include "../self_hosting/lib/signals.patlang"
include "../self_hosting/lib/signal_discovery.patlang"

class Job {
  field next_k = 2
  field primes = 0
  field running = true
}

make a function called is_prime takes k returns yes
  if k < 2 then
    return false
  end
  let d = 2
  while d * d <= k do
    if k % d == 0 then
      return false
    end
    let d = d + 1
  end
  return true
end

make a function called starts_with takes text, prefix returns yes
  return substr(text, 0, prefix.length) == prefix
end

# N from a reply "checked N, found M".
make a function called checked_of takes reply returns n
  let start = "checked ".length
  let i = start
  while (i < reply.length) and (reply[i] != ",") do
    let i = i + 1
  end
  return to_num(substr(reply, start, i - start))
end

let job = new("Job")

when status do
  signal_reply("checked " + (job.next_k - 2) + ", found " + job.primes)
end

when quit do
  job.running = false
  signal_reply("stopping at " + job.primes + " primes")
end

let port = signal_claim(0)
signal_allow(["status", "quit"])
signal_announce("prime_counter", port, [["status", "how many numbers it has checked, and how many primes it found"], ["quit", "stop after the current slice"]])

# The monitor knows only the job's name.
let monitor = thread_spawn(|| do
  let found = signal_discover_one("prime_counter", 60000)
  let p = to_num(found[0])
  sleep_ms(200)
  let first = signal_query(p, "status", "")
  sleep_ms(200)
  let second = signal_query(p, "status", "")
  let last = signal_query(p, "quit", "")
  return [found[1], first, second, last]
end)

# The work, 20 ms at a time: when a slice's budget runs out, budgeted gives
# back a handle, the loop answers whatever signals have come in, and the same
# computation goes on from where it stopped.
let handle = false
while job.running do
  let out = budgeted(20, handle) {
    while job.running do
      if is_prime(job.next_k) then
        job.primes = job.primes + 1
      end
      job.next_k = job.next_k + 1
    end
    true
  }
  if out[0] != "done" then
    let handle = out[1]
  end
  signal_poll(port, 5)
end

let heard = thread_result(monitor)
print("the monitor found the job by name, offering: " + str_join(sd_action_names(heard[0]), ", "))
print("first status has the form 'checked N, found M': " + starts_with(heard[1], "checked "))
print("the second shows more work than the first: " + (checked_of(heard[2]) > checked_of(heard[1])))
print("quit was answered: " + starts_with(heard[3], "stopping at "))
print("the job counted some primes before it stopped: " + (job.primes > 0))

Output:

the monitor found the job by name, offering: status, quit
first status has the form 'checked N, found M': true
the second shows more work than the first: true
quit was answered: true
the job counted some primes before it stopped: true

A monitor that would only ever be a thread of the same Python program could read the job's variables directly. To be watchable from another program as the PatLang job is, the Python version builds the pieces: a TCP server on a port the system picks, a registry file naming the job and its port, and a queue between the server's thread and the job, which answers between its 20 ms slices. That is socketserver, threading, queue and json, all in the standard library, standing in for PatLang's signal_claim, signal_announce, budgeted and when handlers.

The Python version
"""The watched job of showcase/p9_watching_a_job.patlang, in Python.

If the monitor were only ever a thread of the same program, Python would let
it read the job's variables, and no sockets would be needed. The PatLang job
can be watched by another program with no change, so the sketch gives Python
the same: a TCP server on a port the system picks, a registry file naming the
job and its port, and a queue between the server's thread and the job, which
answers between slices of 20 ms. PatLang has these as signal_claim,
signal_announce, budgeted and when handlers; here they are built from
socketserver, threading, queue and json.

Prints the same lines as the PatLang program.
"""
import json
import os
import queue
import socket
import socketserver
import tempfile
import threading
import time

REGISTRY = os.path.join(tempfile.gettempdir(), "showcase_p9_registry.json")
requests = queue.Queue()


class Handler(socketserver.StreamRequestHandler):
    """One request a line; the job answers it between slices."""

    def handle(self):
        name = self.rfile.readline().decode().strip()
        reply = queue.Queue(1)
        requests.put((name, reply))
        self.wfile.write((reply.get() + "\n").encode())


def announce(name, port, actions):
    with open(REGISTRY, "w") as f:
        json.dump({name: {"port": port, "actions": actions}}, f)


def discover(name):
    with open(REGISTRY) as f:
        entry = json.load(f)[name]
    return entry["port"], entry["actions"]


def query(port, name):
    with socket.create_connection(("127.0.0.1", port)) as s:
        s.sendall((name + "\n").encode())
        return s.makefile().readline().strip()


def is_prime(k):
    if k < 2:
        return False
    d = 2
    while d * d <= k:
        if k % d == 0:
            return False
        d += 1
    return True


class Job:
    next_k, primes, running = 2, 0, True


job = Job()
server = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
announce("prime_counter", server.server_address[1], [["status", "how many numbers it has checked, and how many primes it found"], ["quit", "stop after the current slice"]])

heard = []


def monitor():
    port, actions = discover("prime_counter")
    time.sleep(0.2)
    first = query(port, "status")
    time.sleep(0.2)
    second = query(port, "status")
    last = query(port, "quit")
    heard.extend([actions, first, second, last])


watcher = threading.Thread(target=monitor)
watcher.start()

while job.running:
    # one slice of 20 ms of work, then the requests that came in meanwhile
    end = time.monotonic() + 0.02
    while job.running and time.monotonic() < end:
        if is_prime(job.next_k):
            job.primes += 1
        job.next_k += 1
    while not requests.empty():
        name, reply = requests.get()
        if name == "status":
            reply.put(f"checked {job.next_k - 2}, found {job.primes}")
        elif name == "quit":
            job.running = False
            reply.put(f"stopping at {job.primes} primes")

watcher.join()
server.shutdown()
os.remove(REGISTRY)


def b(x):
    return "true" if x else "false"


def checked_of(reply):
    return int(reply[len("checked "):].split(",")[0])


print("the monitor found the job by name, offering: " + ", ".join(a[0] for a in heard[0]))
print("first status has the form 'checked N, found M': " + b(heard[1].startswith("checked ")))
print("the second shows more work than the first: " + b(checked_of(heard[2]) > checked_of(heard[1])))
print("quit was answered: " + b(heard[3].startswith("stopping at ")))
print("the job counted some primes before it stopped: " + b(job.primes > 0))

A key exchange, checked for timing leaks by the compiler

Modular arithmetic and constant-time checking. X25519 lets two parties agree on a shared secret over an open channel. Each keeps a private key, sends a public one, and combines the other's public key with its own private key. The arithmetic is on numbers modulo 2255 โˆ’ 19, which PatLang has as a value type, and the curve code is PatLang written on those values. The program runs the exchange with the test keys from section 6.1 of RFC 7748 and checks the shared secret against the one the RFC gives.

# A key exchange, checked for timing leaks by the compiler.
#
# Paradigms: modular arithmetic and constant-time checking.
#
# X25519 lets two parties agree on a shared secret over an open channel: each
# keeps a private key, sends a public key, and combines the other's public key
# with their own private one. The arithmetic is on numbers modulo 2^255 - 19,
# which PatLang has as a value type (a modint), and the curve code is written
# in PatLang on those values (packages/curve25519/curve25519.patlang).
#
# Code that handles secrets must not take more or less time depending on
# them, or the time it takes gives them away. In most languages that is a
# matter of care and review. Here the compiler checks it:
#
#   v2.exe showcase/p10_ct_exchange.patlang --constant-time
#
# follows every function the exchange reaches, the runtime's own included,
# and reports each branch, memory index or variable-time operation that
# depends on a secret. For the exchange it reports nothing. For
# showcase/p10_ct_leaky.patlang, a PIN check written the obvious way, it
# reports the leak.
#
# This program runs the exchange with the keys of RFC 7748, section 6.1, and
# prints the result, so the values can be checked against the RFC. Printing a
# secret reveals it on purpose, so the timing check is run on
# p10_ct_exchange.patlang, the same exchange with nothing printed.

include "../packages/curve25519/curve25519.patlang"

let nine = cv_hex_bytes("0900000000000000000000000000000000000000000000000000000000000000")
let alice_private = cv_hex_bytes("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a")
let bob_private = cv_hex_bytes("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb")

print("== public keys, sent in the open ==")
let alice_public = x25519(alice_private, nine)
let bob_public = x25519(bob_private, nine)
print("alice: " + cv_hex(alice_public))
print("bob:   " + cv_hex(bob_public))

print("== each combines the other's public key with their own private one ==")
let alice_shared = x25519(alice_private, bob_public)
let bob_shared = x25519(bob_private, alice_public)
print("alice's secret: " + cv_hex(alice_shared))
print("bob's secret:   " + cv_hex(bob_shared))
print("they agree: " + (cv_hex(alice_shared) == cv_hex(bob_shared)))
print("as RFC 7748 gives it: " + (cv_hex(alice_shared) == "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"))

Output:

== public keys, sent in the open ==
alice: 8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a
bob:   de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f
== each combines the other's public key with their own private one ==
alice's secret: 4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742
bob's secret:   4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742
they agree: true
as RFC 7748 gives it: true

Code that handles secrets must take the same time whatever the secrets are, or the time it takes gives them away. PatLang's compiler checks this itself: built with --constant-time, it follows every function the code reaches, the runtime's own included, and reports any branch, memory index or variable-time operation that depends on a secret. Printing the shared secret reveals it on purpose, so the check runs on a copy of the exchange that prints nothing, and finds nothing to report.timing attacks work on cache misses too

# The exchange of p10_key_exchange.patlang with nothing secret printed: what
# the constant-time check is run on.
#
#   v2.exe showcase/p10_ct_exchange.patlang --constant-time
#
# reports no value-dependent branch or access.

include "../packages/curve25519/curve25519.patlang"

let nine = cv_hex_bytes("0900000000000000000000000000000000000000000000000000000000000000")
let alice_private = cv_hex_bytes("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a")
let bob_private = cv_hex_bytes("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb")
let alice_public = x25519(alice_private, nine)
let bob_public = x25519(bob_private, nine)
let alice_shared = x25519(alice_private, bob_public)
let bob_shared = x25519(bob_private, alice_public)
print("done")

The compiler's report:

v2: no value-dependent branch or access

A PIN check written the obvious way stops at the first digit that differs, so a guess with its first digit right takes slightly longer than one without, and timing many guesses recovers the PIN a digit at a time. The same check refuses it and names the function.

# A PIN check written the obvious way, and why it leaks.
#
# The loop stops at the first digit that differs, so a guess with the first
# digit right takes a little longer than one with it wrong. Timing many
# guesses finds the PIN a digit at a time. The digits are held as modints, so
# the compiler treats them as secret, and
#
#   v2.exe showcase/p10_ct_leaky.patlang --constant-time
#
# reports the branch that decides on them, naming pin_matches.

make a function called pin_matches takes pin, guess returns same
  let i = 0
  while i < list_len(pin) do
    if mod_make(pin[i], 10) != mod_make(guess[i], 10) then
      return false
    end
    let i = i + 1
  end
  return true
end

print(pin_matches([4, 7, 1, 9], [4, 7, 2, 0]))

The compiler's report:

v2 constant-time: pin_matches: a branch decides on a secret
v2 error: 1 places where the time can depend on a modint's residue

Python's arbitrary-size integers make the algorithm short to write, and the sketch follows the Montgomery ladder of RFC 7748, section 5, line for line. How long it takes is another matter. Python's integer operations take time that depends on the values, the ladder's conditional swap is arithmetic only because the programmer wrote it carefully, and nothing in the standard distribution checks either. Python code that needs the guarantee calls a library written for the purpose in C or assembly; the cryptography package provides X25519 through OpenSSL.

The Python version
"""The X25519 exchange of showcase/p10_key_exchange.patlang, in Python.

Python's arbitrary-size integers make RFC 7748's algorithm short to write:
the Montgomery ladder below follows section 5 line for line. What Python
cannot say is how long it takes. Its integers take time that depends on their
values (a multiplication of small numbers is quicker than one of large ones),
the ladder's conditional swap is written with arithmetic only as a matter of
care, and no tool in the standard distribution checks any of it. Code that
needs that guarantee calls a library written in C or assembly for the purpose
(the cryptography package wraps OpenSSL's X25519). PatLang's compiler checks
the PatLang code itself with --constant-time.

Prints the same lines as the PatLang program.
"""
P = 2**255 - 19
A24 = 121665


def decode_scalar(k):
    b = bytearray(k)
    b[0] &= 248
    b[31] &= 127
    b[31] |= 64
    return int.from_bytes(b, "little")


def decode_u(u):
    b = bytearray(u)
    b[31] &= 127
    return int.from_bytes(b, "little")


def cswap(swap, x2, x3):
    """Swaps when swap is 1, by arithmetic, as RFC 7748 writes it."""
    mask = -swap
    dummy = mask & (x2 ^ x3)
    return x2 ^ dummy, x3 ^ dummy


def x25519(k, u):
    k, x1 = decode_scalar(k), decode_u(u)
    x2, z2, x3, z3, swap = 1, 0, x1, 1, 0
    for t in reversed(range(255)):
        k_t = (k >> t) & 1
        swap ^= k_t
        x2, x3 = cswap(swap, x2, x3)
        z2, z3 = cswap(swap, z2, z3)
        swap = k_t
        a, b = (x2 + z2) % P, (x2 - z2) % P
        aa, bb = a * a % P, b * b % P
        e = (aa - bb) % P
        c, d = (x3 + z3) % P, (x3 - z3) % P
        da, cb = d * a % P, c * b % P
        x3, z3 = (da + cb) ** 2 % P, x1 * (da - cb) ** 2 % P
        x2, z2 = aa * bb % P, e * (aa + A24 * e) % P
    x2, x3 = cswap(swap, x2, x3)
    z2, z3 = cswap(swap, z2, z3)
    return (x2 * pow(z2, P - 2, P) % P).to_bytes(32, "little")


nine = bytes.fromhex("09" + "00" * 31)
alice_private = bytes.fromhex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a")
bob_private = bytes.fromhex("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb")

print("== public keys, sent in the open ==")
alice_public = x25519(alice_private, nine)
bob_public = x25519(bob_private, nine)
print("alice: " + alice_public.hex())
print("bob:   " + bob_public.hex())

print("== each combines the other's public key with their own private one ==")
alice_shared = x25519(alice_private, bob_public)
bob_shared = x25519(bob_private, alice_public)
print("alice's secret: " + alice_shared.hex())
print("bob's secret:   " + bob_shared.hex())
print("they agree: " + ("true" if alice_shared == bob_shared else "false"))
print("as RFC 7748 gives it: " + ("true" if alice_shared.hex() == "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742" else "false"))

A spec in its own words

Syntax definitions and executable specifications. A currency converter's rates are written as GBP => EUR 117 per 100, a notation defined by a syntax definition at the top of the file. Before the program runs, each line becomes a call that records the rate as a fact. Conversion is exact, so 100 pounds is 3159/25 dollars by way of euros, where 100 * 1.17 * 1.08 in floats is 126.36000000000001. Its behaviour is specified as a Gherkin feature in the same file, and the program runs that feature against the converter every time, matching each step's words to a function and taking the numbers in it as arguments.

# A currency converter, its rates in a notation of their own, and its
# specification run as tests, all in one file.
#
# Paradigms: syntax definitions and executable specifications.
#
# The exchange rates are written in a small notation, "GBP => EUR 117 per
# 100", defined by a syntax definition at the top of the file: before the
# program runs, each line becomes a call that records the rate as a fact.
# Conversion is exact, so 100 pounds is 3159/25 dollars by way of euros,
# where 100 * 1.17 * 1.08 in floats is 126.36000000000001.
#
# The behaviour is specified in Gherkin, as a feature with scenarios, and the
# same program runs that feature against the converter: each step's words are
# matched to a function, with the numbers in it taken as arguments. The
# notation, the code and the specification are kept together, and the
# specification is checked every time the program runs.

include "../self_hosting/lib/gherkin.patlang"

syntax RateTable {
    trigger: Keyword("rates");
    tokens {
        Currency(code) = regex("[A-Z][A-Z][A-Z]", code);
        Amount(n) = regex("[0-9]+", n);
        Arrow = "=>";
        Per = "per";
    }
    rule RateLine {
        let from = expect Currency;
        expect Arrow;
        let to = expect Currency;
        let num = expect Amount;
        expect Per;
        let den = expect Amount;
        return rule_add("rate", [from, to, to_num(num) / to_num(den)], []);
    }
}

rates {
    GBP => EUR 117 per 100
    EUR => USD 108 per 100
    USD => JPY 15000 per 100
}

# amount in from, in to: directly, or through one currency between. The rate
# facts go one way; the other way is the reciprocal.
make a function called rate_between takes from, to returns r
  if from == to then
    return 1
  end
  let direct = solve("rate", [from, to, logic_var("R")])
  if list_len(direct) > 0 then
    return direct[0][2]
  end
  let back = solve("rate", [to, from, logic_var("R")])
  if list_len(back) > 0 then
    return 1 / back[0][2]
  end
  let via = solve("rate", [from, logic_var("Mid"), logic_var("R")])
  let i = 0
  while i < list_len(via) do
    let onward = rate_between_direct(via[i][1], to)
    if onward != 0 then
      return via[i][2] * onward
    end
    let i = i + 1
  end
  return 0
end

make a function called rate_between_direct takes from, to returns r
  let direct = solve("rate", [from, to, logic_var("R")])
  if list_len(direct) > 0 then
    return direct[0][2]
  end
  return 0
end

make a function called convert takes amount, from, to returns out
  let r = rate_between(from, to)
  # no rate between the two
  assert r != 0
  return amount * r
end

# ---- the steps: each sentence, and the function it runs ----

make a function called st_amount takes ctx returns ok
  ctx_set(ctx, "amount", to_num(step_arg(ctx, "n")))
  ctx_set(ctx, "from", step_arg(ctx, "cur"))
  return true
end

make a function called st_convert takes ctx returns ok
  ctx_set(ctx, "to", step_arg(ctx, "cur"))
  ctx_set(ctx, "result", convert(ctx_get(ctx, "amount"), ctx_get(ctx, "from"), step_arg(ctx, "cur")))
  return true
end

make a function called st_result takes ctx returns ok
  return expect(ctx, "the converted amount", "" + ctx_get(ctx, "result"), step_arg(ctx, "want"))
end

make a function called st_back takes ctx returns ok
  # from the currency it was converted to, back to the one the step names
  let back = convert(ctx_get(ctx, "result"), ctx_get(ctx, "to"), step_arg(ctx, "cur"))
  expect(ctx, "back in the currency it started in", step_arg(ctx, "cur"), ctx_get(ctx, "from"))
  return expect(ctx, "converted back", back, ctx_get(ctx, "amount"))
end

let spec = str_join([
  "Feature: converting between currencies",
  "",
  "  Scenario: a direct rate",
  "    Given an amount of 3 GBP",
  "    When it is converted to EUR",
  "    Then the result is 351/100",
  "",
  "  Scenario: a rate the other way is the reciprocal",
  "    Given an amount of 117 EUR",
  "    When it is converted to GBP",
  "    Then the result is 100",
  "",
  "  Scenario: two hops",
  "    Given an amount of 100 GBP",
  "    When it is converted to USD",
  "    Then the result is 3159/25",
  "",
  "  Scenario: there and back loses nothing",
  "    Given an amount of 7 EUR",
  "    When it is converted to USD",
  "    Then converting back to EUR gives the amount again"
], chr(10))

let ctx = ctx_new()
step(ctx, "an amount of {n} {cur}", "st_amount")
step(ctx, "it is converted to {cur}", "st_convert")
step(ctx, "the result is {want}", "st_result")
step(ctx, "converting back to {cur} gives the amount again", "st_back")
run_feature(ctx, spec)
ctx_report(ctx)

Output:

Feature: converting between currencies
Scenario: a direct rate
  ok: the converted amount
Scenario: a rate the other way is the reciprocal
  ok: the converted amount
Scenario: two hops
  ok: the converted amount
Scenario: there and back loses nothing
  ok: back in the currency it started in
  ok: converted back
tests: 5 passed, 0 failed
ALL TESTS PASSED

The Python version reads the rate notation at run time with a regular expression and runs the feature on a step matcher written with re. A Python project would more likely use behave or pytest-bdd, installed beside Python, which keep each feature in a .feature file of its own. PatLang's Gherkin runner is part of its standard library, so the feature can sit inside the program it specifies. fractions.Fraction supplies the exact amounts.PatLang's runner is built-in, unlike Python's

The Python version
"""The currency converter of showcase/p11_spec_in_its_own_words.patlang, in Python.

The rate notation is parsed at run time with a regular expression, where the
PatLang program defines it as syntax, expanded before the program runs into
calls that record facts. The Gherkin feature runs on a step matcher written
here with re. A Python project would use behave or
pytest-bdd, packages installed beside Python, which keep the feature in a
.feature file of its own; PatLang's Gherkin runner is in its standard
library, and the feature can sit in the program it specifies. Exact amounts
come from fractions.Fraction.

Prints the same lines as the PatLang program.
"""
import re
from fractions import Fraction

RATES_TEXT = """
    GBP => EUR 117 per 100
    EUR => USD 108 per 100
    USD => JPY 15000 per 100
"""
RATES = {}
for line in RATES_TEXT.strip().splitlines():
    m = re.fullmatch(r"\s*([A-Z]{3}) => ([A-Z]{3}) (\d+) per (\d+)\s*", line)
    RATES[(m[1], m[2])] = Fraction(int(m[3]), int(m[4]))


def rate_between(a, b):
    if a == b:
        return Fraction(1)
    if (a, b) in RATES:
        return RATES[(a, b)]
    if (b, a) in RATES:
        return 1 / RATES[(b, a)]
    for (x, mid), r in RATES.items():
        if x == a and (mid, b) in RATES:
            return r * RATES[(mid, b)]
    return Fraction(0)


def convert(amount, a, b):
    r = rate_between(a, b)
    assert r != 0
    return amount * r


def show(x):
    return str(x.numerator) if x.denominator == 1 else str(x)


SPEC = """Feature: converting between currencies

  Scenario: a direct rate
    Given an amount of 3 GBP
    When it is converted to EUR
    Then the result is 351/100

  Scenario: a rate the other way is the reciprocal
    Given an amount of 117 EUR
    When it is converted to GBP
    Then the result is 100

  Scenario: two hops
    Given an amount of 100 GBP
    When it is converted to USD
    Then the result is 3159/25

  Scenario: there and back loses nothing
    Given an amount of 7 EUR
    When it is converted to USD
    Then converting back to EUR gives the amount again"""

passed = failed = 0


def expect(label, got, want):
    global passed, failed
    if got == want:
        passed += 1
        print(f"  ok: {label}")
    else:
        failed += 1
        print(f"  FAIL: {label} (got {got}, want {want})")


def st_amount(ctx, n, cur):
    ctx["amount"], ctx["from"] = Fraction(int(n)), cur


def st_convert(ctx, cur):
    ctx["to"] = cur
    ctx["result"] = convert(ctx["amount"], ctx["from"], cur)


def st_result(ctx, want):
    expect("the converted amount", show(ctx["result"]), want)


def st_back(ctx, cur):
    back = convert(ctx["result"], ctx["to"], cur)
    expect("back in the currency it started in", cur, ctx["from"])
    expect("converted back", back, ctx["amount"])


STEPS = [
    (r"an amount of (\S+) (\S+)", st_amount),
    (r"it is converted to (\S+)", st_convert),
    (r"the result is (\S+)", st_result),
    (r"converting back to (\S+) gives the amount again", st_back),
]

ctx = {}
for line in SPEC.splitlines():
    line = line.strip()
    if line.startswith(("Feature:", "Scenario:")):
        if line.startswith("Scenario:"):
            ctx = {}
        print(line)
        continue
    words = line.split(" ", 1)
    if len(words) == 2 and words[0] in ("Given", "When", "Then", "And"):
        for pattern, f in STEPS:
            m = re.fullmatch(pattern, words[1])
            if m:
                f(ctx, *m.groups())
                break
print(f"tests: {passed} passed, {failed} failed")
print("ALL TESTS PASSED" if failed == 0 else "TESTS FAILED")

Graduate Attributes

Directly developed

  • Critical Thinker: Readers compare the security guarantees of PatLang against the timing vulnerabilities inherent in standard Python implementations.
  • Digitally Fluent: Readers examine how different programming languages handle concurrency, cryptography and specification testing through concrete code examples.

Modelled on this page

  • Subject Specialist: Technical concepts are explained through precise references to compiler flags, standard library modules and cryptographic protocols.
  • Researcher: Claims about security and performance are supported by references to RFC standards and observable test outputs.
  • Reflective: The limitations of each approach are stated clearly alongside the trade-offs made in the implementation.

University of Reading Graduate Attributes framework.