Skip to content

Commit 2c4565f

Browse files
committed
Add index.ts
1 parent 7d2e2d2 commit 2c4565f

File tree

3 files changed

+36
-11
lines changed

3 files changed

+36
-11
lines changed

src/compiler/binary-writer.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@ export class BinaryWriter {
3939
this.constantPool = []
4040
}
4141

42+
generateBinary(classFile: ClassFile) {
43+
return this.toBinary(classFile)
44+
}
45+
4246
writeBinary(classFile: ClassFile, filepath: string) {
4347
const filename = filepath + 'Main.class'
4448
const binary = this.toBinary(classFile)

src/compiler/compiler.ts

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import * as fs from 'fs'
2-
import * as peggy from 'peggy'
31
import { ClassFile } from '../ClassFile/types'
42
import { AST } from '../ast/types/packages-and-modules'
53
import {
@@ -55,15 +53,6 @@ export class Compiler {
5553
return classFiles[0]
5654
}
5755

58-
compileFromSource(javaProgram: string) {
59-
const javaPegGrammar = fs.readFileSync(__dirname + '/main.pegjs', 'utf8')
60-
const parser = peggy.generate(javaPegGrammar, {
61-
allowedStartRules: ['CompilationUnit']
62-
})
63-
const ast = parser.parse(javaProgram)
64-
return this.compile(ast)
65-
}
66-
6756
private compileClass(classNode: ClassDeclaration): ClassFile {
6857
const parentClassName = 'java/lang/Object'
6958
this.className = classNode.typeIdentifier

src/compiler/index.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import * as peggy from 'peggy'
2+
import { AST } from '../ast/types/packages-and-modules'
3+
import { Compiler } from './compiler'
4+
import { javaPegGrammar } from './grammar'
5+
import { BinaryWriter } from './binary-writer'
6+
7+
export const compile = (ast: AST): string => {
8+
const compiler = new Compiler()
9+
const classFile = compiler.compile(ast)
10+
11+
const binaryWriter = new BinaryWriter()
12+
const byteArray = binaryWriter.generateBinary(classFile)
13+
const base64encoded = Buffer.from(byteArray).toString('base64')
14+
15+
return base64encoded
16+
}
17+
18+
export const compileFromSource = (javaProgram: string): string => {
19+
const parser = peggy.generate(javaPegGrammar, {
20+
allowedStartRules: ['CompilationUnit'],
21+
cache: true
22+
})
23+
24+
let ast: AST
25+
try {
26+
ast = parser.parse(javaProgram)
27+
} catch (e) {
28+
throw new SyntaxError(e)
29+
}
30+
31+
return compile(ast)
32+
}

0 commit comments

Comments
 (0)