美文网首页
手拉手教你实现一门编程语言 Enkel, 系列 5

手拉手教你实现一门编程语言 Enkel, 系列 5

作者: KevinOfNeu | 来源:发表于2018-09-08 01:30 被阅读0次

本文系 Creating JVM language 翻译的第五篇。
原文中的代码和原文有不一致的地方均在新的代码仓库中更正过,建议参考新的代码仓库。

源码

Github

解析规则的更改

上一节中,我们定义了 Enkel 语言的特性。本节中我们来实现 “类”。

原来的解析规则:

compilationUnit : ( variable | print )* EOF;
variable : VARIABLE ID EQUALS value;

变更后的规则:

compilationUnit : classDeclaration EOF ; //root rule - our code consist consist only of variables and prints (see definition below)
classDeclaration : className '{' classBody '}' ;
className : ID ;
classBody :  ( variable | print )* ;
  • 一个文件有且仅有一个类声明
  • 类声明包含类型和大括号中的类主体
  • 类主体包含变量和打印语句(如我们之前的定义)

更改后的语法规则可视化如下所示:


image

Compiler 更改

主要改变是需要把原来的代码从 ByteCodeGenerator 移动到 CompilationUnitClassDeclaration,逻辑如下:

  1. Compiler 从 SyntaxParseTreeTraverser 获得 AST
  2. Compiler 实例化 CompilationUnit
//Compiler.java
final CompilationUnit compilationUnit = new SyntaxTreeTraverser().getCompilationUnit(fileAbsolutePath);
//Check getCompilationUnit() method body on github
  1. CompilationUnit 负责实例化 ClassDeclaration(需要传递类名和指令序列)
  2. ClassDeclaration 处理类定义指令,以及循环处理 ClassScopeInstructions
 //ClassDeclaration.java
 MethodVisitor mv = classWriter.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
 instructions.forEach(classScopeInstruction -> classScopeInstruction.apply(mv));
image

另外一点改动是: 输出的 .class 文件名字以类名为依据,而不是以 .enk 文件名字为依据。

String className = compilationUnit.getClassName();
String fileName = className + ".class";
OutputStream os = new FileOutputStream(fileName);
IOUtils.write(byteCode,os);

相关文章

网友评论

      本文标题:手拉手教你实现一门编程语言 Enkel, 系列 5

      本文链接:https://www.haomeiwen.com/subject/kcfkgftx.html