Exemplo n.º 1
0
        /// <summary>
        /// Constructs a parser that returns the <see cref="ITextSpan{T}"/> of the parsed value.
        /// </summary>
        /// <typeparam name="T">The result type of the given parser.</typeparam>
        /// <param name="parser">The parser to wrap.</param>
        /// <returns>A parser for the text span of the given parser.</returns>
        public static Parser <ITextSpan <T> > Span <T>(this Parser <T> parser)
        {
            if (parser == null)
            {
                throw new ArgumentNullException(nameof(parser));
            }

            return(i =>
            {
                var r = parser(i);
                if (r.WasSuccessful)
                {
                    var span = new TextSpan <T>
                    {
                        Value = r.Value,
                        Start = Position.FromInput(i),
                        End = Position.FromInput(r.Remainder),
                        Length = r.Remainder.Position - i.Position,
                    };

                    return Result.Success(span, r.Remainder);
                }

                return Result.Failure <ITextSpan <T> >(r.Remainder, r.Message, r.Expectations);
            });
        }
Exemplo n.º 2
0
        /// <summary>
        /// Parses the specified input string.
        /// </summary>
        /// <typeparam name="T">The type of the result.</typeparam>
        /// <param name="parser">The parser.</param>
        /// <param name="input">The input.</param>
        /// <returns>The result of the parser.</returns>
        /// <exception cref="Sprache.ParseException">It contains the details of the parsing error.</exception>
        public static T Parse <T>(this Parser <T> 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));
        }