Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,14 @@ ariadne = "0.5.1"
astro-float = { version = "0.9.5", default-features = false, features = ["std"] }
chumsky = "0.10.0"
clap = { version = "4.5.35", features = ["derive"] }
criterion = { version = "0.5.1", features = ["html_reports"] }

[target.'cfg(not(target_family = "wasm"))'.dependencies]
dirs = "6.0.0"
regex = "1.11.1"
rustyline = "15.0.0"

[dev-dependencies]
criterion = { version = "0.5.1", features = ["html_reports"] }
executable-path = "1.0.0"
indoc = "2.0.6"
pretty_assertions = "1.4.1"
Expand Down
2 changes: 2 additions & 0 deletions crates/val-wasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@ crate-type = ["cdylib", "rlib"]

[dependencies]
console_error_panic_hook = "0.1.7"
serde = { version = "1.0.219", features = ["derive"] }
serde-wasm-bindgen = "0.6.5"
val = { path = "../.." }
wasm-bindgen = "0.2.100"
3 changes: 1 addition & 2 deletions crates/val-wasm/src/ast_node.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use super::*;

#[derive(Clone)]
#[wasm_bindgen(getter_with_clone)]
#[derive(Clone, Serialize)]
pub struct AstNode {
pub kind: String,
pub range: Range,
Expand Down
6 changes: 2 additions & 4 deletions crates/val-wasm/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
use super::*;

#[derive(Debug, Clone)]
#[wasm_bindgen]
#[derive(Clone, Debug, Serialize)]
pub enum ErrorKind {
Evaluator,
Parser,
}

#[derive(Debug, Clone)]
#[wasm_bindgen(getter_with_clone)]
#[derive(Clone, Debug, Serialize)]
pub struct ValError {
pub kind: ErrorKind,
pub message: String,
Expand Down
71 changes: 43 additions & 28 deletions crates/val-wasm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ use {
error::{ErrorKind, ValError},
range::Range,
},
val::{Environment, Evaluator, Expression, Program, Span, Statement},
serde::Serialize,
serde_wasm_bindgen::to_value,
val::{
Environment, Evaluator, Expression, Program, RoundingMode, Span, Statement,
},
wasm_bindgen::prelude::*,
};

Expand All @@ -18,47 +22,58 @@ fn start() {
}

#[wasm_bindgen]
pub fn parse(input: &str) -> Result<AstNode, Vec<ValError>> {
pub fn parse(input: &str) -> Result<JsValue, JsValue> {
match val::parse(input) {
Ok((ast, span)) => Ok(AstNode::from((&ast, &span))),
Ok((ast, span)) => Ok(to_value(&AstNode::from((&ast, &span))).unwrap()),
Err(errors) => Err(
errors
.into_iter()
.map(|error| ValError {
kind: ErrorKind::Parser,
message: error.message,
range: Range::from(error.span),
})
.collect(),
to_value(
&errors
.into_iter()
.map(|error| ValError {
kind: ErrorKind::Parser,
message: error.message,
range: Range::from(error.span),
})
.collect::<Vec<ValError>>(),
)
.unwrap(),
),
}
}

#[wasm_bindgen]
pub fn eval(input: &str) -> Result<String, Vec<ValError>> {
pub fn evaluate(input: &str) -> Result<JsValue, JsValue> {
match val::parse(input) {
Ok(ast) => {
let mut evaluator =
Evaluator::from(Environment::new(val::Config::default()));
let mut evaluator = Evaluator::from(Environment::new(val::Config {
precision: 53,
rounding_mode: RoundingMode::FromZero.into(),
}));

match evaluator.eval(&ast) {
Ok(value) => Ok(value.to_string()),
Err(error) => Err(vec![ValError {
kind: ErrorKind::Evaluator,
message: error.message,
range: Range::from(error.span),
}]),
Ok(value) => Ok(to_value(&value.to_string()).unwrap()),
Err(error) => Err(
to_value(&[ValError {
kind: ErrorKind::Evaluator,
message: error.message,
range: Range::from(error.span),
}])
.unwrap(),
),
}
}
Err(errors) => Err(
errors
.into_iter()
.map(|error| ValError {
kind: ErrorKind::Parser,
message: error.message,
range: Range::from(error.span),
})
.collect(),
to_value(
&errors
.into_iter()
.map(|error| ValError {
kind: ErrorKind::Parser,
message: error.message,
range: Range::from(error.span),
})
.collect::<Vec<ValError>>(),
)
.unwrap(),
),
}
}
3 changes: 1 addition & 2 deletions crates/val-wasm/src/range.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use super::*;

#[derive(Debug, Clone)]
#[wasm_bindgen]
#[derive(Clone, Debug, Serialize)]
pub struct Range {
pub start: u32,
pub end: u32,
Expand Down
File renamed without changes.
2 changes: 2 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ build-wasm:
--out-name val \
--out-dir ../../www/packages/val-wasm

uv run --with arrg tools/example-generator/main.py examples www/src/lib/examples.ts

[group: 'check']
check:
cargo check
Expand Down
1 change: 1 addition & 0 deletions mise.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
[tools]
python = "3.12"
rust = "latest"
31 changes: 18 additions & 13 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,17 @@ fn statement_parser<'a>()
let indexed_ident = simple_ident.foldl(
expression
.clone()
.delimited_by(just('[').padded(), just(']').padded())
.delimited_by(just('['), just(']'))
.padded()
.map_with(|expression, e| (expression, e.span()))
.repeated(),
|base, index| {
let span = (base.1.start..index.1.end).into();
(
Expression::ListAccess(Box::new(base), Box::new(index)),
span,
)
|base, (index, span)| {
let span = (base.1.start..span.end).into();

let expression =
Expression::ListAccess(Box::new(base), Box::new(index));

(expression, span)
},
);

Expand Down Expand Up @@ -215,10 +218,9 @@ fn expression_parser<'a>()
.collect::<Vec<_>>();

let list = items
.clone()
.delimited_by(just('['), just(']'))
.map(Expression::List)
.map_with(|ast, e| (ast, e.span()))
.delimited_by(just('['), just(']'));
.map_with(|ast, e| (ast, e.span()));

let atom = number
.or(boolean)
Expand All @@ -233,10 +235,13 @@ fn expression_parser<'a>()
let list_access = atom.clone().foldl(
expression
.clone()
.delimited_by(just('[').padded(), just(']').padded())
.delimited_by(just('['), just(']'))
.padded()
.map_with(|expression, e| (expression, e.span()))
.repeated(),
|list, index| {
let span = (list.1.start..index.1.end).into();
|list: Spanned<Expression<'a>>,
(index, span): (Spanned<Expression<'a>>, SimpleSpan)| {
let span = (list.1.start..span.end).into();

let expression =
Expression::ListAccess(Box::new(list), Box::new(index));
Expand Down
1 change: 1 addition & 0 deletions tools/example-generator/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.12.3
12 changes: 12 additions & 0 deletions tools/example-generator/justfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
set dotenv-load

export EDITOR := 'nvim'

alias f := fmt

default:
just --list

[group: 'format']
fmt:
uv run ruff check --select I --fix && uv run ruff format
105 changes: 105 additions & 0 deletions tools/example-generator/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import argparse
import os
import shutil
from textwrap import dedent

from arrg import app, argument


def snake_to_camel(snake_str):
components = snake_str.split('_')
return components[0] + ''.join(x.title() for x in components[1:])


@app(
description='Generate a JavaScript dictionary from val source files using imports.',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=dedent(
"""\
Examples:
%(prog)s ./src/tests ./frontend/src/lib/examples.js
%(prog)s /path/to/val/files /path/to/output.js
"""
),
)
class App:
source_dir: str = argument(help='Directory containing the val source files')
output_file: str = argument(help='Path to the output JavaScript file')
examples_dir: str = argument(
help='Path to the assets/examples directory', default=None, nargs='?'
)

def run(self) -> int:
try:
self.generate()
return 0
except Exception as e:
print(f'error: {e}')
return 1

def generate(self):
if not os.path.exists(self.source_dir):
raise FileNotFoundError(f"Source directory '{self.source_dir}' does not exist")

if self.examples_dir is None:
output_dir = os.path.dirname(self.output_file)
base_dir = os.path.dirname(output_dir)
self.examples_dir = os.path.join(base_dir, 'assets', 'examples')

os.makedirs(self.examples_dir, exist_ok=True)
os.makedirs(os.path.dirname(self.output_file), exist_ok=True)

val_files = sorted([f for f in os.listdir(self.source_dir) if f.endswith('.val')])

if not val_files:
print(f'Warning: No .val files found in {self.source_dir}')
return

for file in val_files:
source_file = os.path.join(self.source_dir, file)
target_file = os.path.join(self.examples_dir, file)
shutil.copy2(source_file, target_file)
print(f'Copied {file} to {self.examples_dir}')

imports = []
dictionary_entries = []

for file in val_files:
base_name = file.replace('.val', '')
var_name = snake_to_camel(base_name)
rel_path = os.path.relpath(self.examples_dir, os.path.dirname(self.output_file))
imports.append(f"import {var_name} from '{rel_path}/{file}?raw';")
dictionary_entries.append(f' {var_name}: {var_name}')

content = self._generate_js_dictionary(imports, dictionary_entries)

with open(self.output_file, 'w') as f:
f.write(content)

print(f'Successfully generated JS dictionary at {self.output_file}')
print(f'Processed {len(val_files)} val files')

def _generate_js_dictionary(self, imports, dictionary_entries):
lines = [
'// This file is generated by `example-generator`. Do not edit manually.',
'',
]

for import_line in imports:
lines.append(import_line)

lines.append('')
lines.append('const EXAMPLES = {')

dictionary_text = ',\n'.join(dictionary_entries)
lines.append(dictionary_text)

lines.append('};')
lines.append('')
lines.append('export default EXAMPLES;')

return '\n'.join(lines)


if __name__ == '__main__':
exit(App.from_args().run())
24 changes: 24 additions & 0 deletions tools/example-generator/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[project]
name = "example-generator"
version = "0.0.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12.3"
dependencies = [
"arrg>=0.1.0",
"ruff>=0.11.6",
]

[tool.ruff]
src = ["src"]
indent-width = 2
line-length = 100

[tool.ruff.lint]
select = ["E", "F", "I"]

[tool.ruff.format]
docstring-code-format = true
docstring-code-line-length = 20
indent-style = "space"
quote-style = "single"
Loading