Javac 语法分析1

it2023-11-05  81

Javac 语法分析1

语法分析: 根据一个个 Token 构造出抽象语法树

语法树节点类

基类 JCTree 其他类均在 JCTree 里 定义的静态内部类,比如

JCStatement in JCTree (com.sun.tools.javac.tree) 表示语句 JCMethodDecl in JCTree (com.sun.tools.javac.tree) 表示一个方法定义,包括抽象 和 非抽象方法 JCModifiers in JCTree (com.sun.tools.javac.tree) 修饰符,如 如public等 JCTypeParameter in JCTree (com.sun.tools.javac.tree) 类型参数,比如类,接口 JCImport in JCTree (com.sun.tools.javac.tree) 导入声明 JCExpression in JCTree (com.sun.tools.javac.tree) 表达式 JCCompilationUnit in JCTree (com.sun.tools.javac.tree) 一个Java源文件对应一个 JCCompilationUnit JCCatch in JCTree (com.sun.tools.javac.tree) TypeBoundKind in JCTree (com.sun.tools.javac.tree)

文法

[x] 表示 x 可以出现 0 次或者一次; {x} 表示 x 可以出现 0 次或者多次; (x|y) 表示可以出现 x 或者 y

建立语法树

入口 com.sun.tools.javac.parser.JavacParser#parseCompilationUnit() 解析 包声明、ImportDeclaration 与 TypeDeclaration,然后创建一个编译单元.

public JCTree.JCCompilationUnit parseCompilationUnit() { Token firstToken = token; JCExpression pid = null; JCModifiers mods = null; boolean consumedToplevelDoc = false; boolean seenImport = false; // 看到了 import 的 token boolean seenPackage = false; // 看到了 package 的 token List<JCAnnotation> packageAnnotations = List.nil(); if (token.kind == MONKEYS_AT) // 解析包上注解 mods = modifiersOpt(); if (token.kind == PACKAGE) { // 解析包 seenPackage = true; if (mods != null) { checkNoMods(mods.flags); packageAnnotations = mods.annotations; mods = null; } nextToken(); // 读取下一个token pid = qualident(false); // 解析包名 accept(SEMI); // 处理包名最后的 分号(;) } ListBuffer<JCTree> defs = new ListBuffer<JCTree>(); boolean checkForImports = true; boolean firstTypeDecl = true; while (token.kind != EOF) { if (token.pos > 0 && token.pos <= endPosTable.errorEndPos) { // error recovery skip(checkForImports, false, false, false); if (token.kind == EOF) break; } if (checkForImports && mods == null && token.kind == IMPORT) { // 解析 import seenImport = true; defs.append(importDeclaration()); // 处理 import 声明 } else { // 解析 类型声明 Comment docComment = token.comment(CommentStyle.JAVADOC); if (firstTypeDecl && !seenImport && !seenPackage) { docComment = firstToken.comment(CommentStyle.JAVADOC); consumedToplevelDoc = true; } JCTree def = typeDeclaration(mods, docComment); // 类型声明 if (def instanceof JCExpressionStatement) def = ((JCExpressionStatement)def).expr; defs.append(def); if (def instanceof JCClassDecl) checkForImports = false; mods = null; firstTypeDecl = false; } } JCTree.JCCompilationUnit toplevel = F.at(firstToken.pos).TopLevel(packageAnnotations, pid, defs.toList()); if (!consumedToplevelDoc) attach(toplevel, firstToken.comment(CommentStyle.JAVADOC)); if (defs.isEmpty()) storeEnd(toplevel, S.prevToken().endPos); if (keepDocComments) toplevel.docComments = docComments; if (keepLineMap) toplevel.lineMap = S.getLineMap(); toplevel.endPositions = this.endPosTable; return toplevel; }
最新回复(0)