-
Notifications
You must be signed in to change notification settings - Fork 30.1k
/
idlharness.js
3553 lines (3158 loc) Β· 142 KB
/
idlharness.js
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* For user documentation see docs/_writing-tests/idlharness.md */
/**
* Notes for people who want to edit this file (not just use it as a library):
*
* Most of the interesting stuff happens in the derived classes of IdlObject,
* especially IdlInterface. The entry point for all IdlObjects is .test(),
* which is called by IdlArray.test(). An IdlObject is conceptually just
* "thing we want to run tests on", and an IdlArray is an array of IdlObjects
* with some additional data thrown in.
*
* The object model is based on what WebIDLParser.js produces, which is in turn
* based on its pegjs grammar. If you want to figure out what properties an
* object will have from WebIDLParser.js, the best way is to look at the
* grammar:
*
* https://github.com/darobin/webidl.js/blob/master/lib/grammar.peg
*
* So for instance:
*
* // interface definition
* interface
* = extAttrs:extendedAttributeList? S? "interface" S name:identifier w herit:ifInheritance? w "{" w mem:ifMember* w "}" w ";" w
* { return { type: "interface", name: name, inheritance: herit, members: mem, extAttrs: extAttrs }; }
*
* This means that an "interface" object will have a .type property equal to
* the string "interface", a .name property equal to the identifier that the
* parser found, an .inheritance property equal to either null or the result of
* the "ifInheritance" production found elsewhere in the grammar, and so on.
* After each grammatical production is a JavaScript function in curly braces
* that gets called with suitable arguments and returns some JavaScript value.
*
* (Note that the version of WebIDLParser.js we use might sometimes be
* out-of-date or forked.)
*
* The members and methods of the classes defined by this file are all at least
* briefly documented, hopefully.
*/
(function(){
"use strict";
// Support subsetTestByKey from /common/subset-tests-by-key.js, but make it optional
if (!('subsetTestByKey' in self)) {
self.subsetTestByKey = function(key, callback, ...args) {
return callback(...args);
}
self.shouldRunSubTest = () => true;
}
/// Helpers ///
function constValue (cnt)
{
if (cnt.type === "null") return null;
if (cnt.type === "NaN") return NaN;
if (cnt.type === "Infinity") return cnt.negative ? -Infinity : Infinity;
if (cnt.type === "number") return +cnt.value;
return cnt.value;
}
function minOverloadLength(overloads)
{
// "The value of the Function objectβs βlengthβ property is
// a Number determined as follows:
// ". . .
// "Return the length of the shortest argument list of the
// entries in S."
if (!overloads.length) {
return 0;
}
return overloads.map(function(attr) {
return attr.arguments ? attr.arguments.filter(function(arg) {
return !arg.optional && !arg.variadic;
}).length : 0;
})
.reduce(function(m, n) { return Math.min(m, n); });
}
// A helper to get the global of a Function object. This is needed to determine
// which global exceptions the function throws will come from.
function globalOf(func)
{
try {
// Use the fact that .constructor for a Function object is normally the
// Function constructor, which can be used to mint a new function in the
// right global.
return func.constructor("return this;")();
} catch (e) {
}
// If the above fails, because someone gave us a non-function, or a function
// with a weird proto chain or weird .constructor property, just fall back
// to 'self'.
return self;
}
// https://esdiscuss.org/topic/isconstructor#content-11
function isConstructor(o) {
try {
new (new Proxy(o, {construct: () => ({})}));
return true;
} catch(e) {
return false;
}
}
function throwOrReject(a_test, operation, fn, obj, args, message, cb)
{
if (operation.idlType.generic !== "Promise") {
assert_throws_js(globalOf(fn).TypeError, function() {
fn.apply(obj, args);
}, message);
cb();
} else {
try {
promise_rejects_js(a_test, TypeError, fn.apply(obj, args), message).then(cb, cb);
} catch (e){
a_test.step(function() {
assert_unreached("Throws \"" + e + "\" instead of rejecting promise");
cb();
});
}
}
}
function awaitNCallbacks(n, cb, ctx)
{
var counter = 0;
return function() {
counter++;
if (counter >= n) {
cb();
}
};
}
/// IdlHarnessError ///
// Entry point
self.IdlHarnessError = function(message)
{
/**
* Message to be printed as the error's toString invocation.
*/
this.message = message;
};
IdlHarnessError.prototype = Object.create(Error.prototype);
IdlHarnessError.prototype.toString = function()
{
return this.message;
};
/// IdlArray ///
// Entry point
self.IdlArray = function()
{
/**
* A map from strings to the corresponding named IdlObject, such as
* IdlInterface or IdlException. These are the things that test() will run
* tests on.
*/
this.members = {};
/**
* A map from strings to arrays of strings. The keys are interface or
* exception names, and are expected to also exist as keys in this.members
* (otherwise they'll be ignored). This is populated by add_objects() --
* see documentation at the start of the file. The actual tests will be
* run by calling this.members[name].test_object(obj) for each obj in
* this.objects[name]. obj is a string that will be eval'd to produce a
* JavaScript value, which is supposed to be an object implementing the
* given IdlObject (interface, exception, etc.).
*/
this.objects = {};
/**
* When adding multiple collections of IDLs one at a time, an earlier one
* might contain a partial interface or includes statement that depends
* on a later one. Save these up and handle them right before we run
* tests.
*
* Both this.partials and this.includes will be the objects as parsed by
* WebIDLParser.js, not wrapped in IdlInterface or similar.
*/
this.partials = [];
this.includes = [];
/**
* Record of skipped IDL items, in case we later realize that they are a
* dependency (to retroactively process them).
*/
this.skipped = new Map();
};
IdlArray.prototype.add_idls = function(raw_idls, options)
{
/** Entry point. See documentation at beginning of file. */
this.internal_add_idls(WebIDL2.parse(raw_idls), options);
};
IdlArray.prototype.add_untested_idls = function(raw_idls, options)
{
/** Entry point. See documentation at beginning of file. */
var parsed_idls = WebIDL2.parse(raw_idls);
this.mark_as_untested(parsed_idls);
this.internal_add_idls(parsed_idls, options);
};
IdlArray.prototype.mark_as_untested = function (parsed_idls)
{
for (var i = 0; i < parsed_idls.length; i++) {
parsed_idls[i].untested = true;
if ("members" in parsed_idls[i]) {
for (var j = 0; j < parsed_idls[i].members.length; j++) {
parsed_idls[i].members[j].untested = true;
}
}
}
};
IdlArray.prototype.is_excluded_by_options = function (name, options)
{
return options &&
(options.except && options.except.includes(name)
|| options.only && !options.only.includes(name));
};
IdlArray.prototype.add_dependency_idls = function(raw_idls, options)
{
return this.internal_add_dependency_idls(WebIDL2.parse(raw_idls), options);
};
IdlArray.prototype.internal_add_dependency_idls = function(parsed_idls, options)
{
const new_options = { only: [] }
const all_deps = new Set();
Object.values(this.members).forEach(v => {
if (v.base) {
all_deps.add(v.base);
}
});
// Add both 'A' and 'B' for each 'A includes B' entry.
this.includes.forEach(i => {
all_deps.add(i.target);
all_deps.add(i.includes);
});
this.partials.forEach(p => all_deps.add(p.name));
// Add 'TypeOfType' for each "typedef TypeOfType MyType;" entry.
Object.entries(this.members).forEach(([k, v]) => {
if (v instanceof IdlTypedef) {
let defs = v.idlType.union
? v.idlType.idlType.map(t => t.idlType)
: [v.idlType.idlType];
defs.forEach(d => all_deps.add(d));
}
});
// Add the attribute idlTypes of all the nested members of idls.
const attrDeps = parsedIdls => {
return parsedIdls.reduce((deps, parsed) => {
if (parsed.members) {
for (const attr of Object.values(parsed.members).filter(m => m.type === 'attribute')) {
let attrType = attr.idlType;
// Check for generic members (e.g. FrozenArray<MyType>)
if (attrType.generic) {
deps.add(attrType.generic);
attrType = attrType.idlType;
}
deps.add(attrType.idlType);
}
}
if (parsed.base in this.members) {
attrDeps([this.members[parsed.base]]).forEach(dep => deps.add(dep));
}
return deps;
}, new Set());
};
const testedMembers = Object.values(this.members).filter(m => !m.untested && m.members);
attrDeps(testedMembers).forEach(dep => all_deps.add(dep));
const testedPartials = this.partials.filter(m => !m.untested && m.members);
attrDeps(testedPartials).forEach(dep => all_deps.add(dep));
if (options && options.except && options.only) {
throw new IdlHarnessError("The only and except options can't be used together.");
}
const defined_or_untested = name => {
// NOTE: Deps are untested, so we're lenient, and skip re-encountered definitions.
// e.g. for 'idl' containing A:B, B:C, C:D
// array.add_idls(idl, {only: ['A','B']}).
// array.add_dependency_idls(idl);
// B would be encountered as tested, and encountered as a dep, so we ignore.
return name in this.members
|| this.is_excluded_by_options(name, options);
}
// Maps name -> [parsed_idl, ...]
const process = function(parsed) {
var deps = [];
if (parsed.name) {
deps.push(parsed.name);
} else if (parsed.type === "includes") {
deps.push(parsed.target);
deps.push(parsed.includes);
}
deps = deps.filter(function(name) {
if (!name
|| name === parsed.name && defined_or_untested(name)
|| !all_deps.has(name)) {
// Flag as skipped, if it's not already processed, so we can
// come back to it later if we retrospectively call it a dep.
if (name && !(name in this.members)) {
this.skipped.has(name)
? this.skipped.get(name).push(parsed)
: this.skipped.set(name, [parsed]);
}
return false;
}
return true;
}.bind(this));
deps.forEach(function(name) {
if (!new_options.only.includes(name)) {
new_options.only.push(name);
}
const follow_up = new Set();
for (const dep_type of ["inheritance", "includes"]) {
if (parsed[dep_type]) {
const inheriting = parsed[dep_type];
const inheritor = parsed.name || parsed.target;
const deps = [inheriting];
// For A includes B, we can ignore A, unless B (or some of its
// members) is being tested.
if (dep_type !== "includes"
|| inheriting in this.members && !this.members[inheriting].untested
|| this.partials.some(function(p) {
return p.name === inheriting;
})) {
deps.push(inheritor);
}
for (const dep of deps) {
if (!new_options.only.includes(dep)) {
new_options.only.push(dep);
}
all_deps.add(dep);
follow_up.add(dep);
}
}
}
for (const deferred of follow_up) {
if (this.skipped.has(deferred)) {
const next = this.skipped.get(deferred);
this.skipped.delete(deferred);
next.forEach(process);
}
}
}.bind(this));
}.bind(this);
for (let parsed of parsed_idls) {
process(parsed);
}
this.mark_as_untested(parsed_idls);
if (new_options.only.length) {
this.internal_add_idls(parsed_idls, new_options);
}
}
IdlArray.prototype.internal_add_idls = function(parsed_idls, options)
{
/**
* Internal helper called by add_idls() and add_untested_idls().
*
* parsed_idls is an array of objects that come from WebIDLParser.js's
* "definitions" production. The add_untested_idls() entry point
* additionally sets an .untested property on each object (and its
* .members) so that they'll be skipped by test() -- they'll only be
* used for base interfaces of tested interfaces, return types, etc.
*
* options is a dictionary that can have an only or except member which are
* arrays. If only is given then only members, partials and interface
* targets listed will be added, and if except is given only those that
* aren't listed will be added. Only one of only and except can be used.
*/
if (options && options.only && options.except)
{
throw new IdlHarnessError("The only and except options can't be used together.");
}
var should_skip = name => {
return this.is_excluded_by_options(name, options);
}
parsed_idls.forEach(function(parsed_idl)
{
var partial_types = [
"interface",
"interface mixin",
"dictionary",
"namespace",
];
if (parsed_idl.partial && partial_types.includes(parsed_idl.type))
{
if (should_skip(parsed_idl.name))
{
return;
}
this.partials.push(parsed_idl);
return;
}
if (parsed_idl.type == "includes")
{
if (should_skip(parsed_idl.target))
{
return;
}
this.includes.push(parsed_idl);
return;
}
parsed_idl.array = this;
if (should_skip(parsed_idl.name))
{
return;
}
if (parsed_idl.name in this.members)
{
throw new IdlHarnessError("Duplicate identifier " + parsed_idl.name);
}
switch(parsed_idl.type)
{
case "interface":
this.members[parsed_idl.name] =
new IdlInterface(parsed_idl, /* is_callback = */ false, /* is_mixin = */ false);
break;
case "interface mixin":
this.members[parsed_idl.name] =
new IdlInterface(parsed_idl, /* is_callback = */ false, /* is_mixin = */ true);
break;
case "dictionary":
// Nothing to test, but we need the dictionary info around for type
// checks
this.members[parsed_idl.name] = new IdlDictionary(parsed_idl);
break;
case "typedef":
this.members[parsed_idl.name] = new IdlTypedef(parsed_idl);
break;
case "callback":
this.members[parsed_idl.name] = new IdlCallback(parsed_idl);
break;
case "enum":
this.members[parsed_idl.name] = new IdlEnum(parsed_idl);
break;
case "callback interface":
this.members[parsed_idl.name] =
new IdlInterface(parsed_idl, /* is_callback = */ true, /* is_mixin = */ false);
break;
case "namespace":
this.members[parsed_idl.name] = new IdlNamespace(parsed_idl);
break;
default:
throw parsed_idl.name + ": " + parsed_idl.type + " not yet supported";
}
}.bind(this));
};
IdlArray.prototype.add_objects = function(dict)
{
/** Entry point. See documentation at beginning of file. */
for (var k in dict)
{
if (k in this.objects)
{
this.objects[k] = this.objects[k].concat(dict[k]);
}
else
{
this.objects[k] = dict[k];
}
}
};
IdlArray.prototype.prevent_multiple_testing = function(name)
{
/** Entry point. See documentation at beginning of file. */
this.members[name].prevent_multiple_testing = true;
};
IdlArray.prototype.is_json_type = function(type)
{
/**
* Checks whether type is a JSON type as per
* https://webidl.spec.whatwg.org/#dfn-json-types
*/
var idlType = type.idlType;
if (type.generic == "Promise") { return false; }
// nullable and annotated types don't need to be handled separately,
// as webidl2 doesn't represent them wrapped-up (as they're described
// in WebIDL).
// union and record types
if (type.union || type.generic == "record") {
return idlType.every(this.is_json_type, this);
}
// sequence types
if (type.generic == "sequence" || type.generic == "FrozenArray") {
return this.is_json_type(idlType[0]);
}
if (typeof idlType != "string") { throw new Error("Unexpected type " + JSON.stringify(idlType)); }
switch (idlType)
{
// Numeric types
case "byte":
case "octet":
case "short":
case "unsigned short":
case "long":
case "unsigned long":
case "long long":
case "unsigned long long":
case "float":
case "double":
case "unrestricted float":
case "unrestricted double":
// boolean
case "boolean":
// string types
case "DOMString":
case "ByteString":
case "USVString":
// object type
case "object":
return true;
case "Error":
case "DOMException":
case "Int8Array":
case "Int16Array":
case "Int32Array":
case "Uint8Array":
case "Uint16Array":
case "Uint32Array":
case "Uint8ClampedArray":
case "BigInt64Array":
case "BigUint64Array":
case "Float32Array":
case "Float64Array":
case "ArrayBuffer":
case "DataView":
case "any":
return false;
default:
var thing = this.members[idlType];
if (!thing) { throw new Error("Type " + idlType + " not found"); }
if (thing instanceof IdlEnum) { return true; }
if (thing instanceof IdlTypedef) {
return this.is_json_type(thing.idlType);
}
// dictionaries where all of their members are JSON types
if (thing instanceof IdlDictionary) {
const map = new Map();
for (const dict of thing.get_reverse_inheritance_stack()) {
for (const m of dict.members) {
map.set(m.name, m.idlType);
}
}
return Array.from(map.values()).every(this.is_json_type, this);
}
// interface types that have a toJSON operation declared on themselves or
// one of their inherited interfaces.
if (thing instanceof IdlInterface) {
var base;
while (thing)
{
if (thing.has_to_json_regular_operation()) { return true; }
var mixins = this.includes[thing.name];
if (mixins) {
mixins = mixins.map(function(id) {
var mixin = this.members[id];
if (!mixin) {
throw new Error("Interface " + id + " not found (implemented by " + thing.name + ")");
}
return mixin;
}, this);
if (mixins.some(function(m) { return m.has_to_json_regular_operation() } )) { return true; }
}
if (!thing.base) { return false; }
base = this.members[thing.base];
if (!base) {
throw new Error("Interface " + thing.base + " not found (inherited by " + thing.name + ")");
}
thing = base;
}
return false;
}
return false;
}
};
function exposure_set(object, default_set) {
var exposed = object.extAttrs && object.extAttrs.filter(a => a.name === "Exposed");
if (exposed && exposed.length > 1) {
throw new IdlHarnessError(
`Multiple 'Exposed' extended attributes on ${object.name}`);
}
let result = default_set || ["Window"];
if (result && !(result instanceof Set)) {
result = new Set(result);
}
if (exposed && exposed.length) {
const { rhs } = exposed[0];
// Could be a list or a string.
const set =
rhs.type === "*" ?
[ "*" ] :
rhs.type === "identifier-list" ?
rhs.value.map(id => id.value) :
[ rhs.value ];
result = new Set(set);
}
if (result && result.has("*")) {
return "*";
}
if (result && result.has("Worker")) {
result.delete("Worker");
result.add("DedicatedWorker");
result.add("ServiceWorker");
result.add("SharedWorker");
}
return result;
}
function exposed_in(globals) {
if (globals === "*") {
return true;
}
if ('Window' in self) {
return globals.has("Window");
}
if ('DedicatedWorkerGlobalScope' in self &&
self instanceof DedicatedWorkerGlobalScope) {
return globals.has("DedicatedWorker");
}
if ('SharedWorkerGlobalScope' in self &&
self instanceof SharedWorkerGlobalScope) {
return globals.has("SharedWorker");
}
if ('ServiceWorkerGlobalScope' in self &&
self instanceof ServiceWorkerGlobalScope) {
return globals.has("ServiceWorker");
}
if (Object.getPrototypeOf(self) === Object.prototype) {
// ShadowRealm - only exposed with `"*"`.
return false;
}
throw new IdlHarnessError("Unexpected global object");
}
/**
* Asserts that the given error message is thrown for the given function.
* @param {string|IdlHarnessError} error Expected Error message.
* @param {Function} idlArrayFunc Function operating on an IdlArray that should throw.
*/
IdlArray.prototype.assert_throws = function(error, idlArrayFunc)
{
try {
idlArrayFunc.call(this, this);
} catch (e) {
if (e instanceof AssertionError) {
throw e;
}
// Assertions for behaviour of the idlharness.js engine.
if (error instanceof IdlHarnessError) {
error = error.message;
}
if (e.message !== error) {
throw new IdlHarnessError(`${idlArrayFunc} threw "${e}", not the expected IdlHarnessError "${error}"`);
}
return;
}
throw new IdlHarnessError(`${idlArrayFunc} did not throw the expected IdlHarnessError`);
}
IdlArray.prototype.test = function()
{
/** Entry point. See documentation at beginning of file. */
// First merge in all partial definitions and interface mixins.
this.merge_partials();
this.merge_mixins();
// Assert B defined for A : B
for (const member of Object.values(this.members).filter(m => m.base)) {
const lhs = member.name;
const rhs = member.base;
if (!(rhs in this.members)) throw new IdlHarnessError(`${lhs} inherits ${rhs}, but ${rhs} is undefined.`);
const lhs_is_interface = this.members[lhs] instanceof IdlInterface;
const rhs_is_interface = this.members[rhs] instanceof IdlInterface;
if (rhs_is_interface != lhs_is_interface) {
if (!lhs_is_interface) throw new IdlHarnessError(`${lhs} inherits ${rhs}, but ${lhs} is not an interface.`);
if (!rhs_is_interface) throw new IdlHarnessError(`${lhs} inherits ${rhs}, but ${rhs} is not an interface.`);
}
// Check for circular dependencies.
member.get_reverse_inheritance_stack();
}
Object.getOwnPropertyNames(this.members).forEach(function(memberName) {
var member = this.members[memberName];
if (!(member instanceof IdlInterface)) {
return;
}
var globals = exposure_set(member);
member.exposed = exposed_in(globals);
member.exposureSet = globals;
}.bind(this));
// Now run test() on every member, and test_object() for every object.
for (var name in this.members)
{
this.members[name].test();
if (name in this.objects)
{
const objects = this.objects[name];
if (!objects || !Array.isArray(objects)) {
throw new IdlHarnessError(`Invalid or empty objects for member ${name}`);
}
objects.forEach(function(str)
{
if (!this.members[name] || !(this.members[name] instanceof IdlInterface)) {
throw new IdlHarnessError(`Invalid object member name ${name}`);
}
this.members[name].test_object(str);
}.bind(this));
}
}
};
IdlArray.prototype.merge_partials = function()
{
const testedPartials = new Map();
this.partials.forEach(function(parsed_idl)
{
const originalExists = parsed_idl.name in this.members
&& (this.members[parsed_idl.name] instanceof IdlInterface
|| this.members[parsed_idl.name] instanceof IdlDictionary
|| this.members[parsed_idl.name] instanceof IdlNamespace);
// Ensure unique test name in case of multiple partials.
let partialTestName = parsed_idl.name;
let partialTestCount = 1;
if (testedPartials.has(parsed_idl.name)) {
partialTestCount += testedPartials.get(parsed_idl.name);
partialTestName = `${partialTestName}[${partialTestCount}]`;
}
testedPartials.set(parsed_idl.name, partialTestCount);
if (!parsed_idl.untested) {
test(function () {
assert_true(originalExists, `Original ${parsed_idl.type} should be defined`);
var expected;
switch (parsed_idl.type) {
case 'dictionary': expected = IdlDictionary; break;
case 'namespace': expected = IdlNamespace; break;
case 'interface':
case 'interface mixin':
default:
expected = IdlInterface; break;
}
assert_true(
expected.prototype.isPrototypeOf(this.members[parsed_idl.name]),
`Original ${parsed_idl.name} definition should have type ${parsed_idl.type}`);
}.bind(this), `Partial ${parsed_idl.type} ${partialTestName}: original ${parsed_idl.type} defined`);
}
if (!originalExists) {
// Not good.. but keep calm and carry on.
return;
}
if (parsed_idl.extAttrs)
{
// Special-case "Exposed". Must be a subset of original interface's exposure.
// Exposed on a partial is the equivalent of having the same Exposed on all nested members.
// See https://github.com/heycam/webidl/issues/154 for discrepency between Exposed and
// other extended attributes on partial interfaces.
const exposureAttr = parsed_idl.extAttrs.find(a => a.name === "Exposed");
if (exposureAttr) {
if (!parsed_idl.untested) {
test(function () {
const partialExposure = exposure_set(parsed_idl);
const memberExposure = exposure_set(this.members[parsed_idl.name]);
if (memberExposure === "*") {
return;
}
if (partialExposure === "*") {
throw new IdlHarnessError(
`Partial ${parsed_idl.name} ${parsed_idl.type} is exposed everywhere, the original ${parsed_idl.type} is not.`);
}
partialExposure.forEach(name => {
if (!memberExposure || !memberExposure.has(name)) {
throw new IdlHarnessError(
`Partial ${parsed_idl.name} ${parsed_idl.type} is exposed to '${name}', the original ${parsed_idl.type} is not.`);
}
});
}.bind(this), `Partial ${parsed_idl.type} ${partialTestName}: valid exposure set`);
}
parsed_idl.members.forEach(function (member) {
member.extAttrs.push(exposureAttr);
}.bind(this));
}
parsed_idl.extAttrs.forEach(function(extAttr)
{
// "Exposed" already handled above.
if (extAttr.name === "Exposed") {
return;
}
this.members[parsed_idl.name].extAttrs.push(extAttr);
}.bind(this));
}
if (parsed_idl.members.length) {
test(function () {
var clash = parsed_idl.members.find(function(member) {
return this.members[parsed_idl.name].members.find(function(m) {
return this.are_duplicate_members(m, member);
}.bind(this));
}.bind(this));
parsed_idl.members.forEach(function(member)
{
this.members[parsed_idl.name].members.push(new IdlInterfaceMember(member));
}.bind(this));
assert_true(!clash, "member " + (clash && clash.name) + " is unique");
}.bind(this), `Partial ${parsed_idl.type} ${partialTestName}: member names are unique`);
}
}.bind(this));
this.partials = [];
}
IdlArray.prototype.merge_mixins = function()
{
for (const parsed_idl of this.includes)
{
const lhs = parsed_idl.target;
const rhs = parsed_idl.includes;
var errStr = lhs + " includes " + rhs + ", but ";
if (!(lhs in this.members)) throw errStr + lhs + " is undefined.";
if (!(this.members[lhs] instanceof IdlInterface)) throw errStr + lhs + " is not an interface.";
if (!(rhs in this.members)) throw errStr + rhs + " is undefined.";
if (!(this.members[rhs] instanceof IdlInterface)) throw errStr + rhs + " is not an interface.";
if (this.members[rhs].members.length) {
test(function () {
var clash = this.members[rhs].members.find(function(member) {
return this.members[lhs].members.find(function(m) {
return this.are_duplicate_members(m, member);
}.bind(this));
}.bind(this));
this.members[rhs].members.forEach(function(member) {
assert_true(
this.members[lhs].members.every(m => !this.are_duplicate_members(m, member)),
"member " + member.name + " is unique");
this.members[lhs].members.push(new IdlInterfaceMember(member));
}.bind(this));
assert_true(!clash, "member " + (clash && clash.name) + " is unique");
}.bind(this), lhs + " includes " + rhs + ": member names are unique");
}
}
this.includes = [];
}
IdlArray.prototype.are_duplicate_members = function(m1, m2) {
if (m1.name !== m2.name) {
return false;
}
if (m1.type === 'operation' && m2.type === 'operation'
&& m1.arguments.length !== m2.arguments.length) {
// Method overload. TODO: Deep comparison of arguments.
return false;
}
return true;
}
IdlArray.prototype.assert_type_is = function(value, type)
{
if (type.idlType in this.members
&& this.members[type.idlType] instanceof IdlTypedef) {
this.assert_type_is(value, this.members[type.idlType].idlType);
return;
}
if (type.nullable && value === null)
{
// This is fine
return;
}
if (type.union) {
for (var i = 0; i < type.idlType.length; i++) {
try {
this.assert_type_is(value, type.idlType[i]);
// No AssertionError, so we match one type in the union
return;
} catch(e) {
if (e instanceof AssertionError) {
// We didn't match this type, let's try some others
continue;
}
throw e;
}
}
// TODO: Is there a nice way to list the union's types in the message?
assert_true(false, "Attribute has value " + format_value(value)
+ " which doesn't match any of the types in the union");
}
/**
* Helper function that tests that value is an instance of type according
* to the rules of WebIDL. value is any JavaScript value, and type is an
* object produced by WebIDLParser.js' "type" production. That production
* is fairly elaborate due to the complexity of WebIDL's types, so it's
* best to look at the grammar to figure out what properties it might have.
*/
if (type.idlType == "any")
{
// No assertions to make
return;
}
if (type.array)
{
// TODO: not supported yet
return;
}
if (type.generic === "sequence" || type.generic == "ObservableArray")
{
assert_true(Array.isArray(value), "should be an Array");
if (!value.length)
{
// Nothing we can do.
return;
}
this.assert_type_is(value[0], type.idlType[0]);
return;
}
if (type.generic === "Promise") {
assert_true("then" in value, "Attribute with a Promise type should have a then property");
// TODO: Ideally, we would check on project fulfillment
// that we get the right type
// but that would require making the type check async
return;
}
if (type.generic === "FrozenArray") {
assert_true(Array.isArray(value), "Value should be array");
assert_true(Object.isFrozen(value), "Value should be frozen");
if (!value.length)
{
// Nothing we can do.
return;
}
this.assert_type_is(value[0], type.idlType[0]);
return;
}
type = Array.isArray(type.idlType) ? type.idlType[0] : type.idlType;
switch(type)
{