#expression-parser #arithmetic #math-parser #scripting #scripting-language #parser #language

no-std arithmetic-parser

Parser for arithmetic expressions with flexible literals and type annotations

5 releases (3 breaking)

0.4.0-beta.1 Sep 22, 2024
0.3.0 May 24, 2021
0.2.0 Dec 5, 2020
0.2.0-beta.1 Oct 4, 2020
0.1.0 Jun 1, 2020

#130 in Math

33 downloads per month
Used in 3 crates

MIT/Apache

200KB
4.5K SLoC

Flexible Arithmetic Parser

Build Status License: MIT OR Apache-2.0 rust 1.70+ required no_std supported

Links: Docs.rs crate docs (master)

A versatile parser for arithmetic expressions which allows customizing literal definitions, type annotations and several other aspects of parsing.

Usage

Add this to your Crate.toml:

[dependencies]
arithmetic-parser = "0.4.0-beta.1"

The parser is overall similar to Rust. It supports variables, literals, comments, arithmetic and boolean operations, parentheses, function calls, tuples and tuple destructuring, function definitions, blocks, methods, and type annotations. In other words, the parser forms a foundation of a minimalistic scripting language, while leaving certain aspects up to user (most of all, specification of literals).

See the crate docs for more details on the supported syntax features.

Code sample

Here is an example of code parsed with the grammar with real-valued literals and the only supported type Num:

// This is a comment.
x = 1 + 2.5 * 3 + sin(a^3 / b^2);

// Function declarations have syntax similar to Rust closures.
some_function = |x| {
    r = min(rand(), 0.5);
    r * x
};

// Objects are similar to JavaScript, except they require
// a preceding hash `#`, like in Rhai (https://rhai.rs/).
other_function = |a, b: Num| #{ sum: a + b, diff: a - b };

// Object destructuring is supported as well.
{ sum, diff: Num } = other_function(
    x,
    // Blocks are supported and have a similar syntax to Rust.
    some_function({ x = x - 0.5; x }),
);

// Tuples have syntax similar to Rust (besides spread syntax
// in destructuring, which is similar to one in JavaScript).
(x, ...tail) = (1, 2).map(some_function);

Implementation details

The parser is based on the nom crate. The core trait of the library, Grammar, is designed in such a way that switching optional features should not induce run-time overhead; the unused parsing code paths should be removed during compilation.

See also

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in arithmetic-parser by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~1.2–1.6MB
~30K SLoC