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
77 changes: 77 additions & 0 deletions Coder.Test/Languages/RustInferredLiteralWidthTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Copyright (c) 2023-2026 ktsu-dev contributors

namespace ktsu.Coder.Test.Languages;

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

/// <summary>
/// Tests that a Rust local whose type is inferred from a <c>long</c> or <c>float</c> keeps that width.
/// </summary>
/// <remarks>
/// Rust infers an unconstrained integer literal as <c>i32</c> and a float literal as <c>f64</c>. A
/// <c>long</c> past <c>i32</c>'s range then fails the deny-by-default <c>overflowing_literals</c>
/// lint, and a <c>float</c> silently becomes a <c>double</c>.
/// </remarks>
[TestClass]
public class RustInferredLiteralWidthTests
{
/// <summary>
/// Tests that an inferred local initialised with a <c>long</c> or <c>float</c> is annotated with
/// its width, and one initialised with an <c>int</c> or <c>double</c> is still left to inference.
/// </summary>
[TestMethod]
public void AnInferredLongOrFloatLocal_IsAnnotatedWithItsWidth()
{
string code = new RustGenerator().Generate(Widths());

StringAssert.Contains(code, "let mut big: i64 = 5000000000;", StringComparison.Ordinal);

Check warning on line 29 in Coder.Test/Languages/RustInferredLiteralWidthTests.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=AaEx5rrA-6h8vqtfvChJ&open=AaEx5rrA-6h8vqtfvChJ&pullRequest=212
StringAssert.Contains(code, "let mut narrow: f32 = ", StringComparison.Ordinal);

Check warning on line 30 in Coder.Test/Languages/RustInferredLiteralWidthTests.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=AaEx5rrA-6h8vqtfvChK&open=AaEx5rrA-6h8vqtfvChK&pullRequest=212
StringAssert.Contains(code, "let mut small = 5;", StringComparison.Ordinal);

Check warning on line 31 in Coder.Test/Languages/RustInferredLiteralWidthTests.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=AaEx5rrA-6h8vqtfvChL&open=AaEx5rrA-6h8vqtfvChL&pullRequest=212
StringAssert.Contains(code, "let mut wide = ", StringComparison.Ordinal);

Check warning on line 32 in Coder.Test/Languages/RustInferredLiteralWidthTests.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=AaEx5rrA-6h8vqtfvChM&open=AaEx5rrA-6h8vqtfvChM&pullRequest=212
Assert.DoesNotContain("let mut wide:", code, StringComparison.Ordinal, code);
}

/// <summary>
/// Tests that an unconstrained inferred local holding a <c>long</c> past <c>i32</c>'s range
/// compiles.
/// </summary>
[TestMethod]
public void AnUnconstrainedLongLocal_Compiles()
{
if (ToolchainHarness.FindOnPath("--version", "rustc") is null)
{
Assert.Inconclusive("No Rust compiler on the path, so nothing was compiled.");
return;
}

ToolchainHarness.InTemporaryDirectory(directory =>
{
// Nothing reads the locals, which is what leaves their types unconstrained.
string source = new RustGenerator().Generate(Widths());
string code = $"#![allow(unused_variables, unused_mut, dead_code)]{Environment.NewLine}{source}";
File.WriteAllText(Path.Combine(directory, "widths.rs"), code);

(int exitCode, string output) = ToolchainHarness.Run(
"rustc",
"--crate-type lib --edition 2021 -o widths.rlib widths.rs",
directory);

Assert.AreEqual(0, exitCode, $"rustc rejected the generated source:{Environment.NewLine}{code}{Environment.NewLine}{output}");
});
}

private static SourceFile Widths()
{
FunctionDeclaration function = new("widths");
function.Body.Add(new VariableDeclaration("big", null, new LiteralExpression<long>(5_000_000_000)));
function.Body.Add(new VariableDeclaration("narrow", null, new LiteralExpression<float>(0.1f)));
function.Body.Add(new VariableDeclaration("small", null, new LiteralExpression<int>(5)));
function.Body.Add(new VariableDeclaration("wide", null, new LiteralExpression<double>(0.1)));

SourceFile file = new("widths");
file.Members.Add(function);
return file;
}
}
26 changes: 23 additions & 3 deletions Coder/Languages/RustGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@
/// The associated constants of <c>f64</c>, which need nothing imported.
/// </remarks>
protected override string SpellNonFiniteDouble(double value) =>
double.IsNaN(value) ? "f64::NAN" : value > 0 ? "f64::INFINITY" : "f64::NEG_INFINITY";

