Skip to content

Commit 11b516f

Browse files
cwfitzgeraldlihaoyi
authored andcommitted
Add Documentation for Higher Order Parsers (#212)
* Add documentation of higher-order parsers * Fix error in higher order example * Fix incorrect assert in higher order example
1 parent 4a40500 commit 11b516f

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

fastparse/test/src/fastparse/ExampleTests.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,15 @@ object ExampleTests extends TestSuite{
512512
}
513513
}
514514

515+
'higherorder{
516+
def Indexed[_: P, T](p: => P[T]): P[(Int, T, Int)] = P( Index ~ p ~ Index )
517+
518+
def Add[_: P] = P( Num ~ "+" ~ Num )
519+
def Num[_: P] = Indexed( CharsWhileIn("0-9").rep.! )
520+
521+
val Parsed.Success((0, "1", 1, (2, "2", 3)), _) = parse("1+2", Add(_))
522+
}
523+
515524
'folding{
516525
sealed trait AndOr
517526
case object And extends AndOr

readme/WritingParsers.scalatex

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,3 +418,19 @@
418418
To explicitly isolate a cut to one branch of a parser, place that branch within @hl.scala{NoCut}. Cuts within that branch will prevent backtracking inside that branch, but if that branch fails alternate branches will be tried as normal.
419419

420420
@hl.ref(tests/"ExampleTests.scala", Seq("'composenocut", ""))
421+
422+
@sect{Higher Order Parsers}
423+
424+
@p
425+
It is possible to write functions that take parsers as arguments and return other parsers. These are useful because it allows for the programmatic modification of many different parsers. This can be used to generate a large amount of parsers that only vary in minor ways.
426+
427+
@p
428+
Parser arguments @b{must be passed by name}! Parsers are immediately evaluated, so if they aren't passed by name they will be evaluated when they are passed into a function, not within it, causing either a warning about @hl.scala{a pure expression does nothing in statement position} at compile time or a @hl.scala{ClassCastException} at runtime.
429+
430+
@p
431+
A simple example of a higher order parser is one that adds index information to the beginning and end of the parse.
432+
433+
@hl.ref(tests/"ExampleTests.scala", Seq("'higherorder", ""))
434+
435+
@p
436+
While this is a simple example, this concept to be extended to your hearts content.

0 commit comments

Comments
 (0)