1 | /* |
---|---|
2 | * Copyright (C) 2007-2010 Júlio Vilmar Gesser. |
3 | * Copyright (C) 2011, 2013-2020 The JavaParser Team. |
4 | * |
5 | * This file is part of JavaParser. |
6 | * |
7 | * JavaParser can be used either under the terms of |
8 | * a) the GNU Lesser General Public License as published by |
9 | * the Free Software Foundation, either version 3 of the License, or |
10 | * (at your option) any later version. |
11 | * b) the terms of the Apache License |
12 | * |
13 | * You should have received a copy of both licenses in LICENCE.LGPL and |
14 | * LICENCE.APACHE. Please refer to those files for details. |
15 | * |
16 | * JavaParser is distributed in the hope that it will be useful, |
17 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
19 | * GNU Lesser General Public License for more details. |
20 | */ |
21 | |
22 | package com.github.javaparser; |
23 | |
24 | import com.github.javaparser.ast.CompilationUnit; |
25 | import com.github.javaparser.ast.ImportDeclaration; |
26 | import com.github.javaparser.ast.Node; |
27 | import com.github.javaparser.ast.PackageDeclaration; |
28 | import com.github.javaparser.ast.body.BodyDeclaration; |
29 | import com.github.javaparser.ast.body.MethodDeclaration; |
30 | import com.github.javaparser.ast.body.Parameter; |
31 | import com.github.javaparser.ast.body.TypeDeclaration; |
32 | import com.github.javaparser.ast.expr.*; |
33 | import com.github.javaparser.ast.modules.ModuleDeclaration; |
34 | import com.github.javaparser.ast.modules.ModuleDirective; |
35 | import com.github.javaparser.ast.stmt.BlockStmt; |
36 | import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt; |
37 | import com.github.javaparser.ast.stmt.Statement; |
38 | import com.github.javaparser.ast.type.ClassOrInterfaceType; |
39 | import com.github.javaparser.ast.type.Type; |
40 | import com.github.javaparser.ast.type.TypeParameter; |
41 | |
42 | import java.io.*; |
43 | import java.nio.charset.Charset; |
44 | import java.nio.file.Path; |
45 | |
46 | import static com.github.javaparser.ParseStart.*; |
47 | import static com.github.javaparser.Problem.PROBLEM_BY_BEGIN_POSITION; |
48 | import static com.github.javaparser.Providers.*; |
49 | import static com.github.javaparser.utils.Utils.assertNotNull; |
50 | |
51 | /** |
52 | * Parse Java source code and creates Abstract Syntax Trees. |
53 | * |
54 | * @author Júlio Vilmar Gesser |
55 | * @see StaticJavaParser |
56 | */ |
57 | public final class JavaParser { |
58 | private final ParserConfiguration configuration; |
59 | |
60 | private GeneratedJavaParser astParser = null; |
61 | |
62 | /** |
63 | * Instantiate the parser with default configuration. Note that parsing can also be done with the static methods {@link StaticJavaParser}. |
64 | * Creating an instance will reduce setup time between parsing files. |
65 | */ |
66 | public JavaParser() { |
67 | this(new ParserConfiguration()); |
68 | } |
69 | |
70 | /** |
71 | * Instantiate the parser. Note that parsing can also be done with the static methods {@link StaticJavaParser}. |
72 | * Creating an instance will reduce setup time between parsing files. |
73 | */ |
74 | public JavaParser(ParserConfiguration configuration) { |
75 | this.configuration = configuration; |
76 | } |
77 | |
78 | /** |
79 | * @return The configuration for this parser. |
80 | */ |
81 | public ParserConfiguration getParserConfiguration() { |
82 | return this.configuration; |
83 | } |
84 | |
85 | private GeneratedJavaParser getParserForProvider(Provider provider) { |
86 | if (astParser == null) { |
87 | astParser = new GeneratedJavaParser(provider); |
88 | } else { |
89 | astParser.reset(provider); |
90 | } |
91 | astParser.setTabSize(configuration.getTabSize()); |
92 | astParser.setStoreTokens(configuration.isStoreTokens()); |
93 | if (configuration.getLanguageLevel() != null) { |
94 | switch (configuration.getLanguageLevel()) { |
95 | case JAVA_13: |
96 | case JAVA_14: |
97 | astParser.setYieldSupported(); |
98 | } |
99 | } |
100 | return astParser; |
101 | } |
102 | |
103 | /** |
104 | * Parses source code. |
105 | * It takes the source code from a Provider. |
106 | * The start indicates what can be found in the source code (compilation unit, block, import...) |
107 | * |
108 | * @param start refer to the constants in ParseStart to see what can be parsed. |
109 | * @param provider refer to Providers to see how you can read source. The provider will be closed after parsing. |
110 | * @param <N> the subclass of Node that is the result of parsing in the start. |
111 | * @return the parse result, a collection of encountered problems, and some extra data. |
112 | */ |
113 | public <N extends Node> ParseResult<N> parse(ParseStart<N> start, Provider provider) { |
114 | assertNotNull(start); |
115 | assertNotNull(provider); |
116 | |
117 | for (PreProcessor preProcessor : configuration.getPreProcessors()) { |
118 | provider = preProcessor.process(provider); |
119 | } |
120 | |
121 | final GeneratedJavaParser parser = getParserForProvider(provider); |
122 | try { |
123 | N resultNode = start.parse(parser); |
124 | ParseResult<N> result = new ParseResult<>(resultNode, parser.problems, parser.getCommentsCollection()); |
125 | |
126 | configuration.getPostProcessors() |
127 | .forEach(postProcessor -> postProcessor.process(result, configuration)); |
128 | |
129 | result.getProblems() |
130 | .sort(PROBLEM_BY_BEGIN_POSITION); |
131 | |
132 | return result; |
133 | } catch (Exception e) { |
134 | final String message = e.getMessage() == null ? "Unknown error" : e.getMessage(); |
135 | parser.problems.add(new Problem(message, null, e)); |
136 | return new ParseResult<>(null, parser.problems, parser.getCommentsCollection()); |
137 | } finally { |
138 | try { |
139 | provider.close(); |
140 | } catch (IOException e) { |
141 | // Since we're done parsing and have our result, we don't care about any errors. |
142 | } |
143 | } |
144 | } |
145 | |
146 | /** |
147 | * Parses the Java code contained in the {@link InputStream} and returns a |
148 | * {@link CompilationUnit} that represents it. |
149 | * |
150 | * @param in {@link InputStream} containing Java source code. It will be closed after parsing. |
151 | * @param encoding encoding of the source code |
152 | * @return CompilationUnit representing the Java source code |
153 | * @throws ParseProblemException if the source code has parser errors |
154 | */ |
155 | public ParseResult<CompilationUnit> parse(final InputStream in, Charset encoding) { |
156 | return parse(COMPILATION_UNIT, provider(in, encoding)); |
157 | } |
158 | |
159 | /** |
160 | * Parses the Java code contained in the {@link InputStream} and returns a |
161 | * {@link CompilationUnit} that represents it.<br> |
162 | * |
163 | * @param in {@link InputStream} containing Java source code. It will be closed after parsing. |
164 | * @return CompilationUnit representing the Java source code |
165 | * @throws ParseProblemException if the source code has parser errors |
166 | */ |
167 | public ParseResult<CompilationUnit> parse(final InputStream in) { |
168 | return parse(in, configuration.getCharacterEncoding()); |
169 | } |
170 | |
171 | /** |
172 | * Parses the Java code contained in a {@link File} and returns a |
173 | * {@link CompilationUnit} that represents it. |
174 | * |
175 | * @param file {@link File} containing Java source code. It will be closed after parsing. |
176 | * @param encoding encoding of the source code |
177 | * @return CompilationUnit representing the Java source code |
178 | * @throws ParseProblemException if the source code has parser errors |
179 | * @throws FileNotFoundException the file was not found |
180 | * @deprecated set the encoding in the {@link ParserConfiguration} |
181 | */ |
182 | @Deprecated |
183 | public ParseResult<CompilationUnit> parse(final File file, final Charset encoding) throws FileNotFoundException { |
184 | ParseResult<CompilationUnit> result = parse(COMPILATION_UNIT, provider(file, encoding)); |
185 | result.getResult().ifPresent(cu -> cu.setStorage(file.toPath(), encoding)); |
186 | return result; |
187 | } |
188 | |
189 | /** |
190 | * Parses the Java code contained in a {@link File} and returns a |
191 | * {@link CompilationUnit} that represents it.<br> |
192 | * |
193 | * @param file {@link File} containing Java source code. It will be closed after parsing. |
194 | * @return CompilationUnit representing the Java source code |
195 | * @throws ParseProblemException if the source code has parser errors |
196 | * @throws FileNotFoundException the file was not found |
197 | */ |
198 | public ParseResult<CompilationUnit> parse(final File file) throws FileNotFoundException { |
199 | ParseResult<CompilationUnit> result = parse(COMPILATION_UNIT, provider(file, configuration.getCharacterEncoding())); |
200 | result.getResult().ifPresent(cu -> cu.setStorage(file.toPath(), configuration.getCharacterEncoding())); |
201 | return result; |
202 | } |
203 | |
204 | /** |
205 | * Parses the Java code contained in a file and returns a |
206 | * {@link CompilationUnit} that represents it. |
207 | * |
208 | * @param path path to a file containing Java source code |
209 | * @param encoding encoding of the source code |
210 | * @return CompilationUnit representing the Java source code |
211 | * @throws IOException the path could not be accessed |
212 | * @throws ParseProblemException if the source code has parser errors |
213 | * @deprecated set the encoding in the {@link ParserConfiguration} |
214 | */ |
215 | @Deprecated |
216 | public ParseResult<CompilationUnit> parse(final Path path, final Charset encoding) throws IOException { |
217 | ParseResult<CompilationUnit> result = parse(COMPILATION_UNIT, provider(path, encoding)); |
218 | result.getResult().ifPresent(cu -> cu.setStorage(path, encoding)); |
219 | return result; |
220 | } |
221 | |
222 | /** |
223 | * Parses the Java code contained in a file and returns a |
224 | * {@link CompilationUnit} that represents it.<br> |
225 | * |
226 | * @param path path to a file containing Java source code |
227 | * @return CompilationUnit representing the Java source code |
228 | * @throws ParseProblemException if the source code has parser errors |
229 | * @throws IOException the path could not be accessed |
230 | */ |
231 | public ParseResult<CompilationUnit> parse(final Path path) throws IOException { |
232 | ParseResult<CompilationUnit> result = parse(COMPILATION_UNIT, provider(path, configuration.getCharacterEncoding())); |
233 | result.getResult().ifPresent(cu -> cu.setStorage(path, configuration.getCharacterEncoding())); |
234 | return result; |
235 | } |
236 | |
237 | /** |
238 | * Parses the Java code contained in a resource and returns a |
239 | * {@link CompilationUnit} that represents it.<br> |
240 | * |
241 | * @param path path to a resource containing Java source code. As resource is accessed through a class loader, a |
242 | * leading "/" is not allowed in pathToResource |
243 | * @return CompilationUnit representing the Java source code |
244 | * @throws ParseProblemException if the source code has parser errors |
245 | * @throws IOException the path could not be accessed |
246 | */ |
247 | public ParseResult<CompilationUnit> parseResource(final String path) throws IOException { |
248 | return parse(COMPILATION_UNIT, resourceProvider(path, configuration.getCharacterEncoding())); |
249 | } |
250 | |
251 | /** |
252 | * Parses the Java code contained in a resource and returns a |
253 | * {@link CompilationUnit} that represents it.<br> |
254 | * |
255 | * @param path path to a resource containing Java source code. As resource is accessed through a class loader, a |
256 | * leading "/" is not allowed in pathToResource |
257 | * @param encoding encoding of the source code |
258 | * @return CompilationUnit representing the Java source code |
259 | * @throws ParseProblemException if the source code has parser errors |
260 | * @throws IOException the path could not be accessed |
261 | * @deprecated set the encoding in the {@link ParserConfiguration} |
262 | */ |
263 | @Deprecated |
264 | public ParseResult<CompilationUnit> parseResource(final String path, Charset encoding) throws IOException { |
265 | return parse(COMPILATION_UNIT, resourceProvider(path, encoding)); |
266 | } |
267 | |
268 | /** |
269 | * Parses the Java code contained in a resource and returns a |
270 | * {@link CompilationUnit} that represents it.<br> |
271 | * |
272 | * @param classLoader the classLoader that is asked to load the resource |
273 | * @param path path to a resource containing Java source code. As resource is accessed through a class loader, a |
274 | * leading "/" is not allowed in pathToResource |
275 | * @return CompilationUnit representing the Java source code |
276 | * @throws ParseProblemException if the source code has parser errors |
277 | * @throws IOException the path could not be accessed |
278 | * @deprecated set the encoding in the {@link ParserConfiguration} |
279 | */ |
280 | @Deprecated |
281 | public ParseResult<CompilationUnit> parseResource(final ClassLoader classLoader, final String path, Charset encoding) throws IOException { |
282 | return parse(COMPILATION_UNIT, resourceProvider(classLoader, path, encoding)); |
283 | } |
284 | |
285 | /** |
286 | * Parses Java code from a Reader and returns a |
287 | * {@link CompilationUnit} that represents it.<br> |
288 | * |
289 | * @param reader the reader containing Java source code. It will be closed after parsing. |
290 | * @return CompilationUnit representing the Java source code |
291 | * @throws ParseProblemException if the source code has parser errors |
292 | */ |
293 | public ParseResult<CompilationUnit> parse(final Reader reader) { |
294 | return parse(COMPILATION_UNIT, provider(reader)); |
295 | } |
296 | |
297 | /** |
298 | * Parses the Java code contained in code and returns a |
299 | * {@link CompilationUnit} that represents it. |
300 | * |
301 | * @param code Java source code |
302 | * @return CompilationUnit representing the Java source code |
303 | * @throws ParseProblemException if the source code has parser errors |
304 | */ |
305 | public ParseResult<CompilationUnit> parse(String code) { |
306 | return parse(COMPILATION_UNIT, provider(code)); |
307 | } |
308 | |
309 | /** |
310 | * Parses the Java block contained in a {@link String} and returns a |
311 | * {@link BlockStmt} that represents it. |
312 | * |
313 | * @param blockStatement {@link String} containing Java block code |
314 | * @return BlockStmt representing the Java block |
315 | * @throws ParseProblemException if the source code has parser errors |
316 | */ |
317 | public ParseResult<BlockStmt> parseBlock(final String blockStatement) { |
318 | return parse(BLOCK, provider(blockStatement)); |
319 | } |
320 | |
321 | /** |
322 | * Parses the Java statement contained in a {@link String} and returns a |
323 | * {@link Statement} that represents it. |
324 | * |
325 | * @param statement {@link String} containing Java statement code |
326 | * @return Statement representing the Java statement |
327 | * @throws ParseProblemException if the source code has parser errors |
328 | */ |
329 | public ParseResult<Statement> parseStatement(final String statement) { |
330 | return parse(STATEMENT, provider(statement)); |
331 | } |
332 | |
333 | /** |
334 | * Parses the Java import contained in a {@link String} and returns a |
335 | * {@link ImportDeclaration} that represents it. |
336 | * |
337 | * @param importDeclaration {@link String} containing Java import code |
338 | * @return ImportDeclaration representing the Java import declaration |
339 | * @throws ParseProblemException if the source code has parser errors |
340 | */ |
341 | public ParseResult<ImportDeclaration> parseImport(final String importDeclaration) { |
342 | return parse(IMPORT_DECLARATION, provider(importDeclaration)); |
343 | } |
344 | |
345 | /** |
346 | * Parses the Java expression contained in a {@link String} and returns a |
347 | * {@link Expression} that represents it. |
348 | * |
349 | * @param expression {@link String} containing Java expression |
350 | * @return Expression representing the Java expression |
351 | * @throws ParseProblemException if the source code has parser errors |
352 | */ |
353 | @SuppressWarnings("unchecked") |
354 | public <T extends Expression> ParseResult<T> parseExpression(final String expression) { |
355 | return (ParseResult<T>) parse(EXPRESSION, provider(expression)); |
356 | } |
357 | |
358 | /** |
359 | * Parses the Java annotation contained in a {@link String} and returns a |
360 | * {@link AnnotationExpr} that represents it. |
361 | * |
362 | * @param annotation {@link String} containing Java annotation |
363 | * @return AnnotationExpr representing the Java annotation |
364 | * @throws ParseProblemException if the source code has parser errors |
365 | */ |
366 | public ParseResult<AnnotationExpr> parseAnnotation(final String annotation) { |
367 | return parse(ANNOTATION, provider(annotation)); |
368 | } |
369 | |
370 | /** |
371 | * Parses the Java annotation body declaration(e.g fields or methods) contained in a |
372 | * {@link String} and returns a {@link BodyDeclaration} that represents it. |
373 | * |
374 | * @param body {@link String} containing Java body declaration |
375 | * @return BodyDeclaration representing the Java annotation |
376 | * @throws ParseProblemException if the source code has parser errors |
377 | */ |
378 | public ParseResult<BodyDeclaration<?>> parseAnnotationBodyDeclaration(final String body) { |
379 | return parse(ANNOTATION_BODY, provider(body)); |
380 | } |
381 | |
382 | /** |
383 | * Parses a Java class or interface body declaration(e.g fields or methods) and returns a |
384 | * {@link BodyDeclaration} that represents it. |
385 | * |
386 | * @param body the body of a class or interface |
387 | * @return BodyDeclaration representing the Java interface body |
388 | * @throws ParseProblemException if the source code has parser errors |
389 | */ |
390 | @SuppressWarnings("unchecked") |
391 | public <T extends BodyDeclaration<?>> ParseResult<T> parseBodyDeclaration(String body) { |
392 | return (ParseResult<T>) parse(CLASS_BODY, provider(body)); |
393 | } |
394 | |
395 | /** |
396 | * Parses a Java class or interface type name and returns a {@link ClassOrInterfaceType} that represents it. |
397 | * |
398 | * @param type the type name like a.b.c.X or Y |
399 | * @return ClassOrInterfaceType representing the type |
400 | * @throws ParseProblemException if the source code has parser errors |
401 | */ |
402 | public ParseResult<ClassOrInterfaceType> parseClassOrInterfaceType(String type) { |
403 | return parse(CLASS_OR_INTERFACE_TYPE, provider(type)); |
404 | } |
405 | |
406 | /** |
407 | * Parses a Java type name and returns a {@link Type} that represents it. |
408 | * |
409 | * @param type the type name like a.b.c.X, Y, or int |
410 | * @return ClassOrInterfaceType representing the type |
411 | * @throws ParseProblemException if the source code has parser errors |
412 | */ |
413 | public ParseResult<Type> parseType(String type) { |
414 | return parse(TYPE, provider(type)); |
415 | } |
416 | |
417 | /** |
418 | * Parses a variable declaration expression and returns a {@link com.github.javaparser.ast.expr.VariableDeclarationExpr} |
419 | * that represents it. |
420 | * |
421 | * @param declaration a variable declaration like {@code int x=2;} |
422 | * @return VariableDeclarationExpr representing the type |
423 | * @throws ParseProblemException if the source code has parser errors |
424 | */ |
425 | public ParseResult<VariableDeclarationExpr> parseVariableDeclarationExpr(String declaration) { |
426 | return parse(VARIABLE_DECLARATION_EXPR, provider(declaration)); |
427 | } |
428 | |
429 | /** |
430 | * Parses the this(...) and super(...) statements that may occur at the start of a constructor. |
431 | * |
432 | * @param statement a statement like super("hello"); |
433 | * @return the AST for the statement. |
434 | * @throws ParseProblemException if the source code has parser errors |
435 | */ |
436 | public ParseResult<ExplicitConstructorInvocationStmt> parseExplicitConstructorInvocationStmt(String statement) { |
437 | return parse(EXPLICIT_CONSTRUCTOR_INVOCATION_STMT, provider(statement)); |
438 | } |
439 | |
440 | /** |
441 | * Parses a qualified name (one that can have "."s in it) and returns it as a Name. |
442 | * |
443 | * @param qualifiedName a name like "com.laamella.parameter_source" |
444 | * @return the AST for the name |
445 | * @throws ParseProblemException if the source code has parser errors |
446 | */ |
447 | public ParseResult<Name> parseName(String qualifiedName) { |
448 | return parse(NAME, provider(qualifiedName)); |
449 | } |
450 | |
451 | /** |
452 | * Parses a simple name (one that can NOT have "."s in it) and returns it as a SimpleName. |
453 | * |
454 | * @param name a name like "parameter_source" |
455 | * @return the AST for the name |
456 | * @throws ParseProblemException if the source code has parser errors |
457 | */ |
458 | public ParseResult<SimpleName> parseSimpleName(String name) { |
459 | return parse(SIMPLE_NAME, provider(name)); |
460 | } |
461 | |
462 | /** |
463 | * Parses a single parameter (a type and a name) and returns it as a Parameter. |
464 | * |
465 | * @param parameter a parameter like "int[] x" |
466 | * @return the AST for the parameter |
467 | * @throws ParseProblemException if the source code has parser errors |
468 | */ |
469 | public ParseResult<Parameter> parseParameter(String parameter) { |
470 | return parse(PARAMETER, provider(parameter)); |
471 | } |
472 | |
473 | /** |
474 | * Parses a package declaration and returns it as a PackageDeclaration. |
475 | * |
476 | * @param packageDeclaration a declaration like "package com.microsoft.java;" |
477 | * @return the AST for the parameter |
478 | * @throws ParseProblemException if the source code has parser errors |
479 | */ |
480 | public ParseResult<PackageDeclaration> parsePackageDeclaration(String packageDeclaration) { |
481 | return parse(PACKAGE_DECLARATION, provider(packageDeclaration)); |
482 | } |
483 | |
484 | /** |
485 | * Parses a type declaration and returns it as a TypeDeclaration. |
486 | * |
487 | * @param typeDeclaration a declaration like "class X {}" |
488 | * @return the AST for the type declaration |
489 | * @throws ParseProblemException if the source code has parser errors |
490 | */ |
491 | public ParseResult<TypeDeclaration<?>> parseTypeDeclaration(String typeDeclaration) { |
492 | return parse(TYPE_DECLARATION, provider(typeDeclaration)); |
493 | } |
494 | |
495 | /** |
496 | * Parses a module declaration and returns it as a ModuleDeclaration. |
497 | * |
498 | * @param moduleDeclaration a declaration like "module X {}" |
499 | * @return the AST for the module declaration |
500 | * @throws ParseProblemException if the source code has parser errors |
501 | * @see ModuleDeclaration |
502 | */ |
503 | public ParseResult<ModuleDeclaration> parseModuleDeclaration(String moduleDeclaration) { |
504 | return parse(MODULE_DECLARATION, provider(moduleDeclaration)); |
505 | } |
506 | |
507 | /** |
508 | * Parses a module directive and returns it as a ModuleDirective. |
509 | * |
510 | * @param moduleDirective a directive like "opens C;" |
511 | * @return the AST for the module directive |
512 | * @throws ParseProblemException if the source code has parser errors |
513 | * @see ModuleDirective |
514 | */ |
515 | public ParseResult<ModuleDirective> parseModuleDirective(String moduleDirective) { |
516 | return parse(MODULE_DIRECTIVE, provider(moduleDirective)); |
517 | } |
518 | |
519 | |
520 | /** |
521 | * Parses a type parameter and returns it as a TypeParameter |
522 | * |
523 | * @param typeParameter a parameter like "T extends Serializable" |
524 | * @return the AST for the type parameter |
525 | * @throws ParseProblemException if the source code has parser errors |
526 | */ |
527 | public ParseResult<TypeParameter> parseTypeParameter(String typeParameter) { |
528 | return parse(TYPE_PARAMETER, provider(typeParameter)); |
529 | } |
530 | |
531 | /** |
532 | * Parses a method declaration and returns it as a MethodDeclaration. |
533 | * |
534 | * @param methodDeclaration a method declaration like "void foo() {}" |
535 | * @return the AST for the method declaration |
536 | * @throws ParseProblemException if the source code has parser errors |
537 | * @see MethodDeclaration |
538 | */ |
539 | public ParseResult<MethodDeclaration> parseMethodDeclaration(String methodDeclaration) { |
540 | return parse(METHOD_DECLARATION, provider(methodDeclaration)); |
541 | } |
542 | |
543 | } |
544 |
Members