Check warning on line 344 in Coder/Languages/RustGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

Check warning on line 344 in Coder/Languages/RustGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

Check warning on line 344 in Coder/Languages/RustGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

Check warning on line 344 in Coder/Languages/RustGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

/// <inheritdoc/>
/// <remarks>
Expand Down Expand Up @@ -782,7 +782,7 @@
HashSet<string> reassigned = op.ReturnsBool
? []
: ReassignedNames(funcDecl.Body, [SelfName, .. funcDecl.Parameters.Select(OperandName)]);
string self = op.ReturnsBool ? "&self" : reassigned.Contains(SelfName) ? $"mut {SelfName}" : SelfName;

Check warning on line 785 in Coder/Languages/RustGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

Check warning on line 785 in Coder/Languages/RustGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

Check warning on line 785 in Coder/Languages/RustGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

Check warning on line 785 in Coder/Languages/RustGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.
code.Write($"fn {op.Method}({self}");

foreach (Parameter parameter in funcDecl.Parameters)
Expand Down Expand Up @@ -1238,20 +1238,40 @@
code.Write(varDecl.Name);

bool inferred = varDecl.IsTypeInferred || varDecl.Type is null;
if (!inferred || varDecl.InitialValue is null)
TypeReference? annotation = !inferred ? varDecl.Type
: varDecl.InitialValue is null ? new TypeReference(UnknownTypeName)

Check warning on line 1242 in Coder/Languages/RustGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.

Check warning on line 1242 in Coder/Languages/RustGenerator.cs

View workflow job for this annotation

GitHub Actions / ci / .NET / Analyze & Release

Extract this nested ternary operation into an independent statement.
: KeptWidth(varDecl.InitialValue);

Check warning on line 1243 in Coder/Languages/RustGenerator.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=ktsu-dev_Coder&issues=AaEx5rm0-6h8vqtfvChI&open=AaEx5rm0-6h8vqtfvChI&pullRequest=212

if (annotation is not null)
{
code.Write($": {SpellType(varDecl.Type ?? new TypeReference(UnknownTypeName))}");
code.Write($": {SpellType(annotation)}");
}

if (varDecl.InitialValue is not null)
{
code.Write(" = ");
WriteValue(varDecl.InitialValue, inferred ? null : varDecl.Type, code);
WriteValue(varDecl.InitialValue, annotation, code);
}

EndStatement(code);
}

/// <summary>
/// Reads the width an inferred local must be written with, because Rust would infer another.
/// </summary>
/// <param name="initialValue">The local's initialiser.</param>
/// <returns><c>long</c> or <c>float</c> when the initialiser establishes one; otherwise null.</returns>
/// <remarks>
/// Rust infers an unconstrained integer as <c>i32</c> and a float as <c>f64</c>, so a long or a
/// float that nothing later pins down would silently narrow or widen, and a long past
/// <c>i32</c>'s range does not compile at all. An <c>int</c> or a <c>double</c> is what Rust
/// infers anyway, so it is left to inference.
/// </remarks>
private TypeReference? KeptWidth(Expression initialValue) =>
StaticType(initialValue) is { IsArray: false, Indirection: TypeIndirection.None, TypeArguments.Count: 0, Name: "long" or "float" } width
? width
: null;

/// <inheritdoc/>
/// <remarks>
/// Inside a struct this is a field; at module scope it is a <c>const</c> when the declaration
Expand Down
Loading