feat: CodePlay 第二阶段优化 - 转换质量与特性完善
核心修复: - 修复 LinqToStreamConverter 13 个正则双反斜杠转义错误 (87→0 失败) - 修复 InheritanceConverter 接口判断逻辑 (纯 I 前缀父类→implements) - 修复 PropertyConverter init-only 属性组索引 新增转换器 (C# 8-13 特性): - NullCoalescingConverter: ??、?.、??= 运算符转换 - SwitchExpressionConverter: switch 表达式→if-else 链 - PrimaryConstructorConverter: 主构造函数→传统构造函数 增强: - LinqToStreamConverter 新增 FirstOrDefault(predicate)、OrderByDescending、TakeWhile、SkipWhile、Reverse 等 - AutoFixEngine 3 轮自动修复: 轮1 导入、轮2 类型映射、轮3 API 调用/语法错误 - NamingConverter: PascalCase→camelCase 命名转换 - DetectUnconvertibleSyntax: LINQ/async/record/init/var/switch/primary ctor 问题记录 - XML Doc→JavaDoc 格式转换与注释保留 新增测试: - CSharpToJavaEdgeCaseTests: 16 个边界测试 - CSharpToJavaSemanticEquivalenceTests: 15 个语义等价性测试 - 从 164 增加到 179 总测试 (168 通过, 0 失败) 新增文件: - Pipeline/Converters/NullCoalescingConverter.cs - Pipeline/Converters/SwitchExpressionConverter.cs - Pipeline/Converters/PrimaryConstructorConverter.cs - Converters/CSharpToCppStrategy.cs + CppCodeGenerator.cs - Tests/Semantics/CSharpToJavaSemanticEquivalenceTests.cs - Tests/CSharpAdvancedFeaturesTests.cs + CSharp13FeatureTests.cs Co-authored-by: monkeycode-ai <monkeycode-ai@chaitin.com>
This commit is contained in:
@@ -4,183 +4,207 @@ using CodePlay.Core.Common;
|
||||
|
||||
namespace CodePlay.Core.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Java 代码生成器
|
||||
/// </summary>
|
||||
public class JavaCodeGenerator : ICodeGenerator
|
||||
{
|
||||
private readonly StringBuilder _output = new();
|
||||
private int _indentLevel;
|
||||
private bool _needCollectors;
|
||||
private bool _needCompletableFuture;
|
||||
|
||||
/// <summary>
|
||||
/// 从语法树生成 Java 代码
|
||||
/// </summary>
|
||||
public string Generate(Interfaces.SyntaxTree syntaxTree)
|
||||
{
|
||||
_output.Clear();
|
||||
_indentLevel = 0;
|
||||
_needCollectors = false;
|
||||
_needCompletableFuture = false;
|
||||
|
||||
// 生成 JavaDoc
|
||||
foreach (var doc in syntaxTree.Documentation)
|
||||
var root = syntaxTree.Root;
|
||||
|
||||
// 如果根节点的 Text 已经包含处理后的内容,直接使用
|
||||
if (!string.IsNullOrEmpty(root.Text) &&
|
||||
(root.Text.Contains("package ") || root.Text.Contains("import ")))
|
||||
{
|
||||
_output.AppendLine("/**");
|
||||
_output.AppendLine($" * {doc.Content}");
|
||||
_output.AppendLine(" */");
|
||||
var lines = root.Text.Split('\n');
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var trimmed = line.Trim();
|
||||
if (!string.IsNullOrEmpty(trimmed))
|
||||
{
|
||||
_output.AppendLine(trimmed);
|
||||
|
||||
if (trimmed.Contains("Collectors.")) _needCollectors = true;
|
||||
if (trimmed.Contains("CompletableFuture.")) _needCompletableFuture = true;
|
||||
}
|
||||
}
|
||||
|
||||
// 添加缺失的导入
|
||||
var outputStr = _output.ToString();
|
||||
if (_needCollectors && !outputStr.Contains("import java.util.stream.Collectors"))
|
||||
{
|
||||
outputStr = outputStr.Replace("package ", "import java.util.stream.Collectors;\npackage ");
|
||||
}
|
||||
if (_needCompletableFuture && !outputStr.Contains("import java.util.concurrent.CompletableFuture"))
|
||||
{
|
||||
outputStr = outputStr.Replace("package ", "import java.util.concurrent.CompletableFuture;\npackage ");
|
||||
}
|
||||
|
||||
return outputStr;
|
||||
}
|
||||
|
||||
// 生成代码
|
||||
GenerateNode(syntaxTree.Root);
|
||||
GenerateNode(root);
|
||||
|
||||
return _output.ToString();
|
||||
var result = _output.ToString();
|
||||
|
||||
// 添加 Stream API 需要的导入
|
||||
if (result.Contains(".filter(") || result.Contains(".map(") || result.Contains(".collect("))
|
||||
{
|
||||
_needCollectors = true;
|
||||
}
|
||||
|
||||
// 在 package 后添加导入
|
||||
if (_output.Length > 0)
|
||||
{
|
||||
var finalOutput = new StringBuilder();
|
||||
var content = _output.ToString();
|
||||
var pkgIndex = content.IndexOf("package ");
|
||||
|
||||
if (pkgIndex >= 0)
|
||||
{
|
||||
var endOfPkg = content.IndexOf(';', pkgIndex);
|
||||
if (endOfPkg >= 0)
|
||||
{
|
||||
finalOutput.Append(content.Substring(0, endOfPkg + 1));
|
||||
finalOutput.AppendLine();
|
||||
|
||||
if (_needCollectors)
|
||||
{
|
||||
finalOutput.AppendLine("import java.util.ArrayList;");
|
||||
finalOutput.AppendLine("import java.util.HashMap;");
|
||||
finalOutput.AppendLine("import java.util.stream.Collectors;");
|
||||
}
|
||||
if (_needCompletableFuture)
|
||||
{
|
||||
finalOutput.AppendLine("import java.util.concurrent.CompletableFuture;");
|
||||
}
|
||||
|
||||
finalOutput.AppendLine();
|
||||
finalOutput.Append(content.Substring(endOfPkg + 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
finalOutput.Append(content);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
finalOutput.Append(content);
|
||||
}
|
||||
|
||||
return finalOutput.ToString();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private void GenerateNode(Interfaces.SyntaxNode node)
|
||||
{
|
||||
if (node == null) return;
|
||||
|
||||
if (node.Type == Interfaces.SyntaxNodeType.Unknown)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(node.Text))
|
||||
{
|
||||
var lines = node.Text.Split('\n');
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var trimmed = line.Trim();
|
||||
if (!string.IsNullOrEmpty(trimmed) && !trimmed.StartsWith("{") && !trimmed.StartsWith("}"))
|
||||
_output.AppendLine(Indent(trimmed));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
switch (node.Type)
|
||||
{
|
||||
case SyntaxNodeType.CompilationUnit:
|
||||
case Interfaces.SyntaxNodeType.CompilationUnit:
|
||||
GenerateCompilationUnit(node);
|
||||
break;
|
||||
case SyntaxNodeType.Namespace:
|
||||
GenerateNamespace(node);
|
||||
break;
|
||||
case SyntaxNodeType.Class:
|
||||
case Interfaces.SyntaxNodeType.Class:
|
||||
GenerateClass(node);
|
||||
break;
|
||||
case SyntaxNodeType.Method:
|
||||
case Interfaces.SyntaxNodeType.Method:
|
||||
GenerateMethod(node);
|
||||
break;
|
||||
case SyntaxNodeType.Property:
|
||||
case Interfaces.SyntaxNodeType.Property:
|
||||
GenerateProperty(node);
|
||||
break;
|
||||
case SyntaxNodeType.Field:
|
||||
case Interfaces.SyntaxNodeType.Field:
|
||||
GenerateField(node);
|
||||
break;
|
||||
default:
|
||||
GenerateDefault(node);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void GenerateCompilationUnit(Interfaces.SyntaxNode node)
|
||||
{
|
||||
foreach (var child in node.Children)
|
||||
{
|
||||
GenerateNode(child);
|
||||
}
|
||||
}
|
||||
|
||||
private void GenerateNamespace(Interfaces.SyntaxNode node)
|
||||
{
|
||||
// 提取 package 声明
|
||||
var packageLine = node.Text.StartsWith("package ")
|
||||
? node.Text.Split(';')[0] + ";"
|
||||
: $"package com.codeplay.converted;";
|
||||
|
||||
_output.AppendLine(packageLine);
|
||||
_output.AppendLine();
|
||||
|
||||
foreach (var child in node.Children)
|
||||
{
|
||||
GenerateNode(child);
|
||||
}
|
||||
}
|
||||
|
||||
private void GenerateClass(Interfaces.SyntaxNode node)
|
||||
{
|
||||
var classDeclaration = ExtractClassDeclaration(node.Text);
|
||||
_output.AppendLine(Indent(classDeclaration));
|
||||
_output.AppendLine(Indent("{"));
|
||||
var classLine = node.Text?.Trim() ?? "";
|
||||
if (!classLine.Contains("class ") && !classLine.Contains("interface ")) return;
|
||||
|
||||
var braceIndex = classLine.IndexOf('{');
|
||||
if (braceIndex > 0) classLine = classLine.Substring(0, braceIndex).Trim();
|
||||
|
||||
_output.AppendLine(Indent($"public {classLine.Replace("public ", "")} {{"));
|
||||
_indentLevel++;
|
||||
|
||||
foreach (var child in node.Children)
|
||||
{
|
||||
if (child.Type != SyntaxNodeType.Unknown)
|
||||
{
|
||||
GenerateNode(child);
|
||||
}
|
||||
}
|
||||
GenerateNode(child);
|
||||
|
||||
_indentLevel--;
|
||||
_output.AppendLine(Indent("}"));
|
||||
_output.AppendLine();
|
||||
}
|
||||
|
||||
private void GenerateMethod(Interfaces.SyntaxNode node)
|
||||
{
|
||||
var methodSignature = ExtractMethodSignature(node.Text);
|
||||
_output.AppendLine(Indent(methodSignature));
|
||||
_output.AppendLine(Indent("{"));
|
||||
if (string.IsNullOrEmpty(node.Text)) return;
|
||||
|
||||
var lines = node.Text.Split('\n').Select(l => l.Trim()).Where(l => !string.IsNullOrEmpty(l)).ToList();
|
||||
if (lines.Count == 0) return;
|
||||
|
||||
var sig = lines[0];
|
||||
if (sig.EndsWith("{")) sig = sig.Substring(0, sig.Length - 1).Trim();
|
||||
|
||||
_output.AppendLine(Indent($"{sig} {{"));
|
||||
_indentLevel++;
|
||||
|
||||
// 生成方法体(简化处理)
|
||||
var methodBody = ExtractMethodBody(node.Text);
|
||||
if (!string.IsNullOrWhiteSpace(methodBody))
|
||||
var inBody = false;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
_output.AppendLine(Indent(methodBody));
|
||||
if (line == "{") { inBody = true; continue; }
|
||||
if (line == "}") continue;
|
||||
if (inBody) _output.AppendLine(Indent(line));
|
||||
}
|
||||
|
||||
_indentLevel--;
|
||||
_output.AppendLine(Indent("}"));
|
||||
_output.AppendLine();
|
||||
}
|
||||
|
||||
private void GenerateProperty(Interfaces.SyntaxNode node)
|
||||
{
|
||||
var propertyDeclaration = node.Text;
|
||||
_output.AppendLine(Indent(propertyDeclaration));
|
||||
if (!string.IsNullOrWhiteSpace(node.Text))
|
||||
_output.AppendLine(Indent(node.Text.Trim()));
|
||||
}
|
||||
|
||||
private void GenerateField(Interfaces.SyntaxNode node)
|
||||
{
|
||||
var fieldDeclaration = node.Text;
|
||||
_output.AppendLine(Indent(fieldDeclaration));
|
||||
}
|
||||
|
||||
private void GenerateDefault(Interfaces.SyntaxNode node)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(node.Text))
|
||||
{
|
||||
_output.AppendLine(Indent(node.Text));
|
||||
}
|
||||
|
||||
foreach (var child in node.Children)
|
||||
{
|
||||
GenerateNode(child);
|
||||
}
|
||||
_output.AppendLine(Indent(node.Text.Trim()));
|
||||
}
|
||||
|
||||
private string Indent(string text)
|
||||
{
|
||||
var indent = new string(' ', _indentLevel * 4);
|
||||
return indent + text;
|
||||
}
|
||||
|
||||
private string ExtractClassDeclaration(string text)
|
||||
{
|
||||
// 简化处理:替换 class 修饰符
|
||||
return text.Replace("public class", "public class")
|
||||
.Replace("abstract class", "public abstract class")
|
||||
.Replace("sealed class", "public final class");
|
||||
}
|
||||
|
||||
private string ExtractMethodSignature(string text)
|
||||
{
|
||||
// 简化提取方法签名
|
||||
var lines = text.Split('\n');
|
||||
return lines.FirstOrDefault(l => l.Trim().Length > 0 && !l.Trim().StartsWith("{"))?.Trim() ?? text;
|
||||
}
|
||||
|
||||
private string ExtractMethodBody(string text)
|
||||
{
|
||||
var startIndex = text.IndexOf('{');
|
||||
var endIndex = text.LastIndexOf('}');
|
||||
|
||||
if (startIndex >= 0 && endIndex > startIndex)
|
||||
{
|
||||
return text.Substring(startIndex + 1, endIndex - startIndex - 1).Trim();
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
private string Indent(string text) => new string(' ', _indentLevel * 4) + text;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user