-
-
Notifications
You must be signed in to change notification settings - Fork 419
Expand file tree
/
Copy pathwebidl.js
More file actions
451 lines (425 loc) · 12.5 KB
/
webidl.js
File metadata and controls
451 lines (425 loc) · 12.5 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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// Module core/webidl
// Highlights and links WebIDL marked up inside <pre class="idl">.
// TODO:
// - It could be useful to report parsed IDL items as events
// - don't use generated content in the CSS!
import {
addHashId,
showInlineError,
showInlineWarning,
xmlEscape,
} from "./utils.js";
import { decorateDfn, findDfn } from "./dfn-finder.js";
import { html, webidl2 } from "./import-maps.js";
import { addCopyIDLButton } from "./webidl-clipboard.js";
import { fetchAsset } from "./text-loader.js";
import { registerDefinition } from "./dfn-map.js";
export const name = "core/webidl";
const operationNames = {};
const idlPartials = {};
const templates = {
wrap(items) {
return items
.flat()
.filter(x => x !== "")
.map(x => (typeof x === "string" ? new Text(x) : x));
},
trivia(t) {
if (!t.trim()) {
return t;
}
return html`<span class="idlSectionComment">${t}</span>`;
},
generic(keyword) {
// Shepherd classifies "interfaces" as starting with capital letters,
// like Promise, FrozenArray, etc.
return /^[A-Z]/.test(keyword)
? html`<a data-xref-type="interface" data-cite="WebIDL">${keyword}</a>`
: // Other keywords like sequence, maplike, etc...
html`<a data-xref-type="dfn" data-cite="WebIDL">${keyword}</a>`;
},
reference(wrapped, unescaped, context) {
if (context.type === "extended-attribute" && context.name !== "Exposed") {
return wrapped;
}
let type = "_IDL_";
let cite = null;
let lt;
switch (unescaped) {
case "Window":
type = "interface";
cite = "HTML";
break;
case "object":
type = "interface";
cite = "WebIDL";
break;
default: {
const isWorkerType = unescaped.includes("Worker");
if (isWorkerType && context.type === "extended-attribute") {
lt = `${unescaped}GlobalScope`;
type = "interface";
cite = ["Worker", "DedicatedWorker", "SharedWorker"].includes(
unescaped
)
? "HTML"
: null;
}
}
}
return html`<a data-xref-type="${type}" data-cite="${cite}" data-lt="${lt}"
>${wrapped}</a
>`;
},
name(escaped, { data, parent }) {
if (data.idlType && data.idlType.type === "argument-type") {
return html`<span class="idlParamName">${escaped}</span>`;
}
const idlLink = defineIdlName(escaped, data, parent);
if (data.type !== "enum-value") {
const className = parent ? "idlName" : "idlID";
idlLink.classList.add(className);
}
return idlLink;
},
nameless(escaped, { data, parent }) {
switch (data.type) {
case "constructor":
return defineIdlName(escaped, data, parent);
default:
return escaped;
}
},
type(contents) {
return html`<span class="idlType">${contents}</span>`;
},
inheritance(contents) {
return html`<span class="idlSuperclass">${contents}</span>`;
},
definition(contents, { data, parent }) {
const className = getIdlDefinitionClassName(data);
switch (data.type) {
case "includes":
case "enum-value":
return html`<span class="${className}">${contents}</span>`;
}
const parentName = parent ? parent.name : "";
const { name, idlId } = getNameAndId(data, parentName);
return html`<span
class="${className}"
id="${idlId}"
data-idl
data-title="${name}"
>${contents}</span
>`;
},
extendedAttribute(contents) {
const result = html`<span class="extAttr">${contents}</span>`;
return result;
},
extendedAttributeReference(name) {
return html`<a data-xref-type="extended-attribute">${name}</a>`;
},
};
/**
* Returns a link to existing <dfn> or creates one if doesn’t exists.
*/
function defineIdlName(escaped, data, parent) {
const parentName = parent ? parent.name : "";
const { name } = getNameAndId(data, parentName);
const dfn = findDfn(data, name, {
parent: parentName,
});
const linkType = getDfnType(data.type);
if (dfn) {
if (!data.partial) {
dfn.dataset.export = "";
dfn.dataset.dfnType = linkType;
}
decorateDfn(dfn, data, parentName, name);
const href = `#${dfn.id}`;
return html`<a
data-link-for="${parentName}"
data-link-type="${linkType}"
href="${href}"
class="internalDFN"
><code>${escaped}</code></a
>`;
}
const isDefaultJSON =
data.type === "operation" &&
data.name === "toJSON" &&
data.extAttrs.some(({ name }) => name === "Default");
if (isDefaultJSON) {
return html`<a data-link-type="dfn" data-lt="default toJSON steps"
>${escaped}</a
>`;
}
if (!data.partial) {
const dfn = html`<dfn data-export data-dfn-type="${linkType}"
>${escaped}</dfn
>`;
registerDefinition(dfn, [name]);
decorateDfn(dfn, data, parentName, name);
return dfn;
}
const unlinkedAnchor = html`<a
data-idl="${data.partial ? "partial" : null}"
data-link-type="${linkType}"
data-title="${data.name}"
data-xref-type="${linkType}"
>${escaped}</a
>`;
const showWarnings =
name && data.type !== "typedef" && !(data.partial && !dfn);
if (showWarnings) {
const styledName = data.type === "operation" ? `${name}()` : name;
const ofParent = parentName ? ` \`${parentName}\`'s` : "";
const msg = `Missing \`<dfn>\` for${ofParent} \`${styledName}\` ${data.type}. [More info](https://github.com/w3c/respec/wiki/WebIDL-thing-is-not-defined).`;
showInlineWarning(unlinkedAnchor, msg, "");
}
return unlinkedAnchor;
}
/**
* Map to Shepherd types, for export.
* @see https://tabatkins.github.io/bikeshed/#dfn-types
*/
function getDfnType(idlType) {
switch (idlType) {
case "operation":
return "method";
case "field":
return "dict-member";
case "callback interface":
case "interface mixin":
return "interface";
default:
return idlType;
}
}
function getIdlDefinitionClassName(defn) {
switch (defn.type) {
case "callback interface":
return "idlInterface";
case "operation":
return "idlMethod";
case "field":
return "idlMember";
case "enum-value":
return "idlEnumItem";
case "callback function":
return "idlCallback";
}
return `idl${defn.type[0].toUpperCase()}${defn.type.slice(1)}`;
}
const nameResolverMap = new WeakMap();
function getNameAndId(defn, parent = "") {
if (nameResolverMap.has(defn)) {
return nameResolverMap.get(defn);
}
const result = resolveNameAndId(defn, parent);
nameResolverMap.set(defn, result);
return result;
}
function resolveNameAndId(defn, parent) {
let name = getDefnName(defn);
let idlId = getIdlId(name, parent);
switch (defn.type) {
// Top-level entities with linkable members.
case "callback interface":
case "dictionary":
case "interface":
case "interface mixin": {
idlId += resolvePartial(defn);
break;
}
case "constructor":
case "operation": {
const overload = resolveOverload(name, parent);
if (overload) {
name += overload;
idlId += overload;
} else if (defn.arguments.length) {
idlId += defn.arguments
.map(arg => `-${arg.name.toLowerCase()}`)
.join("");
}
break;
}
}
return { name, idlId };
}
function resolvePartial(defn) {
if (!defn.partial) {
return "";
}
if (!idlPartials[defn.name]) {
idlPartials[defn.name] = 0;
}
idlPartials[defn.name] += 1;
return `-partial-${idlPartials[defn.name]}`;
}
function resolveOverload(name, parentName) {
const qualifiedName = `${parentName}.${name}`;
const fullyQualifiedName = `${qualifiedName}()`;
let overload;
if (!operationNames[fullyQualifiedName]) {
operationNames[fullyQualifiedName] = 0;
}
if (!operationNames[qualifiedName]) {
operationNames[qualifiedName] = 0;
} else {
overload = `!overload-${operationNames[qualifiedName]}`;
}
operationNames[fullyQualifiedName] += 1;
operationNames[qualifiedName] += 1;
return overload || "";
}
function getIdlId(name, parentName) {
if (!parentName) {
return `idl-def-${name.toLowerCase()}`;
}
return `idl-def-${parentName.toLowerCase()}-${name.toLowerCase()}`;
}
function getDefnName(defn) {
switch (defn.type) {
case "enum-value":
return defn.value;
case "operation":
return defn.name;
default:
return defn.name || defn.type;
}
}
/**
* @param {Element} idlElement
* @param {number} index
*/
function renderWebIDL(idlElement, index) {
let parse;
try {
parse = webidl2.parse(idlElement.textContent, {
sourceName: String(index),
});
} catch (e) {
showInlineError(
idlElement,
`Failed to parse WebIDL: ${e.bareMessage}.`,
e.bareMessage,
{ details: `<pre>${e.context}</pre>` }
);
// Skip this <pre> and move on to the next one.
return [];
}
addDataDfnFor(idlElement, parse);
// we add "idl" as the canonical match, so both "webidl" and "idl" work
idlElement.classList.add("def", "idl");
const highlights = webidl2.write(parse, { templates });
html.bind(idlElement)`${highlights}`;
idlElement.querySelectorAll("[data-idl]").forEach(elem => {
if (elem.dataset.dfnFor) {
return;
}
const title = elem.dataset.title;
// Select the nearest ancestor element that can contain members.
const parent = elem.parentElement.closest("[data-idl][data-title]");
if (parent) {
elem.dataset.dfnFor = parent.dataset.title;
}
if (elem.localName === "dfn") {
registerDefinition(elem, [title]);
}
});
// cross reference
const closestCite = idlElement.closest("[data-cite], body");
const { dataset } = closestCite;
if (!dataset.cite) dataset.cite = "WebIDL";
// includes webidl in some form
if (!/\bwebidl\b/i.test(dataset.cite)) {
const cites = dataset.cite.trim().split(/\s+/);
dataset.cite = ["WebIDL", ...cites].join(" ");
}
addIDLHeader(idlElement);
return parse;
}
/**
* Add data-dfn-for to the closest section if not present already.
* @param {HTMLPreElement} idlElement
* @param {ReturnType<typeof webidl2.parse>} parse
*/
function addDataDfnFor(idlElement, parse) {
const closestSection = idlElement.closest("section");
if (closestSection.hasAttribute("data-dfn-for")) return;
const topLevelEntities = ["dictionary", "interface", "callback interface"];
const dfnFors = [];
for (const { tokens } of parse) {
if (topLevelEntities.includes(tokens.base.type)) {
const dfnFor = tokens.name.value;
dfnFors.push(dfnFor);
}
}
if (dfnFors.length === 1) {
closestSection.dataset.dfnFor = dfnFors[0];
} else if (!dfnFors.length) {
return;
} else {
closestSection.dataset.dfnFor = "";
const options = dfnFors.map(dfnFor => `"${dfnFor}"`).join(", ");
const title = "Ambiguous data-dfn-for attribute";
const message = `${title}. Sections describing top-level IDL entities (${topLevelEntities}) require a \`data-dfn-attribute\`. Please add a \`data-dfn-for\` attribute with one of following values: ${options}`;
showInlineError(closestSection, message, title);
}
}
/**
* Adds a "WebIDL" decorative header/permalink to a block of WebIDL.
* @param {HTMLPreElement} pre
*/
export function addIDLHeader(pre) {
addHashId(pre, "webidl");
const header = html`<span class="idlHeader"
><a class="self-link" href="${`#${pre.id}`}">WebIDL</a></span
>`;
pre.prepend(header);
addCopyIDLButton(header);
}
const cssPromise = loadStyle();
async function loadStyle() {
try {
return (await import("text!../../assets/webidl.css")).default;
} catch {
return fetchAsset("webidl.css");
}
}
export async function run() {
const idls = document.querySelectorAll("pre.idl, pre.webidl");
if (!idls.length) {
return;
}
if (!document.querySelector(".idl:not(pre), .webidl:not(pre)")) {
const link = document.querySelector("head link");
if (link) {
const style = document.createElement("style");
style.textContent = await cssPromise;
link.before(style);
}
}
const astArray = [...idls].map(renderWebIDL);
const validations = webidl2.validate(astArray);
for (const validation of validations) {
let details = `<pre>${validation.context}</pre>`;
if (validation.autofix) {
validation.autofix();
const idlToFix = webidl2.write(astArray[validation.sourceName]);
const escaped = xmlEscape(idlToFix);
details += `Try fixing as:
<pre>${escaped}</pre>`;
}
showInlineError(
idls[validation.sourceName],
`WebIDL validation error: ${validation.bareMessage}`,
validation.bareMessage,
{ details }
);
}
document.normalize();
}