roc-syntax-color
A Roc package that colors source code for web pages. Code goes in and HTML comes out, with a span around each comment, string, number, keyword, name and type. It colors seven languages: Roc, JavaScript, Shale, Zig, C, Odin and Python. Below is real code in each, colored by the package.
Each listing is an excerpt, copied verbatim from the file it links. The package wrote every span.
Roc on Shale shows the package at work on whole files: Shale recipes ported to Roc, each one's Roc beside its Shale original.
Roc
From examples/move_box/main.roc
in Luke Boswell's roc-ray, lines 16–95.
© 2024 Luke Boswell and subsequent authors, under the Universal Permissive License 1.0.
The lexer: RocSyntax.roc.
## Everything the app remembers between host cycles: where the box's top-left
## corner is, in logical units from the top-left of the window.
Model : { box : Math.Vec2 }
## The box is a square this many logical units wide.
box_size = 60.F32
## How far the box moves in one second while a key is held, in logical units.
speed = 300.F32
program = { init!, update!, render! }
init! : App.Init(Model, [])
init! = App.init(
App.default.with_title("RocRay Move Box").with_size({ width: 800, height: 600 }),
|_io| Ok({ box: { x: 370, y: 270 } }),
)
## Turn two opposite keys into one number: -1, 0, or 1. Holding both cancels.
axis : Bool, Bool -> F32
axis = |negative, positive|
if (negative and !positive) -1 else if (positive and !negative) 1 else 0
## Which way the arrow keys point. Up is negative because screen y grows
## downwards.
direction : Devices.Snapshot -> Math.Vec2
direction = |devices| {
x: axis(devices.key_down(KeyLeft), devices.key_down(KeyRight)),
y: axis(devices.key_down(KeyUp), devices.key_down(KeyDown)),
}
## The time step to move by. A stall, such as dragging the window, can report a
## whole second or more; moving by all of it at once would make the box jump.
## Clamping keeps every step small.
clamp_dt : F32 -> F32
clamp_dt = |seconds| Math.clamp(seconds, 0, 0.25)
## The rule of the game: move by direction x speed x time, then keep the whole
## box inside the window.
step_box : Math.Vec2, Math.Vec2, F32, { width : F32, height : F32 } -> Math.Vec2
step_box = |box, dir, dt, window| {
x: Math.clamp(box.x + dir.x * speed * dt, 0, window.width - box_size),
y: Math.clamp(box.y + dir.y * speed * dt, 0, window.height - box_size),
}
Msg : []
update! : Model, App.Input(Msg), App.Io => Try(Model, [Exit(I64)])
update! = |model, input, _io| {
devices = input.devices
dt = clamp_dt(input.time.elapsed_seconds)
window = { width: I32.to_f32(input.window.size.width), height: I32.to_f32(input.window.size.height) }
Ok({ ..model, box: step_box(model.box, direction(devices), dt, window) })
}
render! : Model, Draw.Frame => Try({}, [Exit(I64)])
render! = |model, frame| {
frame.clear!(Color.from_hex_rgb(0x101828))
frame.rectangle!({ x: model.box.x, y: model.box.y, width: box_size, height: box_size, style: Draw.filled(Color.from_hex_rgb(0x2f80ed)) })
frame.text_at!({ pos: { x: 20, y: 20 }, text: "Arrow keys move the box - Escape quits", size: 20, color: Color.from_hex_rgb(0xa8b4cc) })
Ok({})
}
window_800x600 = { width: 800, height: 600 }
## Half a second of holding Right moves the box half of `speed` to the right.
expect step_box({ x: 100, y: 100 }, { x: 1, y: 0 }, 0.5, window_800x600) == { x: 250, y: 100 }
## The box stops at the right edge instead of leaving the window.
expect step_box({ x: 730, y: 100 }, { x: 1, y: 0 }, 0.5, window_800x600).x == 800 - box_size
## ...and at the top edge.
expect step_box({ x: 100, y: 10 }, { x: 0, y: -1 }, 0.5, window_800x600).y == 0
## Holding Left and Right together cancels out.
expect direction(Devices.none.with_key_down(KeyLeft).with_key_down(KeyRight)).x == 0
expect direction(Devices.none.with_key_down(KeyUp)).y == -1
## A long stall moves the box by a quarter of a second at most.
expect clamp_dt(3) == 0.25
JavaScript
From index.js of
ms 2.1.3, a tiny, much-used millisecond converter,
lines 1–103. © 2020 Vercel, Inc., under the MIT License.
The lexer: JsSyntax.roc.
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
Shale
From cookbook/rename_words.shale
in Steve's Shale, the whole recipe, 79 lines. Under the Universal Permissive License 1.0.
The lexer: ShaleSyntax.roc.
-- A word renamed across a project, any language: every whole-word `from` in
-- the files matching `like` under `in` becomes `to`, one write a file, a
-- one-line summary each. Whole words only (`fetchUserName` is left when
-- `from` is `fetchUser`), but strings and comments are words too: read the
-- summaries, then `git diff`. For Zig, `zig_rename` reads tokens instead
-- (SHALE-AGENTS.md, "A symbol renamed across a tree").
--
-- shale cookbook:rename_words.shale from=fetchUser to=loadUser in=src ext=ts,tsx
--
-- `ext` is the extensions to change (plain words for the launch line; a
-- glob, `like=`, goes on stdin with `--args-stdin`). `in` is
-- comma-separated files or folders (default the root); folders are
-- walked past hidden ones (.git, .venv) and node_modules, zig-out and
-- .zig-cache. A file that holds `from` only inside longer words is listed,
-- not changed.
--
-- budget: steps=500000000 reads=100000 read_bytes=1000000000 arena_bytes=1000000000
const FROM = arg("from", "")
const TO = arg("to", "")
const IN = arg("in", ".")
const LIKE = arg("like", "*")
const EXT = arg("ext", "")
-- Whether a walked file ends in one of `ext`'s extensions (any, unset).
function wanted(path)
if EXT == "" then return true end
for e in split(EXT, ",") do
if ends_with(path, "." .. trim(e)) then return true end
end
return false
end
if FROM == "" or TO == "" then fail("rename_words: give from=NAME to=NAME [in=dirs] [ext=ts,tsx]") end
function passed_by(path)
for part in {"/node_modules/", "/zig-out/", "/.zig-cache/"} do
if contains("/" .. path .. "/", part) then return true end
end
return false
end
-- One file's whole-word edit; its own function, as `attempt` takes one.
function rename_in(p)
return edit(p, FROM, TO, {all = true, word = true})
end
local renamed = 0
local files = 0
local only_inside = {}
for given in split(IN, ",") do
local place = trim(given)
local paths = {}
if place == "." or is_dir(place) then
local opts = {kind = "file", skip = ".*"}
if LIKE ~= "*" then opts = {kind = "file", skip = ".*", like = LIKE} end
for e in walk_all(place, opts) do
if not passed_by(e.path) and wanted(e.path) then push(paths, e.path) end
end
else
push(paths, place)
end
for p in paths do
if #grep_all(p, FROM) > 0 then
local r = attempt(rename_in, p)
if r.ok then
renamed = renamed + r.value
files = files + 1
elseif r.class == "argument" then
-- `edit` found no whole word: `from` is only inside longer ones.
push(only_inside, p)
else
fail(p .. ": " .. r.error)
end
end
end
end
print(FROM .. " to " .. TO .. ": " .. renamed .. " in " .. files .. " files")
if #only_inside > 0 then print("only inside longer words, left: " .. join(only_inside, ", ")) end
Zig
From lib/std/Random/Xoshiro256.zig
in the Zig standard library, 0.17.0, lines 1–89: the Xoshiro256++ random number generator, without its tests.
Zig standard library, MIT License, © Zig contributors.
The lexer: ZigSyntax.roc.
//! Xoshiro256++ - https://prng.di.unimi.it/xoshiro256plusplus.c
//!
//! PRNG
const std = @import("std");
const math = std.math;
const Xoshiro256 = @This();
s: [4]u64,
pub fn init(init_s: u64) Xoshiro256 {
var x = Xoshiro256{
.s = undefined,
};
x.seed(init_s);
return x;
}
pub fn random(self: *Xoshiro256) std.Random {
return std.Random.init(self, fill);
}
pub fn next(self: *Xoshiro256) u64 {
const r = math.rotl(u64, self.s[0] +% self.s[3], 23) +% self.s[0];
const t = self.s[1] << 17;
self.s[2] ^= self.s[0];
self.s[3] ^= self.s[1];
self.s[1] ^= self.s[2];
self.s[0] ^= self.s[3];
self.s[2] ^= t;
self.s[3] = math.rotl(u64, self.s[3], 45);
return r;
}
// Skip 2^128 places ahead in the sequence
pub fn jump(self: *Xoshiro256) void {
var s: u256 = 0;
var table: u256 = 0x39abdc4529b1661ca9582618e03fc9aad5a61266f0c9392c180ec6d33cfd0aba;
while (table != 0) : (table >>= 1) {
if (@as(u1, @truncate(table)) != 0) {
s ^= @bitCast(self.s);
}
_ = self.next();
}
self.s = @bitCast(s);
}
pub fn seed(self: *Xoshiro256, init_s: u64) void {
// Xoshiro requires 256-bits of seed.
var gen = std.Random.SplitMix64.init(init_s);
self.s[0] = gen.next();
self.s[1] = gen.next();
self.s[2] = gen.next();
self.s[3] = gen.next();
}
pub fn fill(self: *Xoshiro256, buf: []u8) void {
var i: usize = 0;
const aligned_len = buf.len - (buf.len & 7);
// Complete 8 byte segments.
while (i < aligned_len) : (i += 8) {
var n = self.next();
comptime var j: usize = 0;
inline while (j < 8) : (j += 1) {
buf[i + j] = @as(u8, @truncate(n));
n >>= 8;
}
}
// Remaining. (cuts the stream)
if (i != buf.len) {
var n = self.next();
while (i < buf.len) : (i += 1) {
buf[i] = @as(u8, @truncate(n));
n >>= 8;
}
}
}
C
From read-cache.c
in git's first commit,
“Initial revision of "git", the information manager from hell”, lines 1–80: reading and naming the object files.
© 2005 Linus Torvalds, who wrote all of that commit, under the
GNU General Public License, version 2, as git is.
The lexer: CSyntax.roc.
#include "cache.h"
const char *sha1_file_directory = NULL;
struct cache_entry **active_cache = NULL;
unsigned int active_nr = 0, active_alloc = 0;
void usage(const char *err)
{
fprintf(stderr, "read-tree: %s\n", err);
exit(1);
}
static unsigned hexval(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return ~0;
}
int get_sha1_hex(char *hex, unsigned char *sha1)
{
int i;
for (i = 0; i < 20; i++) {
unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
if (val & ~0xff)
return -1;
*sha1++ = val;
hex += 2;
}
return 0;
}
char * sha1_to_hex(unsigned char *sha1)
{
static char buffer[50];
static const char hex[] = "0123456789abcdef";
char *buf = buffer;
int i;
for (i = 0; i < 20; i++) {
unsigned int val = *sha1++;
*buf++ = hex[val >> 4];
*buf++ = hex[val & 0xf];
}
return buffer;
}
/*
* NOTE! This returns a statically allocated buffer, so you have to be
* careful about using it. Do a "strdup()" if you need to save the
* filename.
*/
char *sha1_file_name(unsigned char *sha1)
{
int i;
static char *name, *base;
if (!base) {
char *sha1_file_directory = getenv(DB_ENVIRONMENT) ? : DEFAULT_DB_ENVIRONMENT;
int len = strlen(sha1_file_directory);
base = malloc(len + 60);
memcpy(base, sha1_file_directory, len);
memset(base+len, 0, 60);
base[len] = '/';
base[len+3] = '/';
name = base + len + 1;
}
for (i = 0; i < 20; i++) {
static char hex[] = "0123456789abcdef";
unsigned int val = sha1[i];
char *pos = name + i*2 + (i > 0);
*pos++ = hex[val >> 4];
*pos = hex[val & 0xf];
}
return base;
}
Odin
From core/odin/tokenizer/tokenizer.odin
in Odin at commit ba3b9025, lines 254–330: Odin's own tokenizer reading
Odin's comments, nested /* */ ones included, and the names between them. The package's Odin lexer follows this tokenizer.
© 2016–2025 Ginger Bill, as Odin's licence says, under the zlib License, as Odin is; copied unaltered.
The lexer: OdinSyntax.roc.
scan_comment :: proc(t: ^Tokenizer) -> string {
offset := t.offset-1
next := -1
general: {
if t.ch == '/' || t.ch == '!' { // // #! comments
advance_rune(t)
for t.ch != '\n' && t.ch >= 0 {
advance_rune(t)
}
next = t.offset
if t.ch == '\n' {
next += 1
}
break general
}
/* style comment */
advance_rune(t)
nest := 1
for t.ch >= 0 && nest > 0 {
ch := t.ch
advance_rune(t)
if ch == '/' && t.ch == '*' {
nest += 1
}
if ch == '*' && t.ch == '/' {
nest -= 1
advance_rune(t)
next = t.offset
if nest == 0 {
break general
}
}
}
error(t, offset, "comment not terminated")
}
lit := t.src[offset : t.offset]
// NOTE(bill): Strip CR for line comments
for len(lit) > 2 && lit[1] == '/' && lit[len(lit)-1] == '\r' {
lit = lit[:len(lit)-1]
}
return string(lit)
}
scan_file_tag :: proc(t: ^Tokenizer) -> string {
offset := t.offset - 1
for t.ch != '\n' && t.ch != utf8.RUNE_EOF {
if t.ch == '/' {
next := peek_byte(t, 0)
if next == '/' || next == '*' {
break
}
}
advance_rune(t)
}
return string(t.src[offset : t.offset])
}
scan_identifier :: proc(t: ^Tokenizer) -> string {
offset := t.offset
for is_letter(t.ch) || is_digit(t.ch) {
advance_rune(t)
}
return string(t.src[offset : t.offset])
}
Python
From py/lis.py
in Peter Norvig's pytudes at commit ebda2935, lines 58–132: the parser, the REPL
and eval of Lispy, a Scheme interpreter in Python, most of a Lisp in one screenful.
The file says “(c) Peter Norvig, 2010-18”; © 2010–2017 Peter Norvig, under the MIT License, as pytudes is.
The lexers: PythonSyntax.roc
and PythonLiteral.roc, where its strings and numbers end.
################ Parsing: parse, tokenize, and read_from_tokens
def parse(program):
"Read a Scheme expression from a string."
return read_from_tokens(tokenize(program))
def tokenize(s):
"Convert a string into a list of tokens."
return s.replace('(',' ( ').replace(')',' ) ').split()
def read_from_tokens(tokens):
"Read an expression from a sequence of tokens."
if len(tokens) == 0:
raise SyntaxError('unexpected EOF while reading')
token = tokens.pop(0)
if '(' == token:
L = []
while tokens[0] != ')':
L.append(read_from_tokens(tokens))
tokens.pop(0) # pop off ')'
return L
elif ')' == token:
raise SyntaxError('unexpected )')
else:
return atom(token)
def atom(token):
"Numbers become numbers; every other token is a symbol."
try: return int(token)
except ValueError:
try: return float(token)
except ValueError:
return Symbol(token)
################ Interaction: A REPL
def repl(prompt='lis.py> '):
"A prompt-read-eval-print loop."
while True:
val = eval(parse(input(prompt)))
if val is not None:
print(lispstr(val))
def lispstr(exp):
"Convert a Python object back into a Lisp-readable string."
if isinstance(exp, List):
return '(' + ' '.join(map(lispstr, exp)) + ')'
else:
return str(exp)
################ eval
def eval(x, env=global_env):
"Evaluate an expression in an environment."
if isinstance(x, Symbol): # variable reference
return env[x]
elif not isinstance(x, List): # constant literal
return x
elif x[0] == 'quote': # (quote exp)
(_, exp) = x
return exp
elif x[0] == 'if': # (if test conseq alt)
(_, test, conseq, alt) = x
exp = (conseq if eval(test, env) else alt)
return eval(exp, env)
elif x[0] == 'define': # (define var exp)
(_, var, exp) = x
env[var] = eval(exp, env)
elif x[0] == 'lambda': # (lambda (var...) body)
(_, parms, body) = x
return Procedure(parms, body, env)
else: # (proc arg...)
proc = eval(x[0], env)
args = [eval(exp, env) for exp in x[1:]]
return proc(*args)