Repository navigation
Expand file tree
/
Copy pathLiteralUtils.java
More file actions
238 lines (206 loc) · 8.29 KB
/
Copy pathLiteralUtils.java
File metadata and controls
238 lines (206 loc) · 8.29 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.model;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.sonar.plugins.java.api.tree.ExpressionTree;
import org.sonar.plugins.java.api.tree.LiteralTree;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.Tree.Kind;
import org.sonar.plugins.java.api.tree.UnaryExpressionTree;
public class LiteralUtils {
private static final Pattern UNICODE_ESCAPE = Pattern.compile("\\\\u+([0-9a-fA-F]{4})");
private LiteralUtils() {
// This class only contains static methods
}
@CheckForNull
public static Integer intLiteralValue(ExpressionTree expression) {
if (expression.is(Tree.Kind.INT_LITERAL)) {
return intLiteralValue((LiteralTree) expression);
}
if (expression.is(Tree.Kind.UNARY_MINUS, Tree.Kind.UNARY_PLUS)) {
UnaryExpressionTree unaryExp = (UnaryExpressionTree) expression;
Integer subExpressionIntValue = intLiteralValue(unaryExp.expression());
return expression.is(Tree.Kind.UNARY_MINUS) ? minus(subExpressionIntValue) : subExpressionIntValue;
}
return null;
}
private static Integer intLiteralValue(LiteralTree literal) {
String literalValue = literal.value().replace("_", "");
if (literalValue.startsWith("0b") || literalValue.startsWith("0B")) {
// assume it is used as bit mask
return Integer.parseUnsignedInt(literalValue.substring(2), 2);
}
return Long.decode(literalValue).intValue();
}
/**
* Decodes a character literal using Java's Unicode translation followed by escape processing,
* returning its promoted integer value.
*/
public static int charLiteralValue(LiteralTree literal) {
String translated = UNICODE_ESCAPE.matcher(literal.value())
.replaceAll(match -> Matcher.quoteReplacement(String.valueOf((char) Integer.parseInt(match.group(1), 16))));
return trimQuotes(translated).translateEscapes().charAt(0);
}
@CheckForNull
public static Long longLiteralValue(ExpressionTree tree) {
ExpressionTree expression = tree;
int sign = tree.is(Kind.UNARY_MINUS) ? -1 : 1;
if (tree.is(Kind.UNARY_MINUS, Kind.UNARY_PLUS)) {
expression = ((UnaryExpressionTree) tree).expression();
}
if (expression.is(Kind.INT_LITERAL, Kind.LONG_LITERAL)) {
String value = trimLongSuffix(((LiteralTree) expression).value());
// long as hexadecimal can be written using underscore to separate groups
value = value.replace("_", "");
try {
if (value.startsWith("0b") || value.startsWith("0B")) {
return sign * Long.valueOf(value.substring(2), 2);
}
return sign * Long.decode(value);
} catch (NumberFormatException e) {
// Long.decode() may fail in case of very large long number written in hexadecimal. In such situation, we ignore the number.
// Note that Long.MAX_VALUE = "0x7FFF_FFFF_FFFF_FFFFL", but it is possible to write larger numbers in hexadecimal
// to be used as mask in bitwise operation. For instance:
// 0x8000_0000_0000_0000L (MAX_VALUE + 1),
// 0xFFFF_FFFF_FFFF_FFFFL (only ones),
// 0xFFFF_FFFF_FFFF_FFFEL (only ones except least significant bit), ...
}
}
return null;
}
@CheckForNull
public static Double doubleLiteralValue(ExpressionTree expression) {
int sign = 1;
if (expression.is(Kind.UNARY_MINUS, Kind.UNARY_PLUS)) {
sign = expression.is(Kind.UNARY_MINUS) ? -1 : 1;
expression = ((UnaryExpressionTree) expression).expression();
}
if (expression.is(Kind.FLOAT_LITERAL, Kind.DOUBLE_LITERAL)) {
String value = ((LiteralTree) expression).value().replace("_", "");
return sign*Double.parseDouble(value);
}
return null;
}
@CheckForNull
private static Integer minus(@Nullable Integer nullableInteger) {
return nullableInteger == null ? null : -nullableInteger;
}
public static boolean isEmptyString(Tree tree) {
return tree.is(Tree.Kind.STRING_LITERAL) && trimQuotes(((LiteralTree) tree).value()).isEmpty();
}
public static boolean is0xff(ExpressionTree expression) {
return expression.is(Tree.Kind.INT_LITERAL) && "0xff".equalsIgnoreCase(((LiteralTree) expression).value());
}
public static String trimQuotes(String value) {
int delimiterLength = isTextBlock(value) ? 3 : 1;
return value.substring(delimiterLength, value.length() - delimiterLength);
}
public static boolean isTextBlock(String value) {
return value.startsWith("\"\"\"");
}
public static String trimLongSuffix(String longString) {
if (StringUtils.isBlank(longString)) {
return longString;
}
int lastCharPosition = longString.length() - 1;
char lastChar = longString.charAt(lastCharPosition);
String value = longString;
if (lastChar == 'L' || lastChar == 'l') {
value = longString.substring(0, lastCharPosition);
}
return value;
}
public static boolean hasValue(Tree tree, String expectedValue) {
if (!tree.is(Kind.STRING_LITERAL)) {
return false;
}
String actualValue = trimQuotes(((LiteralTree) tree).value());
return expectedValue.equals(actualValue);
}
public static boolean isTrue(Tree tree) {
return tree.is(Kind.BOOLEAN_LITERAL) && "true".equals(((LiteralTree) tree).value());
}
public static boolean isFalse(Tree tree) {
return tree.is(Kind.BOOLEAN_LITERAL) && "false".equals(((LiteralTree) tree).value());
}
/**
* @return true when the expression is an int literal whose value is zero, in any base:
* decimal ({@code 0}), hexadecimal ({@code 0x0}), octal ({@code 00}) or binary ({@code 0b0}).
*/
public static boolean isZero(ExpressionTree tree) {
if (!tree.is(Kind.INT_LITERAL)) {
return false;
}
try {
return intLiteralValue((LiteralTree) tree) == 0;
} catch (NumberFormatException e) {
return false;
}
}
public static boolean isOne(ExpressionTree tree) {
return tree.is(Kind.INT_LITERAL) && "1".equals(((LiteralTree) tree).value());
}
public static boolean isNegOne(ExpressionTree tree) {
return tree.is(Kind.UNARY_MINUS) && isOne(((UnaryExpressionTree) tree).expression());
}
public static String getAsStringValue(LiteralTree tree) {
if (!tree.is(Kind.TEXT_BLOCK)) {
return tree.is(Kind.STRING_LITERAL) ? trimQuotes(tree.value()) : tree.value();
}
String[] lines = tree.value().split("\r?\n");
int indent = indentationOfTextBlock(lines);
return Arrays.stream(lines)
.skip(1)
.map(String::stripTrailing)
.map(s -> stripIndent(indent, s))
.collect(Collectors.joining("\n"))
.replaceAll("\"\"\"$", "");
}
private static String stripIndent(int indent, String s) {
return s.isEmpty() ? s : s.substring(indent);
}
public static int indentationOfTextBlock(String[] lines) {
return Arrays.stream(lines).skip(1)
.filter(LiteralUtils::isNonEmptyLine)
.mapToInt(LiteralUtils::getIndentation)
.min().orElse(0);
}
private static boolean isNonEmptyLine(String line) {
return line.chars().anyMatch(LiteralUtils::isNotWhiteSpace);
}
/**
* @return Whether c is not a white space character according to the space-stripping rules of text blocks, i.e. whether
* it's a space, tab or form feed
*/
private static boolean isNotWhiteSpace(int c) {
return c != ' ' && c != '\t' && c != '\f';
}
private static int getIndentation(String line) {
for (int i = 0; i < line.length(); ++i) {
if (isNotWhiteSpace(line.charAt(i))) {
return i;
}
}
return line.length();
}
}