-
Notifications
You must be signed in to change notification settings - Fork 3
/
tscheck.js
executable file
·4238 lines (4020 loc) · 115 KB
/
tscheck.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
#!/usr/bin/env node
var fs = require('fs');
var tscore = require('./tscore');
require('sugar');
var Map = require('./lib/map');
var SMap = require('./lib/smap')
var util = require('util');
var esprima = require('esprima');
var program = require('commander');
program.usage("FILE.js FILE.d.ts [options]")
program.option('--compact', 'Report at most one violation per type path')
.option('--missing', 'Report paths that are missing types (implies no-warn)')
.option('--coverage', 'Print declaration file coverage')
.option('--no-analysis', 'Skip static analysis (much faster)')
.option('--no-warn', 'Squelch type errors')
.option('--no-jsnap', 'Do not regenerate .jsnap file, even if older than .js file')
.option('--verbose', 'More verbose fatal error messages')
.option('--path <STR>', 'Report only warnings on the given path', String, '')
.option('--stats', 'Print statistics')
.option('--runtime [browser|node]', 'Runtime environment to use (default: browser)', String, 'browser')
program.parse(process.argv);
if (program.args.length === 0) {
program.help()
}
function fatalError(msg, e) {
console.error(msg)
if (program.verbose && e) {
console.error(e.stack)
}
process.exit(1)
}
switch (program.runtime) {
case 'browser':
case 'node':
break;
default:
fatalError('Invalid runtime: ' + program.runtime)
}
if (program.missing) {
program.analysis = false
program.warn = false
}
function runGC() {
if (this.gc) {
gc();
}
}
function fillExtension(path, ext) {
if (path.endsWith('.' + ext))
return path
if (path.endsWith('.'))
return path + ext
if (path.endsWith('.js')) {
path = path.substring(0, path.length - '.js'.length)
} else if (path.endsWith('.d.ts')) {
path = path.substring(0, path.length - '.d.ts'.length)
}
return path + '.' + ext
}
function getArgumentWithExtension(ext) {
if (program.args.length === 1) {
return fillExtension(program.args[0], ext)
} else {
return program.args.find(function(x) { return x.endsWith('.' + ext) })
}
}
var snapshotWasGenerated = false
function generateSnapshot(jsfile, jsnapfile, callback) {
var jsnap = require('jsnap')
snapshotWasGenerated = true
var fd = fs.openSync(jsnapfile, 'w')
var proc = jsnap({
files: [jsfile],
stdio: ['ignore', fd, 2],
runtime: program.runtime
})
proc.on('exit', function() {
fs.close(fd)
})
proc.on('close', function(code) {
if (code !== 0) {
console.error("jsnap failed with exit code " + code)
process.exit(1)
}
callback(jsnapfile)
})
}
function checkSnapshot(jsfile, jsnapfile, callback) {
if (fs.existsSync(jsnapfile)) {
var js_stat = fs.statSync(jsfile)
var jsnap_stat = fs.statSync(jsnapfile)
if (jsnap_stat.mtime >= js_stat.mtime) {
callback(jsnapfile)
return
}
}
generateSnapshot(jsfile, jsnapfile, callback)
}
var load_handlers = []
function onLoaded(fn) {
if (load_handlers === null) {
fn();
} else {
load_handlers.push(fn)
}
}
var LIB_ORIGIN = ">lib.d.ts"; // pad origin with ">" to ensure it does not collide with user input
var snapshot, typeDecl, sourceFileAst;
function initialize() {
var sourceFile = getArgumentWithExtension('js')
if (!sourceFile) {
fatalError("No .js file specified")
}
if (!fs.existsSync(sourceFile)) {
fatalError("Could not find " + sourceFile)
}
var typeDeclFile = getArgumentWithExtension('d.ts')
if (!typeDeclFile) {
fatalError("No .d.ts file specified")
}
if (!fs.existsSync(typeDeclFile)) {
fatalError("Could not find " + typeDeclFile)
}
var jsnapExt = program.runtime === 'browser' ? 'jsnap' : 'jsnap_node';
var snapshotFile = getArgumentWithExtension(jsnapExt)
if (!snapshotFile) {
snapshotFile = sourceFile + jsnapExt.substring(2) // replace .js -> .jsnap(_node)
}
if (program.jsnap) {
checkSnapshot(sourceFile, snapshotFile, loadInputs)
} else {
if (!fs.existsSync(snapshotFile)) {
fatalError("Could not find " + snapshotFile)
}
loadInputs();
}
function convertUndefined(x) {
return (x && x.isUndefined) ? undefined : x;
}
// Replaces all occurrences of {isUndefined:true} with undefined in the snapshot
function normalizeSnapshot() {
snapshot.heap.forEach(function(obj) {
if (!obj) return;
if (obj.function && obj.function.type === 'BindFunc') {
obj.function.target = convertUndefined(obj.function.target)
obj.function.arguments = obj.function.arguments.map(convertUndefined)
}
if ('env' in obj) {
obj.env = convertUndefined(obj.env)
}
if ('prototype' in obj) {
obj.prototype = convertUndefined(obj.prototype)
}
for (var k in obj.properties) {
var prty = obj.properties[k]
if ('value' in prty) {
prty.value = convertUndefined(prty.value)
}
if ('get' in prty) {
prty.get = convertUndefined(prty.get)
}
if ('set' in prty) {
prty.set = convertUndefined(prty.set)
}
}
})
}
function loadInputs(snapshotFile) {
// Load snapshot
var snapshotText = fs.readFileSync(snapshotFile, 'utf8');
try {
snapshot = JSON.parse(snapshotText);
normalizeSnapshot();
} catch (e) {
if (snapshotWasGenerated) {
console.error('Error while executing library code')
console.error(snapshotText)
fs.unlinkSync(snapshotFile)
process.exit(1)
} else {
fatalError("Parse error in " + snapshotFile, e)
}
}
// Load TypeScript
var typeDeclText = fs.readFileSync(typeDeclFile, 'utf8');
var libFile = __dirname + "/lib/lib.d.ts";
var libFileText = fs.readFileSync(libFile, 'utf8');
try {
typeDecl = tscore([
{file: LIB_ORIGIN, text:libFileText},
{file: typeDeclFile, text:typeDeclText}
])
} catch (e) {
fatalError("Could not parse " + typeDeclFile + ": " + e, e)
}
// Load source code
var sourceFileText = fs.readFileSync(sourceFile, 'utf8')
try {
sourceFileAst = esprima.parse(sourceFileText, {loc:true})
} catch (e) {
fatalError("Syntax error in " + sourceFileText + ": " + e, e)
}
load_handlers.forEach(function(fn) {
fn();
})
load_handlers = null
}
}
initialize()
// -----------------------------------
// Miscellaneous util stuff
// -----------------------------------
var unique_error_ids = new Map;
function reportUniqueError(uid, msg) {
if (unique_error_ids.has(uid))
return;
unique_error_ids.put(uid, true)
console.log(msg)
}
function qualify(host, name) {
if (host === '')
return name;
if (host.startsWith('module:'))
return host.substring('module:'.length) + '::' + name;
return host + '.' + name;
}
function jsonMap(obj,fn) {
var result = {}
for (var k in obj) {
result[k] = fn(obj[k])
}
return result
}
// ---------------------------
// Lookup functions
// ---------------------------
function lookupObject(key) {
var obj = snapshot.heap[key];
if (!obj) {
throw new Error("Missing object with key " + key)
}
return obj;
}
function lookupQType(qname, targs) {
var tdecl = typeDecl.env[qname];
if (!tdecl) {
reportUniqueError('missing:' + qname, "Error: Type " + qname + " is not defined");
return null;
}
if (targs.length !== tdecl.typeParameters.length) {
reportUniqueError('targs:' + qname, "Error: Type " + qname + " expects " + tdecl.typeParameters.length + " type arguments but got " + targs.length);
return null;
}
if (targs.length === 0)
return tdecl.object; // optimization: skip substitution step if there are no type arguments
var tenv = new Map
for (var i=0; i<targs.length; i++) {
tenv.put(tdecl.typeParameters[i], targs[i])
}
return substType(tdecl.object, tenv)
}
function resolveTypeRef(t) {
return lookupQType(t.name, t.typeArguments)
}
function getPrototype(key) {
var obj = lookupObject(key)
return obj.prototype && obj.prototype.key
}
function findPrtyDirect(obj, name) {
return obj.properties.find(function(x) { return x.name == name });
}
function findPrty(obj, name) {
while (obj) {
var prty = findPrtyDirect(obj,name)
if (prty)
return prty;
obj = obj.prototype && lookupObject(obj.prototype.key);
}
return null;
}
// Cyclic Prototype Detection. (Mostly for debugging jsnap)
function checkCyclicPrototype(key) {
var slow = key;
var fast = key;
while (true) {
fast = getPrototype(fast)
if (!fast)
return false;
fast = getPrototype(fast)
if (!fast)
return false;
slow = getPrototype(slow)
if (slow === fast)
return true;
}
}
// ---------------------------------
// Name Type Expressions
// ---------------------------------
var tpath2type = new Map;
function nameType(type, tpath) {
switch (type.type) {
case 'object':
type.path = tpath;
tpath2type.put(tpath, type);
for (var k in type.properties) {
var typePrty = type.properties[k]
nameType(typePrty.type, qualify(tpath, k))
}
if (type.numberIndexer) {
nameType(type.numberIndexer, qualify(tpath, '[number]'))
}
if (type.stringIndexer) {
nameType(type.stringIndexer, qualify(tpath, '[string]'))
}
type.calls.forEach(function(call,i) {
call.typeParameters.forEach(function(tp,j) {
tp.constraint && nameType(tp.constraint, qualify(tpath, 'call:' + i + 'bound:' + j))
})
call.parameters.forEach(function(parm,j) {
nameType(parm.type, qualify(tpath, 'call:' + i + 'arg:' + j))
})
nameType(call.returnType, qualify(tpath, 'call:' + i + ':return'))
})
break;
case 'reference':
type.typeArguments.forEach(function(targ,i) {
nameType(targ, qualify(tpath, 'typearg:' + i))
})
break;
}
}
function nameAllTypes() {
for (var k in typeDecl.env) {
nameType(typeDecl.env[k].object, k)
}
}
onLoaded(nameAllTypes)
// ----------------------------------------------
// Type Parameter Substitution
// ----------------------------------------------
function substTypeParameters(tparams, tenv) {
if (tparams.length === 0)
return { typeParams: [], tenv: tenv };
tenv = tenv.clone()
var typeParams = []
tparams.forEach(function (tparam) {
tenv.remove(tparam.name)
typeParams.push({
name: tparam.name,
constraint: tparam.constraint && substType(tparam.constraint, tenv)
})
})
return {
typeParams: typeParams,
tenv: tenv
}
}
function substParameter(param, tenv) {
return {
name: param.name,
optional: param.optional,
type: substType(param.type, tenv)
}
}
function substCall(call, tenv) {
var typeParamSubst = substTypeParameters(call.typeParameters, tenv)
var typeParams = typeParamSubst.typeParams
tenv = typeParamSubst.tenv
return {
new: call.new,
variadic: call.variadic,
typeParameters: typeParams,
parameters: call.parameters.map(substParameter.fill(undefined, tenv)),
returnType: substType(call.returnType, tenv),
meta: call.meta
}
}
function substPrty(prty, tenv) {
return {
optional: prty.optional,
type: substType(prty.type, tenv),
meta: prty.meta
}
}
function substType(type, tenv) {
switch (type.type) {
case 'type-param':
var t = tenv.get(type.name);
if (t)
return t;
else
return type; // this happens for function type params
case 'object':
return {
type: 'object',
typeParameters: [],
properties: jsonMap(type.properties, substPrty.fill(undefined,tenv)),
calls: type.calls.map(substCall.fill(undefined,tenv)),
stringIndexer: type.stringIndexer && substType(type.stringIndexer, tenv),
numberIndexer: type.numberIndexer && substType(type.numberIndexer, tenv),
brand: type.brand,
path: type.path,
meta: type.meta
}
break;
case 'reference':
return {
type: 'reference',
name: type.name,
typeArguments: type.typeArguments.map(substType.fill(undefined,tenv))
}
default:
return type;
}
}
// ---------------------------------
// Type Canonicalization
// ---------------------------------
var canonical_cache = Object.create(null)
var canonical_next_number = 1;
function canonicalizeKey(key) {
var value = canonical_cache[key]
if (!value) {
value = canonical_next_number++
canonical_cache[key] = value
}
return value
}
function escapeStringConst(str) {
return str; // todo, but only necessary in unrealistic circumstances
}
function canonicalizeValue(value) {
switch (typeof value) {
case 'function':
case 'object':
if (value === null)
return '_';
else
return '#' + value.key;
case 'boolean':
return value ? 't' : 'f';
case 'number':
return 'n:' + value
case 'string':
return 'C:' + escapeStringConst(value) // note: intentionally coincide with string-const type
case 'undefined':
return 'u';
default:
throw new Error("unknown value " + util.inspect(value));
}
}
function canonicalizeCall(call) {
var buf = []
if (call.new)
buf.push('+new')
if (call.variadic)
buf.push('+var')
buf.push('<')
call.typeParameters.forEach(function(tp) {
buf.push(tp.name)
buf.push(',')
})
buf.push('>(')
call.parameters.forEach(function(param) {
buf.push(param.optional ? '?' : '')
buf.push(canonicalizeType(param.type))
buf.push(';')
})
buf.push(')')
buf.push(canonicalizeType(call.returnType))
var key = buf.join('')
return canonicalizeKey(key)
}
function canonicalizeType(type) {
switch (type.type) {
case 'object':
if (type.canonical_id)
return type.canonical_id;
var bag = []
for (var k in type.properties) {
var prty = type.properties[k]
bag.push(k + (prty.optional ? '?' : '') + ':' + canonicalizeType(prty.type))
}
type.calls.forEach(function(call) {
bag.push('#' + canonicalizeCall(call))
})
if (type.stringIndexer)
bag.push('[S]:' + canonicalizeType(type.stringIndexer))
if (type.numberIndexer)
bag.push('[N]:' + canonicalizeType(type.numberIndexer))
var key = bag.sort().join(';')
var id = canonicalizeKey(key);
type.canonical_id = id;
return id;
case 'reference':
if (type.typeArguments.length > 0) {
var key = '@' + type.name + '<' + type.typeArguments.map(canonicalizeType).join(';') + '>'
return canonicalizeKey(key)
} else {
return '@' + type.name;
}
case 'number':
return 'N';
case 'boolean':
return 'B';
case 'string':
return 'S';
case 'string-const':
return 'C:' + escapeStringConst(type.value)
case 'any':
return 'A';
case 'void':
return 'V';
case 'enum':
return 'E:' + type.name;
case 'value':
return 'W:' + canonicalizeValue(type.value);
case 'node':
return 'X:' + type.node.rep().id
case 'opaque-type':
return 'O:' + type.name
case 'type-param':
return 'T:' + type.name
default:
throw new Error("Unrecognized type: " + util.inspect(type))
}
}
// ------------------------------------------------------------
// Index Properties
// ------------------------------------------------------------
function indexProperties(obj) {
if (!obj)
return;
if (obj.propertyMap)
return;
obj.propertyMap = new Map;
obj.properties.forEach(function(prty) {
obj.propertyMap.put(prty.name, prty);
})
if (!obj.prototype)
return;
var parent = lookupObject(obj.prototype.key);
indexProperties(parent)
parent.propertyMap.forEach(function(name,prty) {
if (!obj.propertyMap.has(name)) {
obj.propertyMap.put(name,prty);
}
})
}
onLoaded(function() {
snapshot.heap.forEach(indexProperties);
})
function lookupPath(path, e) {
e = e || function() { throw new Error("Missing value at " + path) }
var value = {key: snapshot.global}
var toks = path.split('.')
for (var i=0; i<toks.length; i++) {
var tok = toks[i];
if (typeof value !== 'object') {
return e(path);
}
var obj = lookupObject(value.key);
var prty = obj.propertyMap.get(tok);
if (!prty || !('value' in prty)) {
return e(path);
}
value = prty.value;
}
return value;
}
// ------------------------------------------------------------
// Determine Enum Values
// ------------------------------------------------------------
var enum_values = new Map;
function determineEnums() {
for (var qname in typeDecl.enums) {
var paths = typeDecl.enums[qname];
var values = paths.map(lookupPath.fill(undefined, function(path) {
console.log("Enum " + qname + " is missing value " + path)
return null;
}));
enum_values.put(qname, values);
}
}
onLoaded(determineEnums)
// ------------------------------------------------------------
// ToObject Coercion
// ------------------------------------------------------------
onLoaded(function() {
ObjectPrototype = lookupPath("Object.prototype");
NumberPrototype = lookupPath("Number.prototype");
StringPrototype = lookupPath("String.prototype");
BooleanPrototype = lookupPath("Boolean.prototype");
FunctionPrototype = lookupPath("Function.prototype");
RegExpPrototype = lookupPath("RegExp.prototype");
ArrayPrototype = lookupPath("Array.prototype");
})
function coerceToObject(x) {
switch (typeof x) {
case 'number': return NumberPrototype;
case 'string': return StringPrototype;
case 'boolean': return BooleanPrototype;
default: return x;
}
}
function coerceTypeToObject(x) {
switch (x.type) {
case 'number': return {type: 'reference', name:'Number', typeArguments: []}
case 'string': return {type: 'reference', name:'String', typeArguments: []}
case 'string-const': return {type: 'reference', name:'String', typeArguments: []}
case 'boolean': return {type: 'reference', name:'Boolean', typeArguments: []}
case 'value':
switch (typeof x) {
case 'number': return {type: 'reference', name:'Number', typeArguments: []}
case 'string': return {type: 'reference', name:'String', typeArguments: []}
case 'boolean': return {type: 'reference', name:'Boolean', typeArguments: []}
default: x
}
default: return x
}
}
// ------------------------------------------------------------
// Mark native functions with call signatures
// ------------------------------------------------------------
var native2callsigs = Object.create(null)
function markNatives() {
var visited = Object.create(null)
function visit(value,type) {
if (value === null || typeof value !== 'object')
return
if (type.type === 'reference') {
var h = canonicalizeType(type) + "~" + value.key
if (h in visited)
return
visited[h] = true
type = resolveTypeRef(type)
}
if (type.type !== 'object')
return
var obj = lookupObject(value.key)
if (type.calls.length > 0 && !obj.function) {
// introduce natives that jsnap did not think was a function
obj.function = {
type: 'native',
id: type.path,
}
}
if (obj.function && obj.function.type === 'native') {
var list = native2callsigs[obj.function.id]
if (!list) {
list = native2callsigs[obj.function.id] = []
}
type.calls.forEach(function(sig) {
list.push(sig)
})
}
for (var k in type.properties) {
if (type.properties[k].meta.origin === LIB_ORIGIN) {
visitPrty(obj.propertyMap.get(k), type.properties[k].type)
}
}
}
function visitPrty(prty,type) {
if (prty && 'value' in prty) {
visit(prty.value, type)
}
}
visit({key: snapshot.global}, {type: 'reference', name: typeDecl.global, typeArguments:[]})
}
onLoaded(markNatives)
function getCallSigsForNative(key) {
return native2callsigs[key] || []
}
// ------------------------------------------------------------
// Mark objects that are used as brands
// ------------------------------------------------------------
var object2brands = new Map
var valid_brands = Object.create(null)
function markBrands() {
var visited = Object.create(null)
function visit(type) {
switch (type.type) {
case 'reference':
type.typeArguments.forEach(visit)
break;
case 'object':
if (type.brand) {
var obj = lookupPath(type.brand + '.prototype', function(){return null})
if (obj && typeof obj === 'object') {
object2brands.push(obj.key, type.brand)
valid_brands[type.brand] = true
}
}
for (var k in type.properties) {
visit(type.properties[k])
}
if (type.numberIndexer) {
visit(type.numberIndexer)
}
if (type.stringIndexer) {
visit(type.stringIndexer)
}
break;
}
}
for (var k in typeDecl.env) {
visit(typeDecl.env[k].object)
}
visit({type: 'reference', name: typeDecl.global, typeArguments:[]})
// function debugBrands(path) {
// var v = lookupPath(path)
// var brands = []
// while (v && typeof v === 'object') {
// brands = brands.concat(getObjectBrands(v.key))
// v = lookupObject(v.key).prototype
// }
// console.log('brands for ' + path + ' = ' + brands.join(','))
// }
// debugBrands('L.Control.Scale.prototype')
// console.log('brands for L.Control.Scale.prototype = ' + getObjectBrands(lookupPath('L.Control.Scale.prototype').key).join(','))
}
onLoaded(markBrands)
function getObjectBrands(key) {
return object2brands.get(key) || []
}
function isValidBrand(brand) {
return !!valid_brands[brand]
}
// ------------------------------------------------------------
// Recursive check of Value vs Type
// ------------------------------------------------------------
// True if `x` is the canonical representation of an integer (no leading zeros etc)
function isNumberString(x) {
return x !== 'Infinity' && x !== 'NaN' && x === String(Math.floor(Number(x)))
}
// True if `x` can be converted to a number
function isNumberLikeString(x) {
return x == 0 || !!Number(x)
}
var tpath2warning = new Map;
function reportError(msg, path, tpath) {
if (program.path && !path.has(program.path))
return
var append = ''
if (program.compact && tpath2warning.has(tpath)) {
// append = ' [REPEAT]'
return
}
tpath2warning.put(tpath, true)
if (program.warn) {
console.log((path || '<global>') + ": " + msg + append)
}
}
function isEmptyMap(obj) {
return Object.keys(obj).length === 0;
}
function treatAsOptionalMember(type, prtyName) {
var prty = type.properties[prtyName];
var t = prty.type;
if (prty.optional)
return true;
if (t.type === 'boolean' && type.meta.kind !== 'interface')
return true; // boolean property in context where it cannot be declared optional
if (t.type === 'object' && t.meta.isEnum && isEmptyMap(t.properties))
return true; // empty enum object
return false;
}
var tpath2values = new Map;
var native_tpaths = new Map;
var assumptions = {}
function check(type, value, path, userPath, parentKey, tpath) {
function must(condition) {
if (!condition) {
if (userPath) {
reportError("expected " + formatType(type) + " but found value " + formatValue(value), path, tpath);
}
return false;
} else {
return true;
}
}
if (!type) {
throw new Error("Undefined type on path: " + path)
}
if (value === null) {
return; // null satisfies all types
}
switch (type.type) {
case 'object':
if (!type.path) {
console.log("Missing type path at value " + path)
}
tpath = type.path; // override tpath with object's own path
tpath2values.push(type.path, value)
if (!userPath) {
native_tpaths.put(type.path, true)
}
value = coerceToObject(value);
if (must(typeof value === 'object')) {
var obj = lookupObject(value.key)
if (checkCyclicPrototype(value.key)) {
reportError("Cyclic prototype chain", path, tpath);
return;
}
for (var k in type.properties) {
var typePrty = type.properties[k]
var isUserPrty = typePrty.meta.origin != LIB_ORIGIN;
var isUserPath = userPath || isUserPrty;
var objPrty = obj.propertyMap.get(k) //findPrty(obj, k)
if (!objPrty) {
if (isUserPrty && !treatAsOptionalMember(type, k)) {
reportError("expected " + formatType(typePrty.type) + " but found nothing", qualify(path,k), qualify(tpath,k))
}
} else {
if ('value' in objPrty) {
check(typePrty.type, objPrty.value, qualify(path,k), isUserPath, value.key, qualify(tpath,k))
} else {
if (objPrty.get) {
var call = {
new: false,
variadic: false,
typeParameters: [],
parameters: [],
returnType: typePrty.type,
meta: {
isGetter: true
}
}
checkCallSignature(call, value.key, objPrty.get.key, qualify(path,k))
}
}
}
}
if (type.stringIndexer && type.stringIndexer.type !== 'any') {
obj.propertyMap.forEach(function(name,objPrty) {
if (objPrty.enumerable && 'value' in objPrty) {
check(type.stringIndexer, objPrty.value, path + '[\'' + name + '\']', userPath, value.key, tpath + '[string]')
}
})
}
if (type.numberIndexer && type.numberIndexer.type !== 'any') {
obj.propertyMap.forEach(function(name,objPrty) {
if (isNumberString(name) && 'value' in objPrty) {
check(type.numberIndexer, objPrty.value, path + '[' + name + ']', userPath, value.key, tpath + '[number]')
}
})
}
if (userPath) {
type.calls.forEach(function (call) {
if (!call.meta.implicit) { // do not check default constructor
checkCallSignature(call, parentKey, value.key, path)
}
})
}
if (type.brand) {
if (hasBrand(value, type.brand) === false) {
reportError("missing prototype for branded type " + type.brand, path, tpath)
}
}
}
break;
case 'reference':
value = coerceToObject(value)
if (!must(typeof value === 'object'))
return; // only object types can match a reference
var assumKey = value.key + '~' + canonicalizeType(type)
if (assumptions[assumKey])
return; // already checked or currently checking
assumptions[assumKey] = true
var objectType = lookupQType(type.name, type.typeArguments)
if (!objectType)
return; // error issued elsewhere
check(objectType, value, path, userPath, parentKey, type.name)
break;
case 'enum':
var vals = enum_values.get(type.name);
if (vals.length === 0) {
must(typeof value !== 'undefined');
} else {
must(vals.some(function(x) { return valuesStrictEq(x,value) }));
}
break;
case 'string-const':
must(typeof value === 'string' && value === type.value)
break;
case 'number':
must(typeof value === 'number');
break;
case 'string':
must(typeof value === 'string');
break;
case 'boolean':
must(typeof value === 'boolean');
break;
case 'any':
break; // no check necessary
case 'void':
must(typeof value === 'undefined');
break;
case 'type-param':
// should be replaced by substType before we get here
throw new Error("Checking value " + formatValue(value) + " against unbound type parameter " + type.name);
default:
throw new Error("Unrecognized type type: " + type.type + " " + util.inspect(type))
}
}
function valuesStrictEq(x,y) {
if (x === y)
return true
if (x && typeof x === 'object' && y && typeof y === 'object')
return x.key === y.key
return false
}
// Returns true if brand is satisfied, false if brand is not satisfied, or null if brand prototype could not be found.
function hasBrand(value, brand) {
var ctor = lookupPath(brand, function() { return null })
if (!ctor || typeof ctor !== 'object')
return null;
var proto = lookupObject(ctor.key).propertyMap.get('prototype')
if (!proto || !proto.value || typeof proto.value !== 'object')
return null;
while (value && typeof value === 'object') {
if (value.key === proto.value.key)
return true
value = lookupObject(value.key).prototype
}
return false;
}
var num_callsigs_analyzed = 0;