Skip to content

Commit ce73017

Browse files
committed
#54 - add unit and integration tests for missing return statement analysis
1 parent e996a64 commit ce73017

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using HydraScript.Infrastructure;
2+
3+
namespace HydraScript.IntegrationTests.ErrorPrograms;
4+
5+
public class FunctionWithoutReturnStatementTests(TestHostFixture fixture) : IClassFixture<TestHostFixture>
6+
{
7+
[Fact]
8+
public void FunctionDeclaration_MissingReturn_HydraScriptError()
9+
{
10+
const string script =
11+
"""
12+
function f(b: boolean) {
13+
if (b)
14+
return 1
15+
}
16+
""";
17+
using var runner = fixture.GetRunner(new TestHostFixture.Options(InMemoryScript: script));
18+
var code = runner.Invoke();
19+
code.Should().Be(Executor.ExitCodes.HydraScriptError);
20+
fixture.LogMessages.Should()
21+
.Contain(x =>
22+
x.Contains("function with non-void return type must have a return statement"));
23+
}
24+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using HydraScript.Application.StaticAnalysis.Visitors;
2+
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes.Declarations;
3+
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes.Declarations.AfterTypesAreLoaded;
4+
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes.Expressions.PrimaryExpressions;
5+
using HydraScript.Domain.FrontEnd.Parser.Impl.Ast.Nodes.Statements;
6+
7+
namespace HydraScript.UnitTests.Application;
8+
9+
public class ReturnAnalyzerTests
10+
{
11+
/// <summary>
12+
/// <code>
13+
/// function f(b: boolean) {
14+
/// if (b)
15+
/// return 1
16+
/// }
17+
/// </code>
18+
/// </summary>
19+
[Fact]
20+
public void Visit_FunctionWithMissingReturn_CodePathEndedWithReturnIsFalse()
21+
{
22+
// Arrange
23+
var functionDeclaration = new FunctionDeclaration(
24+
new IdentifierReference("f"),
25+
new TypeIdentValue(new IdentifierReference("undefined")),
26+
[new NamedArgument("b", new TypeIdentValue(new IdentifierReference("boolean")))],
27+
new BlockStatement([
28+
new IfStatement(
29+
new IdentifierReference("b"),
30+
new ReturnStatement(
31+
new Literal(new TypeIdentValue(new IdentifierReference("number")), 1, "segment")))
32+
]));
33+
34+
// Act
35+
var result = new ReturnAnalyzer().Visit(functionDeclaration);
36+
37+
// Assert
38+
result.CodePathEndedWithReturn.Should().BeFalse();
39+
result.ReturnStatements.Count.Should().Be(1);
40+
result.ReturnStatements[0].Expression.Should().BeOfType<Literal>();
41+
}
42+
}

0 commit comments

Comments
 (0)