-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
146 lines (136 loc) · 4.17 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import * as fs from 'fs';
import * as path from 'path';
const args = process.argv.slice(2);
const sourceFile = args.shift();
const code = fs.readFileSync(sourceFile, 'utf-8');
const programName = path.basename(sourceFile, '.bf');
type Command = {name: string, command: string};
type CommandMatcher = (code: string) => Command;
const defaultMatcher = (name: string, regexp: RegExp): CommandMatcher => {
return (code): Command => {
const match = code.match(regexp);
if (match) {
return {
name,
command: match[0]
}
}
return undefined;
};
}
const commandMatchers: CommandMatcher[] = [
code => {
const match = code.match(/^\[-(>+)\+(<+)\]/);
if (match && match[1].length === match[2].length) {
return {
name: 'moveValR',
command: match[0]
}
}
return undefined
},
code => {
const match = code.match(/^\[-(<+)\+(>+)\]/);
if (match && match[1].length === match[2].length) {
return {
name: 'moveValL',
command: match[0]
}
}
return undefined
},
defaultMatcher('clear', /^\[-\]/),
defaultMatcher('moveR', /^>+/),
defaultMatcher('moveL', /^<+/),
defaultMatcher('plus', /^\++/),
defaultMatcher('minus', /^\-+/),
defaultMatcher('opn', /^\[/),
defaultMatcher('cls', /^\]/),
defaultMatcher('get', /^,/),
defaultMatcher('put', /^\./),
];
const gen = (code: string): string[] => {
const oneLinerCode = code.replace(/\n/g, '');
const steps: string[] = [];
let nestCount = 0;
for (let i = 0; oneLinerCode[i];) {
const currentCode = oneLinerCode.slice(i);
const match = commandMatchers.map(matcher => matcher(currentCode)).find(m=>m);
const nest = () => ' '.repeat(nestCount);
if (match?.name === 'opn') {
steps.push(`${nest()}while (m[p]) {`);
nestCount++;
} else if (match?.name === 'cls') {
nestCount--;
steps.push(`${nest()}}`);
} else if (match?.name === 'moveValR') {
const delta = (match.command.length - 4) / 2;
steps.push(`${nest()}m[p+${delta}]+=m[p];`);
steps.push(`${nest()}m[p]=0;`);
} else if (match?.name === 'moveValL') {
const delta = (match.command.length - 4) / 2;
steps.push(`${nest()}m[p-${delta}]+=m[p];`);
steps.push(`${nest()}m[p]=0;`);
} else if (match?.name === 'clear') {
steps.push(`${nest()}m[p]=0;`);
} else if (match?.name === 'moveR') {
steps.push(`${nest()}p+=${match.command.length};`);
} else if (match?.name === 'moveL') {
steps.push(`${nest()}p-=${match.command.length};`);
} else if (match?.name === 'plus') {
steps.push(`${nest()}m[p]+=${match.command.length};`);
} else if (match?.name === 'minus') {
steps.push(`${nest()}m[p]-=${match.command.length};`);
} else if (match?.name === 'put') {
steps.push(`${nest()}write(m[p]);`);
} else if (match?.name === 'get') {
steps.push(`${nest()}m[p]=await read();`);
} else if ( currentCode[0] != '\n') {
const lastStep = steps.pop();
if (lastStep && lastStep.trim().startsWith('//')) {
steps.push(lastStep + currentCode[0]);
} else {
steps.push(lastStep);
steps.push(`${nest()}// ${currentCode[0]}`)
}
}
i += match?.command?.length || 1;
}
return steps;
}
const genCode =`// Generate from brainfuck code
const write = char => {
if (char > -1) {
process.stdout.write(String.fromCodePoint(char));
}
};
const read = (() => {
const buffer = [];
return () => new Promise((resolve, _) => {
if (buffer.length) {
resolve(buffer.shift());
} else {
process.stdin
.resume()
.setEncoding('utf8')
.once('data', (chunk) => {
buffer.push(...Array.from(chunk).map(c=>c.codePointAt(0)));
resolve(buffer.shift());
process.stdin.pause();
})
.once('end',() => {
buffer.push(-1);
});
}
});
})();
const m = new Int8Array(30000).fill(0);
let p = 0;
(async() => {
${gen(code).join('\n ')}
})();`;
//eval(genCode);
const binPath = path.join(__dirname, 'bin');
fs.mkdirSync(binPath, { recursive: true });
const srcPath = path.join(binPath, `${programName}.js`);
fs.writeFileSync(srcPath, genCode);