using System;
namespace Sprache
{
///
/// Represents a parser.
///
/// The type of the result.
/// The input to parse.
/// The result of the parser.
public delegate IResult Parser(IInput input);
///
/// Contains some extension methods for .
///
public static class ParserExtensions
{
///
/// Tries to parse the input without throwing an exception.
///
/// The type of the result.
/// The parser.
/// The input.
/// The result of the parser
public static IResult TryParse(this Parser parser, string input)
{
if (parser == null) throw new ArgumentNullException(nameof(parser));
if (input == null) throw new ArgumentNullException(nameof(input));
return parser(new Input(input));
}
///
/// Parses the specified input string.
///
/// The type of the result.
/// The parser.
/// The input.
/// The result of the parser.
/// It contains the details of the parsing error.
public static T Parse(this Parser parser, string input)
{
if (parser == null) throw new ArgumentNullException(nameof(parser));
if (input == null) throw new ArgumentNullException(nameof(input));
var result = parser.TryParse(input);
if(result.WasSuccessful)
return result.Value;
throw new ParseException(result.ToString(), Position.FromInput(result.Remainder));
}
}
}