/
Literal.ts
86 lines (75 loc) · 2.38 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
80
81
82
83
84
85
86
import type MagicString from 'magic-string';
import type { CallOptions } from '../CallOptions';
import type { HasEffectsContext } from '../ExecutionContext';
import type { ObjectPath } from '../utils/PathTracker';
import {
getLiteralMembersForValue,
getMemberReturnExpressionWhenCalled,
hasMemberEffectWhenCalled,
type MemberDescription
} from '../values';
import type * as NodeType from './NodeType';
import {
type ExpressionEntity,
type LiteralValueOrUnknown,
UNKNOWN_EXPRESSION,
UnknownValue
} from './shared/Expression';
import { type GenericEsTreeNode, NodeBase } from './shared/Node';
export type LiteralValue = string | boolean | null | number | RegExp | undefined;
export default class Literal<T extends LiteralValue = LiteralValue> extends NodeBase {
declare regex?: {
flags: string;
pattern: string;
};
declare type: NodeType.tLiteral;
declare value: T;
private declare members: { [key: string]: MemberDescription };
deoptimizeThisOnEventAtPath(): void {}
getLiteralValueAtPath(path: ObjectPath): LiteralValueOrUnknown {
if (
path.length > 0 ||
// unknown literals 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' ||
// to support shims for regular expressions
this.context.code.charCodeAt(this.start) === 47
) {
return UnknownValue;
}
return this.value;
}
getReturnExpressionWhenCalledAtPath(path: ObjectPath): ExpressionEntity {
if (path.length !== 1) return UNKNOWN_EXPRESSION;
return getMemberReturnExpressionWhenCalled(this.members, path[0]);
}
hasEffectsWhenAccessedAtPath(path: ObjectPath): boolean {
if (this.value === null) {
return path.length > 0;
}
return path.length > 1;
}
hasEffectsWhenCalledAtPath(
path: ObjectPath,
callOptions: CallOptions,
context: HasEffectsContext
): boolean {
if (path.length === 1) {
return hasMemberEffectWhenCalled(this.members, path[0], callOptions, context);
}
return true;
}
initialise(): void {
this.members = getLiteralMembersForValue(this.value);
}
parseNode(esTreeNode: GenericEsTreeNode): void {
this.value = esTreeNode.value;
this.regex = esTreeNode.regex;
super.parseNode(esTreeNode);
}
render(code: MagicString): void {
if (typeof this.value === 'string') {
(code.indentExclusionRanges as [number, number][]).push([this.start + 1, this.end - 1]);
}
}
}