using System.Text; using CodePlay.Core.Interfaces; using CodePlay.Core.Common; namespace CodePlay.Core.Converters; public class JavaCodeGenerator : ICodeGenerator { private readonly StringBuilder _output = new(); private int _indentLevel; private bool _needCollectors; private bool _needCompletableFuture; public string Generate(Interfaces.SyntaxTree syntaxTree) { _output.Clear(); _indentLevel = 0; _needCollectors = false; _needCompletableFuture = false; var root = syntaxTree.Root; // 如果根节点的 Text 已经包含处理后的内容,直接使用 if (!string.IsNullOrEmpty(root.Text) && (root.Text.Contains("package ") || root.Text.Contains("import "))) { 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(root); 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 Interfaces.SyntaxNodeType.CompilationUnit: GenerateCompilationUnit(node); break; case Interfaces.SyntaxNodeType.Class: GenerateClass(node); break; case Interfaces.SyntaxNodeType.Method: GenerateMethod(node); break; case Interfaces.SyntaxNodeType.Property: GenerateProperty(node); break; case Interfaces.SyntaxNodeType.Field: GenerateField(node); break; } } private void GenerateCompilationUnit(Interfaces.SyntaxNode node) { foreach (var child in node.Children) GenerateNode(child); } private void GenerateClass(Interfaces.SyntaxNode node) { 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) GenerateNode(child); _indentLevel--; _output.AppendLine(Indent("}")); } private void GenerateMethod(Interfaces.SyntaxNode node) { 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 inBody = false; foreach (var line in lines) { if (line == "{") { inBody = true; continue; } if (line == "}") continue; if (inBody) _output.AppendLine(Indent(line)); } _indentLevel--; _output.AppendLine(Indent("}")); } private void GenerateProperty(Interfaces.SyntaxNode node) { if (!string.IsNullOrWhiteSpace(node.Text)) _output.AppendLine(Indent(node.Text.Trim())); } private void GenerateField(Interfaces.SyntaxNode node) { if (!string.IsNullOrWhiteSpace(node.Text)) _output.AppendLine(Indent(node.Text.Trim())); } private string Indent(string text) => new string(' ', _indentLevel * 4) + text; }