feat: 完成 C# 解析器测试、C# 转 Java 转换器和 Web API 控制器
核心功能实现: - 实现 CSharpToJavaStrategy 转换策略(包含类型映射) - 实现 CSharpToJavaConverter 转换器 - 实现 JavaCodeGenerator 代码生成器 - 实现 ConversionService 转换服务 - 实现 ConversionController Web API 控制器 - 注册 Swagger 文档和依赖注入 测试覆盖: - CSharpParserTests: 8 个测试用例 - CSharpToJavaConverterTests: 5 个测试用例 - 共 13 个测试全部通过 任务完成: - Task 1.2: 配置项目依赖 - Task 1.3: 建立基础架构 - Task 2.1: 实现 C# 解析器和测试 - Task 2.4: 实现 C# → Java 转换器 - Task 4.1: 创建 ASP.NET Core Web API Co-authored-by: monkeycode-ai <monkeycode-ai@chaitin.com>
This commit is contained in:
@@ -8,6 +8,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" />
|
||||
<PackageReference Include="TreeSitter" Version="0.1.0-alpha.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using CodePlay.Core.Interfaces;
|
||||
using CodePlay.Core.Models;
|
||||
using CodePlay.Core.Common;
|
||||
using CodePlay.Core.Parsers;
|
||||
|
||||
namespace CodePlay.Core.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// C# 到 Java 代码转换器
|
||||
/// </summary>
|
||||
public class CSharpToJavaConverter : IConverter
|
||||
{
|
||||
private readonly CSharpToJavaStrategy _strategy;
|
||||
private readonly ICodeGenerator _codeGenerator;
|
||||
|
||||
public CSharpToJavaConverter()
|
||||
{
|
||||
_strategy = new CSharpToJavaStrategy();
|
||||
_codeGenerator = new JavaCodeGenerator();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换语法树
|
||||
/// </summary>
|
||||
public async Task<ConversionResult> ConvertAsync(
|
||||
Interfaces.SyntaxTree syntaxTree,
|
||||
LanguageType targetLanguage,
|
||||
ConversionOptions? options = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var result = new ConversionResult
|
||||
{
|
||||
Success = false,
|
||||
Warnings = new List<ConversionWarning>(),
|
||||
Report = new ConversionReport()
|
||||
};
|
||||
|
||||
if (targetLanguage != LanguageType.Java)
|
||||
{
|
||||
result.ErrorMessage = "This converter only supports C# to Java conversion";
|
||||
return result;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var context = new ConversionContext
|
||||
{
|
||||
SourceLanguage = LanguageType.CSharp,
|
||||
TargetLanguage = LanguageType.Java,
|
||||
Options = options
|
||||
};
|
||||
|
||||
// 转换根节点
|
||||
var convertedRoot = _strategy.ConvertNode(syntaxTree.Root, context);
|
||||
|
||||
// 创建新的语法树
|
||||
var convertedTree = new Interfaces.SyntaxTree
|
||||
{
|
||||
Language = LanguageType.Java,
|
||||
Root = convertedRoot,
|
||||
SourceCode = syntaxTree.SourceCode
|
||||
};
|
||||
|
||||
// 保留注释
|
||||
if (options?.KeepComments == true)
|
||||
{
|
||||
convertedTree.Documentation = syntaxTree.Documentation
|
||||
.Select(d => new SyntaxDocumentation
|
||||
{
|
||||
ElementName = d.ElementName,
|
||||
Content = ConvertDocumentation(d.Content),
|
||||
Format = DocFormat.JavaDoc
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
// 生成 Java 代码
|
||||
var generatedCode = _codeGenerator.Generate(convertedTree);
|
||||
|
||||
result.TransformedCode = generatedCode;
|
||||
result.Success = true;
|
||||
|
||||
// 生成报告
|
||||
if (result.Report != null)
|
||||
{
|
||||
result.Report.LinesConverted = syntaxTree.SourceCode?.Split('\n').Length ?? 0;
|
||||
result.Report.ClassesConverted = CountClasses(syntaxTree.Root);
|
||||
result.Report.MethodsConverted = CountMethods(syntaxTree.Root);
|
||||
result.Report.TodoItems = context.TodoItems;
|
||||
result.Report.Issues = context.Issues;
|
||||
result.Report.TransformationLog = context.Logs;
|
||||
}
|
||||
|
||||
context.Logs.Add(new TransformationLog
|
||||
{
|
||||
Timestamp = DateTime.UtcNow,
|
||||
Operation = "Conversion",
|
||||
Details = "C# to Java conversion completed",
|
||||
Level = LogLevel.Info
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
result.ErrorMessage = ex.Message;
|
||||
result.Success = false;
|
||||
}
|
||||
|
||||
return await Task.FromResult(result);
|
||||
}
|
||||
|
||||
private string ConvertDocumentation(string xmlDocContent)
|
||||
{
|
||||
// 简单的 XML Doc 到 JavaDoc 转换
|
||||
return xmlDocContent
|
||||
.Replace("///", " *")
|
||||
.Replace("<summary>", "")
|
||||
.Replace("</summary>", "")
|
||||
.Replace("<param name=", "@param ")
|
||||
.Replace("<returns>", "@return")
|
||||
.Replace("</returns>", "")
|
||||
.Replace("<exception cref=", "@throws ");
|
||||
}
|
||||
|
||||
private int CountClasses(Interfaces.SyntaxNode node)
|
||||
{
|
||||
int count = 0;
|
||||
if (node.Type == SyntaxNodeType.Class) count++;
|
||||
count += node.Children.Sum(CountClasses);
|
||||
return count;
|
||||
}
|
||||
|
||||
private int CountMethods(Interfaces.SyntaxNode node)
|
||||
{
|
||||
int count = 0;
|
||||
if (node.Type == SyntaxNodeType.Method) count++;
|
||||
count += node.Children.Sum(CountMethods);
|
||||
return count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
using CodePlay.Core.Interfaces;
|
||||
using CodePlay.Core.Models;
|
||||
using CodePlay.Core.Common;
|
||||
|
||||
namespace CodePlay.Core.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// C# 到 Java 转换策略
|
||||
/// </summary>
|
||||
public class CSharpToJavaStrategy : IConversionStrategy
|
||||
{
|
||||
/// <summary>
|
||||
/// 源语言
|
||||
/// </summary>
|
||||
public LanguageType SourceLanguage => LanguageType.CSharp;
|
||||
|
||||
/// <summary>
|
||||
/// 目标语言
|
||||
/// </summary>
|
||||
public LanguageType TargetLanguage => LanguageType.Java;
|
||||
|
||||
private readonly List<TypeMapping> _typeMappings = new();
|
||||
|
||||
public CSharpToJavaStrategy()
|
||||
{
|
||||
InitializeTypeMappings();
|
||||
}
|
||||
|
||||
private void InitializeTypeMappings()
|
||||
{
|
||||
_typeMappings.AddRange(new[]
|
||||
{
|
||||
new TypeMapping("System.String", "java.lang.String"),
|
||||
new TypeMapping("System.Int32", "int"),
|
||||
new TypeMapping("System.Int64", "long"),
|
||||
new TypeMapping("System.Boolean", "boolean"),
|
||||
new TypeMapping("System.Double", "double"),
|
||||
new TypeMapping("System.Single", "float"),
|
||||
new TypeMapping("System.Object", "Object"),
|
||||
new TypeMapping("System.Collections.Generic.List", "java.util.ArrayList"),
|
||||
new TypeMapping("System.Collections.Generic.Dictionary", "java.util.HashMap"),
|
||||
new TypeMapping("System.Collections.Generic.IEnumerable", "java.util.stream.Stream"),
|
||||
new TypeMapping("System.Array", "java.util.Arrays"),
|
||||
new TypeMapping("System.Console", "System.out"),
|
||||
new TypeMapping("System.DateTime", "java.time.LocalDateTime"),
|
||||
new TypeMapping("System.TimeSpan", "java.time.Duration"),
|
||||
new TypeMapping("System.Exception", "Exception"),
|
||||
new TypeMapping("System.ArgumentException", "IllegalArgumentException"),
|
||||
new TypeMapping("System.InvalidOperationException", "IllegalStateException"),
|
||||
new TypeMapping("System.NullReferenceException", "NullPointerException"),
|
||||
new TypeMapping("System.Threading.Tasks.Task", "java.util.concurrent.CompletableFuture"),
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 映射类型
|
||||
/// </summary>
|
||||
public string MapType(string sourceType)
|
||||
{
|
||||
var mapping = _typeMappings.FirstOrDefault(m => sourceType.Contains(m.SourceType));
|
||||
return mapping?.TargetType ?? sourceType
|
||||
.Replace("var ", "Object ")
|
||||
.Replace("public ", "public ")
|
||||
.Replace("private ", "private ")
|
||||
.Replace("protected ", "protected ");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换语法节点
|
||||
/// </summary>
|
||||
public Interfaces.SyntaxNode ConvertNode(Interfaces.SyntaxNode node, ConversionContext context)
|
||||
{
|
||||
var newNode = new Interfaces.SyntaxNode
|
||||
{
|
||||
Type = node.Type,
|
||||
Text = ConvertText(node.Text, context),
|
||||
Metadata = new Dictionary<string, object?>(node.Metadata),
|
||||
Parent = node.Parent,
|
||||
Children = new List<Interfaces.SyntaxNode>(),
|
||||
IsUnconvertible = node.IsUnconvertible,
|
||||
TodoDescription = node.TodoDescription
|
||||
};
|
||||
|
||||
foreach (var child in node.Children)
|
||||
{
|
||||
var convertedChild = ConvertNode(child, context);
|
||||
convertedChild.Parent = newNode;
|
||||
newNode.Children.Add(convertedChild);
|
||||
}
|
||||
|
||||
return newNode;
|
||||
}
|
||||
|
||||
private string ConvertText(string text, ConversionContext context)
|
||||
{
|
||||
var result = text;
|
||||
|
||||
// 命名空间转 package
|
||||
if (result.StartsWith("namespace "))
|
||||
{
|
||||
result = result.Replace("namespace ", "package ")
|
||||
.Replace("{", ";");
|
||||
}
|
||||
|
||||
// using 转 import
|
||||
if (result.StartsWith("using "))
|
||||
{
|
||||
result = result.Replace("using ", "import ")
|
||||
.Replace(";", ";");
|
||||
}
|
||||
|
||||
// 类型映射
|
||||
foreach (var mapping in _typeMappings)
|
||||
{
|
||||
result = result.Replace(mapping.SourceType, mapping.TargetType);
|
||||
}
|
||||
|
||||
// C# 特定语法处理
|
||||
result = result.Replace("base.", "super.")
|
||||
.Replace("this.", "this.")
|
||||
.Replace("null", "null")
|
||||
.Replace("true", "true")
|
||||
.Replace("false", "false");
|
||||
|
||||
// 属性转方法
|
||||
result = System.Text.RegularExpressions.Regex.Replace(
|
||||
result,
|
||||
@"public\s+(\w+)\s+(\w+)\s*\{\s*get;\s*set;\s*\}",
|
||||
"private $1 $2;\n public $1 get$2() { return $2; }\n public void set$2($1 value) { this.$2 = value; }"
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 类型映射
|
||||
/// </summary>
|
||||
public class TypeMapping
|
||||
{
|
||||
public string SourceType { get; set; }
|
||||
public string TargetType { get; set; }
|
||||
|
||||
public TypeMapping(string source, string target)
|
||||
{
|
||||
SourceType = source;
|
||||
TargetType = target;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
using System.Text;
|
||||
using CodePlay.Core.Interfaces;
|
||||
using CodePlay.Core.Common;
|
||||
|
||||
namespace CodePlay.Core.Converters;
|
||||
|
||||
/// <summary>
|
||||
/// Java 代码生成器
|
||||
/// </summary>
|
||||
public class JavaCodeGenerator : ICodeGenerator
|
||||
{
|
||||
private readonly StringBuilder _output = new();
|
||||
private int _indentLevel;
|
||||
|
||||
/// <summary>
|
||||
/// 从语法树生成 Java 代码
|
||||
/// </summary>
|
||||
public string Generate(Interfaces.SyntaxTree syntaxTree)
|
||||
{
|
||||
_output.Clear();
|
||||
_indentLevel = 0;
|
||||
|
||||
// 生成 JavaDoc
|
||||
foreach (var doc in syntaxTree.Documentation)
|
||||
{
|
||||
_output.AppendLine("/**");
|
||||
_output.AppendLine($" * {doc.Content}");
|
||||
_output.AppendLine(" */");
|
||||
}
|
||||
|
||||
// 生成代码
|
||||
GenerateNode(syntaxTree.Root);
|
||||
|
||||
return _output.ToString();
|
||||
}
|
||||
|
||||
private void GenerateNode(Interfaces.SyntaxNode node)
|
||||
{
|
||||
switch (node.Type)
|
||||
{
|
||||
case SyntaxNodeType.CompilationUnit:
|
||||
GenerateCompilationUnit(node);
|
||||
break;
|
||||
case SyntaxNodeType.Namespace:
|
||||
GenerateNamespace(node);
|
||||
break;
|
||||
case SyntaxNodeType.Class:
|
||||
GenerateClass(node);
|
||||
break;
|
||||
case SyntaxNodeType.Method:
|
||||
GenerateMethod(node);
|
||||
break;
|
||||
case SyntaxNodeType.Property:
|
||||
GenerateProperty(node);
|
||||
break;
|
||||
case 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("{"));
|
||||
_indentLevel++;
|
||||
|
||||
foreach (var child in node.Children)
|
||||
{
|
||||
if (child.Type != SyntaxNodeType.Unknown)
|
||||
{
|
||||
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("{"));
|
||||
_indentLevel++;
|
||||
|
||||
// 生成方法体(简化处理)
|
||||
var methodBody = ExtractMethodBody(node.Text);
|
||||
if (!string.IsNullOrWhiteSpace(methodBody))
|
||||
{
|
||||
_output.AppendLine(Indent(methodBody));
|
||||
}
|
||||
|
||||
_indentLevel--;
|
||||
_output.AppendLine(Indent("}"));
|
||||
_output.AppendLine();
|
||||
}
|
||||
|
||||
private void GenerateProperty(Interfaces.SyntaxNode node)
|
||||
{
|
||||
var propertyDeclaration = node.Text;
|
||||
_output.AppendLine(Indent(propertyDeclaration));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
using CodePlay.Core.Interfaces;
|
||||
using CodePlay.Core.Models;
|
||||
using CodePlay.Core.Common;
|
||||
using CodePlay.Core.Parsers;
|
||||
using CodePlay.Core.Converters;
|
||||
|
||||
namespace CodePlay.Core.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 代码转换服务
|
||||
/// </summary>
|
||||
public class ConversionService
|
||||
{
|
||||
private readonly Dictionary<(LanguageType, LanguageType), IConverter> _converters = new();
|
||||
|
||||
public ConversionService()
|
||||
{
|
||||
// 注册转换器
|
||||
RegisterConverter(LanguageType.CSharp, LanguageType.Java, new CSharpToJavaConverter());
|
||||
}
|
||||
|
||||
private void RegisterConverter(LanguageType source, LanguageType target, IConverter converter)
|
||||
{
|
||||
_converters[(source, target)] = converter;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 转换代码
|
||||
/// </summary>
|
||||
public async Task<ConversionResult> ConvertAsync(ConversionRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var key = (request.SourceLanguage, request.TargetLanguage);
|
||||
|
||||
if (!_converters.TryGetValue(key, out var converter))
|
||||
{
|
||||
return new ConversionResult
|
||||
{
|
||||
Success = false,
|
||||
ErrorMessage = $"Conversion from {request.SourceLanguage} to {request.TargetLanguage} is not supported"
|
||||
};
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// 解析源代码
|
||||
var parser = CreateParser(request.SourceLanguage);
|
||||
if (parser == null)
|
||||
{
|
||||
return new ConversionResult
|
||||
{
|
||||
Success = false,
|
||||
ErrorMessage = $"Parser for {request.SourceLanguage} is not available"
|
||||
};
|
||||
}
|
||||
|
||||
var syntaxTree = await parser.ParseAsync(request.SourceCode, cancellationToken);
|
||||
|
||||
// 执行转换
|
||||
var result = await converter.ConvertAsync(syntaxTree, request.TargetLanguage, request.Options, cancellationToken);
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ConversionResult
|
||||
{
|
||||
Success = false,
|
||||
ErrorMessage = $"Conversion failed: {ex.Message}"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private IParser? CreateParser(LanguageType language)
|
||||
{
|
||||
return language switch
|
||||
{
|
||||
LanguageType.CSharp => new CSharpParser(),
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查是否支持指定的语言转换
|
||||
/// </summary>
|
||||
public bool IsConversionSupported(LanguageType source, LanguageType target)
|
||||
{
|
||||
return _converters.ContainsKey((source, target));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取支持的语言转换列表
|
||||
/// </summary>
|
||||
public List<(LanguageType Source, LanguageType Target)> GetSupportedConversions()
|
||||
{
|
||||
return _converters.Keys.ToList();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user