CanonSharp/CanonSharp.Tests/Utils/GrammarParserTestBase.cs

32 lines
1.2 KiB
C#
Raw Normal View History

using CanonSharp.Combinator.Abstractions;
using CanonSharp.Pascal.Parser;
using CanonSharp.Pascal.Scanner;
using CanonSharp.Pascal.SyntaxTree;
namespace CanonSharp.Tests.Utils;
public abstract class GrammarParserTestBase
{
protected static T RunParser<T>(IParser<LexicalToken, SyntaxNodeBase> parser, string input) where T : SyntaxNodeBase
{
LexicalScanner scanner = new();
LexicalTokenReadState state = new(scanner.Tokenize(new StringReadState(input)));
IParseResult<LexicalToken, SyntaxNodeBase> parseResult = parser.Parse(state);
return parseResult.Value.Convert<T>();
}
protected static List<T> RunParser<T>(IParser<LexicalToken, IEnumerable<SyntaxNodeBase>> parser,
string input) where T : SyntaxNodeBase
{
LexicalScanner scanner = new();
LexicalTokenReadState state = new(scanner.Tokenize(new StringReadState(input)));
IParseResult<LexicalToken, IEnumerable<SyntaxNodeBase>> parseResult = parser.Parse(state);
return parseResult.Value.Select(node => node.Convert<T>()).ToList();
}
protected static Program ProgramParse(string input)
=> RunParser<Program>(GrammarParser.ProgramParser(), input);
}