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
// pest. Elegant, efficient grammars // Copyright (C) 2016 Dragoș Tiselice // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! # pest. Elegant, efficient grammars //! //! pest is a [PEG](https://en.wikipedia.org/wiki/Parsing_expression_grammar) parser generator with //! *simplicity* and *speed* in mind. //! //! ## Input & Parser //! //! pest works mainly through two `trait`s: `Input` & `Parser`. `Input` is used to remember the //! current position or index of the to-be-parsed input. It also knows how to match a `&str` or //! `char` range against the current position. If it did in fact match, it advances the input by //! incrementing the position. //! //! ``` //! # use pest::Input; //! # use pest::StringInput; //! let mut input = StringInput::new("asdasdf"); // Input mutates its position //! //! assert_eq!(input.pos(), 0); // matching starts from 0, before 'a' //! //! assert!(input.match_string("asd")); // Input::match_string matches "asd"; returns true //! //! assert_eq!(input.pos(), 3); // last match advances the parser by "asd".len() //! //! assert!(input.match_range('a', 'z')); // Input::match_range matches 'a'; returns true //! //! assert_eq!(input.pos(), 4); // last match advances the parser by 1 //! ``` //! //! `Input` is also supposed to return a `&str` `slice` of its input by calling //! [`Input::slice`](trait.Input#tymethod.slice). //! //! `Parser` gets constructed on top of an `Input` and delegates position access to //! [`Parser::pos`](trait.Parser#tymethod.pos) and //! [`Parser::set_pos`](trait.Parser#tymethod.set_pos). Apart from this, `Parser` also gives access //! to its `Token` queue and expected rules to match when it fails. //! //! ## grammar! //! //! The [`grammar!`](macro.grammar!) `macro` processes every rule and generates a method on a //! `Parser` that returns whether the rule has matched its `Input`. `grammar!` can only be used //! inside of [`impl_rdp!`](macro.impl_rdp!) right now until other parser algorithms are //! implemented. //! //! *Note:* `grammar!` may require you to increase the recursion limit of your create with //! `#![recursion_limit = "*"]` where * is the new limit. //! //! When `impl_rdp!` is run, it implements an `enum` called `Rule` that has a value for all //! [non-silent](macro.grammar!#silent-rules-_) rules, but also for //! [`any` and `eoi`](macro.grammar!). These `Rule`s are used within `Token`s to specify the type //! of rule that matched. These `Tokens` are accesible from //! [`Parser::queue`](trait.Parser#tymethod.queue) after parsing. Instead of having the shape of //! an AST, the `Token`s come in a `Vec` in a predefined order that makes them easy to process. //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! impl_rdp! { //! grammar! { //! expression = _{ paren ~ expression? } // expression is silent so we'll only have parens //! paren = { ["("] ~ expression? ~ [")"] } //! } //! } //! //! let mut parser = Rdp::new(StringInput::new("(())()")); //! // ^--^ - Token { paren, 0, 4 }; queue[0] //! // ^^ - Token { paren, 1, 3 }; queue[1] //! // ^^ - Token { paren, 4, 6 }; queue[2] //! //! assert!(parser.expression()); //! assert!(parser.end()); //! //! let queue = vec![ //! Token::new(Rule::paren, 0, 4), //! Token::new(Rule::paren, 1, 3), //! Token::new(Rule::paren, 4, 6) //! ]; //! //! assert_eq!(parser.queue(), &queue); //! # } //! ``` //! //! `Rule`s are also used for error reporting through //! [`Parser::queue`](trait.Parser#tymethod.queue) which is used when a `Parser` failed to parse //! and you want to see what `Rule`s it expected at the last possible position. //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! impl_rdp! { //! grammar! { //! expression = _{ paren ~ expression? } // expression is silent so we'll only have parens //! paren = { ["("] ~ expression? ~ [")"] } //! } //! } //! //! let mut parser = Rdp::new(StringInput::new("(())()foo")); //! // ^ - Parser should expect a paren at pos 6 //! //! assert!(parser.expression()); // the parser goes as deep as it can //! assert!(!parser.end()); // end is not reached, so the whole Input was not matched //! //! assert_eq!(parser.expected(), (vec![Rule::paren], 6)); //! # } //! ``` //! //! *Note:* You can use the `eoi` rule instead of calling //! [`Parser::end`](trait.Parser#tymethod.end) manually. //! //! # Calculator example //! //! This example will concentrate on parsing and solving simple airthmetic with parens, additions, //! subtractions, multiplications, and divisions. //! //! Let's start with defining a rule that matches integers. We first need to match an optional //! `"-"`. //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! impl_rdp! { //! grammar! { //! number = { ["-"]? } //! } //! } //! //! let mut parser = Rdp::new(StringInput::new("-")); //! //! assert!(parser.number()); //! assert!(parser.end()); //! # } //! ``` //! //! In order to match a number, we should deal with two cases: //! //! * number is `0` //! * number is any other number *not* starting with `0` //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! impl_rdp! { //! grammar! { //! number = { ["-"]? ~ (["0"] | ['1'..'9'] ~ ['0'..'9']*) } //! // | | | | | | | | ^ zero or more //! // | | | | | | | ^ digit //! // | | | | | | ^ followed by //! // | | | | | ^ non-zero digit //! // | | | | ^ or //! // | | | ^ zero //! // | | ^ followed by //! // | ^ optional //! // ^ minus //! } //! } //! //! let mut parser = Rdp::new(StringInput::new("-90")); //! //! assert!(parser.number()); //! assert!(parser.end()); //! # } //! ``` //! //! Now let's add operator rules. //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! impl_rdp! { //! grammar! { //! number = { ["-"]? ~ (["0"] | ['1'..'9'] ~ ['0'..'9']*) } //! plus = { ["+"] } //! minus = { ["-"] } //! times = { ["*"] } //! slash = { ["/"] } //! } //! } //! # //! # let mut parser = Rdp::new(StringInput::new("-90")); //! # //! # assert!(parser.number()); //! # assert!(parser.end()); //! # } //! ``` //! //! Because infix precedence is hard to implement in PEG and quite inefficient, pest comes with a //! [rule](macro.grammar!#precedence-climbing) that implements [precedence climbing] //! (https://en.wikipedia.org/wiki/Operator-precedence_parser#Precedence_climbing_method). //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! impl_rdp! { //! grammar! { //! expression = { //! { number } // primary rule is a number //! addition = { plus | minus } // precedence 0 is addition //! multiplication = { times | slash } // precedence 1 is multiplication //! } //! number = { ["-"]? ~ (["0"] | ['1'..'9'] ~ ['0'..'9']*) } //! plus = { ["+"] } //! minus = { ["-"] } //! times = { ["*"] } //! slash = { ["/"] } //! } //! } //! # //! # let mut parser = Rdp::new(StringInput::new("-90")); //! # //! # assert!(parser.number()); //! # assert!(parser.end()); //! # } //! ``` //! //! Before we go any further, let's see what parsing a `number` from an `expression` places on to //! the queue. //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! # impl_rdp! { //! # grammar! { //! # expression = { //! # { number } // primary rule is a number //! # addition = { plus | minus } // precedence 0 is addition //! # multiplication = { times | slash } // precedence 1 is multiplication //! # } //! # number = { ["-"]? ~ (["0"] | ['1'..'9'] ~ ['0'..'9']*) } //! # plus = { ["+"] } //! # minus = { ["-"] } //! # times = { ["*"] } //! # slash = { ["/"] } //! # } //! # } //! # //! let mut parser = Rdp::new(StringInput::new("-90")); //! //! assert!(parser.expression()); //! assert!(parser.end()); //! //! println!("{:?}", parser.queue()); // [Token { rule: expression, start: 0, end: 3 }, //! // Token { rule: number, start: 0, end: 3 }] //! # } //! ``` //! //! Since we're already parsing an `expression` and don't care about its length, we can make it //! [silent](macro.grammar!#silent-rules-_). //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! impl_rdp! { //! grammar! { //! expression = _{ // the underscore tells pest that this rule is silent //! { number } //! addition = { plus | minus } //! multiplication = { times | slash } //! } //! number = { ["-"]? ~ (["0"] | ['1'..'9'] ~ ['0'..'9']*) } //! plus = { ["+"] } //! minus = { ["-"] } //! times = { ["*"] } //! slash = { ["/"] } //! } //! } //! //! let mut parser = Rdp::new(StringInput::new("-90")); //! //! assert!(parser.expression()); //! assert!(parser.end()); //! //! let queue = vec![ //! Token::new(Rule::number, 0, 3) //! ]; //! //! assert_eq!(parser.queue(), &queue); //! # } //! ``` //! //! Adding parens to the whole business is as easy as adding a paren rule to the primary rule of //! the precedence climber. //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! impl_rdp! { //! grammar! { //! expression = _{ //! { ["("] ~ expression ~ [")"] | number } //! addition = { plus | minus } //! multiplication = { times | slash } //! } //! number = { ["-"]? ~ (["0"] | ['1'..'9'] ~ ['0'..'9']*) } //! plus = { ["+"] } //! minus = { ["-"] } //! times = { ["*"] } //! slash = { ["/"] } //! } //! } //! //! let mut parser = Rdp::new(StringInput::new("((-90))")); //! //! assert!(parser.expression()); //! assert!(parser.end()); //! //! let queue = vec![ //! Token::new(Rule::number, 2, 5) //! ]; //! //! assert_eq!(parser.queue(), &queue); //! # } //! ``` //! //! Before we get to the processing of the `Token`s, let's also add white-space to the grammar. //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! impl_rdp! { //! grammar! { //! expression = _{ //! { ["("] ~ expression ~ [")"] | number } //! addition = { plus | minus } //! multiplication = { times | slash } //! } //! number = { ["-"]? ~ (["0"] | ['1'..'9'] ~ ['0'..'9']*) } //! plus = { ["+"] } //! minus = { ["-"] } //! times = { ["*"] } //! slash = { ["/"] } //! //! whitespace = _{ [" "] } //! } //! } //! //! let mut parser = Rdp::new(StringInput::new("2 + 2")); //! //! assert!(parser.expression()); //! assert!(parser.end()); //! # } //! ``` //! //! But now trying to parse `"9 9"` will work and recognize it as a `number`. //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! # impl_rdp! { //! # grammar! { //! # expression = _{ //! # { ["("] ~ expression ~ [")"] | number } //! # addition = { plus | minus } //! # multiplication = { times | slash } //! # } //! # number = { ["-"]? ~ (["0"] | ['1'..'9'] ~ ['0'..'9']*) } //! # plus = { ["+"] } //! # minus = { ["-"] } //! # times = { ["*"] } //! # slash = { ["/"] } //! # //! # whitespace = _{ [" "] } //! # } //! # } //! # //! let mut parser = Rdp::new(StringInput::new("9 9")); //! //! assert!(parser.expression()); //! assert!(parser.end()); //! //! let queue = vec![ //! Token::new(Rule::number, 0, 3) //! ]; //! //! assert_eq!(parser.queue(), &queue); //! # } //! ``` //! //! To solve this issue, we make `number` [atomic](macro.grammar!#atomic-rules-), stopping any //! white-space matching inside of the rule. //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! impl_rdp! { //! grammar! { //! expression = _{ //! { ["("] ~ expression ~ [")"] | number } //! addition = { plus | minus } //! multiplication = { times | slash } //! } //! number = @{ ["-"]? ~ (["0"] | ['1'..'9'] ~ ['0'..'9']*) } //! plus = { ["+"] } //! minus = { ["-"] } //! times = { ["*"] } //! slash = { ["/"] } //! //! whitespace = _{ [" "] } //! } //! } //! //! let mut parser = Rdp::new(StringInput::new("9 9")); //! //! assert!(parser.expression()); //! assert!(!parser.end()); //! # } //! ``` //! //! To process all these `Token`s we'll use the [`process!`](macro.process!) `macro`. This `macro` //! defines matcher methods on the `Parser` that pattern match against a set of `Token`s from the //! front of the queue, calling themselves recursively until everything matched and returned its //! result. //! //! Let's start by defining the signature of the `compute` matcher that will do the computation. We //! need it to return an `i32` in the end. //! //! ```ignore //! compute(&self) -> i32 //! ``` //! //! Now all we need to do is to write the three cases of interest, namely `number`, `addition`, and //! `multiplication`. `number` is captured (its `&str` is being sliced from the `Input`) with the //! `&` pattern and then parsed to an `i32`. //! //! ```ignore //! (&number: number) => number.parse::<i32>().unwrap() //! ``` //! //! `addition` and `multiplication` are virtually identical: //! //! * match the `addition`/`multiplication` `Token` without using it //! * recursively process the left-hand-side by calling `compute` //! * use the `sign` `Token` without capturing its `&str` value //! * recursively process the right-hand-side by calling `compute` //! * match `sign` inside the block and return the appropriate result //! //! ```ignore //! (_: addition, left: compute(), sign, right: compute()) => { //! match sign.rule { //! Rule::plus => left + right, //! Rule::minus => left - right, //! _ => unreachable!() //! } //! }, //! (_: multiplication, left: compute(), sign, right: compute()) => { //! match sign.rule { //! Rule::times => left * right, //! Rule::slash => left / right, //! _ => unreachable!() //! } //! } //! ``` //! //! The reason we're matching `sign` manually inside of the block is because using `_: plus` and //! `_: minus` will cause `left: main()` to be run twice in case the first rule fails. Caching the //! result in this case is non-trivial apart from the fact that duplicate complex patterns are not //! necessarily easier to read. //! //! Now for the whole example: //! //! ``` //! # #[macro_use] extern crate pest; //! # use pest::Parser; //! # use pest::Token; //! # use pest::Input; //! # use pest::StringInput; //! # fn main() { //! impl_rdp! { //! grammar! { //! expression = _{ //! { ["("] ~ expression ~ [")"] | number } //! addition = { plus | minus } //! multiplication = { times | slash } //! } //! number = @{ ["-"]? ~ (["0"] | ['1'..'9'] ~ ['0'..'9']*) } //! plus = { ["+"] } //! minus = { ["-"] } //! times = { ["*"] } //! slash = { ["/"] } //! //! whitespace = _{ [" "] } //! } //! //! process! { //! compute(&self) -> i32 { //! (&number: number) => number.parse::<i32>().unwrap(), //! (_: addition, left: compute(), sign, right: compute()) => { //! match sign.rule { //! Rule::plus => left + right, //! Rule::minus => left - right, //! _ => unreachable!() //! } //! }, //! (_: multiplication, left: compute(), sign, right: compute()) => { //! match sign.rule { //! Rule::times => left * right, //! Rule::slash => left / right, //! _ => unreachable!() //! } //! } //! } //! } //! } //! //! let mut parser = Rdp::new(StringInput::new("(3 + (9 + 3 * 4 + (3 + 1) / 2 - 4)) * 2")); //! //! assert!(parser.expression()); //! assert_eq!(parser.compute(), 44); //! # } //! ``` #[macro_use] mod grammar; #[macro_use] mod process; #[macro_use] mod parsers; mod input; mod inputs; mod parser; pub mod prelude; pub use input::Input; pub use inputs::StringInput; pub use parser::Parser; pub use parsers::Token;