namespace Parsley
{
using System;
public static class ParserQuery
{
///
/// Converts any value into a parser that always succeeds with the given value in its reply.
///
///
/// In monadic terms, this is the 'Unit' function.
///
/// The type of the value to treat as a parse result.
/// The value to treat as a parse result.
public static Parser SucceedWithThisValue(this T value)
{
return new LambdaParser(tokens => new Parsed(value, tokens));
}
///
/// Allows LINQ syntax to construct a new parser from a simpler parser, using a single 'from' clause.
///
public static Parser Select(this Parser parser, Func constructResult)
{
return parser.Bind(t => constructResult(t).SucceedWithThisValue());
}
///
/// Allows LINQ syntax to contruct a new parser from an ordered sequence of simpler parsers, using multiple 'from' clauses.
///
public static Parser SelectMany(this Parser parser, Func> k, Func s)
{
return parser.Bind(x => k(x).Bind(y => s(x, y).SucceedWithThisValue()));
}
///
/// Extend a parser such that, after executing, the remaining input is processed by the next parser in the chain.
///
///
/// In monadic terms, this is the 'Bind' function.
///
private static Parser Bind(this Parser parser, Func> constructNextParser)
{
return new LambdaParser(tokens =>
{
var reply = parser.Parse(tokens);
if (reply.Success)
return constructNextParser(reply.Value).Parse(reply.UnparsedTokens);
return new Error(reply.UnparsedTokens, reply.ErrorMessages);
});
}
}
}