/
Literal.ts
79 lines (68 loc) · 2.13 KB
/
Literal.ts
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
import MagicString from 'magic-string';
import { RenderOptions } from '../../utils/renderHelpers';
import CallOptions from '../CallOptions';
import { ExecutionPathOptions } from '../ExecutionPathOptions';
import {
getLiteralMembersForValue,
getMemberReturnExpressionWhenCalled,
hasMemberEffectWhenCalled,
LiteralValueOrUnknown,
MemberDescription,
ObjectPath,
UNKNOWN_EXPRESSION,
UNKNOWN_VALUE
} from '../values';
import * as NodeType from './NodeType';
import { Node, NodeBase } from './shared/Node';
export type LiteralValue = string | boolean | null | number | RegExp | undefined;
export function isLiteral(node: Node): node is Literal {
return node.type === NodeType.Literal;
}
export default class Literal<T = LiteralValue> extends NodeBase {
type: NodeType.tLiteral;
value: T;
private members: { [key: string]: MemberDescription };
getLiteralValueAtPath(path: ObjectPath): LiteralValueOrUnknown {
if (
path.length > 0 ||
// unknown literals such as bigints can also be null but do not start with an "n"
(this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
typeof this.value === 'bigint'
) {
return UNKNOWN_VALUE;
}
return this.value as any;
}
getReturnExpressionWhenCalledAtPath(path: ObjectPath) {
if (path.length !== 1) return UNKNOWN_EXPRESSION;
return getMemberReturnExpressionWhenCalled(this.members, path[0]);
}
hasEffectsWhenAccessedAtPath(path: ObjectPath) {
if (this.value === null) {
return path.length > 0;
}
return path.length > 1;
}
hasEffectsWhenAssignedAtPath(path: ObjectPath) {
return path.length > 0;
}
hasEffectsWhenCalledAtPath(
path: ObjectPath,
callOptions: CallOptions,
options: ExecutionPathOptions
): boolean {
if (path.length === 1) {
return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, options);
}
return true;
}
initialise() {
this.included = false;
this.members = getLiteralMembersForValue(this.value);
}
render(code: MagicString, _options: RenderOptions) {
if (typeof this.value === 'string') {
(<[number, number][]>code.indentExclusionRanges).push([this.start + 1, this.end - 1]);
}
}
}