Internally, Parsica is designed using paradigms from functional programming. We list them here for anybody who's interested in FP, but you don't need to know them to work with Parsica.
Throughout this document,
$parser1 ≡ $parser2 means that you can swap
$parser2 and vice-versa, and it will not affect the outcome of your program.
Almost all the code is pure and referentially transparent. A notable exception is the combo of
Parser::recurse(). The latter mutates a
Parser. We constrained this so that you can't use the parser when it's not set up yet, and after calling
recurse(), you can't call it again. So not strictly pure, but close enough not to matter much in practice.
The combinators are all pure. Some combinators are implemented as instance methods on
Parser, but these are also pure. You can think of them as functions that take
$this as the first argument.
In fact, very often there are both a function and an instance method for the same combinator, where one is an alias for the other.
There are no generics in PHP 7.4, but we use thee Psalm static typechecker to simulate some of it. The two type are really
T is the type of the resulting output in the case of a successful parse.
ParseResult<T> is approximately an
Either<ParseFailure, ParseSuccess<T>> type.
Parser are functors, using the
ParseResult, the function is only applied to the output if
ParseResult::isSuccess() is true, and ignored in other cases.
Similarly, mapping over
Parser is really mapping over the future
ParseResult<T> is a monoid under the
ParseResult::append() operation, when
T is a monoid as well.
discard() is the zero value.
Parser<T> is a monoid under the
T is a monoid as well.
nothing() is the zero value.
Parser<T> is an applicative functor.
pure()is a parser that will always output its argument, no matter what the input was. Type:
T -> Parser<T>.
apply()is sequential application, aka
pure($callable)->apply($parser)is a parser that applies
$callableto the output of
$parser. It works for callables with multiple arguments, if the callable is curried:
pure(curry($callable))->apply($p1)->apply($p2). We used matteosister/php-curry to test this, but any method for currying functions should work.
*>respectively. Both parsers need to succeed but only the result from one of them is returned.
Parser<T> is a monad.
pure(): see above.
sequence()runs two parsers in sequence, dropping the result of the first one. Both parsers consume input. You may know this as
>>. The type of sequence is
Parser<T> -> Parser<T2> -> Parser<T2>.
bind()sequentially composes a parser and a parser-constructing function, passing the output produced by the first parser as an argument to the second. Both parsers consume input. You may know this as
Parser<T> -> (T -> Parser<T2>) -> Parser<T2>.