-
Notifications
You must be signed in to change notification settings - Fork 328
Expand file tree
/
Copy pathReflection.ts
More file actions
596 lines (521 loc) · 16.7 KB
/
Copy pathReflection.ts
File metadata and controls
596 lines (521 loc) · 16.7 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
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
import { FSharpRef, Record, Union } from "./Types.ts";
import { Exception, MutableArray, combineHashCodes, equalArraysWith, IEquatable, stringHash } from "./Util.ts";
import Decimal from "./Decimal.ts";
import { Some, some } from "./Option.ts";
export type FieldInfo = [string, TypeInfo];
export type PropertyInfo = FieldInfo;
export type ParameterInfo = FieldInfo;
export type Constructor = new (...args: any[]) => any;
export class CaseInfo {
public declaringType: TypeInfo;
public tag: number;
public name: string;
public fields?: FieldInfo[];
constructor(
declaringType: TypeInfo,
tag: number,
name: string,
fields?: FieldInfo[]
) {
this.declaringType = declaringType;
this.tag = tag;
this.name = name;
this.fields = fields;
}
}
export type EnumCase = [string, number];
export class MethodInfo {
public name: string;
public parameters: ParameterInfo[];
public returnType: TypeInfo;
constructor(
name: string,
parameters: ParameterInfo[],
returnType: TypeInfo,
) {
this.name = name;
this.parameters = parameters;
this.returnType = returnType;
}
}
export class TypeInfo implements IEquatable<TypeInfo> {
public fullname: string;
public generics?: TypeInfo[];
public construct?: Constructor;
public parent?: TypeInfo;
public fields?: () => FieldInfo[];
public cases?: () => CaseInfo[];
public enumCases?: EnumCase[];
constructor(
fullname: string,
generics?: TypeInfo[],
construct?: Constructor,
parent?: TypeInfo,
fields?: () => FieldInfo[],
cases?: () => CaseInfo[],
enumCases?: EnumCase[]
) {
this.fullname = fullname;
this.generics = generics;
this.construct = construct;
this.parent = parent;
this.fields = fields;
this.cases = cases;
this.enumCases = enumCases;
}
public toString() {
return fullName(this);
}
public GetHashCode() {
return getHashCode(this);
}
public Equals(other: TypeInfo) {
return equals(this, other);
}
}
export class GenericParameter extends TypeInfo {
constructor(name: string) {
super(name);
}
}
export function getGenerics(t: TypeInfo): TypeInfo[] {
return t.generics != null ? t.generics : [];
}
export function getHashCode(t: TypeInfo) {
const fullnameHash = stringHash(t.fullname);
const genHashes: number[] = getGenerics(t).map(getHashCode);
return combineHashCodes([fullnameHash, ...genHashes]);
}
export function equals(t1: TypeInfo, t2: TypeInfo): boolean {
if (t1.fullname === "") { // Anonymous records
return t2.fullname === ""
&& equalArraysWith(getRecordElements(t1),
getRecordElements(t2),
([k1, v1], [k2, v2]) => k1 === k2 && equals(v1, v2));
} else {
return t1.fullname === t2.fullname
&& equalArraysWith(getGenerics(t1), getGenerics(t2), equals);
}
}
export function class_type(
fullname: string,
generics?: TypeInfo[],
construct?: Constructor,
parent?: TypeInfo): TypeInfo {
return new TypeInfo(fullname, generics, construct, parent);
}
export function record_type(
fullname: string,
generics: TypeInfo[],
construct: Constructor,
fields: () => FieldInfo[]): TypeInfo {
return new TypeInfo(fullname, generics, construct, undefined, fields);
}
export function anonRecord_type(...fields: FieldInfo[]): TypeInfo {
return new TypeInfo("", undefined, undefined, undefined, () => fields);
}
export function union_type(
fullname: string,
generics: TypeInfo[],
construct: Constructor,
cases: () => FieldInfo[][]): TypeInfo {
const t: TypeInfo = new TypeInfo(fullname, generics, construct, undefined, undefined, () => {
const caseNames = construct.prototype.cases() as string[];
return cases().map((fields, i) => new CaseInfo(t, i, caseNames[i], fields))
});
return t;
}
export function tuple_type(...generics: TypeInfo[]): TypeInfo {
return new TypeInfo("System.Tuple`" + generics.length, generics);
}
export function delegate_type(...generics: TypeInfo[]): TypeInfo {
return new TypeInfo("System.Func`" + generics.length, generics);
}
export function lambda_type(argType: TypeInfo, returnType: TypeInfo): TypeInfo {
return new TypeInfo("Microsoft.FSharp.Core.FSharpFunc`2", [argType, returnType]);
}
export function option_type(generic: TypeInfo): TypeInfo {
const t: TypeInfo = new TypeInfo(
"Microsoft.FSharp.Core.FSharpOption`1",
[generic],
undefined,
undefined,
undefined,
() => [
new CaseInfo(t, 0, "None"),
new CaseInfo(t, 1, "Some", [["value", generic]])
]
);
return t;
}
export function list_type(generic: TypeInfo): TypeInfo {
return new TypeInfo("Microsoft.FSharp.Collections.FSharpList`1", [generic]);
}
export function array_type(generic: TypeInfo): TypeInfo {
return new TypeInfo("[]", [generic]);
}
export function enum_type(fullname: string, underlyingType: TypeInfo, enumCases: EnumCase[]): TypeInfo {
return new TypeInfo(fullname, [underlyingType], undefined, undefined, undefined, undefined, enumCases);
}
export function measure_type(fullname: string): TypeInfo {
return new TypeInfo(fullname);
}
export function generic_type(name: string): TypeInfo {
return new GenericParameter(name);
}
export const obj_type: TypeInfo = new TypeInfo("System.Object");
export const unit_type: TypeInfo = new TypeInfo("Microsoft.FSharp.Core.Unit");
export const char_type: TypeInfo = new TypeInfo("System.Char");
export const string_type: TypeInfo = new TypeInfo("System.String");
export const bool_type: TypeInfo = new TypeInfo("System.Boolean");
export const int8_type: TypeInfo = new TypeInfo("System.SByte");
export const uint8_type: TypeInfo = new TypeInfo("System.Byte");
export const int16_type: TypeInfo = new TypeInfo("System.Int16");
export const uint16_type: TypeInfo = new TypeInfo("System.UInt16");
export const int32_type: TypeInfo = new TypeInfo("System.Int32");
export const uint32_type: TypeInfo = new TypeInfo("System.UInt32");
export const int64_type: TypeInfo = new TypeInfo("System.Int64");
export const uint64_type: TypeInfo = new TypeInfo("System.UInt64");
export const int128_type: TypeInfo = new TypeInfo("System.Int128");
export const uint128_type: TypeInfo = new TypeInfo("System.UInt128");
export const nativeint_type: TypeInfo = new TypeInfo("System.IntPtr");
export const unativeint_type: TypeInfo = new TypeInfo("System.UIntPtr");
export const float16_type: TypeInfo = new TypeInfo("System.Half");
export const float32_type: TypeInfo = new TypeInfo("System.Single");
export const float64_type: TypeInfo = new TypeInfo("System.Double");
export const decimal_type: TypeInfo = new TypeInfo("System.Decimal");
export const bigint_type: TypeInfo = new TypeInfo("System.Numerics.BigInteger");
export function name(info: FieldInfo | TypeInfo | CaseInfo | MethodInfo): string {
if (Array.isArray(info)) {
return info[0];
} else if (info instanceof TypeInfo) {
const elemType = getElementType(info);
if (elemType != null) {
return name(elemType) + "[]";
} else {
const i = info.fullname.lastIndexOf(".");
return i === -1 ? info.fullname : info.fullname.slice(i + 1);
}
} else {
return info.name;
}
}
export function fullName(t: TypeInfo): string {
const elemType = getElementType(t);
if (elemType != null) {
return fullName(elemType) + "[]";
} else if (t.generics == null || t.generics.length === 0) {
return t.fullname
} else {
return t.fullname + "[" + t.generics.map((x) => fullName(x)).join(",") + "]";
}
}
export function namespace(t: TypeInfo): string {
const elemType = getElementType(t);
if (elemType != null) {
return namespace(elemType);
} else {
const i = t.fullname.lastIndexOf(".");
return i === -1 ? "" : t.fullname.slice(0, i);
}
}
export function isArray(t: TypeInfo): boolean {
return getElementType(t) != null;
}
export function getElementType(t: TypeInfo): TypeInfo | undefined {
return t.fullname === "[]" && t.generics?.length === 1 ? t.generics[0] : undefined;
}
export function isGenericType(t: TypeInfo) {
return t.generics != null && t.generics.length > 0;
}
export function isGenericParameter(t: TypeInfo) {
return t instanceof GenericParameter;
}
export function isEnum(t: TypeInfo) {
return t.enumCases != null && t.enumCases.length > 0;
}
export function isSubclassOf(t1: TypeInfo, t2: TypeInfo): boolean {
return (t2.fullname === obj_type.fullname) || (t1.parent != null && (t1.parent.Equals(t2) || isSubclassOf(t1.parent, t2)));
}
function isErasedToNumber(t: TypeInfo) {
return isEnum(t) || [
int8_type.fullname,
uint8_type.fullname,
int16_type.fullname,
uint16_type.fullname,
int32_type.fullname,
uint32_type.fullname,
float16_type.fullname,
float32_type.fullname,
float64_type.fullname,
].includes(t.fullname);
}
function isErasedToBigInt(t: TypeInfo) {
return isEnum(t) || [
int64_type.fullname,
uint64_type.fullname,
int128_type.fullname,
uint128_type.fullname,
nativeint_type.fullname,
unativeint_type.fullname,
bigint_type.fullname,
].includes(t.fullname);
}
export function isInstanceOfType(t: TypeInfo, o: any) {
if (t.fullname === obj_type.fullname)
return true;
switch (typeof o) {
case "boolean":
return t.fullname === bool_type.fullname;
case "string":
return t.fullname === string_type.fullname;
case "function":
return isFunction(t);
case "number":
return isErasedToNumber(t);
case "bigint":
return isErasedToBigInt(t);
default:
return t.construct != null && o instanceof t.construct;
}
}
/**
* This doesn't replace types for fields (records) or cases (unions)
* but it should be enough for type comparison purposes
*/
export function getGenericTypeDefinition(t: TypeInfo) {
return t.generics == null ? t : new TypeInfo(t.fullname, t.generics.map(() => obj_type));
}
export function getEnumUnderlyingType(t: TypeInfo) {
return t.generics?.[0];
}
export function getEnumValues(t: TypeInfo): number[] {
if (isEnum(t) && t.enumCases != null) {
return t.enumCases.map((kv) => kv[1]);
} else {
throw new Exception(`${t.fullname} is not an enum type`);
}
}
export function getEnumNames(t: TypeInfo): string[] {
if (isEnum(t) && t.enumCases != null) {
return t.enumCases.map((kv) => kv[0]);
} else {
throw new Exception(`${t.fullname} is not an enum type`);
}
}
function getEnumCase(t: TypeInfo, v: number | string): EnumCase {
if (t.enumCases != null) {
if (typeof v === "string") {
for (const kv of t.enumCases) {
if (kv[0] === v) {
return kv;
}
}
throw new Exception(`'${v}' was not found in ${t.fullname}`);
} else {
for (const kv of t.enumCases) {
if (kv[1] === v) {
return kv;
}
}
// .NET returns the number even if it doesn't match any of the cases
return ["", v];
}
} else {
throw new Exception(`${t.fullname} is not an enum type`);
}
}
export function parseEnum(t: TypeInfo, str: string): number {
// TODO: better int parsing here, parseInt ceils floats: "4.8" -> 4
const value = parseInt(str, 10);
return getEnumCase(t, isNaN(value) ? str : value)[1];
}
export function tryParseEnum(t: TypeInfo, str: string, defValue: FSharpRef<number>): boolean {
try {
defValue.contents = parseEnum(t, str);
return true;
} catch {
return false;
}
}
export function getEnumName(t: TypeInfo, v: number): string {
return getEnumCase(t, v)[0];
}
export function isEnumDefined(t: TypeInfo, v: any): boolean {
try {
const kv = getEnumCase(t, v);
return kv[0] != null && kv[0] !== "";
} catch {
// supress error
}
return false;
}
// FSharpType
export function getUnionCases(t: TypeInfo): CaseInfo[] {
if (t.cases != null) {
return t.cases();
} else {
throw new Exception(`${t.fullname} is not an F# union type`);
}
}
export function getRecordElements(t: TypeInfo): FieldInfo[] {
if (t.fields != null) {
return t.fields();
} else {
throw new Exception(`${t.fullname} is not an F# record type`);
}
}
export function getTupleElements(t: TypeInfo): TypeInfo[] {
if (isTuple(t) && t.generics != null) {
return t.generics;
} else {
throw new Exception(`${t.fullname} is not a tuple type`);
}
}
export function getFunctionElements(t: TypeInfo): [TypeInfo, TypeInfo] {
if (isFunction(t) && t.generics != null) {
const gen = t.generics;
return [gen[0], gen[1]];
} else {
throw new Exception(`${t.fullname} is not an F# function type`);
}
}
export function isUnion(t: any): boolean {
return t instanceof TypeInfo ? t.cases != null : t instanceof Union;
}
export function isRecord(t: any): boolean {
return t instanceof TypeInfo ? t.fields != null : t instanceof Record;
}
export function isTuple(t: TypeInfo): boolean {
return t.fullname.startsWith("System.Tuple");
}
// In .NET this is false for delegates
export function isFunction(t: TypeInfo): boolean {
return t.fullname === "Microsoft.FSharp.Core.FSharpFunc`2";
}
// FSharpValue
export function getUnionFields(v: any, t: TypeInfo): [CaseInfo, any[]] {
const cases = getUnionCases(t);
// Special handling for option types (None is undefined, Some is the value or a Some wrapper)
if (t.fullname === "Microsoft.FSharp.Core.FSharpOption`1") {
if (v == null) {
return [cases[0], []]; // None case
} else {
const innerValue = v instanceof Some ? v.value : v;
return [cases[1], [innerValue]]; // Some case
}
}
const case_ = cases[v.tag];
if (case_ == null) {
throw new Exception(`Cannot find case ${v.name} in union type`);
}
return [case_, v.fields];
}
export function getUnionCaseFields(uci: CaseInfo): FieldInfo[] {
return uci.fields == null ? [] : uci.fields;
}
// This is used as replacement of `FSharpValue.GetRecordFields`
// For `FSharpTypes.GetRecordFields` see `getRecordElements`
// Object.keys returns keys in the order they were added to the object
export function getRecordFields(v: any): MutableArray<any> {
return Object.keys(v).map((k) => v[k]);
}
export function getRecordField(v: any, field: FieldInfo): any {
return v[field[0]];
}
export function getTupleFields(v: any): MutableArray<any> {
return v;
}
export function getTupleField(v: any, i: number): any {
return v[i];
}
export function makeUnion(uci: CaseInfo, values: MutableArray<any>): any {
const expectedLength = (uci.fields || []).length;
if (values.length !== expectedLength) {
throw new Exception(`Expected an array of length ${expectedLength} but got ${values.length}`);
}
// Special handling for option types
if (uci.declaringType.fullname === "Microsoft.FSharp.Core.FSharpOption`1") {
return uci.tag === 0 ? undefined : some(values[0]);
}
const construct = uci.declaringType.construct;
if (construct == null) {
return {};
}
const isSingleCase = uci.declaringType.cases ? uci.declaringType.cases().length == 1 : false;
if (isSingleCase) {
return new construct(...values);
}
else {
return new construct(uci.tag, values);
}
}
export function makeRecord(t: TypeInfo, values: MutableArray<any>): any {
const fields = getRecordElements(t);
if (fields.length !== values.length) {
throw new Exception(`Expected an array of length ${fields.length} but got ${values.length}`);
}
return t.construct != null
? new t.construct(...values)
: fields.reduce((obj, [key, _t], i) => {
obj[key] = values[i];
return obj;
}, {} as any);
}
export function makeTuple(values: MutableArray<any>, _t: TypeInfo): any {
return values;
}
export function makeGenericType(t: TypeInfo, generics: TypeInfo[]): TypeInfo {
return new TypeInfo(
t.fullname,
generics,
t.construct,
t.parent,
t.fields,
t.cases);
}
export function createInstance(t: TypeInfo, consArgs?: any[]): any {
// TODO: Check if consArgs length is same as t.construct?
// (Arg types can still be different)
if (typeof t.construct === "function") {
return new t.construct(...(consArgs ?? []));
} else if (isErasedToNumber(t)) {
return 0;
} else if (isErasedToBigInt(t)) {
return 0n;
} else {
switch (t.fullname) {
case obj_type.fullname:
return {};
case bool_type.fullname:
return false;
case decimal_type.fullname:
return new Decimal(0);
case char_type.fullname:
return "\0";
default:
throw new Exception(`Cannot access constructor of ${t.fullname}`);
}
}
}
export function getValue(propertyInfo: PropertyInfo, v: any): any {
return v[propertyInfo[0]];
}
// Fable.Core.Reflection
function assertUnion(x: any) {
if (!(x instanceof Union)) {
throw new Exception(`Value is not an F# union type`);
}
}
export function getCaseTag(x: any): number {
assertUnion(x);
return x.tag;
}
export function getCaseName(x: any): string {
assertUnion(x);
return x.cases()[x.tag];
}
export function getCaseFields(x: any): any[] {
assertUnion(x);
return x.fields;
}