Skip to content

Commit

Permalink
Add variables
Browse files Browse the repository at this point in the history
Signed-off-by: Christian Lindig <lindig@gmail.com>
  • Loading branch information
lindig committed Jun 11, 2024
1 parent fdcbd56 commit c7e2334
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
5 changes: 4 additions & 1 deletion lib/lexer.mll
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

let digit = ['0'-'9']
let digits = digit digit*
let alpha = ['a'-'z']
let id = alpha (digit|alpha)*

let seconds = digits ('.' digits)?

Expand All @@ -31,7 +33,8 @@ rule token = parse
| '(' { LPAREN }
| ')' { RPAREN }
| '^' { CARET }

| '=' { EQUAL }
| id as id { ID(id) }
| _ { EOL }

| eof { EOL }
19 changes: 18 additions & 1 deletion lib/parser.mly
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@

%{

let fail fmt = Printf.ksprintf failwith fmt

let t = Hashtbl.create 10

let add id num = Hashtbl.replace t id num
let lookup id = Hashtbl.find_opt t id |> function
| Some v -> v
| None -> fail "unknown value %s" id

%}

%token <float> NUM
%token <string> ID
%token PLUS MINUS TIMES DIV CARET
%token LPAREN RPAREN
%token EOL
%token EQUAL EOL
%left PLUS MINUS /* lowest precedence */
%left TIMES DIV /* medium precedence */
%nonassoc UMINUS /* highest precedence */
Expand All @@ -16,6 +31,8 @@ main:
;
expr:
NUM { $1 }
| ID { lookup $1 }
| ID EQUAL expr { add $1 $3; $3 }
| LPAREN expr RPAREN { $2 }
| expr PLUS expr { $1 +. $3 }
| expr MINUS expr { $1 -. $3 }
Expand Down
2 changes: 1 addition & 1 deletion tcalc.opam
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
opam-version: "2.0"
synopsis: "Minimal desktop calculator for timestamps"
description: """
description: """\
TCalc implements a minimal desktop calculator that in addition to
floating point numbers recognises durations in hh:min:sec format and
converts them to seconds. This can simplify time-based calculations."""
Expand Down

0 comments on commit c7e2334

Please sign in to comment.