-
Notifications
You must be signed in to change notification settings - Fork 728
/
Api.java
311 lines (279 loc) · 10.8 KB
/
Api.java
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*
* Copyright 2022 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.checkreturnvalue;
import static com.google.common.base.CharMatcher.whitespace;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.errorprone.matchers.Matchers.anyMethod;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.constructor;
import static java.lang.Character.isJavaIdentifierPart;
import static java.lang.Character.isJavaIdentifierStart;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.annotations.CompileTimeConstant;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import java.util.List;
/**
* Represents a Java method or constructor. Provides a method to parse an API from a string format,
* and another method to create an ErrorProne {@link Matcher} for the API.
*/
// TODO(kak): do we want to be able to represent classes in addition to methods/constructors?
// TODO(kak): if not, then consider renaming to `MethodSignature` or something
@AutoValue
public abstract class Api {
// TODO(b/223668437): use this (or something other than the Matcher<> API)
static Matcher<ExpressionTree> createMatcherFromApis(List<String> apis) {
return anyOf(apis.stream().map(Api::parse).map(Api::matcher).collect(toImmutableList()));
}
static ImmutableSet<Api> createSetFromApis(List<String> apis) {
return apis.stream().map(Api::parse).collect(toImmutableSet());
}
/** Returns the fully qualified type that contains the given method/constructor. */
abstract String className();
/**
* Returns the simple name of the method. If the API is a constructor (i.e., {@code
* isConstructor() == true}), then {@code "<init>"} is returned.
*/
abstract String methodName();
/** Returns the list of fully qualified parameter types for the given method/constructor. */
abstract ImmutableList<String> parameterTypes();
@Override
public final String toString() {
return String.format(
"%s#%s(%s)", className(), methodName(), Joiner.on(',').join(parameterTypes()));
}
/** Returns whether this API represents a constructor or not. */
boolean isConstructor() {
return methodName().equals("<init>");
}
private Matcher<ExpressionTree> matcher() {
return isConstructor()
? constructor().forClass(className()).withParameters(parameterTypes())
: anyMethod()
.onClass(className())
.named(methodName())
// TODO(b/219754967): what about arrays
.withParameters(parameterTypes());
}
/**
* Parses an API string into an {@link Api}. Example API strings are:
*
* <ul>
* <li>a constructor (e.g., {@code java.net.URI#<init>(java.lang.String)})
* <li>a static method (e.g., {@code java.net.URI#create(java.lang.String)})
* <li>an instance method (e.g., {@code java.util.List#get(int)})
* <li>an instance method with types erased (e.g., {@code java.util.List#add(java.lang.Object)})
* </ul>
*/
static Api parse(String api) {
Parser p = new Parser(api);
// Let's parse this in 3 parts:
// * Fully-qualified owning name, followed by #
// * method name, or "<init>", followed by (
// * Any number of parameter types, all but the last followed by a ',', Finishing with )
// * and nothing at the end.
String className = p.owningType();
String methodName = p.methodName();
ImmutableList<String> paramList = p.parameters();
p.ensureNoMoreCharacters();
return new AutoValue_Api(className, methodName, paramList);
}
private static final class Parser {
private final String api;
private int position = -1;
Parser(String api) {
this.api = api;
}
String owningType() {
StringBuilder buffer = new StringBuilder(api.length());
token:
do {
char next = nextLookingFor('#');
switch (next) {
case '#':
// We've hit the end of the leading type, break out.
break token;
case '.':
// OK, separator
break;
default:
checkArgument(
isJavaIdentifierPart(next),
"Unable to parse '%s' because '%s' is not a valid identifier",
api,
next);
}
buffer.append(next);
} while (true);
String type = buffer.toString();
check(!type.isEmpty(), api, "class name cannot be empty");
check(
isJavaIdentifierStart(type.charAt(0)),
api,
"the class name must start with a valid character");
return type;
}
String methodName() {
StringBuilder buffer = new StringBuilder(api.length() - position);
boolean isConstructor = false;
boolean finishedConstructor = false;
// match "<init>", or otherwise a normal method name
token:
do {
char next = nextLookingFor('(');
switch (next) {
case '(':
// We've hit the end of the method name, break out.
break token;
case '<':
// Starting a constructor
check(!isConstructor, api, "Only one '<' is allowed");
check(buffer.length() == 0, api, "'<' must come directly after '#'");
isConstructor = true;
break;
case '>':
check(isConstructor, api, "'<' must come before '>'");
check(!finishedConstructor, api, "Only one '>' is allowed");
finishedConstructor = true;
break;
default:
checkArgument(
isJavaIdentifierPart(next),
"Unable to parse '%s' because '%s' is not a valid identifier",
api,
next);
}
buffer.append(next);
} while (true);
String methodName = buffer.toString();
if (isConstructor) {
check(finishedConstructor, api, "found '<' without closing '>");
// Must be "<init>" exactly
checkArgument(
methodName.equals("<init>"),
"Unable to parse '%s' because %s is an invalid method name",
api,
methodName);
} else {
check(!methodName.isEmpty(), api, "method name cannot be empty");
check(
isJavaIdentifierStart(methodName.charAt(0)),
api,
"the method name must start with a valid character");
}
return methodName;
}
ImmutableList<String> parameters() {
// Text until the next ',' or ')' represents the parameter type.
// If the first token is ')', then we have an empty parameter list.
StringBuilder buffer = new StringBuilder(api.length() - position);
ImmutableList.Builder<String> paramBuilder = ImmutableList.builder();
boolean emptyList = true;
paramList:
do {
char next = nextLookingFor(')');
switch (next) {
case ')':
if (emptyList) {
return ImmutableList.of();
}
// We've hit the end of the whole list, bail out.
paramBuilder.add(consumeParam(buffer));
break paramList;
case ',':
// We've hit the middle of a parameter, consume it
paramBuilder.add(consumeParam(buffer));
break;
case '[':
case ']':
case '.':
// . characters are separators, [ and ] are array characters, they're checked @ the end
buffer.append(next);
break;
default:
checkArgument(
isJavaIdentifierPart(next),
"Unable to parse '%s' because '%s' is not a valid identifier",
api,
next);
emptyList = false;
buffer.append(next);
}
} while (true);
return paramBuilder.build();
}
private String consumeParam(StringBuilder buffer) {
String parameter = buffer.toString();
buffer.setLength(0); // reset the buffer
check(!parameter.isEmpty(), api, "parameters cannot be empty");
check(
isJavaIdentifierStart(parameter.charAt(0)),
api,
"parameters must start with a valid character");
// Array specs must be in balanced pairs at the *end* of the parameter.
boolean parsingArrayStart = false;
boolean hasArraySpecifiers = false;
for (int k = 1; k < parameter.length(); k++) {
char c = parameter.charAt(k);
switch (c) {
case '[':
check(!parsingArrayStart, api, "multiple consecutive [");
hasArraySpecifiers = true;
parsingArrayStart = true;
break;
case ']':
check(parsingArrayStart, api, "unbalanced ] in array type");
parsingArrayStart = false;
break;
default:
check(
!hasArraySpecifiers,
api,
"types with array specifiers should end in those specifiers");
}
}
check(!parsingArrayStart, api, "[ without closing ] at the end of a parameter type");
return parameter;
}
// skip whitespace characters and give the next non-whitespace character. If we hit the end
// without a non-whitespace character, throw expecting the delimiter.
private char nextLookingFor(char delimiter) {
char next;
do {
position++;
checkArgument(
position < api.length(), "Could not parse '%s' as it must contain an '%s'", delimiter);
next = api.charAt(position);
} while (whitespace().matches(next));
return next;
}
void ensureNoMoreCharacters() {
while (++position < api.length()) {
check(whitespace().matches(api.charAt(position)), api, "it should end in ')'");
}
}
}
// The @CompileTimeConstant is for performance - reason should be constant and not eagerly
// constructed.
private static void check(boolean condition, String api, @CompileTimeConstant String reason) {
checkArgument(condition, "Unable to parse '%s' because %s", api, reason);
}
}