-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypeInfo.java
More file actions
114 lines (101 loc) · 2.99 KB
/
TypeInfo.java
File metadata and controls
114 lines (101 loc) · 2.99 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
public final class TypeInfo {
public enum Kind {
INT,
FLOAT,
BOOL,
CHAR,
STRING,
VOID,
ARRAY,
ERROR
}
public static final TypeInfo INT = new TypeInfo(Kind.INT, null);
public static final TypeInfo FLOAT = new TypeInfo(Kind.FLOAT, null);
public static final TypeInfo BOOL = new TypeInfo(Kind.BOOL, null);
public static final TypeInfo CHAR = new TypeInfo(Kind.CHAR, null);
public static final TypeInfo STRING = new TypeInfo(Kind.STRING, null);
public static final TypeInfo VOID = new TypeInfo(Kind.VOID, null);
public static final TypeInfo ERROR = new TypeInfo(Kind.ERROR, null);
private final Kind kind;
private final TypeInfo elementType;
private TypeInfo(Kind kind, TypeInfo elementType) {
this.kind = kind;
this.elementType = elementType;
}
public static TypeInfo arrayOf(TypeInfo elementType) {
return new TypeInfo(Kind.ARRAY, elementType);
}
public Kind getKind() {
return kind;
}
public TypeInfo getElementType() {
return elementType;
}
public boolean isNumeric() {
return kind == Kind.INT || kind == Kind.FLOAT;
}
public boolean isScalar() {
return kind != Kind.ARRAY && kind != Kind.VOID && kind != Kind.ERROR;
}
public boolean isAssignableFrom(TypeInfo source) {
if (this == ERROR || source == ERROR) {
return true;
}
if (kind == source.kind) {
if (kind != Kind.ARRAY) {
return true;
}
return elementType.isSameBase(source.elementType);
}
if (kind == Kind.FLOAT && source.kind == Kind.INT) {
return true;
}
if (kind == Kind.BOOL && source.kind == Kind.INT) {
return true;
}
if (kind == Kind.STRING && source.kind != Kind.ARRAY && source.kind != Kind.VOID) {
return true;
}
return false;
}
public boolean isBoolCoercible() {
return kind == Kind.BOOL || kind == Kind.INT;
}
public boolean isSameBase(TypeInfo other) {
if (this == ERROR || other == ERROR) {
return true;
}
if (kind != other.kind) {
return false;
}
if (kind != Kind.ARRAY) {
return true;
}
return elementType.isSameBase(other.elementType);
}
@Override
public String toString() {
if (kind == Kind.ARRAY) {
return elementType + "[]";
}
return kind.name().toLowerCase();
}
public static TypeInfo fromPrimitive(String name) {
if ("int".equals(name)) {
return INT;
}
if ("float".equals(name)) {
return FLOAT;
}
if ("bool".equals(name)) {
return BOOL;
}
if ("char".equals(name)) {
return CHAR;
}
if ("string".equals(name)) {
return STRING;
}
return ERROR;
}
}