package org.jcnc.snow.compiler; import org.jcnc.snow.compiler.lexer.LexerEngine; import org.jcnc.snow.compiler.lexer.token.Token; import org.jcnc.snow.compiler.parser.core.ParserEngine; import org.jcnc.snow.compiler.parser.ast.ModuleNode; import org.jcnc.snow.compiler.parser.context.ParserContext; import org.jcnc.snow.compiler.parser.ast.base.Node; import org.jcnc.snow.compiler.semantic.core.SemanticAnalyzer; import org.jcnc.snow.compiler.semantic.error.SemanticError; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws IOException { // 读取源文件 String source = Files.readString(Path.of(args[0]), StandardCharsets.UTF_8); // 1. 词法分析 LexerEngine lexerEngine = new LexerEngine(source); List tokens = lexerEngine.getAllTokens(); // 2. 语法分析 ParserContext ctx = new ParserContext(tokens); List ast = new ParserEngine(ctx).parse(); // 3. 语义分析 // 3. 语义分析 // parse() 返回的是顶层 Node 列表,我们只关心 ModuleNode List modules = new ArrayList<>(); for (Node n : ast) { if (n instanceof ModuleNode m) { modules.add(m); } } SemanticAnalyzer analyzer = new SemanticAnalyzer(true); List errors = analyzer.analyze(modules); if (!errors.isEmpty()) { System.err.println("语义分析发现错误:"); for (SemanticError e : errors) { System.err.println(" " + e); } // 遇到错误直接退出 System.exit(1); } else { // 无错误时也打印一条成功信息 System.out.println("语义分析通过,没有发现错误。"); } // 打印 // System.out.println(source); // TokenPrinter.print(tokens); // 打印 Token 列表 // ASTPrinter.print(ast); // 打印 AST // ASTPrinter.printJson(ast); // 打印JSON AST } }