CanonSharp/CanonSharp.Tests/ParserTests/SubprogramParserTests.cs
jackfiled cf19f8197e feat: Grammar Parser (#3)
Reviewed-on: https://git.bupt-hpc.cn/jackfiled/CanonSharp/pulls/3
Co-authored-by: jackfiled <xcrenchangjun@outlook.com>
Co-committed-by: jackfiled <xcrenchangjun@outlook.com>
2024-08-18 12:01:27 +08:00

84 lines
2.9 KiB
C#

using CanonSharp.Pascal.Parser;
using CanonSharp.Pascal.SyntaxTree;
using CanonSharp.Tests.Utils;
namespace CanonSharp.Tests.ParserTests;
public class SubprogramParserTests : GrammarParserTestBase
{
[Fact]
public void ParameterTest1()
{
List<Parameter> parameters = RunParser<Parameter>(GrammarParser.ParameterParser(), "a ,b : integer");
Assert.Equal(2, parameters.Count);
Assert.All(parameters, p =>
{
Assert.False(p.IsReference);
Assert.Equal("integer", p.TypeNode.Convert<TypeNode>().TypeToken.LiteralValue);
});
parameters = RunParser<Parameter>(GrammarParser.ParameterParser(), "var a, b,c: real");
Assert.Equal(3, parameters.Count);
Assert.All(parameters, p =>
{
Assert.True(p.IsReference);
Assert.Equal("real", p.TypeNode.Convert<TypeNode>().TypeToken.LiteralValue);
});
}
[Theory]
[InlineData("(var a, b : integer; c, d : real)", 4)]
[InlineData("(a : boolean; var c, d, e : char)", 4)]
[InlineData("(a : integer)", 1)]
[InlineData("(var b ,c : real)", 2)]
public void FormalParameterTest(string input, int count)
{
List<Parameter> parameters = RunParser<Parameter>(GrammarParser.FormalParameterParser(), input);
Assert.Equal(count, parameters.Count);
}
[Theory]
[InlineData("procedure test", 0)]
[InlineData("procedure test()", 0)]
[InlineData("procedure test(a : integer; var b : real)", 2)]
[InlineData("procedure test(a,b, c : real; var e, f : boolean)", 5)]
[InlineData("function test : integer", 0)]
[InlineData("function test() : real", 0)]
[InlineData("function test(a : integer; var b : real) : boolean", 2)]
[InlineData("function test(a,b, c : real; var e, f : boolean) : char", 5)]
public void SubprogramHeadTest(string input, int count)
{
SubprogramHead head = RunParser<SubprogramHead>(GrammarParser.SubprogramHeadParser(), input);
Assert.Equal(count, head.Parameters.Count);
}
[Fact]
public void SubprogramHeadTest1()
{
SubprogramHead head =
RunParser<SubprogramHead>(GrammarParser.SubprogramHeadParser(), "function test(a : integer) : real");
Assert.Equal("test", head.Identifier.LiteralValue);
Assert.Single(head.Parameters);
Assert.NotNull(head.TypeToken);
Assert.Equal("real", head.TypeToken.Convert<TypeNode>().TypeToken.LiteralValue);
}
[Fact]
public void SubprogramBodyTest1()
{
SubprogramBody body = RunParser<SubprogramBody>(GrammarParser.SubprogramBodyParser(), """
const a = 3;
var c, d : integer; e, f :real;
begin
c := a + d;
end
""");
Assert.Single(body.ConstDeclarations.Statements);
Assert.Equal(2, body.VariableDeclarations.Statements.Count);
Assert.Equal(1, body.MainBlock.Statements.Count);
}
}