-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathLiteral.java
More file actions
87 lines (73 loc) · 2.33 KB
/
Literal.java
File metadata and controls
87 lines (73 loc) · 2.33 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
package com.semmle.js.ast;
import com.semmle.jcorn.TokenType;
import com.semmle.ts.ast.ITypeExpression;
/**
* A literal constant.
*
* <p>A <code>null</code> literal may occur as a TypeScript type annotation - other literals are always
* expressions.
*/
public class Literal extends Expression implements ITypeExpression {
private final TokenType tokenType;
private final Object value;
private final String raw;
public Literal(SourceLocation loc, TokenType tokenType, Object value) {
super("Literal", loc);
// for numbers, check whether they can be represented as integers
if (value instanceof Double) {
Double dvalue = (Double) value;
if (dvalue >= Long.MIN_VALUE && dvalue <= Long.MAX_VALUE && (dvalue % 1) == 0)
value = dvalue.longValue();
} else if (value instanceof CharSequence) {
value = value.toString();
}
this.tokenType = tokenType;
this.value = value;
this.raw = getLoc().getSource();
}
@Override
public <Q, A> A accept(Visitor<Q, A> v, Q q) {
return v.visit(this, q);
}
/** The type of the token corresponding to this literal. */
public TokenType getTokenType() {
return tokenType;
}
/**
* The value of this literal; may be null if this is a null literal or a literal whose value
* cannot be represented by the parser.
*/
public Object getValue() {
return value;
}
/** The source text of this literal. */
public String getRaw() {
return raw;
}
/** Is this a regular expression literal? */
public boolean isRegExp() {
return tokenType == TokenType.regexp;
}
/** Is this a string literal? */
public boolean isStringLiteral() {
return tokenType == TokenType.string;
}
/** The value of this literal expressed as a string. */
public String getStringValue() {
// regular expressions may have a null value; use the raw value instead
if (isRegExp()) return raw;
return String.valueOf(value);
}
/** Is the value of this literal falsy? */
public boolean isFalsy() {
if (isRegExp()) return false;
return value == null
|| value instanceof Number && ((Number) value).intValue() == 0
|| Boolean.FALSE.equals(value)
|| value instanceof String && ((String) value).isEmpty();
}
/** Is the value of this literal truthy? */
public boolean isTruthy() {
return !isFalsy();
}
}