1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
//! Parser for arithmetic expressions with flexible definition of literals and support //! of type annotations. //! //! Overall, parsed grammars are similar to Rust syntax, //! [with a few notable differences](#differences-with-rust). //! //! # Supported syntax features //! //! - **Variables.** A variable name is defined similar to Rust and other programming languages, //! as a sequence of alphanumeric chars and underscores that does not start with a digit. //! - **Literals.** The parser for literals is user-provided, thus allowing to apply the library //! to different domains (e.g., finite group arithmetic). //! - `//` and `/* .. */` **comments**. //! - Basic **arithmetic operations**: `+`, `-` (binary and unary), `*`, `/`, `^` (power). //! The parser outputs AST with nodes organized according to the operation priority. //! - **Function calls**: `foo(1.0, x)`. //! - **Parentheses** which predictably influence operation priority. //! //! The parser supports both complete and streaming (incomplete) modes; the latter is useful //! for REPLs and similar applications. //! //! ## Optional syntax features //! //! These features can be switched on or off when defining a [`Parse`](grammars::Parse) impl //! by declaring the corresponding [`Features`](grammars::Features). //! //! - **Tuples.** A tuple is two or more elements separated by commas, such as `(x, y)` //! or `(1, 2 * x)`. Tuples are parsed both as lvalues and rvalues. //! - **Tuple destructuring.** Using a tuple as an lvalue, for example, `(x, y, z) = foo`. //! The "rest" syntax is also supported, either named or unnamed: `(head, ...tail) = foo`, //! `(a, ..., b, c) = foo`. //! - **Function definitions.** A definition looks like a closure definition in Rust, e.g., //! `|x| x - 10` or `|x, y| { z = max(x, y); (z - x, z - y) }`. A definition may be //! assigned to a variable (which is the way to define named functions). //! - **Destructuring for function args.** Similar to tuple destructuring, it is possible to //! destructure and group args in function definitions, for example, `|(x, y), ...zs| { }`. //! - **Blocks.** A block is several `;`-delimited statements enclosed in `{}` braces, //! e.g, `{ z = max(x, y); (z - x, z - y) }`. The blocks can be used in all contexts //! instead of a simple expression; for example, `min({ z = 5; z - 1 }, 3)`. //! - **Methods.** Method call is a function call separated from the receiver with a `.` char; //! for example, `foo.bar(2, x)`. //! - **Type annotations.** A type annotation in the form `var: Type` can be present //! in the lvalues or in the function argument definitions. The parser for type annotations //! is user-defined. //! - **Boolean operations**: `==`, `!=`, `&&`, `||`, `!`. //! - **Order comparisons,** that is, `>`, `<`, `>=`, and `<=` boolean ops. //! //! ## Differences with Rust //! //! *(within shared syntax constructs; of course, Rust is much more expressive)* //! //! - No keyword for assigning a variable (i.e., no `let` / `let mut`). There are no //! keywords in general. //! - Functions are only defined via the closure syntax. //! - There is "rest" destructuting for tuples and function arguments. //! - Type hints are placed within tuple elements, for example, `(x: Num, _) = y`. //! //! # Crate features //! //! - `std`. Enables support of types from `std`, such as the `Error` trait, and propagates //! to dependencies. //! - `num-complex`. Implements [`NumLiteral`](crate::grammars::NumLiteral) for floating-point //! complex numbers (`Complex32` and `Complex64`). //! - `num-bigint`. Implements [`NumLiteral`](crate::grammars::NumLiteral) for `BigInt` and //! `BigUint` from the `num-bigint` crate. //! //! # Examples //! //! Using a grammar for arithmetic on real values. //! //! ``` //! # use assert_matches::assert_matches; //! use arithmetic_parser::{ //! grammars::{F32Grammar, Parse, Untyped}, //! NomResult, Statement, Expr, FnDefinition, LvalueLen, //! }; //! //! const PROGRAM: &str = r#" //! // This is a comment. //! x = 1 + 2.5 * 3 + sin(a^3 / b^2 /* another comment */); //! // 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) //! "#; //! //! # fn main() -> anyhow::Result<()> { //! let block = Untyped::<F32Grammar>::parse_statements(PROGRAM)?; //! // 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() //! ); //! # Ok(()) //! # } //! ``` #![cfg_attr(not(feature = "std"), no_std)] #![doc(html_root_url = "https://docs.rs/arithmetic-parser/0.2.0")] #![warn(missing_docs, missing_debug_implementations)] #![warn(clippy::all, clippy::pedantic)] #![allow( clippy::missing_errors_doc, clippy::must_use_candidate, clippy::module_name_repetitions )] // Polyfill for `alloc` types. mod alloc { #[cfg(not(feature = "std"))] extern crate alloc; #[cfg(not(feature = "std"))] pub use alloc::{borrow::ToOwned, boxed::Box, format, string::String, vec, vec::Vec}; #[cfg(feature = "std")] pub use std::{borrow::ToOwned, boxed::Box, format, string::String, vec, vec::Vec}; } pub use crate::{ error::{Context, Error, ErrorKind, SpannedError}, ops::{BinaryOp, Op, OpPriority, UnaryOp}, parser::is_valid_variable_name, spans::{ CodeFragment, InputSpan, LocatedSpan, MaybeSpanned, NomResult, Spanned, StripCode, StripResultExt, }, }; use core::fmt; use crate::{ alloc::{vec, Box, Vec}, grammars::Grammar, }; mod error; pub mod grammars; mod ops; mod parser; mod spans; /// Arithmetic expression with an abstract types for type hints and literals. #[derive(Debug)] #[non_exhaustive] pub enum Expr<'a, T: Grammar> { /// Variable use, e.g., `x`. Variable, /// Literal (semantic depends on `T`). Literal(T::Lit), /// Function definition, e.g., `|x, y| { x + y }`. FnDefinition(FnDefinition<'a, T>), /// Function call, e.g., `foo(x, y)` or `|x| { x + 5 }(3)`. Function { /// Function value. In the simplest case, this is a variable, but may also be another /// kind of expression, such as `|x| { x + 5 }` in `|x| { x + 5 }(3)`. name: Box<SpannedExpr<'a, T>>, /// Function arguments. args: Vec<SpannedExpr<'a, T>>, }, /// Method call, e.g., `foo.bar(x, 5)`. Method { /// Name of the called method, e.g. `bar` in `foo.bar(x, 5)`. name: Spanned<'a>, /// Receiver of the call, e.g., `foo` in `foo.bar(x, 5)`. receiver: Box<SpannedExpr<'a, T>>, /// Arguments; e.g., `x, 5` in `foo.bar(x, 5)`. args: Vec<SpannedExpr<'a, T>>, }, /// Unary operation, e.g., `-x`. Unary { /// Operator. op: Spanned<'a, UnaryOp>, /// Inner expression. inner: Box<SpannedExpr<'a, T>>, }, /// Binary operation, e.g., `x + 1`. Binary { /// LHS of the operation. lhs: Box<SpannedExpr<'a, T>>, /// Operator. op: Spanned<'a, BinaryOp>, /// RHS of the operation. rhs: Box<SpannedExpr<'a, T>>, }, /// Tuple expression, e.g., `(x, y + z)`. Tuple(Vec<SpannedExpr<'a, T>>), /// Block expression, e.g., `{ x = 3; x + y }`. Block(Block<'a, T>), } impl<T: Grammar> Expr<'_, T> { /// Returns LHS of the binary expression. If this is not a binary expression, returns `None`. pub fn binary_lhs(&self) -> Option<&SpannedExpr<'_, T>> { match self { Expr::Binary { ref lhs, .. } => Some(lhs), _ => None, } } /// Returns RHS of the binary expression. If this is not a binary expression, returns `None`. pub fn binary_rhs(&self) -> Option<&SpannedExpr<'_, T>> { match self { Expr::Binary { ref rhs, .. } => Some(rhs), _ => None, } } /// Returns the type of this expression. pub fn ty(&self) -> ExprType { match self { Self::Variable => ExprType::Variable, Self::Literal(_) => ExprType::Literal, Self::FnDefinition(_) => ExprType::FnDefinition, Self::Tuple(_) => ExprType::Tuple, Self::Block(_) => ExprType::Block, Self::Function { .. } => ExprType::Function, Self::Method { .. } => ExprType::Method, Self::Unary { .. } => ExprType::Unary, Self::Binary { .. } => ExprType::Binary, } } } impl<T: Grammar> Clone for Expr<'_, T> { fn clone(&self) -> Self { match self { Self::Variable => Self::Variable, Self::Literal(lit) => Self::Literal(lit.clone()), Self::FnDefinition(function) => Self::FnDefinition(function.clone()), Self::Tuple(tuple) => Self::Tuple(tuple.clone()), Self::Block(block) => Self::Block(block.clone()), Self::Function { name, args } => Self::Function { name: name.clone(), args: args.clone(), }, Self::Method { name, receiver, args, } => Self::Method { name: *name, receiver: receiver.clone(), args: args.clone(), }, Self::Unary { op, inner } => Self::Unary { op: *op, inner: inner.clone(), }, Self::Binary { op, lhs, rhs } => Self::Binary { op: *op, lhs: lhs.clone(), rhs: rhs.clone(), }, } } } impl<T> PartialEq for Expr<'_, T> where T: Grammar, T::Lit: PartialEq, T::Type: PartialEq, { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Variable, Self::Variable) => true, (Self::Literal(this), Self::Literal(that)) => this == that, (Self::FnDefinition(this), Self::FnDefinition(that)) => this == that, (Self::Tuple(this), Self::Tuple(that)) => this == that, (Self::Block(this), Self::Block(that)) => this == that, ( Self::Function { name, args }, Self::Function { name: that_name, args: that_args, }, ) => name == that_name && args == that_args, ( Self::Method { name, receiver, args, }, Self::Method { name: that_name, receiver: that_receiver, args: that_args, }, ) => name == that_name && receiver == that_receiver && args == that_args, ( Self::Unary { op, inner }, Self::Unary { op: that_op, inner: that_inner, }, ) => op == that_op && inner == that_inner, ( Self::Binary { lhs, op, rhs }, Self::Binary { lhs: that_lhs, op: that_op, rhs: that_rhs, }, ) => op == that_op && lhs == that_lhs && rhs == that_rhs, _ => false, } } } /// `Expr` with the associated type and code span. pub type SpannedExpr<'a, T> = Spanned<'a, Expr<'a, T>>; /// Type of an `Expr`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ExprType { /// Variable use, e.g., `x`. Variable, /// Literal (semantic depends on the grammar). Literal, /// Function definition, e.g., `|x, y| { x + y }`. FnDefinition, /// Function call, e.g., `foo(x, y)` or `|x| { x + 5 }(3)`. Function, /// Method call, e.g., `foo.bar(x, 5)`. Method, /// Unary operation, e.g., `-x`. Unary, /// Binary operation, e.g., `x + 1`. Binary, /// Tuple expression, e.g., `(x, y + z)`. Tuple, /// Block expression, e.g., `{ x = 3; x + y }`. Block, } impl fmt::Display for ExprType { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str(match self { Self::Variable => "variable", Self::Literal => "literal", Self::FnDefinition => "function definition", Self::Function => "function call", Self::Method => "method call", Self::Unary => "unary operation", Self::Binary => "binary operation", Self::Tuple => "tuple", Self::Block => "block", }) } } /// Length of an assigned lvalue. #[derive(Debug, Clone, Copy, PartialEq)] #[non_exhaustive] pub enum LvalueLen { /// Exact length. Exact(usize), /// Minimum length. AtLeast(usize), } impl LvalueLen { /// Checks if this length matches the provided length of the rvalue. pub fn matches(self, value: usize) -> bool { match self { Self::Exact(len) => value == len, Self::AtLeast(len) => value >= len, } } } impl fmt::Display for LvalueLen { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Exact(len) => write!(formatter, "{}", len), Self::AtLeast(len) => write!(formatter, "at least {}", len), } } } impl From<usize> for LvalueLen { fn from(value: usize) -> Self { Self::Exact(value) } } /// Tuple destructuring, such as `(a, b, ..., c)`. #[derive(Debug, Clone, PartialEq)] pub struct Destructure<'a, T> { /// Start part of the destructuring, e.g, `a` and `b` in `(a, b, ..., c)`. pub start: Vec<SpannedLvalue<'a, T>>, /// Middle part of the destructuring, e.g., `rest` in `(a, b, ...rest, _)`. pub middle: Option<Spanned<'a, DestructureRest<'a, T>>>, /// End part of the destructuring, e.g., `c` in `(a, b, ..., c)`. pub end: Vec<SpannedLvalue<'a, T>>, } impl<T> Destructure<'_, T> { /// Returns the length of destructured elements. pub fn len(&self) -> LvalueLen { if self.middle.is_some() { LvalueLen::AtLeast(self.start.len() + self.end.len()) } else { LvalueLen::Exact(self.start.len()) } } /// Checks if the destructuring is empty. pub fn is_empty(&self) -> bool { self.start.is_empty() } } /// Rest syntax, such as `...rest` in `(a, ...rest, b)`. #[derive(Debug, Clone, PartialEq)] pub enum DestructureRest<'a, T> { /// Unnamed rest syntax, i.e., `...`. Unnamed, /// Named rest syntax, e.g., `...rest`. Named { /// Variable span, e.g., `rest`. variable: Spanned<'a>, /// Type annotation of the value. ty: Option<Spanned<'a, T>>, }, } impl<'a, T> DestructureRest<'a, T> { /// Tries to convert this rest declaration into an lvalue. Return `None` if the rest declaration /// is unnamed. pub fn to_lvalue(&self) -> Option<SpannedLvalue<'a, T>> { match self { Self::Named { variable, .. } => { Some(variable.copy_with_extra(Lvalue::Variable { ty: None })) } _ => None, } } } /// Assignable value. #[derive(Debug, Clone, PartialEq)] #[non_exhaustive] pub enum Lvalue<'a, T> { /// Simple variable, e.g., `x`. Variable { /// Type annotation of the value. ty: Option<Spanned<'a, T>>, }, /// Tuple destructuring, e.g., `(x, y)`. Tuple(Destructure<'a, T>), } impl<T> Lvalue<'_, T> { /// Returns type of this lvalue. pub fn ty(&self) -> LvalueType { match self { Self::Variable { .. } => LvalueType::Variable, Self::Tuple(_) => LvalueType::Tuple, } } } /// [`Lvalue`] with the associated code span. pub type SpannedLvalue<'a, T> = Spanned<'a, Lvalue<'a, T>>; /// Type of an [`Lvalue`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum LvalueType { /// Simple variable, e.g., `x`. Variable, /// Tuple destructuring, e.g., `(x, y)`. Tuple, } impl fmt::Display for LvalueType { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str(match self { Self::Variable => "simple variable", Self::Tuple => "tuple destructuring", }) } } /// Statement: an expression or a variable assignment. #[derive(Debug)] #[non_exhaustive] pub enum Statement<'a, T: Grammar> { /// Expression, e.g., `x + (1, 2)`. Expr(SpannedExpr<'a, T>), /// Assigment, e.g., `(x, y) = (5, 8)`. Assignment { /// LHS of the assignment. lhs: SpannedLvalue<'a, T::Type>, /// RHS of the assignment. rhs: Box<SpannedExpr<'a, T>>, }, } impl<T: Grammar> Statement<'_, T> { /// Returns the type of this statement. pub fn ty(&self) -> StatementType { match self { Self::Expr(_) => StatementType::Expr, Self::Assignment { .. } => StatementType::Assignment, } } } impl<T: Grammar> Clone for Statement<'_, T> { fn clone(&self) -> Self { match self { Self::Expr(expr) => Self::Expr(expr.clone()), Self::Assignment { lhs, rhs } => Self::Assignment { lhs: lhs.clone(), rhs: rhs.clone(), }, } } } impl<T> PartialEq for Statement<'_, T> where T: Grammar, T::Lit: PartialEq, T::Type: PartialEq, { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Expr(this), Self::Expr(that)) => this == that, ( Self::Assignment { lhs, rhs }, Self::Assignment { lhs: that_lhs, rhs: that_rhs, }, ) => lhs == that_lhs && rhs == that_rhs, _ => false, } } } /// Statement with the associated code span. pub type SpannedStatement<'a, T> = Spanned<'a, Statement<'a, T>>; /// Type of a [`Statement`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum StatementType { /// Expression, e.g., `x + (1, 2)`. Expr, /// Assigment, e.g., `(x, y) = (5, 8)`. Assignment, } impl fmt::Display for StatementType { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str(match self { Self::Expr => "expression", Self::Assignment => "variable assignment", }) } } /// Block of statements. /// /// A block may end with a return expression, e.g., `{ x = 1; x }`. #[derive(Debug)] #[non_exhaustive] pub struct Block<'a, T: Grammar> { /// Statements in the block. pub statements: Vec<SpannedStatement<'a, T>>, /// The last statement in the block which is returned from the block. pub return_value: Option<Box<SpannedExpr<'a, T>>>, } impl<T: Grammar> Clone for Block<'_, T> { fn clone(&self) -> Self { Self { statements: self.statements.clone(), return_value: self.return_value.clone(), } } } impl<T> PartialEq for Block<'_, T> where T: Grammar, T::Lit: PartialEq, T::Type: PartialEq, { fn eq(&self, other: &Self) -> bool { self.return_value == other.return_value && self.statements == other.statements } } impl<T: Grammar> Block<'_, T> { /// Creates an empty block. pub fn empty() -> Self { Self { statements: vec![], return_value: None, } } } /// Function definition, e.g., `|x, y| x + y`. /// /// A function definition consists of a list of arguments and the function body. #[derive(Debug)] #[non_exhaustive] pub struct FnDefinition<'a, T: Grammar> { /// Function arguments, e.g., `x, y`. pub args: Spanned<'a, Destructure<'a, T::Type>>, /// Function body, e.g., `x + y`. pub body: Block<'a, T>, } impl<T: Grammar> Clone for FnDefinition<'_, T> { fn clone(&self) -> Self { Self { args: self.args.clone(), body: self.body.clone(), } } } impl<T> PartialEq for FnDefinition<'_, T> where T: Grammar, T::Lit: PartialEq, T::Type: PartialEq, { fn eq(&self, other: &Self) -> bool { self.args == other.args && self.body == other.body } }