-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
214 lines (214 loc) · 11.9 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
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Compiler Explorer Tool</title>
<style>
body{overflow: scroll}
button, label, summary{font-size: 18px}
.toggle{cursor: pointer}
.toggle:not(.full) > .full, .toggle.full > .abbr{display: none}
.tabs{display: flex; flex-flow: row wrap; margin: 0; padding: 0; width: 100%}
#expand{display: block; flex: none; order: 3; width: 25px}
.tabs > .addtab{display: block; flex: none; font-weight: bold; order: 2; padding: 0 15px}
.tabs > .tab{border: 1px solid; border-radius: 5px 5px 0 0; display: grid; flex: auto; order: 1}
.editlabel:not([hidden]) + label, .tab:not(:has(:checked)) + .tabpanel{display: none}
.tabpanel{flex: none; width: 100%; order: 4; position: relative}
#source textarea{height: calc(100vh - 350px); margin: 1px}
#expand.full ~ .tabpanel textarea{height: calc(100vh - 80px)}
.format{opacity: 0.8; position: absolute; right: 1px; top: 3px}
#source textarea, .output{font-family: monospace; white-space: pre-wrap; word-break: break-all}
.input, .output{box-sizing: border-box; margin: 1px; padding: 1px; width: 100%}
#container label{white-space: nowrap}
#fromlink{display: flex; width: 100%}
#fromlink > input{flex: auto}
#output:not([data-loading="0"])::before{content: 'loading...'; display: block}
#stdout:not(:empty)::before, #stderr:not(:empty)::before{content: attr(id) ':'; font-size: x-small}
.output .bold{font-weight: bold}
.output .red{color: red}
.output .green{color: green}
.output .yellow{color: orange}
.output .blue{color: blue}
.output .magenta{color: magenta}
.output .cyan{color: darkcyan}
.output .bold.green:only-child{font-weight: normal}
</style>
<ul id="source" class="tabs">
<li id="expand" class="toggle"><button class="abbr">v</button><button class="full">^</button>
<li class="addtab">+
<li class="tab"><input class="editlabel" hidden><label><input type=radio name="source" checked><a></a></label>
<li class="tabpanel"><button class="format">format</button><textarea class="input"></textarea>
</ul>
<input id="goptions" class="input">
<ul id="container" class="tabs">
<li class="addtab">+
<li class="tab"><input class="editlabel" hidden><label><input type=radio name="container"><a></a></label>
<li class="tabpanel">
<input class="input options">
<select class="input compiler"><option value="gsnapshot"></select>
<details class="filters" open><summary>options</summary>
<label><input type=checkbox name="binaryObject" data-enableif="supportsBinaryObject">binaryObject</label>
<label><input type=checkbox name="binary" data-enableif="supportsBinary">binary</label>
<label><input type=checkbox name="execute" data-enableif="supportsExecute">execute</label>
<label><input type=checkbox name="labels" checked>labels</label>
<label><input type=checkbox name="libraryCode" data-enableif="supportsLibraryCodeFilter" checked>libraryCode</label>
<label><input type=checkbox name="directives" checked>directives</label>
<label><input type=checkbox name="commentOnly" checked>commentOnly</label>
<label><input type=checkbox name="trim" checked>trim</label>
<label><input type=checkbox name="intel" data-enableif="supportsIntel" checked>intel</label>
<label><input type=checkbox name="demangle" data-enableif="supportsDemangle" checked>demangle</label>
</details>
<details><summary>execute</summary>
<input class="input exeargs">
<textarea class="input stdin" placeholder="stdin"></textarea>
</details>
<button name="asm">assembly</button>
<button name="output">output</button>
<button name="ast" data-enableif="supportsAstView">ast</button>
</ul>
<div id="fromlink"><input value="https://godbolt.org/z/qoE4Gqqfn"><button>fill</button></div>
<p id="output" class="output" data-loading="1"><p id="stdout" class="output"><p id="stderr" class="output"></p>
<script>
let request = (url, req = {}, type = 'application/json') =>
fetch('https://godbolt.org/api'+url, {...req, headers: {'Content-Type': type, 'Accept': type}});
let cacheGet = async (cache, i, url) => JSON.parse(cache[i] ??= await request(url).then(x => x.text()));
let stored = (s) => JSON.parse(sessionStorage[s]) ?? [];
let getCompilers = (use_cache = sessionStorage) => cacheGet(use_cache, 'compilers',
'/compilers?fields=id,name,lang,groupName,supportsBinaryObject,' +
'supportsBinary,supportsExecute,supportsLibraryCodeFilter,supportsIntel,supportsDemangle,supportsAstView');
let getInfo = (s, use_cache = localStorage) => cacheGet(use_cache, `preload-${s}`, '/shortlinkinfo/'+s);
let compile = (id, body) => request('/compiler/'+id+'/compile', {method: 'post', body}).then(x => x.json());
let format = (source, body = JSON.stringify({base: 'LLVM', source: source.value})) =>
request('/format/clangformat', {method: 'post', body}).then(x => x.json()).then(x => source.value = x.answer);
let qS = (selector) => document.querySelector(selector);
let qSA = (selector) => [...document.querySelectorAll(selector)];
let create = (tag, props) => Object.assign(document.createElement(tag), props);
function init(node, nodes = []) {
node.replaceChildren(...nodes);
return node;
}
let make_toggle = ({abbr, full, tooltip = ''}) => `<span class="toggle"><span class="abbr" title="${tooltip}">`+
`${abbr}</span><span class="full">${full}</span></span>`;
function clonelabeledtab(old, node = old.cloneNode(true), edit = node.querySelector('.editlabel')) {
node.querySelector('label').addEventListener('dblclick', () => Object.assign(edit, {hidden: false}).focus());
edit.addEventListener('blur', () => {
if (Object.assign(edit, {hidden: true}).value) node.querySelector('label a').text = edit.value;
});
return node;
}
function setuppanel(s, p = s.closest('.tabpanel'), c = stored('compilers').find(x => x.id === s.value)) {
p.previousSibling.querySelector('label a').text = c?.groupName ?? '';
[...p.querySelectorAll('[data-enableif]')].forEach(x => x.disabled = !c?.[x.dataset.enableif]);
}
function loadstate({sessions: [s]}, startup, t = qS('#container')) {
if (!startup) qS('#source textarea').value = s.source;
init(t, [t.querySelector('.addtab'), ...[...s.compilers, ...s.executors.map(x => x.compiler)].flatMap(c => {
const panel = t.querySelector('.tabpanel').cloneNode(true);
[panel.querySelector('.options').value, panel.querySelector('.compiler').value] = [c.options, c.id];
[...panel.querySelectorAll('input[type=checkbox]')].forEach(e => e.checked = c.filters[e.name]);
return [clonelabeledtab(t.querySelector('.tab')), panel];
})]);
qSA('.tabpanel .compiler').forEach(c => setuppanel(c));
t.querySelector('.tab input[type=radio]').checked = true;
}
let shortlink = () => qS('#fromlink > input').value.match(/\/z\/([-\w]+)/)[1];
Promise.all([getInfo(shortlink()), getCompilers()]).then(([info, compilers]) => {
compilers.sort((x, y) => x.id.localeCompare(y.id));
const options = compilers.map(x => create('option', {text: x.lang+' : '+x.name, value: x.id}));
const groups = compilers.reduce((a, x, i) => ((a[x.groupName ?? ''] ??= []).push(options[i]), a), {});
init(qS('.compiler'), Object.keys(groups).map(name => init(create('optgroup', {label: name}), groups[name])));
loadstate(info, true);
}).finally(() => qS('#output').dataset.loading--);
document.addEventListener('click', e => e.target.closest('.toggle')?.classList.toggle('full'));
document.addEventListener('click', e => e.target.matches('.format') && format(e.target.nextSibling));
document.addEventListener('input', e => e.target.matches('.compiler') && setuppanel(e.target));
qS('#fromlink > button').addEventListener('click', () => getInfo(shortlink(), false).then(loadstate));
qSA('.addtab').forEach(b => b.addEventListener('click', e => {
const panel = e.target.closest('.tabs').querySelector('.tab:has(:checked) + .tabpanel, :scope > :last-child');
panel.after(clonelabeledtab(panel.previousSibling), panel.cloneNode(true));
(panel.nextSibling.nextSibling.querySelector('select') ?? {}).value = panel.querySelector('select')?.value;
}));
let actions = {};
let cache = {};
function display(output, attr, data = []) {
const lines = data.map(line => init(create('div'), [line.text]).innerHTML);
const adjusted = Object.values(actions).reduce((h, f) => f(h, {attr}), lines);
init(output, adjusted.map(line => create('div', {innerHTML: line})));
}
qS('#container').addEventListener('click', async ({target: button}) => {
if (!button.matches('button')) return;
qS('#output').dataset.loading++;
try {
const p = button.closest('.tabpanel');
const source = qS('#source textarea').value;
const filenames = qSA('#filenames .text').slice(1).map(a => a.text);
const files = filenames.map((filename, i) => ({filename, contents: qSA('#source textarea')[i+1].value}));
const compiler = p.querySelector('.compiler').value;
const userArguments = qS('#goptions').value+' '+p.querySelector('.options').value;
const compilerOptions = {produceAst: button.name === 'ast', executorRequest: files.length, skipPopArgs: true};
const filterElems = [...p.querySelectorAll('.filters input')];
const filters = Object.fromEntries(filterElems.map(e => [e.name, e.checked]));
const [args, stdin] = ['.exeargs', '.stdin'].map(x => p.querySelector(x).value);
const executeParameters = {args, stdin};
const k = JSON.stringify({source, files, compiler, userArguments, filters, executeParameters});
let res = cache[k];
if (!res || button.name === 'ast' && !res.astOutput) {
const options = {userArguments, compilerOptions, filters, executeParameters};
res = await compile(compiler, JSON.stringify({source, files, options}));
if (res.okToCache) cache[k] = {...cache[k], ...res};
}
const [output, out, err] = qSA('.output').map(output => init(output));
if (button.name === 'ast')
display(output, 'ast', res.astOutput);
else if (button.name === 'asm')
display(output, 'asm', res.asm);
else if ((res.execResult ?? res)?.didExecute === false)
[out, err].forEach(o => display(o, '', (res.execResult ?? res).buildResult[o.id]));
else
[out, err].forEach(o => display(o, '', (res.execResult ?? res)[o.id]));
} finally {
qS('#output').dataset.loading--;
}
});
let add_action = (f) => actions[f.name] = window[f.name] = f;
let replace = (h, re, cb) => h.map(s => s.replace(/(?<=^|>)(.+?)(?=<|$)/g, (m, p1) => p1.replace(re, cb)));
add_action(function strip_ast_output(data, e) {
if (e.attr !== 'ast') return data;
const t = data.map((s, i) => [s, i]).filter(a => a[0].match(/^\x1B\[0;34m[`|]-/)).reverse();
t.forEach((a, i) => a[0].match(/\x1B\[0m implicit\b/) && data.splice(a[1], t[i-1][1] - a[1]));
return replace(data, /\x1B\[0;33m 0x[a-f0-9]+/g, '');
});
add_action(function colorize(data, e) {
if (e.attr === 'asm') return data;
const classmap = {0: '', 1: 'bold', 31: 'red', 32: 'green', 33: 'yellow', 34: 'blue', 35: 'magenta', 36: 'cyan'};
return replace(data, /\x1B\[(.*?)m(?:\x1B\[K)?(.*?)(?=\x1B\[|$)/mg,
(m, p1, p2) => `<span class="${p1.split(';').map(x => classmap[+x]).join(' ')}">${p2}</span>`);
});
add_action(function hyperlink(data, e) {
if (e.attr === 'asm') return data;
return replace(data, /\x1B\]8;;(.*?)\x07(.*?)\x1B]8;;\x07/g, (m, p1, p2) => `<a href="${p1}">${p2}</a>`);
});
add_action(function shorten_filename(data, e) {
const f = RegExp('/opt/compiler-explorer/\\S*?/include/c\\+\\+/[^\\s/]*?/', 'g');
return replace(data, f, m => make_toggle({abbr: '.../', full: m, tooltip: m}));
});
add_action(function shorten_decl(data, e) {
return replace(data, /^.*$/g, (m) => {
let re = /<<|->|(\(|\[|<)|(\)|\]|>)|($)/g;
for (let s = '', r, lastindex, stack = []; r = re.exec(m); lastindex = r.index) {
s += m.slice(lastindex, r.index);
if (r[1]) stack.push({...r, pos: s.length + r[0].length});
if (r[2]) {
while (stack.length && r[0] !== '>' && stack.at(-1)[1] !== {')': '(', ']': '['}[r[0]])
stack.pop();
if (stack.length && (r[0] !== '>' || stack.at(-1)[1] === '<')) {
const l = stack.pop();
const [full, tooltip] = [s.slice(l.pos), m.slice(l.index + l[0].length, r.index)];
if (r.index - l.index > 30)
s = s.slice(0, l.pos) + make_toggle({abbr: '...', full, tooltip});
}
}
if (r[3] === '') return s;
}
});
});
</script>