Files
Your NameandClaude Opus 5.5 7cf9727bcd Rename the language from Dino to Rex
Files use .rex, the command is rex, and the crate, runtime prefixes,
docs, editor files and examples all use the new name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:51:23 +01:00

131 lines
3.7 KiB
Rexx

// Recursive descent: assignment < + - < * / % < unary minus < ^ < calls and atoms.
import token
import ast
pub struct Parser {
tokens: []token.Token
at: int
func peek(): token.Token { return tokens[at] }
func next(): token.Token {
var t = tokens[at]
if at < tokens.len() - 1 { at += 1 }
return t
}
func is_op(text: string): bool {
var t = peek()
return t.kind == token.Kind.Op && t.text == text
}
func expect(kind: token.Kind, what: string): error {
if peek().kind != kind {
return error("expected {what} at column {peek().pos + 1}")
}
next()
return nil
}
pub func statement(): (ast.Node, error) {
// `name = expression`
if peek().kind == token.Kind.Name && at + 1 < tokens.len() {
var after = tokens[at + 1]
if after.kind == token.Kind.Op && after.text == "=" {
var name = next().text
next()
var value = sum()?
return ast.assign(name, value), finish()
}
}
var e = sum()?
return e, finish()
}
func finish(): error {
if peek().kind != token.Kind.End {
return error("unexpected `{peek().text}` at column {peek().pos + 1}")
}
return nil
}
func sum(): (ast.Node, error) {
var left = product()?
for is_op("+") || is_op("-") {
var op = next().text
var right = product()?
left = ast.bin(op, left, right)
}
return left, nil
}
func product(): (ast.Node, error) {
var left = unary()?
for is_op("*") || is_op("/") || is_op("%") {
var op = next().text
var right = unary()?
left = ast.bin(op, left, right)
}
return left, nil
}
func unary(): (ast.Node, error) {
if is_op("-") {
next()
var inner = unary()?
return ast.neg(inner), nil
}
return power()
}
func power(): (ast.Node, error) {
var base = atom()?
if is_op("^") {
next()
var exp = unary()?
return ast.bin("^", base, exp), nil
}
return base, nil
}
func atom(): (ast.Node, error) {
var t = next()
match t.kind {
Num => {
var v, err = t.text.to_float()
if err != nil { return ast.Node.Num(0.0), error("bad number `{t.text}` at column {t.pos + 1}") }
return ast.Node.Num(v), nil
}
Name => {
if peek().kind == token.Kind.Open {
next()
var args: []ast.Node
if peek().kind != token.Kind.Close {
args.push(sum()?)
for is_op(",") {
next()
args.push(sum()?)
}
}
expect(token.Kind.Close, "`)`")?
return ast.Node.Call(t.text, args), nil
}
return ast.Node.Var(t.text), nil
}
Open => {
var inner = sum()?
expect(token.Kind.Close, "`)`")?
return inner, nil
}
End => return ast.Node.Num(0.0), error("the calculation ends too early (column {t.pos + 1})")
_ => return ast.Node.Num(0.0), error("unexpected `{t.text}` at column {t.pos + 1}")
}
}
}
pub func parse(src: string): (ast.Node, error) {
var tokens = token.tokenize(src)?
var p = Parser{tokens, 0}
return p.statement()
}