-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathClause.ts
More file actions
468 lines (426 loc) · 13.8 KB
/
Copy pathClause.ts
File metadata and controls
468 lines (426 loc) · 13.8 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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import type Note from './Note';
import type Example from './Example';
import type Spec from './Spec';
import type { AlgorithmType, PartialBiblioEntry, Signature, Type } from './Biblio';
import type { Context } from './Context';
import { ParseError, TypeParser } from './type-parser';
import Builder from './Builder';
import type { ParsedHeader } from './header-parser';
import { formatPreamble, parseStructuredHeaderDl, formatHeader, parseH1 } from './header-parser';
import { offsetToLineAndColumn, traverseWhile } from './utils';
const aoidTypes = [
'abstract operation',
'sdo',
'syntax-directed operation',
'host-defined abstract operation',
'implementation-defined abstract operation',
'numeric method',
];
export const SPECIAL_KINDS_MAP = new Map([
['normative-optional', 'Normative Optional'],
['legacy', 'Legacy'],
['deprecated', 'Deprecated'],
]);
export const SPECIAL_KINDS = [...SPECIAL_KINDS_MAP.keys()];
export function extractStructuredHeader(header: Element): Element | null {
const dl = traverseWhile(
header.nextElementSibling,
'nextElementSibling',
el => el.nodeName === 'DEL',
);
if (dl == null || dl.tagName !== 'DL' || !dl.classList.contains('header')) {
return null;
}
return dl;
}
export default class Clause extends Builder {
/** @internal */ id: string;
/** @internal */ namespace: string;
/** @internal */ parentClause: Clause;
/** @internal */ header: Element | null;
/** @internal */ title!: string | null;
/** @internal */ titleHTML!: string;
/** @internal */ subclauses: Clause[];
/** @internal */ number: string;
/** @internal */ aoid: string | null;
/** @internal */ type: string | null;
/** @internal */ notes: Note[];
/** @internal */ editorNotes: Note[];
/** @internal */ examples: Example[];
/** @internal */ readonly effects: string[]; // this is held by identity and mutated by Spec.ts
/** @internal */ signature: Signature | null;
/** @internal */ skipGlobalChecks: boolean;
/** @internal */ skipReturnChecks: boolean;
isAnnex: boolean;
isBackMatter: boolean;
isNormative: boolean;
constructor(spec: Spec, node: HTMLElement, parent: Clause, number: string) {
super(spec, node);
this.parentClause = parent;
this.id = node.getAttribute('id')!;
this.number = number;
this.subclauses = [];
this.notes = [];
this.editorNotes = [];
this.examples = [];
this.effects = [];
this.skipGlobalChecks = false;
this.skipReturnChecks = false;
this.isAnnex = node.nodeName === 'EMU-ANNEX';
this.isBackMatter = this.isAnnex && node.hasAttribute('back-matter');
this.isNormative = !this.isAnnex || node.hasAttribute('normative');
// namespace is either the entire spec or the parent clause's namespace.
let parentNamespace = spec.namespace;
if (parent) {
parentNamespace = parent.namespace;
}
// Reset figure numbering for each Annex
if (this.isAnnex && !this.parentClause) {
spec._figureCounts.figure = 0;
spec._figureCounts.table = 0;
spec._figurePrefix = `${number}.`;
}
if (node.hasAttribute('namespace')) {
this.namespace = node.getAttribute('namespace')!;
spec.biblio.createNamespace(this.namespace, parentNamespace);
} else {
this.namespace = parentNamespace;
}
this.aoid = node.getAttribute('aoid');
if (this.aoid === '') {
// <emu-clause id=foo aoid> === <emu-clause id=foo aoid=foo>
this.aoid = node.id;
}
this.type = node.getAttribute('type');
if (this.type === '') {
this.type = null;
}
this.signature = null;
const header = traverseWhile(
this.node.firstElementChild,
'nextElementSibling',
// skip <del> and oldids
el => el.nodeName === 'DEL' || (el.nodeName === 'SPAN' && el.children.length === 0),
);
let headerH1 = traverseWhile(header, 'firstElementChild', el => el.nodeName === 'INS', {
once: true,
});
if (headerH1 == null) {
this.spec.warn({
type: 'node',
ruleId: 'missing-header',
message: `could not locate header element`,
node: this.node,
});
headerH1 = null;
} else if (headerH1.tagName !== 'H1') {
this.spec.warn({
type: 'node',
ruleId: 'missing-header',
message: `could not locate header element; found <${header!.tagName.toLowerCase()}> before any <h1>`,
node: header!,
});
headerH1 = null;
} else {
this.buildStructuredHeader(headerH1, header!);
}
this.header = headerH1;
if (headerH1 == null) {
this.title = 'UNKNOWN';
this.titleHTML = 'UNKNOWN';
}
}
/** @internal */ buildStructuredHeader(header: Element, headerSurrogate: Element = header) {
const dl = extractStructuredHeader(headerSurrogate);
if (dl === null) {
return;
}
// if we find such a DL, treat this as a structured header
const type = this.type;
let headerSource;
const headerLocation = this.spec.locate(header);
if (headerLocation != null) {
headerSource = headerLocation.source.slice(
headerLocation.startTag.endOffset,
headerLocation.endTag.startOffset,
);
} else {
headerSource = header.innerHTML;
}
const parseResult = parseH1(headerSource);
if (parseResult.type !== 'failure') {
try {
this.signature = parsedHeaderToSignature(parseResult);
} catch (e) {
if (e instanceof ParseError) {
const { line, column } = offsetToLineAndColumn(headerSource, e.offset);
this.spec.warn({
type: 'contents',
ruleId: 'type-parsing',
message: e.message,
node: header,
nodeRelativeLine: line,
nodeRelativeColumn: column,
});
} else {
throw e;
}
}
}
const { name, formattedHeader, formattedParams, formattedReturnType } = formatHeader(
this.spec,
header,
parseResult,
);
if (type === 'numeric method' && name != null && !name.includes('::')) {
this.spec.warn({
type: 'contents',
ruleId: 'numeric-method-for',
message: 'numeric methods should be of the form `Type::operation`',
node: header,
nodeRelativeLine: 1,
nodeRelativeColumn: 1,
});
}
if (type === 'sdo' && (formattedHeader ?? header.innerHTML).includes('(')) {
// SDOs are rendered without parameter lists in the header, for the moment
const currentHeader = formattedHeader ?? header.innerHTML;
header.innerHTML = (
currentHeader.substring(0, currentHeader.indexOf('(')) +
currentHeader.substring(currentHeader.lastIndexOf(')') + 1)
).trim();
if (
header.children.length === 1 &&
['INS', 'DEL', 'MARK'].includes(header.children[0].tagName)
) {
header.children[0].innerHTML = header.children[0].innerHTML.trim();
}
} else if (formattedHeader != null) {
header.innerHTML = formattedHeader;
}
const {
description,
for: _for,
effects,
redefinition,
skipGlobalChecks,
skipReturnChecks,
} = parseStructuredHeaderDl(this.spec, type, dl);
const paras = formatPreamble(
this.spec,
this.node,
dl,
type,
name ?? 'UNKNOWN',
formattedParams ?? 'UNPARSEABLE ARGUMENTS',
formattedReturnType,
_for,
description,
);
dl.replaceWith(...paras);
if (!redefinition) {
if (this.node.hasAttribute('aoid')) {
this.spec.warn({
type: 'attr',
ruleId: 'header-format',
message: `nodes with structured headers should not include an AOID`,
node: this.node,
attr: 'aoid',
});
} else if (name != null && type != null && aoidTypes.includes(type)) {
this.node.setAttribute('aoid', name);
this.aoid = name;
}
}
this.skipGlobalChecks = skipGlobalChecks;
this.skipReturnChecks = skipReturnChecks;
this.effects.push(...effects);
for (const effect of effects) {
if (!this.spec._effectWorklist.has(effect)) {
this.spec._effectWorklist.set(effect, []);
}
this.spec._effectWorklist.get(effect)!.push(this);
}
}
/** @internal */ buildNotes() {
if (this.notes.length === 1) {
this.notes[0].build();
} else {
// pass along note index
this.notes.forEach((note, i) => {
note.build(i + 1);
});
}
this.editorNotes.forEach(note => note.build());
}
/** @internal */ buildExamples() {
if (this.examples.length === 1) {
this.examples[0].build();
} else {
// pass along example index
this.examples.forEach((example, i) => {
example.build(i + 1);
});
}
}
canHaveEffect(effectName: string) {
// The following effects are runtime only:
//
// user-code: Only runtime can call user code.
if (this.title !== null && this.title.startsWith('Static Semantics:')) {
if (effectName === 'user-code') return false;
}
return true;
}
static async enter({ spec, node, clauseStack, clauseNumberer }: Context) {
if (!node.id) {
spec.warn({
type: 'node',
ruleId: 'missing-id',
message: "clause doesn't have an id",
node,
});
}
let nextNumber = '';
if (node.nodeName !== 'EMU-INTRO') {
nextNumber = clauseNumberer.next(clauseStack, node);
}
const parent = clauseStack[clauseStack.length - 1] || null;
const clause = new Clause(spec, node, parent, nextNumber);
if (parent) {
parent.subclauses.push(clause);
} else {
spec.subclauses.push(clause);
}
clauseStack.push(clause);
}
static exit({ node, spec, clauseStack, inAlg, currentId }: Context) {
const clause = clauseStack[clauseStack.length - 1];
clause.buildExamples();
clause.buildNotes();
// prettier-ignore
const attributes = SPECIAL_KINDS
.filter(kind => node.hasAttribute(kind))
.map(kind => SPECIAL_KINDS_MAP.get(kind));
if (attributes.length > 0) {
const tag = spec.doc.createElement('div');
tag.className = 'attributes-tag';
const text = attributes.join(', ');
const contents = spec.doc.createTextNode(text);
tag.append(contents);
node.prepend(tag);
// we've already walked past the text node, so it won't get picked up by the usual process for autolinking
spec._textNodes[clause.namespace] = spec._textNodes[clause.namespace] || [];
spec._textNodes[clause.namespace].push({
node: contents,
clause,
inAlg,
currentId,
});
}
// clauses are always at the spec-level namespace.
const entry: PartialBiblioEntry = {
type: 'clause',
id: clause.id,
aoid: clause.aoid,
title: clause.title!,
titleHTML: clause.titleHTML,
number: clause.number,
};
if (clause.aoid) {
const existing = spec.biblio.keysForNamespace(spec.namespace);
if (existing.has(clause.aoid)) {
spec.warn({
type: 'node',
node,
ruleId: 'duplicate-definition',
message: `duplicate definition ${JSON.stringify(clause.aoid)}`,
});
} else {
const signature = clause.signature;
let kind: AlgorithmType | undefined =
clause.type != null && aoidTypes.includes(clause.type)
? (clause.type as AlgorithmType)
: undefined;
// @ts-ignore
if (kind === 'sdo') {
kind = 'syntax-directed operation';
}
const op: PartialBiblioEntry = {
type: 'op',
aoid: clause.aoid,
refId: clause.id,
kind,
signature,
effects: clause.effects,
_node: clause.node,
_skipReturnChecks: clause.skipReturnChecks,
};
if (clause.skipGlobalChecks) {
op.skipGlobalChecks = true;
}
if (
signature?.return?.kind === 'union' &&
signature.return.types.some(e => e.kind === 'completion') &&
signature.return.types.some(e => e.kind !== 'completion')
) {
spec.warn({
type: 'node',
node: clause.header!,
ruleId: 'completion-union',
message: `algorithms should return either completions or things which are not completions, never both`,
});
}
spec.biblio.add(op, spec.namespace);
}
}
spec.biblio.add(entry, spec.namespace);
clauseStack.pop();
}
getSecnumHTML() {
if (!this.number || this.isBackMatter) return '';
if (this.isAnnex) {
const isInnerAnnex = this.node.parentElement?.nodeName === 'EMU-ANNEX';
if (isInnerAnnex) {
return `<span class="secnum">${this.number}</span> `;
} else {
return `<span class="secnum">Annex ${this.number} <span class="annex-kind">(${this.isNormative ? 'normative' : 'informative'})</span></span> `;
}
} else {
return `<span class="secnum">${this.number}</span> `;
}
}
static elements = ['EMU-INTRO', 'EMU-CLAUSE', 'EMU-ANNEX'];
static linkElements = Clause.elements;
}
function parseType(type: string, offset: number): Type {
try {
return TypeParser.parse(type);
} catch (e) {
if (e instanceof ParseError) {
e.offset += offset;
}
throw e;
}
}
function parsedHeaderToSignature(parsedHeader: ParsedHeader): Signature {
const ret = {
parameters: parsedHeader.params
.filter(p => p.wrappingTag !== 'del')
.map(p => ({
name: p.name,
type: p.type == null ? null : parseType(p.type, p.typeOffset),
})),
optionalParameters: parsedHeader.optionalParams
.filter(p => p.wrappingTag !== 'del')
.map(p => ({
name: p.name,
type: p.type == null ? null : parseType(p.type, p.typeOffset),
})),
return:
parsedHeader.returnType == null
? null
: parseType(parsedHeader.returnType, parsedHeader.returnOffset),
};
return ret;
}