Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions Coder.Cli/SampleCLI.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) 2023-2026 ktsu-dev contributors
// Copyright (c) 2023-2026 ktsu-dev contributors

namespace ktsu.Coder.Cli;

Expand Down Expand Up @@ -99,7 +99,12 @@ public static void Main(string[] args)
#pragma warning restore CA1031 // Do not catch general exception types
}

private static FunctionDeclaration CreateSampleFunction()
/// <summary>
/// Builds the sample function the CLI demonstrates: <c>calculate_sum(a, b, include_debug)</c>,
/// which returns the sum of its two integer arguments.
/// </summary>
/// <returns>The function declaration.</returns>
public static FunctionDeclaration CreateSampleFunction()
{
FunctionDeclaration function = new("calculate_sum")
{
Expand All @@ -112,7 +117,10 @@ private static FunctionDeclaration CreateSampleFunction()
function.Parameters.Add(new Parameter("include_debug", "bool") { IsOptional = true, DefaultValue = Literal.Bool(false) });

// Add function body
function.Body.Add(new ReturnStatement(new AstLeafNode<string>("a + b")));
// An expression, not text: a string leaf is written as a string literal, so the function
// would return the text "a + b" rather than the sum.
function.Body.Add(new ReturnStatement(
new BinaryExpression(new VariableReference("a"), BinaryOperator.Add, new VariableReference("b"))));

return function;
}
Expand Down
63 changes: 63 additions & 0 deletions Coder.Test/Cli/SampleFunctionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Copyright (c) 2023-2026 ktsu-dev contributors

namespace ktsu.Coder.Test.Cli;

using ktsu.Coder.Ast;
using ktsu.Coder.Cli;
using ktsu.Coder.Languages;
using ktsu.Coder.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

/// <summary>
/// Tests the sample function <see cref="CoderCLI"/> demonstrates, which the README shows as the
/// canonical usage example.
/// </summary>
[TestClass]
public class SampleFunctionTests
{
/// <summary>
/// Tests that the sample returns the sum of its arguments, not the text <c>"a + b"</c>, in every
/// language and after a YAML round-trip.
/// </summary>
[TestMethod]
public void SampleFunctionReturnsTheSumNotAString()
{
FunctionDeclaration function = CoderCLI.CreateSampleFunction();
YamlSerializer serializer = new();
AstNode? reloaded = new YamlDeserializer().Deserialize(serializer.Serialize(function));
Assert.IsNotNull(reloaded);

ILanguageGenerator[] generators =
[
new PythonGenerator(),
new CSharpGenerator(),
new CppGenerator(),
new JavaScriptGenerator(),
new RustGenerator(),
new GoGenerator(),
new CGenerator(),
];

foreach (ILanguageGenerator generator in generators)
{
foreach (AstNode node in new[] { function, reloaded })
{
string code = generator.Generate(node);
StringAssert.Contains(code, "a + b", $"{generator.GetType().Name} does not add the arguments:\n{code}");

Check warning on line 46 in Coder.Test/Cli/SampleFunctionTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.Contains' instead of 'StringAssert.Contains'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaG8CjjiMOgPm5Xezj-n&open=AaG8CjjiMOgPm5Xezj-n&pullRequest=471
Assert.DoesNotContain("\"a + b\"", code, $"{generator.GetType().Name} returns a string literal:\n{code}");
}
Comment thread
matt-edmondson marked this conversation as resolved.
Resolved
}
}

/// <summary>
/// Tests the Python the README shows for the sample.
/// </summary>
[TestMethod]
public void SamplePythonReturnsTheSum()
{
string code = new PythonGenerator().Generate(CoderCLI.CreateSampleFunction());

StringAssert.Contains(code, "def calculate_sum(a: int, b: int, include_debug: bool = False) -> int:", StringComparison.Ordinal);

Check warning on line 60 in Coder.Test/Cli/SampleFunctionTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.Contains' instead of 'StringAssert.Contains'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaG8CjjiMOgPm5Xezj-l&open=AaG8CjjiMOgPm5Xezj-l&pullRequest=471
StringAssert.Contains(code, " return (a + b)", StringComparison.Ordinal);

Check warning on line 61 in Coder.Test/Cli/SampleFunctionTests.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'Assert.Contains' instead of 'StringAssert.Contains'

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaG8CjjiMOgPm5Xezj-m&open=AaG8CjjiMOgPm5Xezj-m&pullRequest=471
}
}
2 changes: 2 additions & 0 deletions Coder.Test/Coder.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,7 @@
<ProjectReference Include="..\Coder\Coder.csproj" />
<ProjectReference Include="..\Coder.Graph\Coder.Graph.csproj" />
<ProjectReference Include="..\Coder.Editor\Coder.Editor.csproj" />
<!-- The sample tests generate the function the CLI demonstrates. -->
<ProjectReference Include="..\Coder.Cli\Coder.Cli.csproj" />
</ItemGroup>
</Project>
42 changes: 25 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,8 @@ function.Parameters.Add(new Parameter("debug", "bool")
});

// Add function body
function.Body.Add(new ReturnStatement(new AstLeafNode<string>("a + b")));
function.Body.Add(new ReturnStatement(
new BinaryExpression(new VariableReference("a"), BinaryOperator.Add, new VariableReference("b"))));
```

### Serializing to YAML
Expand All @@ -276,21 +277,28 @@ Output:

```yaml
functionDeclaration:
name: calculate_sum
returnType: int
parameters:
- name: a
type: int
- name: b
type: int
- name: debug
type: bool
isOptional: true
defaultValue: false
body:
- returnStatement:
expression:
Leaf<String>: a + b
name: calculate_sum
returnType: int
parameters:
- name: a
type: int
- name: b
type: int
- name: debug
type: bool
isOptional: true
defaultValue: "false"
body:
- returnStatement:
expression:
binaryExpression:
left:
variableReference:
name: a
operator: Add
right:
variableReference:
name: b
```

### Generating Code
Expand All @@ -305,7 +313,7 @@ Output:

```python
def calculate_sum(a: int, b: int, debug: bool = False) -> int:
return "a + b"
return (a + b)
```

### Round-trip Serialization
Expand Down
Loading