public static Parser <List <T>, TToken> Many <T, TToken>(this Parser <T, TToken> parser, int least = 0, int most = int.MaxValue)
        {
            if (parser is null)
            {
                throw new ArgumentNullException(nameof(parser));
            }

            return(input =>
            {
                List <T> elements = new List <T>();
                LexemeString <TToken> remainder = input;

                for (int i = 0; i <= most; i++)
                {
                    var result = parser(remainder);

                    if (!result.IsSuccessful)
                    {
                        if (i < least)
                        {
                            return ParserResult.Error <T, List <T>, TToken>(result);
                            //return ParserResult.Error<List<T>, TToken>("Too few elements. Expected at least " + least, remainder);
                        }

                        return ParserResult.Success(elements, remainder);
                    }

                    elements.Add(result.Result);

                    remainder = result.RemainingLexemes;
                }

                return ParserResult.Success(elements, remainder);
            });
        }
Example #2
0
 /// <summary>
 /// Returns a parser success of <paramref name="value"/>.
 /// </summary>
 /// <typeparam name="T">The return type of the parser.</typeparam>
 /// <typeparam name="TToken">The type of the tokens.</typeparam>
 /// <param name="value">The value to succeed with.</param>
 /// <returns>The parser created.</returns>
 public static Parser <T, TToken> Value <T, TToken>(T value) =>
 input => ParserResult.Success(value, input);
Example #3
0
 /// <summary>
 /// Parses a singular lexeme from the input and advances the input by one.
 /// Returns an error with <paramref name="errorMessage"/> if the input is empty.
 /// </summary>
 /// <typeparam name="TToken">The type of the tokens.</typeparam>
 /// <param name="errorMessage">The error message to return.</param>
 /// <returns>The parser created.</returns>
 public static Parser <Lexeme <TToken>, TToken> One <TToken>(string errorMessage) =>
 input =>
 input.Length == 0
         ? ParserResult.Error <Lexeme <TToken>, TToken>(errorMessage, input)
         : ParserResult.Success(input[0], input.Advance(1));