-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTypeMapper.ts
More file actions
48 lines (44 loc) · 1.54 KB
/
Copy pathTypeMapper.ts
File metadata and controls
48 lines (44 loc) · 1.54 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
import { PrimitiveType } from "./PrimitiveType";
import { ArrayType, ObjectType, Type, TypeArgument, Wildcard } from "./Project";
export interface TypeMapper {
map(type: Type | TypeArgument): string;
}
interface Mapping {
primitive?(type: PrimitiveType, mapper: TypeMapper): string;
object?(type: ObjectType, mapper: TypeMapper): string;
array?(type: ArrayType, mapper: TypeMapper): string;
wildcard?(type: Wildcard, mapper: TypeMapper): string;
}
const defaultMapping = {
array(type: ArrayType, mapper: TypeMapper) {
return `${mapper.map(type.component)}${"[]".repeat(type.dimension)}`;
},
wildcard(type: Wildcard, mapper: TypeMapper) {
return (
"?" +
(type.constraint == undefined
? ""
: ` ${type.constraint.kind} ${mapper.map(type.constraint.type)}`)
);
},
};
export function createTypeMapper(mapping: Mapping): TypeMapper {
function map(type: Type | TypeArgument): string {
let result: string | undefined;
if (type instanceof PrimitiveType) {
result = mapping.primitive?.(type, { map });
} else if (type instanceof ObjectType) {
result = mapping.object?.(type, { map });
} else if (type instanceof ArrayType) {
result = (mapping.array ?? defaultMapping.array)(type, { map });
} else if (type instanceof Wildcard) {
result = (mapping.wildcard ?? defaultMapping.wildcard)(type, { map });
}
if (result == undefined) {
throw new Error(`no mapping for ${type.name} (${type.constructor.name})`);
} else {
return result;
}
}
return { map };
}