-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpreprocess_browser.js
More file actions
90 lines (83 loc) · 2.87 KB
/
preprocess_browser.js
File metadata and controls
90 lines (83 loc) · 2.87 KB
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
// Browser-compatible specialization of the gamestate engine.
// Imports deps from deps.js (single source of truth, shared with CLI preprocess.js).
import { deps } from './deps.js';
import { preprocessJavaScript } from './preprocessor.js';
const implies = {};
for (let x in deps) {
let ys = deps[x];
for (let y of ys) {
if (implies[y] === undefined) {
implies[y] = [];
}
implies[y].push(x);
}
}
function resolveDefines(config) {
const defines = {};
const visited = {};
let go = true;
while (go) {
go = false;
const new_defines = {};
for (let xd of [config, defines]) {
for (let key in xd) {
if (visited[key]) {
continue;
}
visited[key] = true;
go = true;
if (implies[key] !== undefined) {
for (let implies_key of implies[key]) {
if (defines[implies_key] === undefined) {
new_defines[implies_key] = true;
}
}
}
}
}
for (let new_key in new_defines) {
defines[new_key] = true;
}
}
return defines;
}
// Take the raw gamestate.jscpp source and a preprocessor config,
// and return a code string suitable for new Function() injection.
// The result has no import/export statements, no this.log() calls,
// and returns { Player, GameState } when called.
export function specializeGamestate(gamestateSource, config) {
const defines = resolveDefines(config);
// Run the C-preprocessor-style preprocessing
let code = preprocessJavaScript(gamestateSource, defines);
// Transform from ES module to injectable function body:
const lines = code.split('\n');
const out = [];
for (let line of lines) {
const trimmed = line.trim();
// Replace the import line with stance constants (other imports are passed as function args)
if (trimmed.startsWith('import ') && trimmed.includes('card_info')) {
out.push('const NO_STANCE = 0;');
out.push('const FIST_STANCE = 1;');
out.push('const STICK_STANCE = -1;');
continue;
}
// Remove export { ready };
if (trimmed === 'export { ready };') {
continue;
}
// Strip this.log(...) calls for nolog
if (/^\s*this\.log\(/.test(line)) {
continue;
}
// Remove 'export' keyword from declarations
if (trimmed.startsWith('export class ') ||
trimmed.startsWith('export const ') ||
trimmed.startsWith('export function ')) {
out.push(line.replace('export ', ''));
continue;
}
out.push(line);
}
out.push('return { Player, GameState };');
return out.join('\n');
}