Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

C#: keep a method in C# when a default is not a literal (#1387)

jakalijey5ac3ce3da299
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 92afbc5d..46028853 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -223,6 +223,10 @@
(#1337 by @jakalijey).
from one JVM start to the next. `List.of`, `Collectors.toList`, and a `toMap` or `groupingBy`
given a `TreeMap` or `LinkedHashMap` supplier are not (#1343 by @jakalijey).
+- C#: a method whose parameter default is not a literal (`int width = Width`, `Pad.Width`,
+ `Width * 2`) stays in C# with the reason, as PHP does for a class constant: the wrapper is another
+ class, so the name did not compile there. Numbers, strings, chars, `true`, `false`, `null` and
+ `default` are still copied (#1335 by @jakalijey).
- Swift: `Set<String>`, `Dictionary<String, Int>` and `Swift.Set<Int>`, and a set or dictionary
built by a call (`Set(words)`, `Set<String>(...)`, `Dictionary(grouping:by:)`), are a hash
iteration order risk, as a bare `Set`, `Dictionary` or `[K: V]` already were (#1344 by @jakalijey).
diff --git a/docs/types.md b/docs/types.md
index 51308ef5..a0a8b7bc 100644
--- a/docs/types.md
+++ b/docs/types.md
@@ -267,7 +267,9 @@ Its properties are the public instance auto-properties with `get` and `set` or `
`public record Point(double X, double Y)`. Other members, such as a getter-only `{ get; }` or a
static property, are left out and their types are not checked.
-`ref`, `out`, `in` and `params` parameters and generic methods are refused.
+`ref`, `out`, `in` and `params` parameters and generic methods are refused. So is a parameter whose
+default is not a literal (`int width = Width`): the wrapper is another class and cannot see the
+name. Numbers, strings, `true`, `false`, `null` and `default` are copied as written.
## Ruby
diff --git a/src/lang/csharp.rs b/src/lang/csharp.rs
index bec1088c..ae288754 100644
--- a/src/lang/csharp.rs
+++ b/src/lang/csharp.rs
@@ -815,10 +815,24 @@ fn method_export(
let after = p
.child_by_field_name("name")
.map_or(usize::MAX, |n| n.end_byte());
- let default = named_children(p)
+ let default_node = named_children(p)
.into_iter()
- .find(|c| c.start_byte() >= after)
- .map(|d| text(d, source).to_string());
+ .find(|c| c.start_byte() >= after);
+ if let Some(d) = default_node.filter(|d| !literal_default(*d)) {
+ // The wrapper is another class, so a name the default reads is not in scope there.
+ let d = text(d, source).trim();
+ blocker.get_or_insert_with(|| {
+ if matches!(
+ default_node.map(|n| n.kind()),
+ Some("identifier" | "member_access_expression")
+ ) {
+ format!("has a default that names `{d}`, which the wrapper cannot see")
+ } else {
+ format!("has a default (`{d}`) that is not a literal, which the wrapper cannot copy")
+ }
+ });
+ }
+ let default = default_node.map(|d| text(d, source).to_string());
signature.push(format!("{ty} {pname}"));
params.push(Param {
name: pname,
@@ -910,6 +924,33 @@ fn collect(node: Node, namespace: &str, path: &str, source: &str, out: &mut Vec<
}
}
+/// Whether a parameter's default can be copied into the wrapper as it is written: a number (a
+/// negative one too), a string, a char, `true`, `false`, `null` or `default`.
+fn literal_default(node: Node) -> bool {
+ match node.kind() {
+ "integer_literal"
+ | "real_literal"
+ | "string_literal"
+ | "verbatim_string_literal"
+ | "raw_string_literal"
+ | "character_literal"
+ | "boolean_literal"
+ | "null_literal" => true,
+ "default_expression" => named_children(node)
+ .iter()
+ .all(|t| t.kind() == "predefined_type"),
+ "prefix_unary_expression" => {
+ let operand = named_children(node);
+ operand.len() == 1
+ && matches!(operand[0].kind(), "integer_literal" | "real_literal")
+ && node
+ .child(0)
+ .is_some_and(|op| matches!(op.kind(), "-" | "+"))
+ }
+ _ => false,
+ }
+}
+
/// `public static` methods of the file's public classes. `prototype` holds the declaring class's
/// fully qualified name and the signature: `Acme.Text.Slug.Slugify(string text)`.
pub fn exports(path: &str, source: &str) -> Vec<ExportedFn> {
@@ -1056,6 +1097,57 @@ mod tests {
assert_eq!(fns[0].prototype.as_deref(), Some("Acme.Text.A.B()"));
}
+ #[test]
+ fn a_default_that_names_a_constant_stays_in_csharp() {
+ let src = "namespace Acme.Textkit.Text;\n\
+ public static class Pad {\n\
+ public const int Width = 8;\n\
+ public static string Left(string @class, int width = Width, string sep = \"\\\"\\\\\") => @class;\n\
+ public static string Right(string s, int width = Pad.Width) => s;\n\
+ public static int Twice(int n = Width * 2) => n;\n\
+ public static string Name(string @event, int @params = 0) => @event;\n\
+ public static string Lit(int n = 0, string s = \"a\", bool b = false, double d = -1.5, int m = -3, string? t = null, int z = default, long l = 10L, string v = @\"x\\y\") => s;\n\
+ public static int Typed(int n = default(int)) => n;\n\
+ public static int Hidden(System.Collections.Generic.List<int> xs = default(Inner)) => 1;\n\
+ }\n";
+ let fns = exports("src/Text/Pad.cs", src);
+ let blocker = |name: &str| {
+ fns.iter()
+ .find(|f| f.name == name)
+ .unwrap_or_else(|| panic!("{name} not in {fns:?}"))
+ .blocker
+ .clone()
+ };
+ assert_eq!(
+ blocker("Left").as_deref(),
+ Some("has a default that names `Width`, which the wrapper cannot see")
+ );
+ assert_eq!(
+ blocker("Right").as_deref(),
+ Some("has a default that names `Pad.Width`, which the wrapper cannot see")
+ );
+ assert!(
+ blocker("Twice")
+ .as_deref()
+ .is_some_and(|b| b.contains("`Width * 2`")),
+ "{:?}",
+ blocker("Twice")
+ );
+ assert_eq!(blocker("Name"), None);
+ assert_eq!(blocker("Lit"), None);
+ assert_eq!(blocker("Typed"), None);
+ assert!(
+ blocker("Hidden")
+ .as_deref()
+ .is_some_and(|b| b.contains("`default(Inner)`")),
+ "{:?}",
+ blocker("Hidden")
+ );
+ let lit = fns.iter().find(|f| f.name == "Lit").unwrap();
+ assert_eq!(lit.params[0].default.as_deref(), Some("0"));
+ assert_eq!(lit.params[3].default.as_deref(), Some("-1.5"));
+ }
+
#[test]
fn flags_risks_and_usings() {
let src = "using System.Text.RegularExpressions;\nusing Newtonsoft.Json;\n\