Docs

Creators

Overview

Grizzly is a small language for transforming tabular data. It's built for data analysts and engineers who'd otherwise reach for a general-purpose language or a SQL dialect to do the same repetitive work. Tables are first-class values, definable inline or loaded from a file. Every transformation is just an ordinary function, chained with pipes rather than nested calls or query clauses. Code reads top to bottom in the same order it runs, so a pipeline looks like the sequence of steps it performs. Writing Grizzly should feel like describing a data pipeline, not programming one.

Host language and build

Running it

CommandWhat it does
./run <file>Executes a program.
./run --tokenize <file>Prints the token stream.
./run --parse <file>Prints the parsed tree.
./run --eval <file>Evaluates each expression and prints its value.
./runStarts the REPL.
./run --tokenizeStarts the REPL, printing only tokens.
./run --parseStarts the REPL, printing only the parsed tree.

In the REPL, an entry continues onto the next line (with a ... prompt) while a (, [, or { is unclosed. An empty line gives up on an incomplete entry and reports its syntax error.

./run wraps that binary. After cargo install --path ., use grizzly in place of ./run.

Exit codes: 0 on success, 65 on a static error (lexical, syntax), 70 on a runtime error (type mismatch, division by zero, undefined name, arity mismatch).

Jupyter

To run Grizzly in Jupyter notebooks, install grizzly on your PATH, then register the kernel once (needs Jupyter installed):

cargo install --path .
python3 editors/jupyter/grizzly_kernel.py install

Pick the "Grizzly" kernel in JupyterLab. Cells share one interpreter and echo each expression's value, like the REPL. The kernel is a wrapper kernel that runs cells on grizzly --cells.

File extension

.griz

Editor support: VS Code extension.

Lexical structure

Keywords

KeywordPurpose
returnReturn a value from a function
if / elseConditional
match / caseMulti-branch conditional
for / inLoop over a List
whileLoop while a condition holds
and / or / notBoolean operators
true / falseBoolean literals
nullThe absence of a value
tableIntroduces a table literal

Operators

OperatorCategoryOperandsAssociativityPrecedenceMeaning
=assignmentbinaryright0x = y
+= -= *= /=assignmentbinaryright0x OP= y means x = x OP y
|>pipebinaryleft0x |> f means f(x), x |> f(a) means f(x, a)
|=assignmentbinaryright0x |= f1 |> f2 means x = x |> f1 |> f2
orlogicalbinaryleft1 (loosest)
andlogicalbinaryleft2
notlogicalunaryright3
== !=comparisonbinarynone4
< <= > >=comparisonbinarynone4
+ -arithmeticbinaryleft5
++stringbinaryleft5concatenation
* / %arithmeticbinaryleft6
- (unary)arithmeticunaryright7
^arithmeticbinaryright8 (tightest)exponent
->othern/an/an/alambda arrow, introduces a lambda's body
=>othern/an/an/amatch arrow, introduces a case/else clause's result

Literals

KindSyntaxProduces
Integer42Int
Float3.14Float
String"hello", escapes: \n \t \\ \" \{Str
Interpolated string"Hi {name}, you earn {salary}"Str
Booleantrue, falseBool
NullnullNull
List[1, 2, 3]List(T)
Tabletable [ a | b, 1 | 2, 3 | 4 ] (header row, then rows; cells |-separated, rows ,-separated)Table

Identifiers

Examples:

sales
customer_name
_total
amount2

Comments

String interpolation

Whitespace and termination

Token output format

Token(type=, lexeme=, literal=, line=)

Fields: token type, lexeme, literal value (or empty), line number.

String literals print escaped.

Grammar

program     → statement* EOF

statement   → exprStmt
            | ifStmt
            | whileStmt
            | forStmt
            | returnStmt
            | block

exprStmt    → expression ";"

ifStmt      → "if" expression block ( "else" ( ifStmt | block ) )?

whileStmt   → "while" expression block

forStmt     → "for" IDENTIFIER "in" expression block

returnStmt  → "return" expression? ";"

block       → "{" statement* "}"

expression  → assignment

assignment  → IDENTIFIER ( "=" | "+=" | "-=" | "*=" | "/=" | "|=" ) assignment
            | lambda
            | pipe

lambda      → ( IDENTIFIER | "(" parameters? ")" ) "->" ( expression | block )

parameters  → parameter ( "," parameter )*

parameter   → IDENTIFIER ( "=" expression )?

pipe        → logicOr ( "|>" logicOr )*

logicOr     → logicAnd ( "or" logicAnd )*

logicAnd    → logicNot ( "and" logicNot )*

logicNot    → "not" logicNot
            | comparison

comparison  → term ( ( "==" | "!=" | "<" | "<=" | ">" | ">=" ) term )?

term        → factor ( ( "+" | "-" | "++" ) factor )*

factor      → unary ( ( "*" | "/" | "%" ) unary )*

unary       → "-" unary
            | exponent

exponent    → call ( "^" unary )?

call        → primary ( "(" arguments? ")" )*

arguments   → argument ( "," argument )*

argument    → ( IDENTIFIER ":" )? expression

exprList    → expression ( "," expression )*

primary     → INTEGER | FLOAT | STRING | "true" | "false" | "null"
            | IDENTIFIER
            | "(" expression ")"
            | "[" exprList? "]"
            | table

table       → "table" "[" header ( "," row )* "]"

header      → IDENTIFIER ( "|" IDENTIFIER )*

row         → expression ( "|" expression )*

Parse output format

(+ 2 (* 3 4))
(* (group (+ 2 3)) 4)
(- (- 1 2) 3)

Parser quirks

Semantics

Values and types

TypeHost representation
IntValue::Int(i64)
FloatValue::Float(f64)
StrValue::Str(String)
BoolValue::Bool(bool)
NullValue::Null
nativeValue::Native(Native)
FunctionValue::Function(Rc<Function>)
ListValue::List(Rc<Vec<Value>>)
TableValue::Table(Rc<Table>)

Values are a Rust enum (a tagged union). One type holds any Grizzly value, matching on the variant tells the evaluator what it has, and the compiler flags a match that forgets a type.

A List is immutable, so it's behind an Rc and copies share one Vec. append returns a new list.

A Table is ordered, named columns of equal length, plus the group columns set by group_by (none otherwise). Each column is an Rc<Vec<Value>>, so verbs that keep a column (select, rename, add_col) share it instead of copying it. Like a List, a Table is never changed in place.

A Function is a lambda turned into a value: its parameters, its body, and the environment it was created in. It's behind an Rc, so copying the value shares the same function. Natives and functions both implement one Callable trait (arity and call), so a call checks callability and arity in one place for both.

Value printing

TypePrints asExample
Intas written5
Floatalways with a decimal point5.0, never 5
exponent form when very large or small1e20, 1e-7
non-finite values by nameinf, -inf, NaN
Strwithout quotes"hi" prints hi
Boolits keywordtrue, false
Nullits keywordnull
nativeits name<native fn print>
Functiona placeholder<fn>
Listelements by these rules, in brackets[1, 2.0, a]
Tablean aligned grid, see below

A Table prints as a header line, a rule line, then one line per row:

name | dept  | salary
-----+-------+-------
Ana  | eng   | 60000
Cy   | sales | 70000

Truthiness

TypeFalseyTruthy
Int0any other Int
Float0.0, -0.0any other Float, even NaN
Str""any non-empty Str
Boolfalsetrue
Nullnullnever
List[]any non-empty List
Tableno rowsone or more rows
native, Functionneveralways

Operator semantics

Operands are evaluated left to right, and both are evaluated before the operator applies, except for and and or, which short-circuit.

Arithmetic: + - * / % ^, unary -

Concatenation: ++

Comparison: < <= > >=

Equality: == !=

Logical: and or not

Scope and bindings

Control flow and functions

Planned for Lab 5, not built yet: the if ... then ... else expression form, match/case, and string interpolation.

Tables

filter is built; the other verbs are planned. The call machinery they need (parameter kinds, row context, column names, named arguments) is built. Table verbs can't use plain call evaluation: in filter(t, salary > 50000), salary is a column, not a variable, and the condition must run once per row.

Parameter kinds

Each native declares a kind for each parameter. The call path reads the kinds and handles every verb the same way, so no verb parses its own arguments.

KindThe native receivesExample
valuethe evaluated argument, as for any callt in filter(t, ...)
rowthe unevaluated expression, run once per rowsalary > 50000
columna column name, written as a bare identifiersalary in sort(t, ...)
optionone of a fixed set of bare wordsdesc, left
named rowany number of name: row pairsbonus: salary * 0.1
named columnany number of name: column pairsdept: department
namedfixed names, each taking a column or optionon: dept, how: left

A parameter can be variadic (select(t, cols...)) or optional (sort's direction). Lambdas have only value parameters. The aggregates are the one case whose kind depends on where they're called, see Group context.

Row context

Column names

Named arguments

Group context

Cells and columns

Joins

CSV

Verbs

No native changes its arguments; each verb returns a new table. In the signatures, t is a table, col a column name, expr a row expression, and ... means one or more (zero or more for distinct).

Rows

VerbSignatureResult
filterfilter(t, expr)Rows where expr is truthy
sortsort(t, col, asc | desc)Stable; the direction is optional and defaults to asc
distinctdistinct(t, col...)First row of each unique combination; no columns means all
headhead(t, n)First n rows, or all of them if n is past the end
tailtail(t, n)Last n rows
sliceslice(t, from, to)Rows from up to but not including to, counting from 0

A negative count or index is a runtime error (exit 70). slice clamps both ends to the row count. sort orders by the comparison rules and puts null cells last in either direction; a column mixing numbers and strings is a runtime error (exit 70). Comparing strings depends on #309.

Columns

VerbSignatureResult
selectselect(t, col...)Those columns, in the order given
dropdrop(t, col...)Every other column
add_coladd_col(t, name: expr, ...)New columns at the end; each must be new
update_colupdate_col(t, name: expr, ...)Replaces values in place; each must exist
renamerename(t, old: new, ...)Columns keep their position

Grouping and combining

VerbSignatureResult
group_bygroup_by(t, col...)Marks group columns, see Group context
summarizesummarize(t, name: expr, ...)One row per group, see Group context
joinjoin(t, other, on: col, how: kind)See Joins
concatconcat(t...)Rows stacked; same column names in the same order

Access and files

NativeSignatureResult
pullpull(t, col)The column as a List
first_rowfirst_row(t)A one-row table; an empty table gives an empty table
getget(t, col)The cell of a one-row table; other row counts are errors
read_csvread_csv(path)A table, see CSV
write_csvwrite_csv(t, path)null, see CSV
write_jsonwrite_json(t, path)null, see CSV

Aggregates and values

NativeSignatureResult
sumsum(expr)Total of the numbers; 0 when there are none
meanmean(expr)Average as a Float; null when there are none
medianmedian(expr)Middle number; the mean of the two middle values when the count is even
min/maxmin(expr), max(expr)Smallest or largest, by the comparison rules
countcount(expr)Number of values
fill_nullfill_null(x, default)default when x is null, else x; works on any value

Aggregates take a row expression inside summarize and a List elsewhere, see Group context.

Wrapping a verb

A lambda can't forward a row expression. In my_filter = (t, cond) -> filter(t, cond);, the call my_filter(t, salary > 50000) evaluates salary > 50000 at the call site, where salary is undefined, since lambdas have only value parameters. Wrappers instead capture what varies as values:

earns_over = (t, amount) -> filter(t, salary > amount);

Native functions

NameArgumentsReturnsNotes
print1, anyNullWrites the value and a newline to stdout
to_string1, anyStrConverts a value to text using the value printing rules
length1, Str, List, or TableIntCharacters in a Str (not bytes), elements in a List, or rows in a Table
to_int1, StrIntParses an integer; unparseable input is Can't convert 'abc' to Int
to_float1, StrFloatParses a float; unparseable input is Can't convert 'abc' to Float
append2, List and anyListA new list with the value at the end; the original is unchanged

A wrong argument type is Argument must be followed by what the native takes, e.g. length(1) is Argument must be a string, list, or table, and append(1, 2) is Argument must be a list. Both errors are runtime errors (exit 70).

Output: in file mode, only print writes to stdout, and expression statements discard their values. The REPL also prints the value of each bare expression, except a call that returns null, so print(5); prints 5 once instead of 5 then null. --eval follows the same rule.

Errors and diagnostics

Diagnostics are printed to stderr as Error at line N: <message>.

Error at line 1: Unexpected character '@'
Error at line 1: Unterminated string
Error at line 1: Invalid escape sequence '\q'
Error at line 1: Invalid number
Error at line 1: Missing '='

Syntax errors also name the token where parsing failed, or end at end of file.

Error at line 1: Missing expression at ';'
Error at line 1: Missing ')' at ';'
Error at line 2: Missing '}' at end
Error at line 1: Missing ';' at end
FailureExit code
Bad usage64
Lexical error65
Syntax error65
Unreadable file66
Runtime error70

Testing conventions

FolderActivityModeFlag
tests/lab1Scannersidecar--tokenize
tests/lab2Parsersidecar--parse
tests/lab3Evaluatorinline--eval
tests/lab4Contextinlinenone
tests/lab5Functionsinlinenone

Each folder has a manifest.json and one .griz file per test case, mostly grouped into subfolders by feature (e.g. tests/lab2/groupings, tests/lab3/arithmetic). Inline folders annotate with # expect:, # expect runtime error:, and # expect error:. Error cases are one per file, prefixed invalid- (e.g. tests/lab3/arithmetic/invalid-divide-by-zero.griz).

Run locally with:

curl -sSL https://raw.githubusercontent.com/WhiteLicorice/cmsc-124-harness/v1.1/run_tests.py -o run_tests.py
./build.sh
python3 run_tests.py tests/lab1

Sample code

Variables, arithmetic, strings, booleans

age = 25;
name = "Ana";
rate = 0.2;

total = 10 + 5 * 2;
avg = total / 3;
greeting = "Hi, " ++ name ++ "!";
can_vote = age >= 18 and name != "";

Control flow

if age >= 65 {
  status = "senior";
} else if age >= 18 {
  status = "adult";
} else {
  status = "minor";
}

i = 0;
while i < 5 {
  print(i);
  i = i + 1;
}

for n in [1, 2, 3, 4, 5] {
  print(n * n);
}

band = match age {
  case > 65 => "senior"
  case > 18 => "adult"
  else => "minor"
};

Functions, closures, wrapping a verb

tax = (amount, rate) -> amount * rate;

make_adder = n -> (x -> x + n);
add5 = make_adder(5);
add5(10);

earns_over = (t, amount) -> filter(t, salary > amount);

Creating a table

small = table [
  name  | dept    | salary,
  "Ana" | "eng"   | 60000,
  "Bo"  | "eng"   | 45000,
  "Cy"  | "sales" | 70000
];

employees = read_csv("employees.csv");

Filtering and selecting

employees |> filter(salary > 50000);
employees |> filter(salary > 50000 and dept == "eng");

employees |> select(name, dept, salary);
employees |> drop(ssn, internal_notes);

employees |= select(name, age) |> filter(age > 18);

Adding and computing columns

employees |> add_col(bonus: salary * 0.10);

employees |> add_col(
  band: if salary > 100000 then "exec" else "standard"
);

employees |> add_col(
  band: match salary {
    case > 150000 => "exec"
    case > 100000 => "senior"
    else => "standard"
  }
);

Grouping and aggregating

employees
  |> group_by(dept)
  |> summarize(
       total: sum(salary),
       average: mean(salary),
       headcount: count(salary)
     );

employees
  |> group_by(dept)
  |> summarize(
       total: sum(salary),
       exec_total: sum(if salary > 100000 then salary else 0)
     );

Slicing

employees |> slice(10, 20);
employees |> head(5);
employees |> tail(5);

Sorting, distinct

employees |> sort(salary, desc);
employees |> distinct(dept);

Joining and combining tables

merged = employees |> join(departments, on: dept, how: left);
combined = concat(q1_sales, q2_sales, q3_sales);
renamed = employees |> rename(dept: department, salary: pay);

Column and row access

salaries = employees |> pull(salary);
avg = mean(salaries);

first = employees |> first_row();

first_salary = get(first, salary);

Nulls

employees |= update_col(quantity: fill_null(quantity, 0));

String interpolation

name = "Ana";
salary = 60000;

"Hi {name}, you earn {salary}";

Writing output

write_csv(employees, "out.csv");
write_json(employees, "out.json");

Lists (script-level, not table data)

files = ["jan.csv", "feb.csv", "mar.csv"];
n = length(files);
more = append(files, "apr.csv");

# same transform, run once per file
for f in files {
  data = read_csv(f);
  summary = data |> group_by(dept) |> summarize(total: sum(revenue));
  write_csv(summary, f ++ "_summary.csv");
}

# one output table per distinct group
depts = employees |> distinct(dept) |> pull(dept);
for d in depts {
  employees |> filter(dept == d) |> write_csv(d ++ "_employees.csv");
}

# sweep a scalar parameter across the same computation
for rate in [0.05, 0.10, 0.15] {
  print(tax(50000, rate));
}

Full example: monthly regional report

monthly_regional_report = () -> {
  orders = read_csv("orders.csv");
  customers = read_csv("customers.csv");

  orders |= update_col(quantity: fill_null(quantity, 0));

  customers |= add_col(
    tier: match lifetime_spend {
      case > 10000 => "vip"
      case > 1000  => "regular"
      else => "new"
    }
  );

  enriched =
    orders
      |> join(customers, on: customer_id, how: left)
      |> add_col(revenue: quantity * unit_price);

  high_value_orders =
    enriched |> filter(tier == "vip" and revenue > 500);

  regional_totals =
    enriched
      |> group_by(region, month)
      |> summarize(
           total_revenue: sum(revenue),
           order_count: count(order_id),
           vip_revenue: sum(if tier == "vip" then revenue else 0)
         )
      |> sort(total_revenue);

  write_csv(regional_totals, "regional_report.csv");
  write_csv(high_value_orders, "vip_orders_flagged.csv");

  return regional_totals;
};

monthly_regional_report();

Design rationale

The language design is grounded in tabular data transformation. Each decision exists to make pipelines read and write naturally, with the structure of the language following the way data transformations are expressed.

Read order is execution order. SQL makes you write queries in an order that doesn't match how they execute or how you reason about them. Grizzly instead uses a top-down sequence of transformations, so the code reads in the same order it runs. This is the central design principle behind the language.

Mostly one way to do things. Grizzly deliberately avoids alternative spellings for the same operation. => is for match, -> is for lambdas, + is arithmetic, and ++ is concatenation. A small set of distinct primitives keeps code predictable and consistent.

Functions over keywords. filter, join, sort, and sum are ordinary functions. Keywords are reserved for constructs that genuinely need special syntax, such as if, match, loops, and table. User-defined transformations therefore look and behave like built-ins.

No object system. Tables and lists are plain values. Operations are functions, such as filter(table, condition), and can be written with pipes as table |> filter(condition). There are no methods, classes, or dot notation.

Functions are values. Functions can be assigned, passed, returned, or written anonymously (x -> x + 1). This provides closures naturally and lets users build new transformations from existing functions.

Everything produces a value. if, match, and blocks are expressions. Their results can be assigned, passed to functions, or composed with other expressions. For example, sum(if tier == "vip" then revenue else 0) works because if produces a value.

Pipes make sequences readable. |> turns nested calls like sort(summarize(filter(...))) into a sequence where each step follows the previous one. The syntax exists to preserve Grizzly's top-down reading order.

Semicolons terminate statements. Explicit ; makes statement boundaries clear across line breaks, so pipelines, calls, and table literals can span multiple lines without special newline rules.

Braces delimit blocks. Braces give blocks explicit boundaries without requiring indentation-based parsing. Square brackets hold data, list and table literals, making data visually distinct from code.

Row-context evaluation, not vectorization. Table verbs like filter and add_col evaluate their expression argument once per row, with column names bound as ordinary scalars for that row. Every operator (+, >, and, or, ...) is always scalar-to-scalar; there is no vector/column value type and no broadcasting. This keeps operator semantics uniform instead of giving and/or/comparisons a second, elementwise meaning depending on whether their operands are scalars or columns.

Known limitations

Changelog

ActivityWhat changed in the language
Lab 1Scanner with the full token vocabulary (keywords, operators, punctuation), --tokenize flag and line REPL, string escapes \n \t \\ \" \{, Int and Float literals (digits on both sides of .), # line comments
Lab 2Recursive descent parser for expressions, --parse flag and parse REPL, ;-terminated expressions, prefix AST printer with (group ...), ^ right-associative, non-chaining comparisons, syntax error recovery at ;
Lab 3Tree-walking evaluator, --eval flag and value-printing REPL, Int/Float/Str/Bool/Null values, checked Int arithmetic, IEEE 754 Floats, ++ concatenation, truthiness rule, runtime errors with exit 70
Lab 4Plain ./run <file> executes programs and the REPL keeps state across lines, native print bound as a global, identifiers and calls, assignment as an expression with = += -= *= /= |=, braced blocks with lexical scope and no declaration keyword, environment restored after runtime errors, syntax error recovery at ;, }, and statement keywords