This repository has been archived by the owner on Oct 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
81 lines (64 loc) · 2.28 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import fs = require('fs')
import rimraf = require('rimraf')
import process = require('process')
import { logError, logInfo } from './src/debug-print'
import lex = require('./src/lexical-analyser')
import parser = require('./src/parser')
import generator = require('./src/code-generator')
import optimiser = require('./src/optimiser')
import child_process = require('child_process')
const tempFolder = `.\\tmp-${process.pid}\\`
const tempSource = 'compiled.c'
const tempCompiled = 'compiled.exe'
const gccDir = 'C:\\MinGW\\bin\\'
const gcc = 'g++.exe'
const compile = `${gccDir}${gcc} ${tempFolder}${tempSource} -o ${tempFolder}${tempCompiled}`
/* <command> <app> <target file> <debug> */
let filePath: string = (process.argv.length > 1) ? process.argv[2] : null
const debug = (process.argv.length > 2) ? (process.argv[3] == "--debug") : false
let log = (message: string) => {
if (debug) {
logInfo(message)
}
}
try {
/* Open file */
log(`Opening ${filePath}...`)
fs.readFileSync(filePath, 'utf8')
/* Get tokens */
log('Running lexical analyser...')
let tokens: Token[] = lex.readFile(filePath, debug)
/* Parse tokens into tree */
log('Running parser...')
let syntaxTree: SyntaxTree = parser.parseTokens(tokens, debug)
/* Optmise tree */
log('Running optimiser...')
let optimisedTree: SyntaxTree = optimiser.optimise(syntaxTree, debug)
/* Compile C code from tree */
log('Running compiler...')
let code: string = generator.compile(optimisedTree)
log(`Compiled code: \n${code}`)
/* Write C code to file */
log('Saving compiled code...')
if (!fs.existsSync(tempFolder)) {
fs.mkdirSync(tempFolder)
}
fs.writeFileSync(`${tempFolder}${tempSource}`, code)
/* Compile C code */
log('Making executable...')
child_process.execSync(compile)
/* Execute compiled code */
log('Running executable...')
let returned: Buffer = child_process.execFileSync(`${tempFolder}${tempCompiled}`)
console.log(returned.toString())
} catch (e) {
logError(e)
if (debug) {
logError(`Stack: ${(<Error>e).stack}`)
}
}
/* Cleanup */
log('Deleting temporary files...')
rimraf(tempFolder, () => {
log('Done!')
})