[−][src]Crate arithmetic_parser
Parser for arithmetic expressions with flexible definition of literals and support of type annotations.
Examples
Using a grammar for arithmetic on real values.
use arithmetic_parser::{ grammars::F32Grammar, GrammarExt, NomResult, Span, Statement, Expr, FnDefinition, LvalueLen, }; use nom::number::complete::float; const PROGRAM: &str = r#" # This is a comment. x = 1 + 2.5 * 3 + sin(a^3 / b^2); # Function declarations have syntax similar to Rust closures. some_function = |a, b| (a + b, a - b); other_function = |x| { r = min(rand(), 0.5); r * x }; # Tuples and blocks are supported and have a similar syntax to Rust. (y, z) = some_function({ x = x - 0.5; x }, x); other_function(y - z) "#; let block = F32Grammar::parse_statements(Span::new(PROGRAM)).unwrap(); // First statement is an assignment. assert_matches!( block.statements[0].extra, Statement::Assignment { ref lhs, .. } if lhs.fragment == "x" ); // The RHS of the second statement is a function. let some_function = match &block.statements[1].extra { Statement::Assignment { rhs, .. } => &rhs.extra, _ => panic!("Unexpected parsing result"), }; // This function has a single argument and a single statement in the body. assert_matches!( some_function, Expr::FnDefinition(FnDefinition { ref args, ref body }) if args.extra.len() == LvalueLen::Exact(2) && body.statements.is_empty() && body.return_value.is_some() );
Modules
| grammars | Standard grammars. |
Structs
| Block | Block of statements. |
| Destructure | Tuple destructuring, such as |
| Features | Parsing features for a |
| FnDefinition | Function definition, e.g., |
| SpannedError | Parsing error with the associated code span. |
Enums
| BinaryOp | Binary arithmetic operation. |
| Context | Parsing context. |
| DestructureRest | Rest syntax, such as |
| Error | Parsing error. |
| Expr | Arithmetic expression with an abstract types for type hints and literals. |
| Lvalue | Assignable value. |
| LvalueLen | Length of an assigned lvalue. |
| Op | Generic operation, either unary or binary. |
| Statement | Statement: an expression or a variable assignment. |
| UnaryOp | Unary operation. |
Traits
| Grammar | Unites all necessary parsers to form a complete grammar definition. |
| GrammarExt | Extension trait for |
Type Definitions
| NomResult | Parsing outcome generalized by the type returned on success. |
| Span | Code span. |
| Spanned | Value with an associated code span. |
| SpannedExpr |
|
| SpannedLvalue |
|
| SpannedStatement | Statement with the associated code span. |