File tree Expand file tree Collapse file tree 3 files changed +36
-11
lines changed
Expand file tree Collapse file tree 3 files changed +36
-11
lines changed Original file line number Diff line number Diff 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 )
Original file line number Diff line number Diff line change 1- import * as fs from 'fs'
2- import * as peggy from 'peggy'
31import { ClassFile } from '../ClassFile/types'
42import { AST } from '../ast/types/packages-and-modules'
53import {
@@ -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
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments