This repository has been archived by the owner on Nov 14, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
299 lines (251 loc) · 13.8 KB
/
index.html
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
<!--
TODO
- Defer fetching compiler until first compilation
- Implement different targets
- Only fetch files required for each target
-->
<html>
<head>
<meta charset="utf-8">
<title>The WebAssembly Go Compiler</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/wasm_exec.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/lz-string.min.js"></script>
<script src="js/jquery-linedtextarea.js"></script>
<script src="js/playground.js"></script>
<script>
// For future when multiple OSs and Architectures are supported
var target = ""
// Generates a random name for a file if none is specified
function makeFileID(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function download(data, filename=makeFileID(10)){
// Create an element to contain the binary as a data URI
var downloadLink = document.createElement('a');
// Generate a URI from the file
var blob = new Blob([data], {type: "application/octet-stream"});
// Set it's href to the binary URI
downloadLink.href = URL.createObjectURL(blob);
// Set the download filename
downloadLink.download = filename;
// Firefox requires the link to be in the body so make it invisible and add it
downloadLink.style.visibility = "hidden";
document.body.appendChild(downloadLink);
// Simulate click on the link (trigger download)
downloadLink.click();
// Remove the link when done
document.body.removeChild(downloadLink);
}
$(document).ready(function() {
// Set up code area
$('#code').linedtextarea();
$('#code').attr('wrap', 'off');
// Ensure the browser supports webassembly
if (!WebAssembly || !WebAssembly.instantiate) {
$('#run').val('Unsupported Browser');
$('#controls input select').attr('disabled', true);
return;
}
let cmds = {};
// Define function to execute Go webassembly in its environment
const exec = (wasm, args, env={}) => new Promise((resolve, reject) => {
const go = new Go();
go.exit = resolve;
go.argv = go.argv.concat(args || []);
go.env = env;
WebAssembly.instantiate(wasm, go.importObject).then((result) => go.run(result.instance)).catch(reject);
});
// Create a semi-random download filename
$('#filename').val("IBGC-"+Math.floor(Date.now() / 1000)+"-"+makeFileID(5));
// Keep track of which components we have fetched last in order to avoid re-fetching
var currentTargetComponents = null;
// Create the encoder and decoder to transfer files between the Go filesystem and JS.
// This was originally within the Promise but was moved out when splitting up the Promise
// to more easily allow supporting multiple targets
const decoder = new TextDecoder('utf-8');
const encoder = new TextEncoder('utf-8');
// Prefetch components which are used regardless of platform
['compile', 'link', 'gofmt']
.map((cmd) => fetch('compiler/cmd/' + cmd + '.wasm')
.then((response) => response.arrayBuffer())
.then((buf) => {
cmds[cmd] = new Uint8Array(buf);
}).then(() => {
// Hide loading and show the controls
$('#loading').hide();
$('#controls').show();
})
)
// Create the "playground" to handle the compiling
playground({
codeEl: '#code',
outputEl: '#output',
runEl: '#run',
enableHistory: false,
enableShortcuts: true,
transport: {
Run: (body, output) => {
// Check if the target was selected or not and refuse to compile if not
if (currentTargetComponents == null || currentTargetComponents == "null") {
output({
Kind: 'start',
});
output({
Kind: 'stderr',
Body: 'Please select a target OS/Arch first!',
});
output({
Kind: 'end',
});
} else {
$('#controls input select').attr('disabled', true);
writeToGoFilesystem('/main.go', body);
output({
Kind: 'start',
});
goStderr = (buf) => {
output({
Kind: 'stderr',
Body: decoder.decode(buf),
});
};
goStdout = (buf) => {
output({
Kind: 'stdout',
Body: decoder.decode(buf),
});
};
// Let the user know that the compiler is starting as sometimes it takes a while
output({
Kind: 'stdout',
Body: 'Starting compilation...\n',
});
// Get the target OS and arch to compile for. These will be placed in environment variables for the compiler
const target = currentTargetComponents.split("/");
// Arguments to pass to the compiler
var compileArgs = ['-v', '-p', 'main', '-complete', '-goversion', 'go1.15.1', '-dwarf=false', '-pack', '-importcfg', 'importcfg', 'main.go'];
// Arguments to pass to the linker
var linkArgs = ['-v', '-s', '-w', '-importcfg', 'importcfg.link', '-buildmode=pie', '-o', 'a.out', 'main.a'];
exec(cmds['compile'], compileArgs, {"GOOS": target[0], "GOARCH": target[1]})
.then((code) => code || exec(cmds['link'], linkArgs, {"GOOS": target[0], "GOARCH": target[1]}))
.then((code) => code || download(readFromGoFilesystem('a.out'), $('#filename').val()))
.then((code) => {
output({
Kind: 'end',
Body: code ? 'status ' + code + '.' : undefined,
});
})
.catch((err) => {
output({
Kind: 'end',
Body: 'wasm error: ' + (err.message || 'unknown'),
});
})
.finally(() => $('#controls input select').attr('disabled', false))
;
return {
Kill: () => {},
};
}
},
},
});
$('#target').bind('change click', function(event) {
// If the selected components are not the ones previously selected, and they are not
// "null", fetch the new components
if (currentTargetComponents != $('#target').val() && $('#target').val() != "null") {
// Lock the controls while new components are being fetched, and show loading
$('#controls').hide();
$('#loading').show()
Promise.all(
[
'/runtime.a',
'/internal/bytealg.a',
'/internal/cpu.a',
'/runtime/internal/atomic.a',
'/runtime/internal/math.a',
'/runtime/internal/sys.a',
].map((path) => fetch('compiler/prebuilt/'+$('#target').val()+path)
.then((response) => response.arrayBuffer())
.then((buf) => writeToGoFilesystem('prebuilt'+path, new Uint8Array(buf)))
)
).then(() => {
writeToGoFilesystem('/importcfg', encoder.encode(
"packagefile runtime=prebuilt/runtime.a"
));
writeToGoFilesystem('/importcfg.link', encoder.encode(
"packagefile command-line-arguments=main.a\n" +
"packagefile runtime=prebuilt/runtime.a\n" +
"packagefile internal/bytealg=prebuilt/internal/bytealg.a\n" +
"packagefile internal/cpu=prebuilt/internal/cpu.a\n" +
"packagefile runtime/internal/atomic=prebuilt/runtime/internal/atomic.a\n" +
"packagefile runtime/internal/math=prebuilt/runtime/internal/math.a\n" +
"packagefile runtime/internal/sys=prebuilt/runtime/internal/sys.a"
));
// Set the current target components to the ones just loaded to avoid needlessly reloading
currentTargetComponents = $('#target').val();
// Hide loading and show the controls again
$('#loading').hide();
$('#controls').show();
})
} else if ($('#target').val() == "null") {
// Disallow switching back to "please select"
$('#target').val(currentTargetComponents);
}
});
// Define what format does
$('#fmt').click(() => {
$('#controls input select').attr('disabled', true);
writeToGoFilesystem('/main.go', $('#code').val());
goStderr = (buf) => console.log(decoder.decode(buf));
goStdout = goStderr;
exec(cmds['gofmt'], ['-w', 'main.go'])
.then((code) => {
if (!code) {
$('#code').val(decoder.decode(readFromGoFilesystem('main.go')));
}
})
.finally(() => $('#controls input select').attr('disabled', false))
;
});
});
</script>
</head>
<body itemscope itemtype="http://schema.org/CreativeWork">
<div id="banner">
<div id="head" itemprop="name">The WebAssembly Go Compiler</div>
<p id="loading" style="float:left;padding:0px;font-family:sans-serif;font-style:italic;">Loading compiler components. This may take a while...</p>
<div id="controls" style="display:none;">
<input type="text" placeholder="File Name" id="filename" />
<select id="target">
<option value="null" selected="selected">(Please Select)</option>
<optgroup label="Linux">
<option value="linux/amd64">Linux/AMD64</option>
</optgroup>
<optgroup label="Windows">
<option value="windows/amd64">Windows/AMD64</option>
</optgroup>
</select>
<input type="button" value="Compile" id="run" />
<input type="button" value="Format" id="fmt" />
</div>
<a style="float:right;padding:15px;font-family:sans-serif;" href="https://github.com/TR-SLimey/IBGC" target="_blank">github.com/TR-SLimey/IBGC</a>
</div>
<div id="wrap">
<textarea itemprop="description" id="code" name="code" autocorrect="off" autocomplete="off" autocapitalize="off" spellcheck="false">package main
func main() {
println("Hello from WebAssembly Go Compiler!")
}
</textarea>
</div>
<div id="output"></div>
</body>
</html>