j3.27.0.0 working

This commit is contained in:
Mann Patel
2025-10-11 02:02:27 -06:00
parent 6c591bbf37
commit d80c25c5d7
2973 changed files with 383519 additions and 51603 deletions

View File

@@ -0,0 +1,30 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
/**
* Core information about this library.
*/
public class JavaParserBuild {
public static final String PROJECT_VERSION = "${project.version}";
public static final String PROJECT_NAME = "${project.name}";
public static final String PROJECT_BUILD_FINAL_NAME = "${project.build.finalName}";
}

View File

@@ -0,0 +1,209 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.ast.Node.NODE_BY_BEGIN_POSITION;
import static java.util.stream.Collectors.toList;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.comments.Comment;
import com.github.javaparser.ast.comments.LineComment;
import com.github.javaparser.utils.PositionUtils;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
/**
* Assigns comments to nodes of the AST.
*
* @author Sebastian Kuerten
* @author Júlio Vilmar Gesser
*/
class CommentsInserter {
private final ParserConfiguration configuration;
CommentsInserter(ParserConfiguration configuration) {
this.configuration = configuration;
}
/**
* Comments are attributed to the thing they comment and are removed from
* the comments.
*/
private void insertComments(CompilationUnit cu, TreeSet<Comment> comments) {
if (comments.isEmpty()) return;
/* I should sort all the direct children and the comments, if a comment
is the first thing then it is a comment to the CompilationUnit */
// FIXME if there is no package it could be also a comment to the following class...
// so I could use some heuristics in these cases to distinguish the two
// cases
List<Node> children = cu.getChildNodes();
Comment firstComment = comments.iterator().next();
if (cu.getPackageDeclaration().isPresent()
&& (children.isEmpty()
|| PositionUtils.areInOrder(
firstComment, cu.getPackageDeclaration().get()))) {
cu.setComment(firstComment);
comments.remove(firstComment);
}
}
/**
* This method try to attributes the nodes received to child of the node. It
* returns the node that were not attributed.
*/
void insertComments(Node node, TreeSet<Comment> commentsToAttribute) {
if (commentsToAttribute.isEmpty()) return;
if (node instanceof CompilationUnit) {
insertComments((CompilationUnit) node, commentsToAttribute);
}
/* the comment can...
1) be inside one of the children, then the comment should be associated to this child
2) be outside all children. They could be preceding nothing, a comment or a child.
If they preceed a child they are assigned to it, otherwise they remain "orphans"
*/
List<Node> children = node.getChildNodes().stream()
. // Never attribute comments to modifiers.
filter(n -> !(n instanceof Modifier))
.collect(toList());
boolean attributeToAnnotation = !(configuration.isIgnoreAnnotationsWhenAttributingComments());
for (Node child : children) {
TreeSet<Comment> commentsInsideChild = new TreeSet<>(NODE_BY_BEGIN_POSITION);
commentsInsideChild.addAll(commentsToAttribute.stream()
.filter(comment -> comment.hasRange())
.filter(comment -> PositionUtils.nodeContains(child, comment, !attributeToAnnotation))
.collect(toList()));
commentsToAttribute.removeAll(commentsInsideChild);
insertComments(child, commentsInsideChild);
}
attributeLineCommentsOnSameLine(commentsToAttribute, children);
/* if a comment is on the line right before a node it should belong
to that node*/
if (!commentsToAttribute.isEmpty()) {
if (commentIsOnNextLine(node, commentsToAttribute.first())) {
node.setComment(commentsToAttribute.first());
commentsToAttribute.remove(commentsToAttribute.first());
}
}
/* at this point I create an ordered list of all remaining comments and
children */
Comment previousComment = null;
final List<Comment> attributedComments = new LinkedList<>();
List<Node> childrenAndComments = new LinkedList<>();
// Avoid attributing comments to a meaningless container.
childrenAndComments.addAll(children);
commentsToAttribute.removeAll(attributedComments);
childrenAndComments.addAll(commentsToAttribute);
PositionUtils.sortByBeginPosition(
childrenAndComments, configuration.isIgnoreAnnotationsWhenAttributingComments());
for (Node thing : childrenAndComments) {
if (thing instanceof Comment) {
previousComment = (Comment) thing;
if (!previousComment.isOrphan()) {
previousComment = null;
}
} else {
if (previousComment != null && !thing.getComment().isPresent()) {
if (!configuration.isDoNotAssignCommentsPrecedingEmptyLines()
|| !thereAreLinesBetween(previousComment, thing)) {
thing.setComment(previousComment);
attributedComments.add(previousComment);
previousComment = null;
}
}
}
}
commentsToAttribute.removeAll(attributedComments);
// all the remaining are orphan nodes
for (Comment c : commentsToAttribute) {
if (c.isOrphan()) {
node.addOrphanComment(c);
}
}
}
private void attributeLineCommentsOnSameLine(TreeSet<Comment> commentsToAttribute, List<Node> children) {
/* I can attribute in line comments to elements preceeding them, if
there is something contained in their line */
List<Comment> attributedComments = new LinkedList<>();
commentsToAttribute.stream()
.filter(comment -> comment.hasRange())
.filter(Comment::isLineComment)
.forEach(comment -> children.stream()
.filter(child -> child.hasRange())
.forEach(child -> {
Range commentRange = comment.getRange().get();
Range childRange = child.getRange().get();
if (childRange.end.line == commentRange.begin.line
&& attributeLineCommentToNodeOrChild(child, comment.asLineComment())) {
attributedComments.add(comment);
}
}));
commentsToAttribute.removeAll(attributedComments);
}
private boolean attributeLineCommentToNodeOrChild(Node node, LineComment lineComment) {
if (!node.hasRange() || !lineComment.hasRange()) {
return false;
}
// The node start and end at the same line as the comment,
// let's give to it the comment
if (node.getBegin().get().line == lineComment.getBegin().get().line
&& !node.getComment().isPresent()) {
if (!(node instanceof Comment)) {
node.setComment(lineComment);
}
return true;
}
// try with all the children, sorted by reverse position (so the
// first one is the nearest to the comment
List<Node> children = new LinkedList<>();
children.addAll(node.getChildNodes());
PositionUtils.sortByBeginPosition(children);
Collections.reverse(children);
for (Node child : children) {
if (attributeLineCommentToNodeOrChild(child, lineComment)) {
return true;
}
}
return false;
}
private boolean thereAreLinesBetween(Node a, Node b) {
if (!a.hasRange() || !b.hasRange()) {
return true;
}
if (!PositionUtils.areInOrder(a, b)) {
return thereAreLinesBetween(b, a);
}
int endOfA = a.getEnd().get().line;
return b.getBegin().get().line > endOfA + 1;
}
private boolean commentIsOnNextLine(Node a, Comment c) {
if (!c.hasRange() || !a.hasRange()) return false;
return c.getRange().get().end.line + 1 == a.getRange().get().begin.line;
}
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.observer.Observable;
import java.util.Optional;
import java.util.function.Predicate;
/**
* An object that can have a parent node.
*/
public interface HasParentNode<T> extends Observable {
/**
* Returns true if the parent has a parent
*/
default boolean hasParentNode() {
return getParentNode().isPresent();
}
/**
* Returns the parent node, or {@code Optional.empty} if no parent is set.
*/
Optional<Node> getParentNode();
/**
* Sets the parent node.
*
* @param parentNode the parent node, or {@code null} to set no parent.
* @return {@code this}
*/
T setParentNode(Node parentNode);
/**
* Returns the parent node from the perspective of the children of this node.
* <p>
* That is, this method returns {@code this} for everything except {@code NodeList}. A {@code NodeList} returns its
* parent node instead. This is because a {@code NodeList} sets the parent of all its children to its own parent
* node (see {@link com.github.javaparser.ast.NodeList} for details).
*/
Node getParentNodeForChildren();
/**
* Walks the parents of this node and returns the first node of type {@code type}, or {@code empty()} if none is
* found. The given type may also be an interface type, such as one of the {@code NodeWith...} interface types.
*/
default <N> Optional<N> findAncestor(Class<N>... types) {
return findAncestor(x -> true, types);
}
/**
* Walks the parents of this node and returns the first node of type {@code type} that matches {@code predicate}, or
* {@code empty()} if none is found. The given type may also be an interface type, such as one of the
* {@code NodeWith...} interface types.
* @deprecated
* This method is no longer acceptable to find ancestor.
* <p> Use {@link findAncestor(Predicate, Class)} instead.
*/
@Deprecated
default <N> Optional<N> findAncestor(Class<N> type, Predicate<N> predicate) {
return findAncestor(predicate, type);
}
/**
* Walks the parents of this node and returns the first node that matches one of types {@code types}, or
* {@code empty()} if none is found. The given type may also be an interface type, such as one of the
* {@code NodeWith...} interface types.
* @param <N>
*/
default <N> Optional<N> findAncestor(Predicate<N> predicate, Class<N>... types) {
if (!hasParentNode()) return Optional.empty();
Node parent = getParentNode().get();
for (Class<N> type : types) {
if (type.isAssignableFrom(parent.getClass()) && predicate.test(type.cast(parent))) {
return Optional.of(type.cast(parent));
}
}
return parent.findAncestor(predicate, types);
}
/**
* Determines whether this {@code HasParentNode} node is a descendant of the given node. A node is <i>not</i> a
* descendant of itself.
*
* @param ancestor the node for which to determine whether it has this node as an ancestor.
* @return {@code true} if this node is a descendant of the given node, and {@code false} otherwise.
* @see Node#isAncestorOf(Node)
*/
default boolean isDescendantOf(Node ancestor) {
return findAncestor(n -> n == ancestor, Node.class).isPresent();
}
}

View File

@@ -0,0 +1,523 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.ParseStart.*;
import static com.github.javaparser.Problem.PROBLEM_BY_BEGIN_POSITION;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.Providers.resourceProvider;
import static com.github.javaparser.utils.Utils.assertNotNull;
import static java.util.stream.Collectors.toList;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.modules.ModuleDeclaration;
import com.github.javaparser.ast.modules.ModuleDirective;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.List;
import java.util.function.Supplier;
/**
* Parse Java source code and creates Abstract Syntax Trees.
*
* @author Júlio Vilmar Gesser
* @see StaticJavaParser
*/
public final class JavaParser {
private final ParserConfiguration configuration;
private GeneratedJavaParser astParser = null;
/**
* Instantiate the parser with default configuration. Note that parsing can also be done with the static methods {@link StaticJavaParser}.
* Creating an instance will reduce setup time between parsing files.
*/
public JavaParser() {
this(new ParserConfiguration());
}
/**
* Instantiate the parser. Note that parsing can also be done with the static methods {@link StaticJavaParser}.
* Creating an instance will reduce setup time between parsing files.
*/
public JavaParser(ParserConfiguration configuration) {
this.configuration = configuration;
}
/**
* @return The configuration for this parser.
*/
public ParserConfiguration getParserConfiguration() {
return this.configuration;
}
private GeneratedJavaParser getParserForProvider(Provider provider) {
if (astParser == null) {
astParser = new GeneratedJavaParser(provider);
} else {
astParser.reset(provider);
}
astParser.setTabSize(configuration.getTabSize());
astParser.setStoreTokens(configuration.isStoreTokens());
ParserConfiguration.LanguageLevel languageLevel = configuration.getLanguageLevel();
if (languageLevel != null) {
if (languageLevel.isYieldSupported()) {
astParser.setYieldSupported();
}
}
return astParser;
}
/**
* Parses source code.
* It takes the source code from a Provider.
* The start indicates what can be found in the source code (compilation unit, block, import...)
*
* @param start refer to the constants in ParseStart to see what can be parsed.
* @param provider refer to Providers to see how you can read source. The provider will be closed after parsing.
* @param <N> the subclass of Node that is the result of parsing in the start.
* @return the parse result, a collection of encountered problems, and some extra data.
*/
public <N extends Node> ParseResult<N> parse(ParseStart<N> start, Provider provider) {
assertNotNull(start);
assertNotNull(provider);
List<Processor> processors =
configuration.getProcessors().stream().map(Supplier::get).collect(toList());
for (Processor processor : processors) {
provider = processor.preProcess(provider);
}
final GeneratedJavaParser parser = getParserForProvider(provider);
try {
N resultNode = start.parse(parser);
ParseResult<N> result = new ParseResult<>(resultNode, parser.problems, parser.getCommentsCollection());
for (Processor processor : processors) {
processor.postProcess(result, configuration);
}
result.getProblems().sort(PROBLEM_BY_BEGIN_POSITION);
return result;
} catch (Exception e) {
final String message = e.getMessage() == null ? "Unknown error" : e.getMessage();
parser.problems.add(new Problem(message, null, e));
return new ParseResult<>(null, parser.problems, parser.getCommentsCollection());
} finally {
try {
provider.close();
} catch (IOException e) {
// Since we're done parsing and have our result, we don't care about any errors.
}
}
}
/**
* Parses the Java code contained in the {@link InputStream} and returns a
* {@link CompilationUnit} that represents it.
*
* @param in {@link InputStream} containing Java source code. It will be closed after parsing.
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
*/
public ParseResult<CompilationUnit> parse(final InputStream in, Charset encoding) {
return parse(COMPILATION_UNIT, provider(in, encoding));
}
/**
* Parses the Java code contained in the {@link InputStream} and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param in {@link InputStream} containing Java source code. It will be closed after parsing.
* @return CompilationUnit representing the Java source code
*/
public ParseResult<CompilationUnit> parse(final InputStream in) {
return parse(in, configuration.getCharacterEncoding());
}
/**
* Parses the Java code contained in a {@link File} and returns a
* {@link CompilationUnit} that represents it.
*
* @param file {@link File} containing Java source code. It will be closed after parsing.
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
* @throws FileNotFoundException the file was not found
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public ParseResult<CompilationUnit> parse(final File file, final Charset encoding) throws FileNotFoundException {
ParseResult<CompilationUnit> result = parse(COMPILATION_UNIT, provider(file, encoding));
result.getResult().ifPresent(cu -> cu.setStorage(file.toPath(), encoding));
return result;
}
/**
* Parses the Java code contained in a {@link File} and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param file {@link File} containing Java source code. It will be closed after parsing.
* @return CompilationUnit representing the Java source code
* @throws FileNotFoundException the file was not found
*/
public ParseResult<CompilationUnit> parse(final File file) throws FileNotFoundException {
ParseResult<CompilationUnit> result =
parse(COMPILATION_UNIT, provider(file, configuration.getCharacterEncoding()));
result.getResult().ifPresent(cu -> cu.setStorage(file.toPath(), configuration.getCharacterEncoding()));
return result;
}
/**
* Parses the Java code contained in a file and returns a
* {@link CompilationUnit} that represents it.
*
* @param path path to a file containing Java source code
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
* @throws IOException the path could not be accessed
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public ParseResult<CompilationUnit> parse(final Path path, final Charset encoding) throws IOException {
ParseResult<CompilationUnit> result = parse(COMPILATION_UNIT, provider(path, encoding));
result.getResult().ifPresent(cu -> cu.setStorage(path, encoding));
return result;
}
/**
* Parses the Java code contained in a file and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param path path to a file containing Java source code
* @return CompilationUnit representing the Java source code
* @throws IOException the path could not be accessed
*/
public ParseResult<CompilationUnit> parse(final Path path) throws IOException {
ParseResult<CompilationUnit> result =
parse(COMPILATION_UNIT, provider(path, configuration.getCharacterEncoding()));
result.getResult().ifPresent(cu -> cu.setStorage(path, configuration.getCharacterEncoding()));
return result;
}
/**
* Parses the Java code contained in a resource and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param path path to a resource containing Java source code. As resource is accessed through a class loader, a
* leading "/" is not allowed in pathToResource
* @return CompilationUnit representing the Java source code
* @throws IOException the path could not be accessed
*/
public ParseResult<CompilationUnit> parseResource(final String path) throws IOException {
return parse(COMPILATION_UNIT, resourceProvider(path, configuration.getCharacterEncoding()));
}
/**
* Parses the Java code contained in a resource and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param path path to a resource containing Java source code. As resource is accessed through a class loader, a
* leading "/" is not allowed in pathToResource
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
* @throws IOException the path could not be accessed
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public ParseResult<CompilationUnit> parseResource(final String path, Charset encoding) throws IOException {
return parse(COMPILATION_UNIT, resourceProvider(path, encoding));
}
/**
* Parses the Java code contained in a resource and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param classLoader the classLoader that is asked to load the resource
* @param path path to a resource containing Java source code. As resource is accessed through a class loader, a
* leading "/" is not allowed in pathToResource
* @return CompilationUnit representing the Java source code
* @throws IOException the path could not be accessed
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public ParseResult<CompilationUnit> parseResource(
final ClassLoader classLoader, final String path, Charset encoding) throws IOException {
return parse(COMPILATION_UNIT, resourceProvider(classLoader, path, encoding));
}
/**
* Parses Java code from a Reader and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param reader the reader containing Java source code. It will be closed after parsing.
* @return CompilationUnit representing the Java source code
*/
public ParseResult<CompilationUnit> parse(final Reader reader) {
return parse(COMPILATION_UNIT, provider(reader));
}
/**
* Parses the Java code contained in code and returns a
* {@link CompilationUnit} that represents it.
*
* @param code Java source code
* @return CompilationUnit representing the Java source code
*/
public ParseResult<CompilationUnit> parse(String code) {
return parse(COMPILATION_UNIT, provider(code));
}
/**
* Parses the Java block contained in a {@link String} and returns a
* {@link BlockStmt} that represents it.
*
* @param blockStatement {@link String} containing Java block code
* @return BlockStmt representing the Java block
*/
public ParseResult<BlockStmt> parseBlock(final String blockStatement) {
return parse(BLOCK, provider(blockStatement));
}
/**
* Parses the Java statement contained in a {@link String} and returns a
* {@link Statement} that represents it.
*
* @param statement {@link String} containing Java statement code
* @return Statement representing the Java statement
*/
public ParseResult<Statement> parseStatement(final String statement) {
return parse(STATEMENT, provider(statement));
}
/**
* Parses the Java import contained in a {@link String} and returns a
* {@link ImportDeclaration} that represents it.
*
* @param importDeclaration {@link String} containing Java import code
* @return ImportDeclaration representing the Java import declaration
*/
public ParseResult<ImportDeclaration> parseImport(final String importDeclaration) {
return parse(IMPORT_DECLARATION, provider(importDeclaration));
}
/**
* Parses the Java expression contained in a {@link String} and returns a
* {@link Expression} that represents it.
*
* @param expression {@link String} containing Java expression
* @return Expression representing the Java expression
*/
@SuppressWarnings("unchecked")
public <T extends Expression> ParseResult<T> parseExpression(final String expression) {
return (ParseResult<T>) parse(EXPRESSION, provider(expression));
}
/**
* Parses the Java annotation contained in a {@link String} and returns a
* {@link AnnotationExpr} that represents it.
*
* @param annotation {@link String} containing Java annotation
* @return AnnotationExpr representing the Java annotation
*/
public ParseResult<AnnotationExpr> parseAnnotation(final String annotation) {
return parse(ANNOTATION, provider(annotation));
}
/**
* Parses the Java annotation body declaration(e.g fields or methods) contained in a
* {@link String} and returns a {@link BodyDeclaration} that represents it.
*
* @param body {@link String} containing Java body declaration
* @return BodyDeclaration representing the Java annotation
*/
public ParseResult<BodyDeclaration<?>> parseAnnotationBodyDeclaration(final String body) {
return parse(ANNOTATION_BODY, provider(body));
}
/**
* Parses a Java class or interface body declaration(e.g fields or methods) and returns a
* {@link BodyDeclaration} that represents it.
*
* @param body the body of a class or interface
* @return BodyDeclaration representing the Java interface body
*/
@SuppressWarnings("unchecked")
public <T extends BodyDeclaration<?>> ParseResult<T> parseBodyDeclaration(String body) {
return (ParseResult<T>) parse(CLASS_BODY, provider(body));
}
/**
* Parses a Java class or interface type name and returns a {@link ClassOrInterfaceType} that represents it.
*
* @param type the type name like a.b.c.X or Y
* @return ClassOrInterfaceType representing the type
*/
public ParseResult<ClassOrInterfaceType> parseClassOrInterfaceType(String type) {
return parse(CLASS_OR_INTERFACE_TYPE, provider(type));
}
/**
* Parses a Java type name and returns a {@link Type} that represents it.
*
* @param type the type name like a.b.c.X, Y, or int
* @return ClassOrInterfaceType representing the type
*/
public ParseResult<Type> parseType(String type) {
return parse(TYPE, provider(type));
}
/**
* Parses a variable declaration expression and returns a {@link com.github.javaparser.ast.expr.VariableDeclarationExpr}
* that represents it.
*
* @param declaration a variable declaration like {@code int x=2;}
* @return VariableDeclarationExpr representing the type
*/
public ParseResult<VariableDeclarationExpr> parseVariableDeclarationExpr(String declaration) {
return parse(VARIABLE_DECLARATION_EXPR, provider(declaration));
}
/**
* Parses the this(...) and super(...) statements that may occur at the start of a constructor.
*
* @param statement a statement like super("hello");
* @return the AST for the statement.
*/
public ParseResult<ExplicitConstructorInvocationStmt> parseExplicitConstructorInvocationStmt(String statement) {
return parse(EXPLICIT_CONSTRUCTOR_INVOCATION_STMT, provider(statement));
}
/**
* Parses a qualified name (one that can have "."s in it) and returns it as a Name.
*
* @param qualifiedName a name like "com.laamella.parameter_source"
* @return the AST for the name
*/
public ParseResult<Name> parseName(String qualifiedName) {
return parse(NAME, provider(qualifiedName));
}
/**
* Parses a simple name (one that can NOT have "."s in it) and returns it as a SimpleName.
*
* @param name a name like "parameter_source"
* @return the AST for the name
*/
public ParseResult<SimpleName> parseSimpleName(String name) {
return parse(SIMPLE_NAME, provider(name));
}
/**
* Parses a single parameter (a type and a name) and returns it as a Parameter.
*
* @param parameter a parameter like "int[] x"
* @return the AST for the parameter
*/
public ParseResult<Parameter> parseParameter(String parameter) {
return parse(PARAMETER, provider(parameter));
}
/**
* Parses a package declaration and returns it as a PackageDeclaration.
*
* @param packageDeclaration a declaration like "package com.microsoft.java;"
* @return the AST for the parameter
*/
public ParseResult<PackageDeclaration> parsePackageDeclaration(String packageDeclaration) {
return parse(PACKAGE_DECLARATION, provider(packageDeclaration));
}
/**
* Parses a type declaration and returns it as a TypeDeclaration.
*
* @param typeDeclaration a declaration like "class X {}"
* @return the AST for the type declaration
*/
public ParseResult<TypeDeclaration<?>> parseTypeDeclaration(String typeDeclaration) {
return parse(TYPE_DECLARATION, provider(typeDeclaration));
}
/**
* Parses a module declaration and returns it as a ModuleDeclaration.
*
* @param moduleDeclaration a declaration like "module X {}"
* @return the AST for the module declaration
* @see ModuleDeclaration
*/
public ParseResult<ModuleDeclaration> parseModuleDeclaration(String moduleDeclaration) {
return parse(MODULE_DECLARATION, provider(moduleDeclaration));
}
/**
* Parses a module directive and returns it as a ModuleDirective.
*
* @param moduleDirective a directive like "opens C;"
* @return the AST for the module directive
* @see ModuleDirective
*/
public ParseResult<ModuleDirective> parseModuleDirective(String moduleDirective) {
return parse(MODULE_DIRECTIVE, provider(moduleDirective));
}
/**
* Parses a type parameter and returns it as a TypeParameter
*
* @param typeParameter a parameter like "T extends Serializable"
* @return the AST for the type parameter
*/
public ParseResult<TypeParameter> parseTypeParameter(String typeParameter) {
return parse(TYPE_PARAMETER, provider(typeParameter));
}
/**
* Parses a method declaration and returns it as a MethodDeclaration.
*
* @param methodDeclaration a method declaration like "void foo() {}"
* @return the AST for the method declaration
* @see MethodDeclaration
*/
public ParseResult<MethodDeclaration> parseMethodDeclaration(String methodDeclaration) {
return parse(METHOD_DECLARATION, provider(methodDeclaration));
}
/**
* Parses an array initializer expression and returns it as ArrayInitializerExpr.
*
* @param arrayInitializerExpr an array initializer like "{1,2,3}"
* @return the AST for the array initializer expression
* @see ArrayInitializerExpr
*/
public ParseResult<ArrayInitializerExpr> parseArrayInitializerExpr(String arrayInitializerExpr) {
return parse(ARRAY_INITIALIZER_EXPR, provider(arrayInitializerExpr));
}
}

View File

@@ -0,0 +1,198 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.modules.ModuleDeclaration;
import com.github.javaparser.ast.modules.ModuleDirective;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.javadoc.Javadoc;
import java.io.*;
import java.nio.file.Path;
import java.util.Objects;
public class JavaParserAdapter {
/**
* Wraps the {@link JavaParser}.
*
* @param parser The java parser to be used.
*
* @return The created QuickJavaParser.
*/
public static JavaParserAdapter of(JavaParser parser) {
return new JavaParserAdapter(parser);
}
private final JavaParser parser;
public JavaParserAdapter(JavaParser parser) {
this.parser = Objects.requireNonNull(parser, "A non-null parser should be provided.");
}
public JavaParser getParser() {
return parser;
}
/**
* Helper function to handle the result in a simpler way.
*
* @param result The result to be handled.
*
* @param <T> The return type.
*
* @return The parsed value.
*/
private <T extends Node> T handleResult(ParseResult<T> result) {
if (result.isSuccessful()) {
return result.getResult().orElse(null);
}
throw new ParseProblemException(result.getProblems());
}
public ParserConfiguration getParserConfiguration() {
return parser.getParserConfiguration();
}
public CompilationUnit parse(InputStream in) {
return handleResult(getParser().parse(in));
}
public CompilationUnit parse(File file) throws FileNotFoundException {
return handleResult(getParser().parse(file));
}
public CompilationUnit parse(Path path) throws IOException {
return handleResult(getParser().parse(path));
}
public CompilationUnit parse(Reader reader) {
return handleResult(getParser().parse(reader));
}
public CompilationUnit parse(String code) {
return handleResult(getParser().parse(code));
}
public CompilationUnit parseResource(String path) throws IOException {
return handleResult(getParser().parseResource(path));
}
public BlockStmt parseBlock(String blockStatement) {
return handleResult(getParser().parseBlock(blockStatement));
}
public Statement parseStatement(String statement) {
return handleResult(getParser().parseStatement(statement));
}
public ImportDeclaration parseImport(String importDeclaration) {
return handleResult(getParser().parseImport(importDeclaration));
}
public <T extends Expression> T parseExpression(String expression) {
return handleResult(getParser().parseExpression(expression));
}
public AnnotationExpr parseAnnotation(String annotation) {
return handleResult(getParser().parseAnnotation(annotation));
}
public BodyDeclaration<?> parseAnnotationBodyDeclaration(String body) {
return handleResult(getParser().parseAnnotationBodyDeclaration(body));
}
public BodyDeclaration<?> parseBodyDeclaration(String body) {
return handleResult(getParser().parseBodyDeclaration(body));
}
public ClassOrInterfaceType parseClassOrInterfaceType(String type) {
return handleResult(getParser().parseClassOrInterfaceType(type));
}
public Type parseType(String type) {
return handleResult(getParser().parseType(type));
}
public VariableDeclarationExpr parseVariableDeclarationExpr(String declaration) {
return handleResult(getParser().parseVariableDeclarationExpr(declaration));
}
public Javadoc parseJavadoc(String content) {
return JavadocParser.parse(content);
}
public ExplicitConstructorInvocationStmt parseExplicitConstructorInvocationStmt(String statement) {
return handleResult(getParser().parseExplicitConstructorInvocationStmt(statement));
}
public Name parseName(String qualifiedName) {
return handleResult(getParser().parseName(qualifiedName));
}
public SimpleName parseSimpleName(String name) {
return handleResult(getParser().parseSimpleName(name));
}
public Parameter parseParameter(String parameter) {
return handleResult(getParser().parseParameter(parameter));
}
public PackageDeclaration parsePackageDeclaration(String packageDeclaration) {
return handleResult(getParser().parsePackageDeclaration(packageDeclaration));
}
public TypeDeclaration<?> parseTypeDeclaration(String typeDeclaration) {
return handleResult(getParser().parseTypeDeclaration(typeDeclaration));
}
public ModuleDeclaration parseModuleDeclaration(String moduleDeclaration) {
return handleResult(getParser().parseModuleDeclaration(moduleDeclaration));
}
public ModuleDirective parseModuleDirective(String moduleDirective) {
return handleResult(getParser().parseModuleDirective(moduleDirective));
}
public TypeParameter parseTypeParameter(String typeParameter) {
return handleResult(getParser().parseTypeParameter(typeParameter));
}
public MethodDeclaration parseMethodDeclaration(String methodDeclaration) {
return handleResult(getParser().parseMethodDeclaration(methodDeclaration));
}
public ArrayInitializerExpr parseArrayInitializerExpr(String arrayInitializerExpr) {
return handleResult(getParser().parseArrayInitializerExpr(arrayInitializerExpr));
}
}

View File

@@ -0,0 +1,844 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.utils.CodeGenerationUtils.f;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.utils.LineSeparator;
import java.util.List;
import java.util.Optional;
/**
* A token from a parsed source file.
* (Awkwardly named "Java"Token since JavaCC already generates an internal class Token.)
* It is a node in a double linked list called token list.
*/
public class JavaToken {
public static final JavaToken INVALID = new JavaToken();
private Range range;
private int kind;
private String text;
private JavaToken previousToken = null;
private JavaToken nextToken = null;
private JavaToken() {
this(null, 0, "INVALID", null, null);
}
public JavaToken(int kind, String text) {
this(null, kind, text, null, null);
}
JavaToken(Token token, List<JavaToken> tokens) {
// You could be puzzled by the following lines
//
// The reason why these lines are necessary is the fact that Java is ambiguous. There are cases where the
// sequence of characters ">>>" and ">>" should be recognized as the single tokens ">>>" and ">>". In other
// cases however we want to split those characters in single GT tokens (">").
//
// For example, in expressions ">>" and ">>>" are valid, while when defining types we could have this:
//
// List<List<Set<String>>>>
//
// You can see that the sequence ">>>>" should be interpreted as four consecutive ">" tokens closing a type
// parameter list.
//
// The JavaCC handle this case by first recognizing always the longest token, and then depending on the context
// putting back the unused chars in the stream. However in those cases the token provided is invalid: it has an
// image corresponding to the text originally recognized, without considering that after some characters could
// have been put back into the stream.
//
// So in the case of:
//
// List<List<Set<String>>>>
// ___ -> recognized as ">>>", then ">>" put back in the stream but Token(type=GT, image=">>>") passed to this
// class
// ___ -> recognized as ">>>", then ">>" put back in the stream but Token(type=GT, image=">>>") passed to this
// class
// __ -> recognized as ">>", then ">" put back in the stream but Token(type=GT, image=">>") passed to this
// class
// _ -> Token(type=GT, image=">") good!
//
// So given the image could be wrong but the type is correct, we look at the type of the token and we fix
// the image. Everybody is happy and we can keep this horrible thing as our little secret.
Range range = Range.range(token.beginLine, token.beginColumn, token.endLine, token.endColumn);
String text = token.image;
if (token.kind == GeneratedJavaParserConstants.GT) {
range = Range.range(token.beginLine, token.beginColumn, token.endLine, token.beginColumn);
text = ">";
} else if (token.kind == GeneratedJavaParserConstants.RSIGNEDSHIFT) {
range = Range.range(token.beginLine, token.beginColumn, token.endLine, token.beginColumn + 1);
text = ">>";
}
this.range = range;
this.kind = token.kind;
this.text = text;
if (!tokens.isEmpty()) {
final JavaToken previousToken = tokens.get(tokens.size() - 1);
this.previousToken = previousToken;
previousToken.nextToken = this;
} else {
previousToken = null;
}
}
/**
* Create a token of a certain kind.
*/
public JavaToken(int kind) {
String content = GeneratedJavaParserConstants.tokenImage[kind];
if (content.startsWith("\"")) {
content = content.substring(1, content.length() - 1);
}
if (TokenTypes.isEndOfLineToken(kind)) {
content = LineSeparator.SYSTEM.asRawString();
} else if (TokenTypes.isWhitespace(kind)) {
content = " ";
}
this.kind = kind;
this.text = content;
}
public JavaToken(Range range, int kind, String text, JavaToken previousToken, JavaToken nextToken) {
assertNotNull(text);
this.range = range;
this.kind = kind;
this.text = text;
this.previousToken = previousToken;
this.nextToken = nextToken;
}
public Optional<Range> getRange() {
return Optional.ofNullable(range);
}
/*
* Returns true if the token has a range
*/
public boolean hasRange() {
return getRange().isPresent();
}
public int getKind() {
return kind;
}
void setKind(int kind) {
this.kind = kind;
}
public String getText() {
return text;
}
public Optional<JavaToken> getNextToken() {
return Optional.ofNullable(nextToken);
}
public Optional<JavaToken> getPreviousToken() {
return Optional.ofNullable(previousToken);
}
public void setRange(Range range) {
this.range = range;
}
public void setText(String text) {
this.text = text;
}
public String asString() {
return text;
}
/**
* @return the token range that goes from the beginning to the end of the token list this token is a part of.
*/
public TokenRange toTokenRange() {
return new TokenRange(findFirstToken(), findLastToken());
}
@Override
public String toString() {
String text = getText()
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\r\n", "\\r\\n")
.replace("\t", "\\t");
return f(
"\"%s\" <%s> %s",
text, getKind(), getRange().map(Range::toString).orElse("(?)-(?)"));
}
/**
* Used by the parser while constructing nodes. No tokens should be invalid when the parser is done.
*/
public boolean valid() {
return !invalid();
}
/**
* Used by the parser while constructing nodes. No tokens should be invalid when the parser is done.
*/
public boolean invalid() {
return this == INVALID;
}
public enum Category {
WHITESPACE_NO_EOL,
EOL,
COMMENT,
IDENTIFIER,
KEYWORD,
LITERAL,
SEPARATOR,
OPERATOR;
public boolean isWhitespaceOrComment() {
return isWhitespace() || this == COMMENT;
}
public boolean isWhitespace() {
return this == WHITESPACE_NO_EOL || this == EOL;
}
public boolean isEndOfLine() {
return this == EOL;
}
public boolean isComment() {
return this == COMMENT;
}
public boolean isWhitespaceButNotEndOfLine() {
return this == WHITESPACE_NO_EOL;
}
public boolean isIdentifier() {
return this == IDENTIFIER;
}
public boolean isKeyword() {
return this == KEYWORD;
}
public boolean isLiteral() {
return this == LITERAL;
}
public boolean isSeparator() {
return this == SEPARATOR;
}
public boolean isOperator() {
return this == OPERATOR;
}
}
@Generated("com.github.javaparser.generator.core.other.TokenKindGenerator")
public enum Kind {
EOF(0),
SPACE(1),
WINDOWS_EOL(2),
UNIX_EOL(3),
OLD_MAC_EOL(4),
SINGLE_LINE_COMMENT(5),
ENTER_JAVADOC_COMMENT(6),
ENTER_MULTILINE_COMMENT(7),
JAVADOC_COMMENT(8),
MULTI_LINE_COMMENT(9),
COMMENT_CONTENT(10),
ABSTRACT(11),
ASSERT(12),
BOOLEAN(13),
BREAK(14),
BYTE(15),
CASE(16),
CATCH(17),
CHAR(18),
CLASS(19),
CONST(20),
CONTINUE(21),
_DEFAULT(22),
DO(23),
DOUBLE(24),
ELSE(25),
ENUM(26),
EXTENDS(27),
FALSE(28),
FINAL(29),
FINALLY(30),
FLOAT(31),
FOR(32),
GOTO(33),
IF(34),
IMPLEMENTS(35),
IMPORT(36),
INSTANCEOF(37),
INT(38),
INTERFACE(39),
LONG(40),
NATIVE(41),
NEW(42),
NON_SEALED(43),
NULL(44),
PACKAGE(45),
PERMITS(46),
PRIVATE(47),
PROTECTED(48),
PUBLIC(49),
RECORD(50),
RETURN(51),
SEALED(52),
SHORT(53),
STATIC(54),
STRICTFP(55),
SUPER(56),
SWITCH(57),
SYNCHRONIZED(58),
THIS(59),
THROW(60),
THROWS(61),
TRANSIENT(62),
TRUE(63),
TRY(64),
VOID(65),
VOLATILE(66),
WHILE(67),
YIELD(68),
REQUIRES(69),
TO(70),
WITH(71),
OPEN(72),
OPENS(73),
USES(74),
MODULE(75),
EXPORTS(76),
PROVIDES(77),
TRANSITIVE(78),
WHEN(79),
LONG_LITERAL(80),
INTEGER_LITERAL(81),
DECIMAL_LITERAL(82),
HEX_LITERAL(83),
OCTAL_LITERAL(84),
BINARY_LITERAL(85),
FLOATING_POINT_LITERAL(86),
DECIMAL_FLOATING_POINT_LITERAL(87),
DECIMAL_EXPONENT(88),
HEXADECIMAL_FLOATING_POINT_LITERAL(89),
HEXADECIMAL_EXPONENT(90),
HEX_DIGITS(91),
UNICODE_ESCAPE(92),
CHARACTER_LITERAL(93),
STRING_LITERAL(94),
ENTER_TEXT_BLOCK(95),
TEXT_BLOCK_LITERAL(96),
TEXT_BLOCK_CONTENT(97),
IDENTIFIER(98),
LETTER(99),
PART_LETTER(100),
LPAREN(101),
RPAREN(102),
LBRACE(103),
RBRACE(104),
LBRACKET(105),
RBRACKET(106),
SEMICOLON(107),
COMMA(108),
DOT(109),
ELLIPSIS(110),
AT(111),
DOUBLECOLON(112),
ASSIGN(113),
LT(114),
BANG(115),
TILDE(116),
HOOK(117),
COLON(118),
ARROW(119),
EQ(120),
GE(121),
LE(122),
NE(123),
SC_AND(124),
SC_OR(125),
INCR(126),
DECR(127),
PLUS(128),
MINUS(129),
STAR(130),
SLASH(131),
BIT_AND(132),
BIT_OR(133),
XOR(134),
REM(135),
LSHIFT(136),
PLUSASSIGN(137),
MINUSASSIGN(138),
STARASSIGN(139),
SLASHASSIGN(140),
ANDASSIGN(141),
ORASSIGN(142),
XORASSIGN(143),
REMASSIGN(144),
LSHIFTASSIGN(145),
RSIGNEDSHIFTASSIGN(146),
RUNSIGNEDSHIFTASSIGN(147),
RUNSIGNEDSHIFT(148),
RSIGNEDSHIFT(149),
GT(150),
CTRL_Z(151);
private final int kind;
Kind(int kind) {
this.kind = kind;
}
public static Kind valueOf(int kind) {
switch (kind) {
case 151:
return CTRL_Z;
case 150:
return GT;
case 149:
return RSIGNEDSHIFT;
case 148:
return RUNSIGNEDSHIFT;
case 147:
return RUNSIGNEDSHIFTASSIGN;
case 146:
return RSIGNEDSHIFTASSIGN;
case 145:
return LSHIFTASSIGN;
case 144:
return REMASSIGN;
case 143:
return XORASSIGN;
case 142:
return ORASSIGN;
case 141:
return ANDASSIGN;
case 140:
return SLASHASSIGN;
case 139:
return STARASSIGN;
case 138:
return MINUSASSIGN;
case 137:
return PLUSASSIGN;
case 136:
return LSHIFT;
case 135:
return REM;
case 134:
return XOR;
case 133:
return BIT_OR;
case 132:
return BIT_AND;
case 131:
return SLASH;
case 130:
return STAR;
case 129:
return MINUS;
case 128:
return PLUS;
case 127:
return DECR;
case 126:
return INCR;
case 125:
return SC_OR;
case 124:
return SC_AND;
case 123:
return NE;
case 122:
return LE;
case 121:
return GE;
case 120:
return EQ;
case 119:
return ARROW;
case 118:
return COLON;
case 117:
return HOOK;
case 116:
return TILDE;
case 115:
return BANG;
case 114:
return LT;
case 113:
return ASSIGN;
case 112:
return DOUBLECOLON;
case 111:
return AT;
case 110:
return ELLIPSIS;
case 109:
return DOT;
case 108:
return COMMA;
case 107:
return SEMICOLON;
case 106:
return RBRACKET;
case 105:
return LBRACKET;
case 104:
return RBRACE;
case 103:
return LBRACE;
case 102:
return RPAREN;
case 101:
return LPAREN;
case 100:
return PART_LETTER;
case 99:
return LETTER;
case 98:
return IDENTIFIER;
case 97:
return TEXT_BLOCK_CONTENT;
case 96:
return TEXT_BLOCK_LITERAL;
case 95:
return ENTER_TEXT_BLOCK;
case 94:
return STRING_LITERAL;
case 93:
return CHARACTER_LITERAL;
case 92:
return UNICODE_ESCAPE;
case 91:
return HEX_DIGITS;
case 90:
return HEXADECIMAL_EXPONENT;
case 89:
return HEXADECIMAL_FLOATING_POINT_LITERAL;
case 88:
return DECIMAL_EXPONENT;
case 87:
return DECIMAL_FLOATING_POINT_LITERAL;
case 86:
return FLOATING_POINT_LITERAL;
case 85:
return BINARY_LITERAL;
case 84:
return OCTAL_LITERAL;
case 83:
return HEX_LITERAL;
case 82:
return DECIMAL_LITERAL;
case 81:
return INTEGER_LITERAL;
case 80:
return LONG_LITERAL;
case 79:
return WHEN;
case 78:
return TRANSITIVE;
case 77:
return PROVIDES;
case 76:
return EXPORTS;
case 75:
return MODULE;
case 74:
return USES;
case 73:
return OPENS;
case 72:
return OPEN;
case 71:
return WITH;
case 70:
return TO;
case 69:
return REQUIRES;
case 68:
return YIELD;
case 67:
return WHILE;
case 66:
return VOLATILE;
case 65:
return VOID;
case 64:
return TRY;
case 63:
return TRUE;
case 62:
return TRANSIENT;
case 61:
return THROWS;
case 60:
return THROW;
case 59:
return THIS;
case 58:
return SYNCHRONIZED;
case 57:
return SWITCH;
case 56:
return SUPER;
case 55:
return STRICTFP;
case 54:
return STATIC;
case 53:
return SHORT;
case 52:
return SEALED;
case 51:
return RETURN;
case 50:
return RECORD;
case 49:
return PUBLIC;
case 48:
return PROTECTED;
case 47:
return PRIVATE;
case 46:
return PERMITS;
case 45:
return PACKAGE;
case 44:
return NULL;
case 43:
return NON_SEALED;
case 42:
return NEW;
case 41:
return NATIVE;
case 40:
return LONG;
case 39:
return INTERFACE;
case 38:
return INT;
case 37:
return INSTANCEOF;
case 36:
return IMPORT;
case 35:
return IMPLEMENTS;
case 34:
return IF;
case 33:
return GOTO;
case 32:
return FOR;
case 31:
return FLOAT;
case 30:
return FINALLY;
case 29:
return FINAL;
case 28:
return FALSE;
case 27:
return EXTENDS;
case 26:
return ENUM;
case 25:
return ELSE;
case 24:
return DOUBLE;
case 23:
return DO;
case 22:
return _DEFAULT;
case 21:
return CONTINUE;
case 20:
return CONST;
case 19:
return CLASS;
case 18:
return CHAR;
case 17:
return CATCH;
case 16:
return CASE;
case 15:
return BYTE;
case 14:
return BREAK;
case 13:
return BOOLEAN;
case 12:
return ASSERT;
case 11:
return ABSTRACT;
case 10:
return COMMENT_CONTENT;
case 9:
return MULTI_LINE_COMMENT;
case 8:
return JAVADOC_COMMENT;
case 7:
return ENTER_MULTILINE_COMMENT;
case 6:
return ENTER_JAVADOC_COMMENT;
case 5:
return SINGLE_LINE_COMMENT;
case 4:
return OLD_MAC_EOL;
case 3:
return UNIX_EOL;
case 2:
return WINDOWS_EOL;
case 1:
return SPACE;
case 0:
return EOF;
default:
throw new IllegalArgumentException(f("Token kind %i is unknown.", kind));
}
}
public boolean isPrimitive() {
return this == BYTE
|| this == CHAR
|| this == SHORT
|| this == INT
|| this == LONG
|| this == FLOAT
|| this == DOUBLE;
}
public int getKind() {
return kind;
}
}
public JavaToken.Category getCategory() {
return TokenTypes.getCategory(kind);
}
/**
* Inserts newToken into the token list just before this token.
*/
public void insert(JavaToken newToken) {
assertNotNull(newToken);
getPreviousToken().ifPresent(p -> {
p.nextToken = newToken;
newToken.previousToken = p;
});
previousToken = newToken;
newToken.nextToken = this;
}
/**
* Inserts newToken into the token list just after this token.
*/
public void insertAfter(JavaToken newToken) {
assertNotNull(newToken);
getNextToken().ifPresent(n -> {
n.previousToken = newToken;
newToken.nextToken = n;
});
nextToken = newToken;
newToken.previousToken = this;
}
/**
* Links the tokens around the current token together, making the current token disappear from the list.
*/
public void deleteToken() {
final Optional<JavaToken> nextToken = getNextToken();
final Optional<JavaToken> previousToken = getPreviousToken();
previousToken.ifPresent(p -> p.nextToken = nextToken.orElse(null));
nextToken.ifPresent(n -> n.previousToken = previousToken.orElse(null));
}
/**
* Replaces the current token with newToken.
*/
public void replaceToken(JavaToken newToken) {
assertNotNull(newToken);
getPreviousToken().ifPresent(p -> {
p.nextToken = newToken;
newToken.previousToken = p;
});
getNextToken().ifPresent(n -> {
n.previousToken = newToken;
newToken.nextToken = n;
});
}
/**
* @return the last token in the token list.
*/
public JavaToken findLastToken() {
JavaToken current = this;
while (current.getNextToken().isPresent()) {
current = current.getNextToken().get();
}
return current;
}
/**
* @return the first token in the token list.
*/
public JavaToken findFirstToken() {
JavaToken current = this;
while (current.getPreviousToken().isPresent()) {
current = current.getPreviousToken().get();
}
return current;
}
@Override
public int hashCode() {
int result = kind;
result = 31 * result + text.hashCode();
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JavaToken javaToken = (JavaToken) o;
if (kind != javaToken.kind) return false;
if (!text.equals(javaToken.text)) return false;
return true;
}
}

View File

@@ -0,0 +1,154 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.utils.Utils.*;
import com.github.javaparser.ast.comments.JavadocComment;
import com.github.javaparser.javadoc.Javadoc;
import com.github.javaparser.javadoc.JavadocBlockTag;
import com.github.javaparser.javadoc.description.JavadocDescription;
import com.github.javaparser.utils.LineSeparator;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* The class responsible for parsing the content of JavadocComments and producing JavadocDocuments.
* <a href="https://docs.oracle.com/javase/1.5.0/docs/tooldocs/windows/javadoc.html">The Javadoc specification.</a>
*/
class JavadocParser {
private static String BLOCK_TAG_PREFIX = "@";
private static Pattern BLOCK_PATTERN = Pattern.compile("^\\s*" + BLOCK_TAG_PREFIX, Pattern.MULTILINE);
public static Javadoc parse(JavadocComment comment) {
return parse(comment.getContent());
}
public static Javadoc parse(String commentContent) {
List<String> cleanLines = cleanLines(normalizeEolInTextBlock(commentContent, LineSeparator.SYSTEM));
int indexOfFirstBlockTag = cleanLines.stream()
.filter(JavadocParser::isABlockLine)
.map(cleanLines::indexOf)
.findFirst()
.orElse(-1);
List<String> blockLines;
String descriptionText;
if (indexOfFirstBlockTag == -1) {
descriptionText = trimRight(String.join(LineSeparator.SYSTEM.asRawString(), cleanLines));
blockLines = Collections.emptyList();
} else {
descriptionText = trimRight(
String.join(LineSeparator.SYSTEM.asRawString(), cleanLines.subList(0, indexOfFirstBlockTag)));
// Combine cleaned lines, but only starting with the first block tag till the end
// In this combined string it is easier to handle multiple lines which actually belong together
String tagBlock = cleanLines.subList(indexOfFirstBlockTag, cleanLines.size()).stream()
.collect(Collectors.joining(LineSeparator.SYSTEM.asRawString()));
// Split up the entire tag back again, considering now that some lines belong to the same block tag.
// The pattern splits the block at each new line starting with the '@' symbol, thus the symbol
// then needs to be added again so that the block parsers handles everything correctly.
blockLines = BLOCK_PATTERN
.splitAsStream(tagBlock)
.filter(s1 -> !s1.isEmpty())
.map(s -> BLOCK_TAG_PREFIX + s)
.collect(Collectors.toList());
}
Javadoc document = new Javadoc(JavadocDescription.parseText(descriptionText));
blockLines.forEach(l -> document.addBlockTag(parseBlockTag(l)));
return document;
}
private static JavadocBlockTag parseBlockTag(String line) {
line = line.trim().substring(1);
String tagName = nextWord(line);
String rest = line.substring(tagName.length()).trim();
return new JavadocBlockTag(tagName, rest);
}
private static boolean isABlockLine(String line) {
return line.trim().startsWith(BLOCK_TAG_PREFIX);
}
private static String trimRight(String string) {
while (!string.isEmpty() && Character.isWhitespace(string.charAt(string.length() - 1))) {
string = string.substring(0, string.length() - 1);
}
return string;
}
private static List<String> cleanLines(String content) {
String[] lines = content.split(LineSeparator.SYSTEM.asRawString());
if (lines.length == 0) {
return Collections.emptyList();
}
List<String> cleanedLines = Arrays.stream(lines)
.map(l -> {
int asteriskIndex = startsWithAsterisk(l);
if (asteriskIndex == -1) {
return l;
}
if (l.length() > (asteriskIndex + 1)) {
char c = l.charAt(asteriskIndex + 1);
if (c == ' ' || c == '\t') {
return l.substring(asteriskIndex + 2);
}
}
return l.substring(asteriskIndex + 1);
})
.collect(Collectors.toList());
// lines containing only whitespace are normalized to empty lines
cleanedLines =
cleanedLines.stream().map(l -> l.trim().isEmpty() ? "" : l).collect(Collectors.toList());
// if the first starts with a space, remove it
if (!cleanedLines.get(0).isEmpty()
&& (cleanedLines.get(0).charAt(0) == ' ' || cleanedLines.get(0).charAt(0) == '\t')) {
cleanedLines.set(0, cleanedLines.get(0).substring(1));
}
// drop empty lines at the beginning and at the end
while (cleanedLines.size() > 0 && cleanedLines.get(0).trim().isEmpty()) {
cleanedLines = cleanedLines.subList(1, cleanedLines.size());
}
while (cleanedLines.size() > 0
&& cleanedLines.get(cleanedLines.size() - 1).trim().isEmpty()) {
cleanedLines = cleanedLines.subList(0, cleanedLines.size() - 1);
}
return cleanedLines;
}
// Visible for testing
static int startsWithAsterisk(String line) {
if (line.startsWith("*")) {
return 0;
}
if ((line.startsWith(" ") || line.startsWith("\t")) && line.length() > 1) {
int res = startsWithAsterisk(line.substring(1));
if (res == -1) {
return -1;
}
return 1 + res;
}
return -1;
}
}

View File

@@ -0,0 +1,150 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import com.github.javaparser.utils.LineSeparator;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* {@link Provider} un-escaping unicode escape sequences in the input sequence.
*/
public class LineEndingProcessingProvider implements Provider {
private static final int EOF = -1;
private static final int DEFAULT_BUFFER_SIZE = 2048;
/**
* The "other" provider which we are wrapping around / reading from.
*/
private final Provider _input;
/**
* The buffer that we're storing data within.
*/
private final char[] _data;
/**
* The number of characters in {@link #_data}.
*/
private int _len = 0;
/**
* The position in {@link #_data} where to read the next source character from.
*/
private int _pos = 0;
private final Map<LineSeparator, Integer> eolCounts = new HashMap<>();
public LineEndingProcessingProvider(Provider input) {
this(DEFAULT_BUFFER_SIZE, input);
}
public LineEndingProcessingProvider(int bufferSize, Provider input) {
_input = input;
_data = new char[bufferSize];
}
@Override
public void close() throws IOException {
_input.close();
}
private int fillBuffer() throws IOException {
_pos = 0;
int direct = _input.read(_data, 0, _data.length);
if (direct != 0) {
_len = direct;
}
return direct;
}
public LineSeparator getDetectedLineEnding() {
return LineSeparator.getLineEnding(
eolCounts.getOrDefault(LineSeparator.CR, 0),
eolCounts.getOrDefault(LineSeparator.LF, 0),
eolCounts.getOrDefault(LineSeparator.CRLF, 0));
}
private boolean isBufferEmpty() {
return _pos >= _len;
}
/**
* Retrieves the next un-escaped character from the buffered {@link #_input}.
*
* @return The next character or {@code -1} if no more input is available.
*/
private int nextBufferedChar() throws IOException {
while (isBufferEmpty()) {
int direct = fillBuffer();
if (direct < 0) {
return EOF;
}
}
return _data[_pos++];
}
@Override
public int read(char[] buffer, final int offset, int len) throws IOException {
int pos = offset;
int stop = offset + len;
LineSeparator previousLineSeparator = null;
while (pos < stop) {
int ch = nextBufferedChar();
if (ch < 0) {
if (pos == offset) {
// Nothing read yet, this is the end of the stream.
return EOF;
}
break;
}
String str = String.valueOf((char) ch);
Optional<LineSeparator> lookup = LineSeparator.lookup(str);
if (lookup.isPresent()) {
LineSeparator lineSeparator = lookup.get();
// Track the number of times this character is found..
eolCounts.putIfAbsent(lineSeparator, 0);
eolCounts.put(lineSeparator, eolCounts.get(lineSeparator) + 1);
// Handle line separators of length two (specifically CRLF)
// TODO: Make this more generic than just CRLF (e.g. track the previous char rather than the previous
// line separator
if (lineSeparator == LineSeparator.LF) {
if (previousLineSeparator == LineSeparator.CR) {
eolCounts.putIfAbsent(LineSeparator.CRLF, 0);
eolCounts.put(LineSeparator.CRLF, eolCounts.get(LineSeparator.CRLF) + 1);
}
}
// If "this" (current) char <strong>is</strong> a line separator, set the next loop's "previous" to this
previousLineSeparator = lineSeparator;
} else {
// If "this" (current) char <strong>is not</strong> a line separator, set the next loop's "previous" to
// null
previousLineSeparator = null;
}
buffer[pos++] = (char) ch;
}
return pos - offset;
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.utils.Utils.assertNotNull;
import static java.util.Collections.singletonList;
import com.github.javaparser.utils.LineSeparator;
import java.util.List;
/**
* Thrown when parsing problems occur during parsing with the static methods on JavaParser.
*/
public class ParseProblemException extends RuntimeException {
/**
* The problems that were encountered during parsing
*/
private final List<Problem> problems;
public ParseProblemException(List<Problem> problems) {
super(createMessage(assertNotNull(problems)));
this.problems = problems;
}
public ParseProblemException(Throwable throwable) {
this(singletonList(new Problem(throwable.getMessage(), null, throwable)));
}
private static String createMessage(List<Problem> problems) {
StringBuilder message = new StringBuilder();
for (Problem problem : problems) {
message.append(problem.toString()).append(LineSeparator.SYSTEM);
}
return message.toString();
}
public List<Problem> getProblems() {
return problems;
}
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import com.github.javaparser.ast.comments.CommentsCollection;
import com.github.javaparser.utils.LineSeparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
/**
* The results given when parsing with an instance of JavaParser.
*/
public class ParseResult<T> {
private final T result;
private final List<Problem> problems;
private final CommentsCollection commentsCollection;
/**
* General constructor.
*
* @param result the AST, or empty if it wasn't created.
* @param problems a list of encountered parsing problems.
*/
public ParseResult(T result, List<Problem> problems, CommentsCollection commentsCollection) {
this.commentsCollection = commentsCollection;
this.result = result;
this.problems = problems;
}
/**
* @return if parsing was successful, meaning no errors of any kind were encountered.
*/
public boolean isSuccessful() {
return problems.isEmpty() && result != null;
}
/**
* Calls the consumer with the result if parsing was succesful.
*/
public void ifSuccessful(Consumer<T> consumer) {
if (isSuccessful()) {
consumer.accept(result);
}
}
/**
* @return the list of encountered parsing problems. Empty when no problems were encountered.
*/
public List<Problem> getProblems() {
return problems;
}
/**
* @return the {@code i}'th encountered parsing problem. May throw <code>IndexOutOfBoundsException</code>.
*/
public Problem getProblem(int i) {
return getProblems().get(i);
}
/**
* @return the complete collection of comments encountered while parsing.
*/
public Optional<CommentsCollection> getCommentsCollection() {
return Optional.ofNullable(commentsCollection);
}
/**
* @return the AST of the parsed source code, or empty if parsing failed completely.
*/
public Optional<T> getResult() {
return Optional.ofNullable(result);
}
@Override
public String toString() {
if (isSuccessful()) {
return "Parsing successful";
}
StringBuilder message = new StringBuilder("Parsing failed:").append(LineSeparator.SYSTEM);
for (Problem problem : problems) {
message.append(problem.toString()).append(LineSeparator.SYSTEM);
}
return message.toString();
}
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.modules.ModuleDeclaration;
import com.github.javaparser.ast.modules.ModuleDirective;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
/**
* The start production for JavaParser.
* Tells JavaParser what piece of Java code it can expect.
* For example,
* COMPILATION_UNIT indicates a complete Java file,
* and CLASS_BODY would indicate the part of a class that is within { and }.
*
* @see JavaParser#parse(ParseStart, Provider)
*/
@FunctionalInterface
public interface ParseStart<R> {
ParseStart<CompilationUnit> COMPILATION_UNIT = GeneratedJavaParser::CompilationUnit;
ParseStart<BlockStmt> BLOCK = GeneratedJavaParser::BlockParseStart;
ParseStart<Statement> STATEMENT = GeneratedJavaParser::BlockStatementParseStart;
ParseStart<ImportDeclaration> IMPORT_DECLARATION = GeneratedJavaParser::ImportDeclarationParseStart;
ParseStart<Expression> EXPRESSION = GeneratedJavaParser::ExpressionParseStart;
ParseStart<AnnotationExpr> ANNOTATION = GeneratedJavaParser::AnnotationParseStart;
ParseStart<BodyDeclaration<?>> ANNOTATION_BODY = GeneratedJavaParser::AnnotationBodyDeclarationParseStart;
ParseStart<BodyDeclaration<?>> CLASS_BODY = GeneratedJavaParser::ClassOrInterfaceBodyDeclarationParseStart;
ParseStart<ClassOrInterfaceType> CLASS_OR_INTERFACE_TYPE = GeneratedJavaParser::ClassOrInterfaceTypeParseStart;
ParseStart<Type> TYPE = GeneratedJavaParser::ResultTypeParseStart;
ParseStart<TypeParameter> TYPE_PARAMETER = GeneratedJavaParser::TypeParameterParseStart;
ParseStart<VariableDeclarationExpr> VARIABLE_DECLARATION_EXPR =
GeneratedJavaParser::VariableDeclarationExpressionParseStart;
ParseStart<ExplicitConstructorInvocationStmt> EXPLICIT_CONSTRUCTOR_INVOCATION_STMT =
GeneratedJavaParser::ExplicitConstructorInvocationParseStart;
ParseStart<Name> NAME = GeneratedJavaParser::NameParseStart;
ParseStart<SimpleName> SIMPLE_NAME = GeneratedJavaParser::SimpleNameParseStart;
ParseStart<Parameter> PARAMETER = GeneratedJavaParser::ParameterParseStart;
ParseStart<PackageDeclaration> PACKAGE_DECLARATION = GeneratedJavaParser::PackageDeclarationParseStart;
ParseStart<TypeDeclaration<?>> TYPE_DECLARATION = GeneratedJavaParser::TypeDeclarationParseStart;
ParseStart<ModuleDeclaration> MODULE_DECLARATION = GeneratedJavaParser::ModuleDeclarationParseStart;
ParseStart<ModuleDirective> MODULE_DIRECTIVE = GeneratedJavaParser::ModuleDirectiveParseStart;
ParseStart<MethodDeclaration> METHOD_DECLARATION = GeneratedJavaParser::MethodDeclarationParseStart;
ParseStart<ArrayInitializerExpr> ARRAY_INITIALIZER_EXPR = GeneratedJavaParser::ArrayInitializer;
R parse(GeneratedJavaParser parser) throws ParseException;
}

View File

@@ -0,0 +1,511 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.ParserConfiguration.LanguageLevel.POPULAR;
import com.github.javaparser.UnicodeEscapeProcessingProvider.PositionMapping;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.validator.ProblemReporter;
import com.github.javaparser.ast.validator.Validator;
import com.github.javaparser.ast.validator.language_level_validations.*;
import com.github.javaparser.ast.validator.postprocessors.*;
import com.github.javaparser.printer.lexicalpreservation.DefaultLexicalPreservingPrinter;
import com.github.javaparser.printer.lexicalpreservation.LexicalPreservingPrinter;
import com.github.javaparser.resolution.SymbolResolver;
import com.github.javaparser.utils.LineSeparator;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
/**
* The configuration that is used by the parser.
* Note that this can be changed even when reusing the same JavaParser instance.
* It will pick up the changes.
*/
public class ParserConfiguration {
public enum LanguageLevel {
/**
* Java 1.0
*/
JAVA_1_0(new Java1_0Validator(), null),
/**
* Java 1.1
*/
JAVA_1_1(new Java1_1Validator(), null),
/**
* Java 1.2
*/
JAVA_1_2(new Java1_2Validator(), null),
/**
* Java 1.3
*/
JAVA_1_3(new Java1_3Validator(), null),
/**
* Java 1.4
*/
JAVA_1_4(new Java1_4Validator(), null),
/**
* Java 5
*/
JAVA_5(new Java5Validator(), null),
/**
* Java 6
*/
JAVA_6(new Java6Validator(), null),
/**
* Java 7
*/
JAVA_7(new Java7Validator(), null),
/**
* Java 8
*/
JAVA_8(new Java8Validator(), null),
/**
* Java 9
*/
JAVA_9(new Java9Validator(), null),
/**
* Java 10
*/
JAVA_10(new Java10Validator(), new Java10PostProcessor()),
/**
* Java 10 -- including incubator/preview/second preview features.
* Note that preview features, unless otherwise specified, follow the grammar and behaviour of the latest released JEP for that feature.
*/
JAVA_10_PREVIEW(new Java10PreviewValidator(), new Java10PostProcessor()),
/**
* Java 11
*/
JAVA_11(new Java11Validator(), new Java11PostProcessor()),
/**
* Java 11 -- including incubator/preview/second preview features.
* Note that preview features, unless otherwise specified, follow the grammar and behaviour of the latest released JEP for that feature.
*/
JAVA_11_PREVIEW(new Java11PreviewValidator(), new Java11PostProcessor()),
/**
* Java 12
*/
JAVA_12(new Java12Validator(), new Java12PostProcessor()),
/**
* Java 12 -- including incubator/preview/second preview features.
* Note that preview features, unless otherwise specified, follow the grammar and behaviour of the latest released JEP for that feature.
* <ul>
* <li>Switch expressions are permitted, with a single label only and no yield.</li>
* </ul>
*/
JAVA_12_PREVIEW(new Java12PreviewValidator(), new Java12PostProcessor()),
/**
* Java 13
*/
JAVA_13(new Java13Validator(), new Java13PostProcessor()),
/**
* Java 13 -- including incubator/preview/second preview features.
* Note that preview features, unless otherwise specified, follow the grammar and behaviour of the latest released JEP for that feature.
* <ul>
* <li>Switch expressions are permitted, with a single label only.</li>
* </ul>
*/
JAVA_13_PREVIEW(new Java13PreviewValidator(), new Java13PostProcessor()),
/**
* Java 14
*/
JAVA_14(new Java14Validator(), new Java14PostProcessor()),
/**
* Java 14 -- including incubator/preview/second preview features.
* Note that preview features, unless otherwise specified, follow the grammar and behaviour of the latest released JEP for that feature.
*/
JAVA_14_PREVIEW(new Java14PreviewValidator(), new Java14PostProcessor()),
/**
* Java 15
*/
JAVA_15(new Java15Validator(), new Java15PostProcessor()),
/**
* Java 15 -- including incubator/preview/second preview features.
* Note that preview features, unless otherwise specified, follow the grammar and behaviour of the latest released JEP for that feature.
*/
JAVA_15_PREVIEW(new Java15PreviewValidator(), new Java15PostProcessor()),
/**
* Java 16
*/
JAVA_16(new Java16Validator(), new Java16PostProcessor()),
/**
* Java 16 -- including incubator/preview/second preview features.
* Note that preview features, unless otherwise specified, follow the grammar and behaviour of the latest released JEP for that feature.
*/
JAVA_16_PREVIEW(new Java16PreviewValidator(), new Java16PostProcessor()),
/**
* Java 17
*/
JAVA_17(new Java17Validator(), new Java17PostProcessor()),
/**
* Java 17 -- including incubator/preview/second preview features.
* Note that preview features, unless otherwise specified, follow the grammar and behaviour of the latest released JEP for that feature.
*/
JAVA_17_PREVIEW(new Java17PreviewValidator(), new Java17PostProcessor()),
/**
* Java 18
*/
JAVA_18(new Java18Validator(), new Java18PostProcessor()),
/**
* Java 19
*/
JAVA_19(new Java19Validator(), new Java19PostProcessor()),
/**
* Java 20
*/
JAVA_20(new Java20Validator(), new Java20PostProcessor()),
/**
* Java 21
*/
JAVA_21(new Java21Validator(), new Java21PostProcessor());
/**
* Does no post processing or validation. Only for people wanting the fastest parsing.
*/
public static LanguageLevel RAW = null;
/**
* The most used Java version.
*/
public static LanguageLevel POPULAR = JAVA_11;
/**
* The latest Java version that is available.
*/
public static LanguageLevel CURRENT = JAVA_18;
/**
* The newest Java features supported.
*/
public static LanguageLevel BLEEDING_EDGE = JAVA_21;
final Validator validator;
final PostProcessors postProcessor;
private static final LanguageLevel[] yieldSupport = new LanguageLevel[] {
JAVA_13,
JAVA_13_PREVIEW,
JAVA_14,
JAVA_14_PREVIEW,
JAVA_15,
JAVA_15_PREVIEW,
JAVA_16,
JAVA_16_PREVIEW,
JAVA_17,
JAVA_17_PREVIEW,
JAVA_18,
JAVA_19,
JAVA_20,
JAVA_21
};
LanguageLevel(Validator validator, PostProcessors postProcessor) {
this.validator = validator;
this.postProcessor = postProcessor;
}
public boolean isYieldSupported() {
return Arrays.stream(yieldSupport).anyMatch(level -> level == this);
}
}
// TODO: Add a configurable option e.g. setDesiredLineEnding(...) to replace/swap out existing line endings
private boolean detectOriginalLineSeparator = true;
private boolean storeTokens = true;
private boolean attributeComments = true;
private boolean doNotAssignCommentsPrecedingEmptyLines = true;
private boolean ignoreAnnotationsWhenAttributingComments = false;
private boolean lexicalPreservationEnabled = false;
private boolean preprocessUnicodeEscapes = false;
private SymbolResolver symbolResolver = null;
private int tabSize = 1;
private LanguageLevel languageLevel = POPULAR;
private Charset characterEncoding = Providers.UTF8;
private final List<Supplier<Processor>> processors = new ArrayList<>();
private class UnicodeEscapeProcessor extends Processor {
private UnicodeEscapeProcessingProvider _unicodeDecoder;
@Override
public Provider preProcess(Provider innerProvider) {
if (isPreprocessUnicodeEscapes()) {
_unicodeDecoder = new UnicodeEscapeProcessingProvider(innerProvider);
return _unicodeDecoder;
}
return innerProvider;
}
@Override
public void postProcess(ParseResult<? extends Node> result, ParserConfiguration configuration) {
if (isPreprocessUnicodeEscapes()) {
result.getResult().ifPresent(root -> {
PositionMapping mapping = _unicodeDecoder.getPositionMapping();
if (!mapping.isEmpty()) {
root.walk(node -> node.getRange().ifPresent(range -> node.setRange(mapping.transform(range))));
}
});
}
}
}
private class LineEndingProcessor extends Processor {
private LineEndingProcessingProvider _lineEndingProcessingProvider;
@Override
public Provider preProcess(Provider innerProvider) {
if (isDetectOriginalLineSeparator()) {
_lineEndingProcessingProvider = new LineEndingProcessingProvider(innerProvider);
return _lineEndingProcessingProvider;
}
return innerProvider;
}
@Override
public void postProcess(ParseResult<? extends Node> result, ParserConfiguration configuration) {
if (isDetectOriginalLineSeparator()) {
result.getResult().ifPresent(rootNode -> {
LineSeparator detectedLineSeparator = _lineEndingProcessingProvider.getDetectedLineEnding();
// Set the line ending on the root node
rootNode.setData(Node.LINE_SEPARATOR_KEY, detectedLineSeparator);
// // Set the line ending on all children of the root node -- FIXME: Should ignore """textblocks"""
// rootNode.findAll(Node.class)
// .forEach(node -> node.setData(Node.LINE_SEPARATOR_KEY, detectedLineSeparator));
});
}
}
}
public ParserConfiguration() {
processors.add(() -> ParserConfiguration.this.new UnicodeEscapeProcessor());
processors.add(() -> ParserConfiguration.this.new LineEndingProcessor());
processors.add(() -> new Processor() {
@Override
public void postProcess(ParseResult<? extends Node> result, ParserConfiguration configuration) {
if (configuration.isAttributeComments()) {
result.ifSuccessful(resultNode -> result.getCommentsCollection()
.ifPresent(comments -> new CommentsInserter(configuration)
.insertComments(resultNode, comments.copy().getComments())));
}
}
});
processors.add(() -> new Processor() {
@Override
public void postProcess(ParseResult<? extends Node> result, ParserConfiguration configuration) {
LanguageLevel languageLevel = getLanguageLevel();
if (languageLevel != null) {
if (languageLevel.postProcessor != null) {
languageLevel.postProcessor.postProcess(result, configuration);
}
if (languageLevel.validator != null) {
languageLevel.validator.accept(
result.getResult().get(), new ProblemReporter(newProblem -> result.getProblems()
.add(newProblem)));
}
}
}
});
processors.add(() -> new Processor() {
@Override
public void postProcess(ParseResult<? extends Node> result, ParserConfiguration configuration) {
configuration
.getSymbolResolver()
.ifPresent(symbolResolver -> result.ifSuccessful(resultNode -> {
if (resultNode instanceof CompilationUnit) {
resultNode.setData(Node.SYMBOL_RESOLVER_KEY, symbolResolver);
}
}));
}
});
processors.add(() -> new Processor() {
@Override
public void postProcess(ParseResult<? extends Node> result, ParserConfiguration configuration) {
if (configuration.isLexicalPreservationEnabled()) {
result.ifSuccessful(resultNode -> {
LexicalPreservingPrinter.setup(resultNode);
resultNode.setData(Node.PRINTER_KEY, new DefaultLexicalPreservingPrinter());
});
}
}
});
}
public boolean isAttributeComments() {
return attributeComments;
}
/**
* Whether to run CommentsInserter, which will put the comments that were found in the source code into the comment
* and javadoc fields of the nodes it thinks they refer to.
*/
public ParserConfiguration setAttributeComments(boolean attributeComments) {
this.attributeComments = attributeComments;
return this;
}
public boolean isDoNotAssignCommentsPrecedingEmptyLines() {
return doNotAssignCommentsPrecedingEmptyLines;
}
public ParserConfiguration setDoNotAssignCommentsPrecedingEmptyLines(
boolean doNotAssignCommentsPrecedingEmptyLines) {
this.doNotAssignCommentsPrecedingEmptyLines = doNotAssignCommentsPrecedingEmptyLines;
return this;
}
public boolean isIgnoreAnnotationsWhenAttributingComments() {
return ignoreAnnotationsWhenAttributingComments;
}
public ParserConfiguration setIgnoreAnnotationsWhenAttributingComments(
boolean ignoreAnnotationsWhenAttributingComments) {
this.ignoreAnnotationsWhenAttributingComments = ignoreAnnotationsWhenAttributingComments;
return this;
}
public ParserConfiguration setStoreTokens(boolean storeTokens) {
this.storeTokens = storeTokens;
if (!storeTokens) {
setAttributeComments(false);
}
return this;
}
public boolean isStoreTokens() {
return storeTokens;
}
public int getTabSize() {
return tabSize;
}
/**
* When a TAB character is encountered during parsing, the column position will be increased by this value.
* By default it is 1.
*/
public ParserConfiguration setTabSize(int tabSize) {
this.tabSize = tabSize;
return this;
}
/**
* Disabled by default.
* When this is enabled, LexicalPreservingPrinter.print can be used to reproduce
* the original formatting of the file.
*/
public ParserConfiguration setLexicalPreservationEnabled(boolean lexicalPreservationEnabled) {
this.lexicalPreservationEnabled = lexicalPreservationEnabled;
return this;
}
public boolean isLexicalPreservationEnabled() {
return lexicalPreservationEnabled;
}
/**
* Retrieve the SymbolResolver to be used while parsing, if any.
*/
public Optional<SymbolResolver> getSymbolResolver() {
return Optional.ofNullable(symbolResolver);
}
/**
* Set the SymbolResolver to be injected while parsing.
*/
public ParserConfiguration setSymbolResolver(SymbolResolver symbolResolver) {
this.symbolResolver = symbolResolver;
return this;
}
public List<Supplier<Processor>> getProcessors() {
return processors;
}
public ParserConfiguration setLanguageLevel(LanguageLevel languageLevel) {
this.languageLevel = languageLevel;
return this;
}
public LanguageLevel getLanguageLevel() {
return languageLevel;
}
/**
* When set to true, unicode escape handling is done by preprocessing the whole input,
* meaning that all unicode escapes are turned into unicode characters before parsing.
* That means the AST will never contain literal unicode escapes. However,
* positions in the AST will point to the original input, which is exactly the same as without this option.
* Without this option enabled, the unicode escapes will not be processed and are transfered intact to the AST.
*/
public ParserConfiguration setPreprocessUnicodeEscapes(boolean preprocessUnicodeEscapes) {
this.preprocessUnicodeEscapes = preprocessUnicodeEscapes;
return this;
}
public boolean isPreprocessUnicodeEscapes() {
return preprocessUnicodeEscapes;
}
public ParserConfiguration setDetectOriginalLineSeparator(boolean detectOriginalLineSeparator) {
this.detectOriginalLineSeparator = detectOriginalLineSeparator;
return this;
}
public boolean isDetectOriginalLineSeparator() {
return detectOriginalLineSeparator;
}
public Charset getCharacterEncoding() {
return characterEncoding;
}
/**
* The character encoding used for reading input from files and streams. By default UTF8 is used.
*/
public ParserConfiguration setCharacterEncoding(Charset characterEncoding) {
this.characterEncoding = characterEncoding;
return this;
}
}

View File

@@ -0,0 +1,207 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.utils.Utils.assertNotNull;
import java.util.Objects;
/**
* A position in a source file. Lines and columns start counting at 1.
*/
public class Position implements Comparable<Position> {
public final int line;
public final int column;
/**
* The first line -- note that it is 1-indexed (i.e. the first line is line 1, as opposed to 0)
*/
public static final int FIRST_LINE = 1;
/**
* The first column -- note that it is 1-indexed (i.e. the first column is column 1, as opposed to 0)
*/
public static final int FIRST_COLUMN = 1;
/**
* The first position in the file.
*/
public static final Position HOME = new Position(FIRST_LINE, FIRST_COLUMN);
/**
* Line numbers must be positive, thus
*/
public static final int ABSOLUTE_BEGIN_LINE = -1;
public static final int ABSOLUTE_END_LINE = -2;
/**
* TODO: Do we refer to the characters as columns,
* ...or the spaces between (thus also before/after) characters as columns?
*/
public Position(int line, int column) {
if (line < Position.ABSOLUTE_END_LINE) {
throw new IllegalArgumentException("Can't position at line " + line);
}
if (column < -1) {
// TODO: This allows/permits column 0, which seemingly contradicts first column being 1
// ... (see also nextLine() which indicates 1 being the first column of the next line)
// ... (see also valid() which requires a column > 0)
// TODO: Maybe we need an "ABSOLUTE_BEGIN_LINE" and "ABSOLUTE_END_LINE"?
throw new IllegalArgumentException("Can't position at column " + column);
}
this.line = line;
this.column = column;
}
/**
* Convenient factory method.
*
* @deprecated Use the constructor (e.g. {@code new Position(line, column)})
*/
@Deprecated
public static Position pos(int line, int column) {
return new Position(line, column);
}
/**
* @return Jump to the given column number, while retaining the current line number.
*/
public Position withColumn(int column) {
return new Position(this.line, column);
}
/**
* @return Jump to the given line number, while retaining the current column number.
*/
public Position withLine(int line) {
return new Position(line, this.column);
}
/**
* @return a position that is "characters" characters more to the right than this position.
*/
public Position right(int characters) {
return new Position(line, this.column + characters);
}
/**
* @return a position that is on the start of the next line from this position.
*/
public Position nextLine() {
return new Position(line + 1, FIRST_COLUMN);
}
/**
* Check if the position is usable,
* also checks for special positions (ABSOLUTE_BEGIN_LINE and ABSOLUTE_END_LINE).
* Does not know what it is pointing at, so it can't check if the position is after the end of the source.
* @return true if the position is usable or a special position.
*/
public boolean valid() {
return ABSOLUTE_END_LINE == line || ABSOLUTE_BEGIN_LINE == line || line >= FIRST_LINE && column >= FIRST_COLUMN;
}
/**
* @see #valid()
* @return The inverse of {@link #valid()}
*/
public boolean invalid() {
return !valid();
}
/**
* @return If this position is valid, this.
* Otherwise, if the alternativePosition is valid, return that.
* Otherwise, just return this.
*/
public Position orIfInvalid(Position alternativePosition) {
assertNotNull(alternativePosition);
if (this.valid()) {
return this;
}
return alternativePosition.valid() ? alternativePosition : this;
}
/**
* @param otherPosition the other position to compare to
* @return true if this position is after the given position
*/
public boolean isAfter(Position otherPosition) {
assertNotNull(otherPosition);
if (line == otherPosition.line) {
return column > otherPosition.column;
}
return line > otherPosition.line || otherPosition.line == Position.ABSOLUTE_BEGIN_LINE;
}
public boolean isAfterOrEqual(Position otherPosition) {
return isAfter(otherPosition) || equals(otherPosition);
}
/**
* @param otherPosition the other position to compare to
* @return true if this position is before the given position
*/
public boolean isBefore(Position otherPosition) {
assertNotNull(otherPosition);
if (line == otherPosition.line) {
return column < otherPosition.column;
}
return line < otherPosition.line || otherPosition.line == Position.ABSOLUTE_END_LINE;
}
public boolean isBeforeOrEqual(Position otherPosition) {
return isBefore(otherPosition) || equals(otherPosition);
}
@Override
public int compareTo(Position otherPosition) {
assertNotNull(otherPosition);
if (isBefore(otherPosition)) {
return -1;
}
if (isAfter(otherPosition)) {
return 1;
}
return 0;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Position otherPosition = (Position) o;
return Objects.equals(line, otherPosition.line) && Objects.equals(column, otherPosition.column);
}
@Override
public int hashCode() {
return Objects.hash(line, column);
}
@Override
public String toString() {
return "(line " + line + ",col " + column + ")";
}
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.utils.LineSeparator;
import java.util.Comparator;
import java.util.Optional;
/**
* A problem that was encountered during parsing.
*/
public class Problem {
private final String message;
private final TokenRange location;
private final Throwable cause;
public Problem(String message, TokenRange location, Throwable cause) {
assertNotNull(message);
this.message = message;
this.location = location;
this.cause = cause;
}
@Override
public String toString() {
final StringBuilder str = new StringBuilder(getVerboseMessage());
if (cause != null) {
str.append(LineSeparator.SYSTEM).append("Problem stacktrace : ").append(LineSeparator.SYSTEM);
for (int i = 0; i < cause.getStackTrace().length; i++) {
StackTraceElement ste = cause.getStackTrace()[i];
str.append(" ").append(ste.toString());
if (i + 1 != cause.getStackTrace().length) str.append(LineSeparator.SYSTEM);
}
}
return str.toString();
}
/**
* @return the message that was passed into the constructor.
*/
public String getMessage() {
return message;
}
/**
* @return the message plus location information.
*/
public String getVerboseMessage() {
return getLocation()
.map(l -> l.getBegin().getRange().map(r -> r.begin.toString()).orElse("(line ?,col ?)") + " " + message)
.orElse(message);
}
/**
* @return the location that was passed into the constructor.
*/
public Optional<TokenRange> getLocation() {
return Optional.ofNullable(location);
}
/**
* @return the cause that was passed into the constructor.
*/
public Optional<Throwable> getCause() {
return Optional.ofNullable(cause);
}
/**
* Sorts problems on position.
*/
public static Comparator<Problem> PROBLEM_BY_BEGIN_POSITION = (a, b) -> {
final Optional<Position> aBegin =
a.getLocation().flatMap(l -> l.getBegin().getRange().map(r -> r.begin));
final Optional<Position> bBegin =
b.getLocation().flatMap(l -> l.getBegin().getRange().map(r -> r.begin));
if (aBegin.isPresent() && bBegin.isPresent()) {
return aBegin.get().compareTo(bBegin.get());
}
if (a.getLocation().isPresent() || b.getLocation().isPresent()) {
if (a.getLocation().isPresent()) {
return 1;
}
return -1;
}
return 0;
};
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import com.github.javaparser.ast.Node;
public class Processor {
/**
* Makes the parser do a post-parsing step before the result is returned to the user.
*/
public void postProcess(ParseResult<? extends Node> result, ParserConfiguration configuration) {}
/**
* Adds a pre-parsing step, which has access to the sourcecode through the innerProvider.
*/
public Provider preProcess(Provider innerProvider) {
return innerProvider;
}
}

View File

@@ -0,0 +1,109 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.utils.Utils.assertNotNull;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Factory for providers of source code for JavaParser. Providers that have no parameter for encoding but need it will
* use UTF-8.
*/
public final class Providers {
public static final Charset UTF8 = Charset.forName("utf-8");
private Providers() {}
public static Provider provider(Reader reader) {
return new StreamProvider(assertNotNull(reader));
}
public static Provider provider(InputStream input, Charset encoding) {
assertNotNull(input);
assertNotNull(encoding);
try {
return new StreamProvider(input, encoding.name());
} catch (IOException e) {
// The only one that is thrown is UnsupportedCharacterEncodingException,
// and that's a fundamental problem, so runtime exception.
throw new RuntimeException(e);
}
}
public static Provider provider(InputStream input) {
return provider(input, UTF8);
}
public static Provider provider(File file, Charset encoding) throws FileNotFoundException {
return provider(new FileInputStream(assertNotNull(file)), assertNotNull(encoding));
}
public static Provider provider(File file) throws FileNotFoundException {
return provider(assertNotNull(file), UTF8);
}
public static Provider provider(Path path, Charset encoding) throws IOException {
return provider(Files.newInputStream(assertNotNull(path)), assertNotNull(encoding));
}
public static Provider provider(Path path) throws IOException {
return provider(assertNotNull(path), UTF8);
}
public static Provider provider(String source) {
return new StringProvider(assertNotNull(source));
}
/**
* Provide a Provider from the resource found in class loader with the provided encoding.<br> As resource is
* accessed through a class loader, a leading "/" is not allowed in pathToResource
*/
public static Provider resourceProvider(ClassLoader classLoader, String pathToResource, Charset encoding)
throws IOException {
InputStream resourceAsStream = classLoader.getResourceAsStream(pathToResource);
if (resourceAsStream == null) {
throw new IOException("Cannot find " + pathToResource);
}
return provider(resourceAsStream, encoding);
}
/**
* Provide a Provider from the resource found in the current class loader with the provided encoding.<br> As
* resource is accessed through a class loader, a leading "/" is not allowed in pathToResource
*/
public static Provider resourceProvider(String pathToResource, Charset encoding) throws IOException {
ClassLoader classLoader = Provider.class.getClassLoader();
return resourceProvider(classLoader, pathToResource, encoding);
}
/**
* Provide a Provider from the resource found in the current class loader with UTF-8 encoding.<br> As resource is
* accessed through a class loader, a leading "/" is not allowed in pathToResource
*/
public static Provider resourceProvider(String pathToResource) throws IOException {
return resourceProvider(pathToResource, UTF8);
}
}

View File

@@ -0,0 +1,254 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
/**
* A range of characters in a source file, from "begin" to "end", including the characters at "begin" and "end".
*/
public class Range {
public final Position begin;
public final Position end;
/**
* A range of characters in a source file, from "begin" to "end".
* This range is inclusive of the characters at the "begin" and "end" positions.
* <p>
* Note that if the given parameters are reversed (i.e. the end is earlier than begin, then the values are swapped.
*
* @param begin The starting position of the range.
* @param end The end position of the range.
*/
public Range(Position begin, Position end) {
if (begin == null) {
throw new IllegalArgumentException("begin can't be null");
}
if (end == null) {
throw new IllegalArgumentException("end can't be null");
}
// Force `begin` to be the position that is earliest within the document:
if (begin.isBefore(end)) {
this.begin = begin;
this.end = end;
} else {
this.begin = end;
this.end = begin;
}
}
/**
* Create a new `Range` object using the given begin and end position.
*
* @param begin The starting position of the range.
* @param end The end position of the range.
* @return A new `Range` object with the given start/end position.
*/
public static Range range(Position begin, Position end) {
return new Range(begin, end);
}
/**
* Create a new `Range` object using the given begin and end line/column values.
* Valid values for each parameter are per the constructor of{@link Position}.
*
* @param beginLine The start line of the range.
* @param beginColumn The start line column of the range.
* @param endLine The end line of the range.
* @param endColumn The end column of the range.
* @return A new `Range` object with the given start/end position.
*/
public static Range range(int beginLine, int beginColumn, int endLine, int endColumn) {
return new Range(new Position(beginLine, beginColumn), new Position(endLine, endColumn));
}
/**
* @param beginColumn The value used to replace the current begin column number.
* Valid values are per the constructor of{@link Position}.
* @return A copy of this `Range` object, but with the begin column number replaced with the given column number.
*/
public Range withBeginColumn(int beginColumn) {
return range(begin.withColumn(beginColumn), end);
}
/**
* @param beginLine The value used to replace the current begin line number.
* Valid values are per the constructor of{@link Position}.
* @return A copy of this `Range` object, but with the begin line number replaced with the given line number.
*/
public Range withBeginLine(int beginLine) {
return range(begin.withLine(beginLine), end);
}
/**
* @param endColumn The value used to replace the current end column number.
* Valid values are per the constructor of{@link Position}.
* @return A copy of this `Range` object, but with the end column number replaced with the given line column.
*/
public Range withEndColumn(int endColumn) {
return range(begin, end.withColumn(endColumn));
}
/**
* @param endLine The value used to replace the current end line number.
* Valid values are per the constructor of{@link Position}.
* @return A copy of this `Range` object, but with the end line number replaced with the given line number.
*/
public Range withEndLine(int endLine) {
return range(begin, end.withLine(endLine));
}
/**
* @param begin The value used to replace the current begin position.
* @return A copy of this `Range` object, but with the begin position replaced with the given position.
*/
public Range withBegin(Position begin) {
return range(begin, this.end);
}
/**
* @param end The value used to replace the current end position.
* @return A copy of this `Range` object, but with the end position replaced with the given position.
*/
public Range withEnd(Position end) {
return range(this.begin, end);
}
/**
* Does this loosely contain the other range?
* <p>
* As {@link #strictlyContains(Range)}, but also allow ranges which have an equal start and/or end position.
* In these cases, the `other` range is not strictly "inside" of this range.
*/
public boolean contains(Range other) {
boolean beginResult = (begin.isBeforeOrEqual(other.begin));
if (!beginResult) return false;
return end.isAfterOrEqual(other.end);
}
/**
* Does this loosely contain the other range?
* <p>
* As {@link #strictlyContains(Position)}, but a position that is on the "edge" of this range will also pass.
* <p>
* For example, if the given position is equal to the start or end position of this range.
* In these cases, the `other` range is not strictly "inside" of this range.
*/
public boolean contains(Position position) {
return strictlyContains(position) || begin.equals(position) || end.equals(position);
}
/**
* Does this strictly contain the other range?
* <p>
* It means that this has to be larger than other and it has to start before other and end after other.
*/
public boolean strictlyContains(Range other) {
boolean beginResult = (begin.isBefore(other.begin));
boolean endResult = (end.isAfter(other.end));
return beginResult && endResult;
}
/**
* Does this strictly contain position.
* <p>
* It means that the position is after the begin of this range and before the end of this range.
*/
public boolean strictlyContains(Position position) {
return position.isAfter(begin) && position.isBefore(end);
}
/**
* Does the other 'Range' overlap with this 'Range'?
* <p>
* If two ranges overlap, this range or the other range contains the begin or the end of the other range.
* <p>
* Note that if the ends are "touching" (i.e. a begin position == end position), this counts as an overlap
* because the positions refer to characters, as opposed to boundary between characters.
* <p>
* For example, there is an overlap at "C" in the following ranges, with "C" existing within both ranges:
* <pre>
* Range 1: ABC
* Range 2: CDE</pre>
*/
public boolean overlapsWith(Range other) {
return (contains(other.begin) || contains(other.end)) || (other.contains(begin) || other.contains(end));
}
/**
* @param position The position to compare against.
* @return True if the end of this range is before (but not equal to) the given position to compare against.
*/
public boolean isBefore(Position position) {
return end.isBefore(position);
}
/**
* @param other The range to compare against.
* @return True if the end of this range is before (but not equal to) the given position to compare against.
*/
public boolean isBefore(Range other) {
return end.isBefore(other.begin);
}
/**
* @param position The position to compare against.
* @return True if the start of this range is after (but not equal to) the given position to compare against.
*/
public boolean isAfter(Position position) {
return begin.isAfter(position);
}
/**
* @param other The range to compare against.
* @return True if the start of this range is after (but not equal to) the given position to compare against.
*/
public boolean isAfter(Range other) {
return begin.isAfter(other.end);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Range range = (Range) o;
return begin.equals(range.begin) && end.equals(range.end);
}
@Override
public int hashCode() {
return 31 * begin.hashCode() + end.hashCode();
}
@Override
public String toString() {
return begin + "-" + end;
}
/**
* @return The number of lines that this range represents.
* <p>
* If the start line and end line are the same, this range is limited to just one line.
*/
public int getLineCount() {
return end.line - begin.line + 1;
}
}

View File

@@ -0,0 +1,555 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.modules.ModuleDeclaration;
import com.github.javaparser.ast.modules.ModuleDirective;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.javadoc.Javadoc;
import com.github.javaparser.quality.NotNull;
import com.github.javaparser.quality.Preconditions;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Path;
/**
* A simpler, static API than {@link JavaParser}.
*/
public final class StaticJavaParser {
// use ThreadLocal to resolve possible concurrency issues.
private static final ThreadLocal<ParserConfiguration> localConfiguration =
ThreadLocal.withInitial(ParserConfiguration::new);
/**
* Get the configuration for the parse... methods. Deprecated method.
*
* @deprecated use {@link #getParserConfiguration()} instead
*/
@Deprecated
public static ParserConfiguration getConfiguration() {
return getParserConfiguration();
}
/**
* Get the configuration for the parse... methods.
*/
public static ParserConfiguration getParserConfiguration() {
return localConfiguration.get();
}
/**
* Set the configuration for the static parse... methods.
* This is a STATIC field, so modifying it will directly change how all static parse... methods work!
*/
public static void setConfiguration(@NotNull ParserConfiguration configuration) {
Preconditions.checkNotNull(configuration, "Parameter configuration can't be null.");
localConfiguration.set(configuration);
}
/**
* Parses the Java code contained in the {@link InputStream} and returns a
* {@link CompilationUnit} that represents it.
*
* @param in {@link InputStream} containing Java source code. It will be closed after parsing.
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public static CompilationUnit parse(@NotNull final InputStream in, @NotNull Charset encoding) {
Preconditions.checkNotNull(in, "Parameter in can't be null.");
Preconditions.checkNotNull(encoding, "Parameter encoding can't be null.");
return handleResult(newParser().parse(in, encoding));
}
/**
* Parses the Java code contained in the {@link InputStream} and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param in {@link InputStream} containing Java source code. It will be closed after parsing.
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
*/
public static CompilationUnit parse(@NotNull final InputStream in) {
Preconditions.checkNotNull(in, "Parameter in can't be null.");
return newParserAdapted().parse(in);
}
/**
* Parses the Java code contained in a {@link File} and returns a
* {@link CompilationUnit} that represents it.
*
* @param file {@link File} containing Java source code. It will be closed after parsing.
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws FileNotFoundException the file was not found
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public static CompilationUnit parse(@NotNull final File file, @NotNull final Charset encoding)
throws FileNotFoundException {
Preconditions.checkNotNull(file, "Parameter file can't be null.");
Preconditions.checkNotNull(encoding, "Parameter encoding can't be null.");
return handleResult(newParser().parse(file, encoding));
}
/**
* Parses the Java code contained in a {@link File} and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param file {@link File} containing Java source code. It will be closed after parsing.
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws FileNotFoundException the file was not found
*/
public static CompilationUnit parse(@NotNull final File file) throws FileNotFoundException {
Preconditions.checkNotNull(file, "Parameter file can't be null.");
return newParserAdapted().parse(file);
}
/**
* Parses the Java code contained in a file and returns a
* {@link CompilationUnit} that represents it.
*
* @param path path to a file containing Java source code
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
* @throws IOException the path could not be accessed
* @throws ParseProblemException if the source code has parser errors
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public static CompilationUnit parse(@NotNull final Path path, @NotNull final Charset encoding) throws IOException {
Preconditions.checkNotNull(path, "Parameter path can't be null.");
Preconditions.checkNotNull(encoding, "Parameter encoding can't be null.");
return handleResult(newParser().parse(path, encoding));
}
/**
* Parses the Java code contained in a file and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param path path to a file containing Java source code
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws IOException the path could not be accessed
*/
public static CompilationUnit parse(@NotNull final Path path) throws IOException {
Preconditions.checkNotNull(path, "Parameter path can't be null.");
return newParserAdapted().parse(path);
}
/**
* Parses the Java code contained in a resource and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param path path to a resource containing Java source code. As resource is accessed through a class loader, a
* leading "/" is not allowed in pathToResource
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws IOException the path could not be accessed
*/
public static CompilationUnit parseResource(@NotNull final String path) throws IOException {
Preconditions.checkNotNull(path, "Parameter path can't be null.");
return newParserAdapted().parseResource(path);
}
/**
* Parses the Java code contained in a resource and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param path path to a resource containing Java source code. As resource is accessed through a class loader, a
* leading "/" is not allowed in pathToResource
* @param encoding encoding of the source code
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws IOException the path could not be accessed
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public static CompilationUnit parseResource(@NotNull final String path, @NotNull Charset encoding)
throws IOException {
Preconditions.checkNotNull(path, "Parameter path can't be null.");
Preconditions.checkNotNull(encoding, "Parameter encoding can't be null.");
return handleResult(newParser().parseResource(path, encoding));
}
/**
* Parses the Java code contained in a resource and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param classLoader the classLoader that is asked to load the resource
* @param path path to a resource containing Java source code. As resource is accessed through a class loader, a
* leading "/" is not allowed in pathToResource
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
* @throws IOException the path could not be accessed
* @deprecated set the encoding in the {@link ParserConfiguration}
*/
@Deprecated
public static CompilationUnit parseResource(
@NotNull final ClassLoader classLoader, @NotNull final String path, @NotNull Charset encoding)
throws IOException {
Preconditions.checkNotNull(classLoader, "Parameter classLoader can't be null.");
Preconditions.checkNotNull(path, "Parameter path can't be null.");
Preconditions.checkNotNull(encoding, "Parameter encoding can't be null.");
return handleResult(newParser().parseResource(classLoader, path, encoding));
}
/**
* Parses Java code from a Reader and returns a
* {@link CompilationUnit} that represents it.<br>
*
* @param reader the reader containing Java source code. It will be closed after parsing.
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
*/
public static CompilationUnit parse(@NotNull final Reader reader) {
Preconditions.checkNotNull(reader, "Parameter reader can't be null.");
return newParserAdapted().parse(reader);
}
/**
* Parses the Java code contained in code and returns a
* {@link CompilationUnit} that represents it.
*
* @param code Java source code
* @return CompilationUnit representing the Java source code
* @throws ParseProblemException if the source code has parser errors
*/
public static CompilationUnit parse(@NotNull String code) {
Preconditions.checkNotNull(code, "Parameter code can't be null.");
return newParserAdapted().parse(code);
}
/**
* Parses the Java block contained in a {@link String} and returns a
* {@link BlockStmt} that represents it.
*
* @param blockStatement {@link String} containing Java block code
* @return BlockStmt representing the Java block
* @throws ParseProblemException if the source code has parser errors
*/
public static BlockStmt parseBlock(@NotNull final String blockStatement) {
Preconditions.checkNotNull(blockStatement, "Parameter blockStatement can't be null.");
return newParserAdapted().parseBlock(blockStatement);
}
/**
* Parses the Java statement contained in a {@link String} and returns a
* {@link Statement} that represents it.
*
* @param statement {@link String} containing Java statement code
* @return Statement representing the Java statement
* @throws ParseProblemException if the source code has parser errors
*/
public static Statement parseStatement(@NotNull final String statement) {
Preconditions.checkNotNull(statement, "Parameter statement can't be null.");
return newParserAdapted().parseStatement(statement);
}
/**
* Parses the Java import contained in a {@link String} and returns a
* {@link ImportDeclaration} that represents it.
*
* @param importDeclaration {@link String} containing Java import code
* @return ImportDeclaration representing the Java import declaration
* @throws ParseProblemException if the source code has parser errors
*/
public static ImportDeclaration parseImport(@NotNull final String importDeclaration) {
Preconditions.checkNotNull(importDeclaration, "Parameter importDeclaration can't be null.");
return newParserAdapted().parseImport(importDeclaration);
}
/**
* Parses the Java expression contained in a {@link String} and returns a
* {@link Expression} that represents it.
*
* @param expression {@link String} containing Java expression
* @return Expression representing the Java expression
* @throws ParseProblemException if the source code has parser errors
*/
public static <T extends Expression> T parseExpression(@NotNull final String expression) {
Preconditions.checkNotNull(expression, "Parameter expression can't be null.");
return newParserAdapted().parseExpression(expression);
}
/**
* Parses the Java annotation contained in a {@link String} and returns a
* {@link AnnotationExpr} that represents it.
*
* @param annotation {@link String} containing Java annotation
* @return AnnotationExpr representing the Java annotation
* @throws ParseProblemException if the source code has parser errors
*/
public static AnnotationExpr parseAnnotation(@NotNull final String annotation) {
Preconditions.checkNotNull(annotation, "Parameter annotation can't be null.");
return newParserAdapted().parseAnnotation(annotation);
}
/**
* Parses the Java annotation body declaration(e.g fields or methods) contained in a
* {@link String} and returns a {@link BodyDeclaration} that represents it.
*
* @param body {@link String} containing Java body declaration
* @return BodyDeclaration representing the Java annotation
* @throws ParseProblemException if the source code has parser errors
*/
public static BodyDeclaration<?> parseAnnotationBodyDeclaration(@NotNull final String body) {
Preconditions.checkNotNull(body, "Parameter body can't be null.");
return newParserAdapted().parseAnnotationBodyDeclaration(body);
}
/**
* Parses a Java class or interface body declaration(e.g fields or methods) and returns a
* {@link BodyDeclaration} that represents it.
*
* @param body the body of a class or interface
* @return BodyDeclaration representing the Java interface body
* @throws ParseProblemException if the source code has parser errors
*/
public static BodyDeclaration<?> parseBodyDeclaration(@NotNull String body) {
Preconditions.checkNotNull(body, "Parameter body can't be null.");
return newParserAdapted().parseBodyDeclaration(body);
}
/**
* Parses a Java class or interface type name and returns a {@link ClassOrInterfaceType} that represents it.
*
* @param type the type name like a.b.c.X or Y
* @return ClassOrInterfaceType representing the type
* @throws ParseProblemException if the source code has parser errors
*/
public static ClassOrInterfaceType parseClassOrInterfaceType(@NotNull String type) {
Preconditions.checkNotNull(type, "Parameter type can't be null.");
return newParserAdapted().parseClassOrInterfaceType(type);
}
/**
* Parses a Java type name and returns a {@link Type} that represents it.
*
* @param type the type name like a.b.c.X, Y, or int
* @return ClassOrInterfaceType representing the type
* @throws ParseProblemException if the source code has parser errors
*/
public static Type parseType(@NotNull String type) {
Preconditions.checkNotNull(type, "Parameter type can't be null.");
return newParserAdapted().parseType(type);
}
/**
* Parses a variable declaration expression and returns a {@link VariableDeclarationExpr}
* that represents it.
*
* @param declaration a variable declaration like {@code int x=2;}
* @return VariableDeclarationExpr representing the type
* @throws ParseProblemException if the source code has parser errors
*/
public static VariableDeclarationExpr parseVariableDeclarationExpr(@NotNull String declaration) {
Preconditions.checkNotNull(declaration, "Parameter declaration can't be null.");
return newParserAdapted().parseVariableDeclarationExpr(declaration);
}
/**
* Parses the content of a JavadocComment and returns a {@link Javadoc} that
* represents it.
*
* @param content a variable declaration like {@code content of my javadoc\n * second line\n * third line}
* @return Javadoc representing the content of the comment
* @throws ParseProblemException if the source code has parser errors
*/
public static Javadoc parseJavadoc(@NotNull String content) {
Preconditions.checkNotNull(content, "Parameter content can't be null.");
return JavadocParser.parse(content);
}
/**
* Parses the this(...) and super(...) statements that may occur at the start of a constructor.
*
* @param statement a statement like super("hello");
* @return the AST for the statement.
* @throws ParseProblemException if the source code has parser errors
*/
public static ExplicitConstructorInvocationStmt parseExplicitConstructorInvocationStmt(@NotNull String statement) {
Preconditions.checkNotNull(statement, "Parameter statement can't be null.");
return newParserAdapted().parseExplicitConstructorInvocationStmt(statement);
}
/**
* Parses a qualified name (one that can have "."s in it) and returns it as a Name.
*
* @param qualifiedName a name like "com.laamella.parameter_source"
* @return the AST for the name
* @throws ParseProblemException if the source code has parser errors
*/
public static Name parseName(@NotNull String qualifiedName) {
Preconditions.checkNotNull(qualifiedName, "Parameter qualifiedName can't be null.");
return newParserAdapted().parseName(qualifiedName);
}
/**
* Parses a simple name (one that can NOT have "."s in it) and returns it as a SimpleName.
*
* @param name a name like "parameter_source"
* @return the AST for the name
* @throws ParseProblemException if the source code has parser errors
*/
public static SimpleName parseSimpleName(@NotNull String name) {
Preconditions.checkNotNull(name, "Parameter name can't be null.");
return newParserAdapted().parseSimpleName(name);
}
/**
* Parses a single parameter (a type and a name) and returns it as a Parameter.
*
* @param parameter a parameter like "int[] x"
* @return the AST for the parameter
* @throws ParseProblemException if the source code has parser errors
*/
public static Parameter parseParameter(@NotNull String parameter) {
Preconditions.checkNotNull(parameter, "Parameter parameter can't be null.");
return newParserAdapted().parseParameter(parameter);
}
/**
* Parses a package declaration and returns it as a PackageDeclaration.
*
* @param packageDeclaration a declaration like "package com.microsoft.java;"
* @return the AST for the parameter
* @throws ParseProblemException if the source code has parser errors
*/
public static PackageDeclaration parsePackageDeclaration(@NotNull String packageDeclaration) {
Preconditions.checkNotNull(packageDeclaration, "Parameter packageDeclaration can't be null.");
return newParserAdapted().parsePackageDeclaration(packageDeclaration);
}
/**
* Parses a type declaration and returns it as a TypeDeclaration.
*
* @param typeDeclaration a declaration like "class X {}"
* @return the AST for the type declaration
* @throws ParseProblemException if the source code has parser errors
*/
public static TypeDeclaration<?> parseTypeDeclaration(@NotNull String typeDeclaration) {
Preconditions.checkNotNull(typeDeclaration, "Parameter typeDeclaration can't be null.");
return newParserAdapted().parseTypeDeclaration(typeDeclaration);
}
/**
* Parses a module declaration and returns it as a ModuleDeclaration.
*
* @param moduleDeclaration a declaration like "module X {}"
* @return the AST for the module declaration
* @throws ParseProblemException if the source code has parser errors
* @see ModuleDeclaration
*/
public static ModuleDeclaration parseModuleDeclaration(@NotNull String moduleDeclaration) {
Preconditions.checkNotNull(moduleDeclaration, "Parameter moduleDeclaration can't be null.");
return newParserAdapted().parseModuleDeclaration(moduleDeclaration);
}
/**
* Parses a module directive and returns it as a ModuleDirective.
*
* @param moduleDirective a directive like "opens C;"
* @return the AST for the module directive
* @throws ParseProblemException if the source code has parser errors
* @see ModuleDirective
*/
public static ModuleDirective parseModuleDirective(@NotNull String moduleDirective) {
Preconditions.checkNotNull(moduleDirective, "Parameter moduleDirective can't be null.");
return newParserAdapted().parseModuleDirective(moduleDirective);
}
/**
* Parses a type parameter and returns it as a TypeParameter
*
* @param typeParameter a parameter like "T extends Serializable"
* @return the AST for the type parameter
* @throws ParseProblemException if the source code has parser errors
*/
public static TypeParameter parseTypeParameter(@NotNull String typeParameter) {
Preconditions.checkNotNull(typeParameter, "Parameter typeParameter can't be null.");
return newParserAdapted().parseTypeParameter(typeParameter);
}
/**
* Parses a method declaration and returns it as a MethodDeclaration.
*
* @param methodDeclaration a method declaration like "void foo() {}"
* @return the AST for the method declaration
* @throws ParseProblemException if the source code has parser errors
* @see MethodDeclaration
*/
public static MethodDeclaration parseMethodDeclaration(@NotNull String methodDeclaration) {
Preconditions.checkNotNull(methodDeclaration, "Parameter methodDeclaration can't be null.");
return newParserAdapted().parseMethodDeclaration(methodDeclaration);
}
/**
* Parses an array initializer expression and returns it as ArrayInitializerExpr.
*
* @param arrayInitializerExpr an array initializer like "{1,2,3}"
* @return the AST for the array initializer expression
* @throws ParseProblemException if the source code has parser errors
* @see ArrayInitializerExpr
*/
public static ArrayInitializerExpr parseArrayInitializerExpr(@NotNull String arrayInitializerExpr) {
Preconditions.checkNotNull(arrayInitializerExpr, "Parameter arrayInitializerExpr can't be null.");
return newParserAdapted().parseArrayInitializerExpr(arrayInitializerExpr);
}
// Private methods
private static JavaParser newParser() {
return new JavaParser(getParserConfiguration());
}
private static JavaParserAdapter newParserAdapted() {
return new JavaParserAdapter(newParser());
}
@Deprecated
private static <T extends Node> T handleResult(ParseResult<T> result) {
if (result.isSuccessful()) {
return result.getResult().get();
}
throw new ParseProblemException(result.getProblems());
}
private StaticJavaParser() {}
}

View File

@@ -0,0 +1,107 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.utils.Utils.assertNotNull;
import java.util.Iterator;
import java.util.Optional;
/**
* The range of tokens covered by this node.
*/
public class TokenRange implements Iterable<JavaToken> {
public static final TokenRange INVALID = new TokenRange(JavaToken.INVALID, JavaToken.INVALID);
private final JavaToken begin;
private final JavaToken end;
public TokenRange(JavaToken begin, JavaToken end) {
this.begin = assertNotNull(begin);
this.end = assertNotNull(end);
}
public JavaToken getBegin() {
return begin;
}
public JavaToken getEnd() {
return end;
}
public Optional<Range> toRange() {
if (begin.hasRange() && end.hasRange()) {
return Optional.of(
new Range(begin.getRange().get().begin, end.getRange().get().end));
}
return Optional.empty();
}
public TokenRange withBegin(JavaToken begin) {
return new TokenRange(assertNotNull(begin), end);
}
public TokenRange withEnd(JavaToken end) {
return new TokenRange(begin, assertNotNull(end));
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (JavaToken t : this) {
result.append(t.getText());
}
return result.toString();
}
@Override
public Iterator<JavaToken> iterator() {
return new Iterator<JavaToken>() {
private boolean hasNext = true;
private JavaToken current = begin;
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public JavaToken next() {
JavaToken retval = current;
if (current == null) {
throw new IllegalStateException("Attempting to move past end of range.");
}
if (current == end) {
hasNext = false;
}
current = current.getNextToken().orElse(null);
if (current == null && hasNext) {
throw new IllegalStateException("End token is not linked to begin token.");
}
return retval;
}
};
}
}

View File

@@ -0,0 +1,266 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import static com.github.javaparser.GeneratedJavaParserConstants.*;
import com.github.javaparser.utils.LineSeparator;
/**
* Complements GeneratedJavaParserConstants
*/
public class TokenTypes {
public static boolean isWhitespace(int kind) {
return getCategory(kind).isWhitespace();
}
public static boolean isEndOfLineToken(int kind) {
return getCategory(kind).isEndOfLine();
}
public static boolean isWhitespaceOrComment(int kind) {
return getCategory(kind).isWhitespaceOrComment();
}
/**
* @deprecated Use {@link #isWhitespaceButNotEndOfLine(int)} which more explicitly reflects that this also includes
* other whitespace e.g. {@code EOF} and {@code CTRL_Z} and a large number of other characters.
* See the grammar for details of exactly which characters are included as a "space" (.
* <pre>{@code
* <SPACE: [" ", "\t", "\f", "\u0085", "\u00A0", "\u1680", "\u180e", "\u2000", "\u2001", "\u2002", "\u2003", "\u2004", "\u2005",
* "\u2006", "\u2007", "\u2008", "\u2009", "\u200a", "\u200b", "\u200c", "\u200d", "\u2028", "\u2029", "\u202f", "\u205f", "\u2060", "\u3000", "\ufeff"]>
* }</pre>
*/
@Deprecated
public static boolean isSpaceOrTab(int kind) {
return isWhitespaceButNotEndOfLine(kind);
}
public static boolean isWhitespaceButNotEndOfLine(int kind) {
return getCategory(kind).isWhitespaceButNotEndOfLine();
}
public static boolean isComment(int kind) {
return getCategory(kind).isComment();
}
/**
* @return the kind of EOL token to use on the platform you're running on.
*/
public static int eolTokenKind(LineSeparator lineSeparator) {
if (lineSeparator.equalsString(LineSeparator.LF)) {
return UNIX_EOL;
}
if (lineSeparator.equalsString(LineSeparator.CRLF)) {
return WINDOWS_EOL;
}
if (lineSeparator.equalsString(LineSeparator.CR)) {
return OLD_MAC_EOL;
}
throw new AssertionError("Unknown EOL character sequence");
}
public static int eolTokenKind() {
return eolTokenKind(LineSeparator.SYSTEM);
}
/**
* @return the token kind for a single space.
*/
public static int spaceTokenKind() {
return SPACE;
}
/**
* Category of a token, a little more detailed than
* <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.5">The JLS</a>.
*/
public static JavaToken.Category getCategory(int kind) {
switch (kind) {
case WINDOWS_EOL:
case UNIX_EOL:
case OLD_MAC_EOL:
return JavaToken.Category.EOL;
case EOF:
case SPACE:
case CTRL_Z:
return JavaToken.Category.WHITESPACE_NO_EOL;
case SINGLE_LINE_COMMENT:
case JAVADOC_COMMENT:
case MULTI_LINE_COMMENT:
return JavaToken.Category.COMMENT;
case ABSTRACT:
case ASSERT:
case BOOLEAN:
case BREAK:
case BYTE:
case CASE:
case CATCH:
case CHAR:
case CLASS:
case CONST:
case CONTINUE:
case _DEFAULT:
case DO:
case DOUBLE:
case ELSE:
case ENUM:
case EXTENDS:
case FINAL:
case FINALLY:
case FLOAT:
case FOR:
case GOTO:
case IF:
case IMPLEMENTS:
case IMPORT:
case INSTANCEOF:
case INT:
case INTERFACE:
case LONG:
case NATIVE:
case NEW:
case PACKAGE:
case PRIVATE:
case PROTECTED:
case PUBLIC:
case RECORD:
case RETURN:
case SHORT:
case STATIC:
case STRICTFP:
case SUPER:
case SWITCH:
case SYNCHRONIZED:
case THIS:
case THROW:
case THROWS:
case TRANSIENT:
case TRY:
case VOID:
case VOLATILE:
case WHILE:
case YIELD:
case REQUIRES:
case TO:
case WITH:
case OPEN:
case OPENS:
case USES:
case MODULE:
case EXPORTS:
case PROVIDES:
case TRANSITIVE:
case PERMITS:
case SEALED:
case NON_SEALED:
case WHEN:
return JavaToken.Category.KEYWORD;
case LONG_LITERAL:
case INTEGER_LITERAL:
case DECIMAL_LITERAL:
case HEX_LITERAL:
case OCTAL_LITERAL:
case BINARY_LITERAL:
case FLOATING_POINT_LITERAL:
case DECIMAL_FLOATING_POINT_LITERAL:
case DECIMAL_EXPONENT:
case HEXADECIMAL_FLOATING_POINT_LITERAL:
case HEXADECIMAL_EXPONENT:
case CHARACTER_LITERAL:
case STRING_LITERAL:
case TEXT_BLOCK_LITERAL:
case TRUE:
case FALSE:
case NULL:
return JavaToken.Category.LITERAL;
case IDENTIFIER:
return JavaToken.Category.IDENTIFIER;
case LPAREN:
case RPAREN:
case LBRACE:
case RBRACE:
case LBRACKET:
case RBRACKET:
case SEMICOLON:
case COMMA:
case DOT:
case ELLIPSIS:
case AT:
case DOUBLECOLON:
return JavaToken.Category.SEPARATOR;
case ASSIGN:
case LT:
case BANG:
case TILDE:
case HOOK:
case COLON:
case EQ:
case LE:
case GE:
case NE:
case SC_OR:
case SC_AND:
case INCR:
case DECR:
case PLUS:
case MINUS:
case STAR:
case SLASH:
case BIT_AND:
case BIT_OR:
case XOR:
case REM:
case LSHIFT:
case PLUSASSIGN:
case MINUSASSIGN:
case STARASSIGN:
case SLASHASSIGN:
case ANDASSIGN:
case ORASSIGN:
case XORASSIGN:
case REMASSIGN:
case LSHIFTASSIGN:
case RSIGNEDSHIFTASSIGN:
case RUNSIGNEDSHIFTASSIGN:
case ARROW:
case RUNSIGNEDSHIFT:
case RSIGNEDSHIFT:
case GT:
return JavaToken.Category.OPERATOR;
// The following are tokens that are only used internally by the lexer
case ENTER_JAVADOC_COMMENT:
case ENTER_MULTILINE_COMMENT:
case COMMENT_CONTENT:
case HEX_DIGITS:
case LETTER:
case UNICODE_ESCAPE:
case PART_LETTER:
case TEXT_BLOCK_CONTENT:
case ENTER_TEXT_BLOCK:
default:
throw new AssertionError(
"Unable to categorise token kind " + kind
+ " -- has it recently been added to the grammar but not classified within TokenTypes.java, perhaps?");
}
}
}

View File

@@ -0,0 +1,581 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* {@link Provider} un-escaping unicode escape sequences in the input sequence.
*/
public class UnicodeEscapeProcessingProvider implements Provider {
private static final char LF = '\n';
private static final char CR = '\r';
private static final char BACKSLASH = '\\';
private static final int EOF = -1;
private char[] _data;
/**
* The number of characters in {@link #_data}.
*/
private int _len = 0;
/**
* The position in {@link #_data} where to read the next source character from.
*/
private int _pos = 0;
private boolean _backslashSeen;
private final LineCounter _inputLine = new LineCounter();
private final LineCounter _outputLine = new LineCounter();
private final PositionMappingBuilder _mappingBuilder = new PositionMappingBuilder(_outputLine, _inputLine);
private Provider _input;
/**
* Creates a {@link UnicodeEscapeProcessingProvider}.
*/
public UnicodeEscapeProcessingProvider(Provider input) {
this(2048, input);
}
/**
* Creates a {@link UnicodeEscapeProcessingProvider}.
*/
public UnicodeEscapeProcessingProvider(int bufferSize, Provider input) {
_input = input;
_data = new char[bufferSize];
}
/**
* The {@link LineCounter} of the input file.
*/
public LineCounter getInputCounter() {
return _inputLine;
}
/**
* The {@link LineCounter} of the output file.
*/
public LineCounter getOutputCounter() {
return _outputLine;
}
@Override
public int read(char[] buffer, final int offset, int len) throws IOException {
int pos = offset;
int stop = offset + len;
while (pos < stop) {
int ch = _outputLine.process(nextOutputChar());
if (ch < 0) {
if (pos == offset) {
// Nothing read yet, this is the end of the stream.
return EOF;
}
break;
}
_mappingBuilder.update();
buffer[pos++] = (char) ch;
}
return pos - offset;
}
@Override
public void close() throws IOException {
_input.close();
}
/**
* Produces the next un-escaped character to be written to the output.
*
* @return The next character or {@code -1} if no more characters are available.
*/
private int nextOutputChar() throws IOException {
int next = nextInputChar();
switch (next) {
case EOF:
return EOF;
case BACKSLASH: {
if (_backslashSeen) {
return clearBackSlashSeen(next);
}
return backSlashSeen();
}
default: {
// An arbitrary character.
return clearBackSlashSeen(next);
}
}
}
private int clearBackSlashSeen(int next) {
_backslashSeen = false;
return next;
}
private int backSlashSeen() throws IOException {
_backslashSeen = true;
int next = nextInputChar();
switch (next) {
case EOF:
// End of file after backslash produces the backslash itself.
return BACKSLASH;
case 'u': {
return unicodeStartSeen();
}
default: {
pushBack(next);
return BACKSLASH;
}
}
}
private int unicodeStartSeen() throws IOException {
int uCnt = 1;
while (true) {
int next = nextInputChar();
switch (next) {
case EOF: {
pushBackUs(uCnt);
return BACKSLASH;
}
case 'u': {
uCnt++;
continue;
}
default: {
return readDigits(uCnt, next);
}
}
}
}
private int readDigits(int uCnt, int next3) throws IOException {
int digit3 = digit(next3);
if (digit3 < 0) {
pushBack(next3);
pushBackUs(uCnt);
return BACKSLASH;
}
int next2 = nextInputChar();
int digit2 = digit(next2);
if (digit2 < 0) {
pushBack(next2);
pushBack(next3);
pushBackUs(uCnt);
return BACKSLASH;
}
int next1 = nextInputChar();
int digit1 = digit(next1);
if (digit1 < 0) {
pushBack(next1);
pushBack(next2);
pushBack(next3);
pushBackUs(uCnt);
return BACKSLASH;
}
int next0 = nextInputChar();
int digit0 = digit(next0);
if (digit0 < 0) {
pushBack(next0);
pushBack(next1);
pushBack(next2);
pushBack(next3);
pushBackUs(uCnt);
return BACKSLASH;
}
int ch = digit3 << 12 | digit2 << 8 | digit1 << 4 | digit0;
return clearBackSlashSeen(ch);
}
private void pushBackUs(int cnt) {
for (int n = 0; n < cnt; n++) {
pushBack('u');
}
}
private static int digit(int ch) {
if (ch >= '0' && ch <= '9') {
return ch - '0';
}
if (ch >= 'A' && ch <= 'F') {
return 10 + ch - 'A';
}
if (ch >= 'a' && ch <= 'f') {
return 10 + ch - 'a';
}
return -1;
}
/**
* Processes column/line information from the input file.
*
* @return The next character or {@code -1} if no more input is available.
*/
private int nextInputChar() throws IOException {
int result = nextBufferedChar();
return _inputLine.process(result);
}
/**
* Retrieves the next un-escaped character from the buffered {@link #_input}.
*
* @return The next character or {@code -1} if no more input is available.
*/
private int nextBufferedChar() throws IOException {
while (isBufferEmpty()) {
int direct = fillBuffer();
if (direct < 0) {
return EOF;
}
}
return _data[_pos++];
}
private boolean isBufferEmpty() {
return _pos >= _len;
}
private int fillBuffer() throws IOException {
_pos = 0;
int direct = _input.read(_data, 0, _data.length);
if (direct != 0) {
_len = direct;
}
return direct;
}
private void pushBack(int ch) {
if (ch < 0) {
return;
}
if (isBufferEmpty()) {
_pos = _data.length;
_len = _data.length;
} else if (_pos == 0) {
if (_len == _data.length) {
// Buffer is completely full, no push possible, enlarge buffer.
char[] newData = new char[_data.length + 1024];
_len = newData.length;
_pos = newData.length - _data.length;
System.arraycopy(_data, 0, newData, _pos, _data.length);
_data = newData;
} else {
// Move contents to the right.
int cnt = _len - _pos;
_pos = _data.length - _len;
_len = _data.length;
System.arraycopy(_data, 0, _data, _pos, cnt);
}
}
_data[--_pos] = (char) ch;
}
/**
* The {@link PositionMapping} being built during processing the file.
*/
public PositionMapping getPositionMapping() {
return _mappingBuilder.getMapping();
}
/**
* An algorithm mapping {@link Position} form two corresponding files.
*/
public static final class PositionMapping {
private final List<DeltaInfo> _deltas = new ArrayList<>();
/**
* Creates a {@link UnicodeEscapeProcessingProvider.PositionMapping}.
*/
public PositionMapping() {
super();
}
/**
* Whether this is the identity transformation.
*/
public boolean isEmpty() {
return _deltas.isEmpty();
}
void add(int line, int column, int lineDelta, int columnDelta) {
_deltas.add(new DeltaInfo(line, column, lineDelta, columnDelta));
}
/**
* Looks up the {@link PositionUpdate} for the given Position.
*/
public PositionUpdate lookup(Position position) {
int result = Collections.binarySearch(_deltas, position);
if (result >= 0) {
return _deltas.get(result);
}
int insertIndex = -result - 1;
if (insertIndex == 0) {
// Before the first delta info, identity mapping.
return PositionUpdate.NONE;
}
return _deltas.get(insertIndex - 1);
}
/**
* Algorithm updating a {@link Position} from one file to a
* {@link Position} in a corresponding file.
*/
public static interface PositionUpdate {
/**
* The identity position mapping.
*/
PositionUpdate NONE = new PositionUpdate() {
@Override
public int transformLine(int line) {
return line;
}
@Override
public int transformColumn(int column) {
return column;
}
@Override
public Position transform(Position pos) {
return pos;
}
};
/**
* Maps the given line to an original line.
*/
int transformLine(int line);
/**
* Maps the given column to an original column.
*/
int transformColumn(int column);
/**
* The transformed position.
*/
default Position transform(Position pos) {
int line = pos.line;
int column = pos.column;
int transformedLine = transformLine(line);
int transformedColumn = transformColumn(column);
return new Position(transformedLine, transformedColumn);
}
}
private static final class DeltaInfo extends Position implements PositionUpdate {
/**
* The offset to add to the {@link #line} and all following source
* positions up to the next {@link PositionUpdate}.
*/
private final int _lineDelta;
/**
* The offset to add to the {@link #column} and all following
* source positions up to the next {@link PositionUpdate}.
*/
private final int _columnDelta;
/**
* Creates a {@link PositionUpdate}.
*/
public DeltaInfo(int line, int column, int lineDelta, int columnDelta) {
super(line, column);
_lineDelta = lineDelta;
_columnDelta = columnDelta;
}
@Override
public int transformLine(int sourceLine) {
return sourceLine + _lineDelta;
}
@Override
public int transformColumn(int sourceColumn) {
return sourceColumn + _columnDelta;
}
@Override
public String toString() {
return "(" + line + ", " + column + ": " + _lineDelta + ", " + _columnDelta + ")";
}
}
/**
* Transforms the given {@link Position}.
*/
public Position transform(Position pos) {
return lookup(pos).transform(pos);
}
/**
* Transforms the given {@link Range}.
*/
public Range transform(Range range) {
Position begin = transform(range.begin);
Position end = transform(range.end);
if (begin == range.begin && end == range.end) {
// No change.
return range;
}
return new Range(begin, end);
}
}
private static final class PositionMappingBuilder {
private LineCounter _left;
private LineCounter _right;
private final PositionMapping _mapping = new PositionMapping();
private int _lineDelta = 0;
private int _columnDelta = 0;
/**
* Creates a {@link PositionMappingBuilder}.
*
* @param left The source {@link LineCounter}.
* @param right The target {@link LineCounter}.
*/
public PositionMappingBuilder(LineCounter left, LineCounter right) {
_left = left;
_right = right;
update();
}
/**
* The built {@link PositionMapping}.
*/
public PositionMapping getMapping() {
return _mapping;
}
public void update() {
int lineDelta = _right.getLine() - _left.getLine();
int columnDelta = _right.getColumn() - _left.getColumn();
if (lineDelta != _lineDelta || columnDelta != _columnDelta) {
_mapping.add(_left.getLine(), _left.getColumn(), lineDelta, columnDelta);
_lineDelta = lineDelta;
_columnDelta = columnDelta;
}
}
}
/**
* Processor keeping track of the current line and column in a stream of
* incoming characters.
*
* @see #process(int)
*/
public static final class LineCounter {
/**
* Whether {@link #CR} has been seen on the input as last character.
*/
private boolean _crSeen;
private int _line = 1;
private int _column = 1;
/**
* Creates a {@link UnicodeEscapeProcessingProvider.LineCounter}.
*/
public LineCounter() {
super();
}
/**
* The line of the currently processed input character.
*/
public int getLine() {
return _line;
}
/**
* The column of the currently processed input character.
*/
public int getColumn() {
return _column;
}
/**
* The current position.
*/
public Position getPosition() {
return new Position(getLine(), getColumn());
}
/**
* Analyzes the given character for line feed.
*/
public int process(int ch) {
switch (ch) {
case EOF: {
break;
}
case CR: {
incLine();
_crSeen = true;
break;
}
case LF: {
// CR LF does only count as a single line terminator.
if (_crSeen) {
_crSeen = false;
} else {
incLine();
}
break;
}
default: {
_crSeen = false;
_column++;
}
}
return ch;
}
private void incLine() {
_line++;
_column = 1;
}
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
/**
* Access specifier. Represents one of the possible levels of
* access permitted by the language.
*
* @author Federico Tomassetti
* @since July 2014
*/
public enum AccessSpecifier {
PUBLIC("public"),
PRIVATE("private"),
PROTECTED("protected"),
NONE("");
private String codeRepresenation;
AccessSpecifier(String codeRepresentation) {
this.codeRepresenation = codeRepresentation;
}
public String asString() {
return this.codeRepresenation;
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Tells tools that this is the constructor which directly initializes all fields (except "range" and "comment")
*/
@Target(ElementType.CONSTRUCTOR)
@Retention(RetentionPolicy.RUNTIME)
public @interface AllFieldsConstructor {}

View File

@@ -0,0 +1,190 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.IntegerLiteralExpr;
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.ArrayCreationLevelMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import java.util.Optional;
/**
* In {@code new int[1][2];} there are two ArrayCreationLevel objects,
* the first one contains the expression "1",
* the second the expression "2".
*/
public class ArrayCreationLevel extends Node implements NodeWithAnnotations<ArrayCreationLevel> {
@OptionalProperty
private Expression dimension;
private NodeList<AnnotationExpr> annotations = new NodeList<>();
public ArrayCreationLevel() {
this(null, null, new NodeList<>());
}
public ArrayCreationLevel(int dimension) {
this(null, new IntegerLiteralExpr("" + dimension), new NodeList<>());
}
public ArrayCreationLevel(Expression dimension) {
this(null, dimension, new NodeList<>());
}
@AllFieldsConstructor
public ArrayCreationLevel(Expression dimension, NodeList<AnnotationExpr> annotations) {
this(null, dimension, annotations);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ArrayCreationLevel(TokenRange tokenRange, Expression dimension, NodeList<AnnotationExpr> annotations) {
super(tokenRange);
setDimension(dimension);
setAnnotations(annotations);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* Sets the dimension
*
* @param dimension the dimension, can be null
* @return this, the ArrayCreationLevel
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ArrayCreationLevel setDimension(final Expression dimension) {
if (dimension == this.dimension) {
return this;
}
notifyPropertyChange(ObservableProperty.DIMENSION, this.dimension, dimension);
if (this.dimension != null) this.dimension.setParentNode(null);
this.dimension = dimension;
setAsParentNodeOf(dimension);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<Expression> getDimension() {
return Optional.ofNullable(dimension);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<AnnotationExpr> getAnnotations() {
return annotations;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ArrayCreationLevel setAnnotations(final NodeList<AnnotationExpr> annotations) {
assertNotNull(annotations);
if (annotations == this.annotations) {
return this;
}
notifyPropertyChange(ObservableProperty.ANNOTATIONS, this.annotations, annotations);
if (this.annotations != null) this.annotations.setParentNode(null);
this.annotations = annotations;
setAsParentNodeOf(annotations);
return this;
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public ArrayCreationLevel removeDimension() {
return setDimension((Expression) null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.remove(i);
return true;
}
}
if (dimension != null) {
if (node == dimension) {
removeDimension();
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ArrayCreationLevel clone() {
return (ArrayCreationLevel) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ArrayCreationLevelMetaModel getMetaModel() {
return JavaParserMetaModel.arrayCreationLevelMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.set(i, (AnnotationExpr) replacementNode);
return true;
}
}
if (dimension != null) {
if (node == dimension) {
setDimension((Expression) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
}

View File

@@ -0,0 +1,895 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.JavaToken.Kind.EOF;
import static com.github.javaparser.Providers.UTF8;
import static com.github.javaparser.Providers.provider;
import static com.github.javaparser.Range.range;
import static com.github.javaparser.StaticJavaParser.parseName;
import static com.github.javaparser.ast.Modifier.createModifierList;
import static com.github.javaparser.utils.CodeGenerationUtils.subtractPaths;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.*;
import com.github.javaparser.ast.body.*;
import com.github.javaparser.ast.comments.Comment;
import com.github.javaparser.ast.comments.JavadocComment;
import com.github.javaparser.ast.expr.Name;
import com.github.javaparser.ast.modules.ModuleDeclaration;
import com.github.javaparser.ast.nodeTypes.NodeWithName;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.CompilationUnitMetaModel;
import com.github.javaparser.metamodel.InternalProperty;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import com.github.javaparser.printer.ConfigurablePrinter;
import com.github.javaparser.printer.Printer;
import com.github.javaparser.printer.configuration.PrinterConfiguration;
import com.github.javaparser.utils.ClassUtils;
import com.github.javaparser.utils.CodeGenerationUtils;
import com.github.javaparser.utils.Utils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* <p>
* This class represents the entire compilation unit. Each java file denotes a
* compilation unit.
* </p>
* A compilation unit start with an optional package declaration,
* followed by zero or more import declarations,
* followed by zero or more type declarations.
*
* @author Julio Vilmar Gesser
* @see PackageDeclaration
* @see ImportDeclaration
* @see TypeDeclaration
* @see Storage
*/
public class CompilationUnit extends Node {
private static final String JAVA_LANG = "java.lang";
@OptionalProperty
private PackageDeclaration packageDeclaration;
private NodeList<ImportDeclaration> imports;
private NodeList<TypeDeclaration<?>> types;
@OptionalProperty
private ModuleDeclaration module;
@InternalProperty
private Storage storage;
public CompilationUnit() {
this(null, null, new NodeList<>(), new NodeList<>(), null);
}
public CompilationUnit(String packageDeclaration) {
this(null, new PackageDeclaration(new Name(packageDeclaration)), new NodeList<>(), new NodeList<>(), null);
}
@AllFieldsConstructor
public CompilationUnit(
PackageDeclaration packageDeclaration,
NodeList<ImportDeclaration> imports,
NodeList<TypeDeclaration<?>> types,
ModuleDeclaration module) {
this(null, packageDeclaration, imports, types, module);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public CompilationUnit(
TokenRange tokenRange,
PackageDeclaration packageDeclaration,
NodeList<ImportDeclaration> imports,
NodeList<TypeDeclaration<?>> types,
ModuleDeclaration module) {
super(tokenRange);
setPackageDeclaration(packageDeclaration);
setImports(imports);
setTypes(types);
setModule(module);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* Declare a specific printer
*/
public CompilationUnit printer(Printer printer) {
setData(PRINTER_KEY, printer);
return this;
}
/*
* If there is no declared printer, returns a new default printer else returns a new printer with the current configuration
*/
@Override
protected Printer getPrinter() {
if (!containsData(PRINTER_KEY)) {
// create a default printer
Printer printer = createDefaultPrinter();
printer(printer);
}
return getData(PRINTER_KEY);
}
/*
* Return the printer initialized with the specified configuration
*/
@Override
protected Printer getPrinter(PrinterConfiguration config) {
Printer printer = getPrinter();
if (printer instanceof ConfigurablePrinter) {
((ConfigurablePrinter) printer).setConfiguration(config);
}
printer(printer);
return printer;
}
/**
* @deprecated getComments was a too generic name and it could be confused with getComment
* or getAllContainedComments
* Use {@link #getAllComments()} instead
*/
@Deprecated
public List<Comment> getComments() {
List<Comment> comments = this.getAllContainedComments();
this.getComment().ifPresent(comments::add);
return comments;
}
/**
* Return a list containing all comments declared in this compilation unit.
* Including javadocs, line comments and block comments of all types,
* inner-classes and other members.<br>
* If there is no comment, an empty list is returned.
*
* @return list with all comments of this compilation unit.
* @see JavadocComment
* @see com.github.javaparser.ast.comments.LineComment
* @see com.github.javaparser.ast.comments.BlockComment
*/
public List<Comment> getAllComments() {
List<Comment> comments = this.getAllContainedComments();
this.getComment().ifPresent(comments::add);
return comments;
}
/**
* Retrieves the list of imports declared in this compilation unit or
* {@code null} if there is no import.
*
* @return the list of imports or {@code none} if there is no import
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<ImportDeclaration> getImports() {
return imports;
}
public ImportDeclaration getImport(int i) {
return getImports().get(i);
}
/**
* Retrieves the package declaration of this compilation unit.<br>
* If this compilation unit has no package declaration (default package),
* {@code Optional.none()} is returned.
*
* @return the package declaration or {@code none}
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<PackageDeclaration> getPackageDeclaration() {
return Optional.ofNullable(packageDeclaration);
}
/**
* Return the list of top level types declared in this compilation unit.<br>
* If there are no types declared, {@code none} is returned.
*
* @return the list of types or {@code none} null if there is no type
* @see AnnotationDeclaration
* @see ClassOrInterfaceDeclaration
* @see EnumDeclaration
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<TypeDeclaration<?>> getTypes() {
return types;
}
/**
* Convenience method that wraps {@code getTypes()}.<br>
* If {@code i} is out of bounds, throws <code>IndexOutOfBoundsException.</code>
*
* @param i the index of the type declaration to retrieve
*/
public TypeDeclaration<?> getType(int i) {
return getTypes().get(i);
}
/**
* Sets the list of imports of this compilation unit. The list is initially
* {@code null}.
*
* @param imports the list of imports
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public CompilationUnit setImports(final NodeList<ImportDeclaration> imports) {
assertNotNull(imports);
if (imports == this.imports) {
return this;
}
notifyPropertyChange(ObservableProperty.IMPORTS, this.imports, imports);
if (this.imports != null) this.imports.setParentNode(null);
this.imports = imports;
setAsParentNodeOf(imports);
return this;
}
public CompilationUnit setImport(int i, ImportDeclaration imports) {
getImports().set(i, imports);
return this;
}
/**
* adds an import if not implicitly imported by java (i.e. java.lang) or
* added before. Asterisk imports overrule the other imports within the same package.
*
* @param importDeclaration
* @return {@code this}
*/
public CompilationUnit addImport(ImportDeclaration importDeclaration) {
if (importDeclaration.isAsterisk()) {
getImports()
.removeIf(im -> Objects.equals(
getImportPackageName(im).get(),
getImportPackageName(importDeclaration).orElse(null)));
}
if (!isImplicitImport(importDeclaration)
&& getImports().stream()
.noneMatch(im -> im.equals(importDeclaration)
|| (im.isAsterisk()
&& Objects.equals(
getImportPackageName(im).get(),
getImportPackageName(importDeclaration)
.orElse(null))))) {
getImports().add(importDeclaration);
}
return this;
}
/**
* @param importDeclaration
* @return {@code true}, if the import is implicit
*/
private boolean isImplicitImport(ImportDeclaration importDeclaration) {
Optional<Name> importPackageName = getImportPackageName(importDeclaration);
if (importPackageName.isPresent()) {
if (parseName(JAVA_LANG).equals(importPackageName.get())) {
// java.lang is implicitly imported
return true;
}
if (packageDeclaration != null) {
// the import is within the same package
Name currentPackageName = packageDeclaration.getName();
return currentPackageName.equals(importPackageName.get());
}
return false;
}
return true;
}
private static Optional<Name> getImportPackageName(ImportDeclaration importDeclaration) {
return (importDeclaration.isAsterisk()
? new Name(importDeclaration.getName(), "*")
: importDeclaration.getName())
.getQualifier();
}
/**
* Sets or clear the package declarations of this compilation unit.
*
* @param packageDeclaration the packageDeclaration declaration to set or {@code null} to default package
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public CompilationUnit setPackageDeclaration(final PackageDeclaration packageDeclaration) {
if (packageDeclaration == this.packageDeclaration) {
return this;
}
notifyPropertyChange(ObservableProperty.PACKAGE_DECLARATION, this.packageDeclaration, packageDeclaration);
if (this.packageDeclaration != null) this.packageDeclaration.setParentNode(null);
this.packageDeclaration = packageDeclaration;
setAsParentNodeOf(packageDeclaration);
return this;
}
/**
* Sets the list of types declared in this compilation unit.
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public CompilationUnit setTypes(final NodeList<TypeDeclaration<?>> types) {
assertNotNull(types);
if (types == this.types) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPES, this.types, types);
if (this.types != null) this.types.setParentNode(null);
this.types = types;
setAsParentNodeOf(types);
return this;
}
public CompilationUnit setType(int i, TypeDeclaration<?> type) {
NodeList<TypeDeclaration<?>> copy = new NodeList<>();
copy.addAll(getTypes());
getTypes().set(i, type);
notifyPropertyChange(ObservableProperty.TYPES, copy, types);
return this;
}
public CompilationUnit addType(TypeDeclaration<?> type) {
NodeList<TypeDeclaration<?>> copy = new NodeList<>();
copy.addAll(getTypes());
getTypes().add(type);
notifyPropertyChange(ObservableProperty.TYPES, copy, types);
return this;
}
/**
* sets the package declaration of this compilation unit
*
* @param name the name of the package
* @return this, the {@link CompilationUnit}
*/
public CompilationUnit setPackageDeclaration(String name) {
setPackageDeclaration(new PackageDeclaration(parseName(name)));
return this;
}
/**
* Add an import to the list of {@link ImportDeclaration} of this compilation unit<br>
* shorthand for {@link #addImport(String, boolean, boolean)} with name,false,false
*
* @param name the import name
* @return this, the {@link CompilationUnit}
*/
public CompilationUnit addImport(String name) {
return addImport(name, false, false);
}
/**
* Add an import to the list of {@link ImportDeclaration} of this compilation unit<br>
* shorthand for {@link #addImport(String)} with clazz.getName()
*
* @param clazz the class to import
* @return this, the {@link CompilationUnit}
* @throws IllegalArgumentException if clazz is an anonymous or local class
*/
public CompilationUnit addImport(Class<?> clazz) {
if (clazz.isArray()) {
return addImport(clazz.getComponentType());
}
if (ClassUtils.isPrimitiveOrWrapper(clazz)
|| JAVA_LANG.equals(clazz.getPackage().getName())) return this;
if (clazz.isAnonymousClass() || clazz.isLocalClass())
throw new IllegalArgumentException(
clazz.getName() + " is an anonymous or local class therefore it can't be added with addImport");
return addImport(clazz.getCanonicalName());
}
/**
* Add an import to the list of {@link ImportDeclaration} of this compilation unit<br>
* <b>This method check if no import with the same name is already in the list</b>
*
* @param name the import name
* @param isStatic is it an "import static"
* @param isAsterisk does the import end with ".*"
* @return this, the {@link CompilationUnit}
*/
public CompilationUnit addImport(String name, boolean isStatic, boolean isAsterisk) {
if (name == null) {
return this;
}
return addImport(new ImportDeclaration(name, isStatic, isAsterisk));
}
/**
* Add a public class to the types of this compilation unit
*
* @param name the class name
* @return the newly created class
*/
public ClassOrInterfaceDeclaration addClass(String name) {
return addClass(name, Modifier.Keyword.PUBLIC);
}
/**
* Add a class to the types of this compilation unit
*
* @param name the class name
* @param modifiers the modifiers (like Modifier.PUBLIC)
* @return the newly created class
*/
public ClassOrInterfaceDeclaration addClass(String name, Modifier.Keyword... modifiers) {
ClassOrInterfaceDeclaration classOrInterfaceDeclaration =
new ClassOrInterfaceDeclaration(createModifierList(modifiers), false, name);
getTypes().add(classOrInterfaceDeclaration);
return classOrInterfaceDeclaration;
}
/**
* Add a public interface class to the types of this compilation unit
*
* @param name the interface name
* @return the newly created class
*/
public ClassOrInterfaceDeclaration addInterface(String name) {
return addInterface(name, Modifier.Keyword.PUBLIC);
}
/**
* Add an interface to the types of this compilation unit
*
* @param name the interface name
* @param modifiers the modifiers (like Modifier.PUBLIC)
* @return the newly created class
*/
public ClassOrInterfaceDeclaration addInterface(String name, Modifier.Keyword... modifiers) {
ClassOrInterfaceDeclaration classOrInterfaceDeclaration =
new ClassOrInterfaceDeclaration(createModifierList(modifiers), true, name);
getTypes().add(classOrInterfaceDeclaration);
return classOrInterfaceDeclaration;
}
/**
* Add a public enum to the types of this compilation unit
*
* @param name the enum name
* @return the newly created class
*/
public EnumDeclaration addEnum(String name) {
return addEnum(name, Modifier.Keyword.PUBLIC);
}
/**
* Add an enum to the types of this compilation unit
*
* @param name the enum name
* @param modifiers the modifiers (like Modifier.PUBLIC)
* @return the newly created class
*/
public EnumDeclaration addEnum(String name, Modifier.Keyword... modifiers) {
EnumDeclaration enumDeclaration = new EnumDeclaration(createModifierList(modifiers), name);
getTypes().add(enumDeclaration);
return enumDeclaration;
}
/**
* Add a public annotation declaration to the types of this compilation unit
*
* @param name the annotation name
* @return the newly created class
*/
public AnnotationDeclaration addAnnotationDeclaration(String name) {
return addAnnotationDeclaration(name, Modifier.Keyword.PUBLIC);
}
/**
* Add an annotation declaration to the types of this compilation unit
*
* @param name the annotation name
* @param modifiers the modifiers (like Modifier.PUBLIC)
* @return the newly created class
*/
public AnnotationDeclaration addAnnotationDeclaration(String name, Modifier.Keyword... modifiers) {
AnnotationDeclaration annotationDeclaration = new AnnotationDeclaration(createModifierList(modifiers), name);
getTypes().add(annotationDeclaration);
return annotationDeclaration;
}
/**
* Try to get a top level class declaration by its name
*
* @param className the class name (case-sensitive)
*/
public Optional<ClassOrInterfaceDeclaration> getClassByName(String className) {
return getTypes().stream()
.filter(type -> type.getNameAsString().equals(className)
&& type instanceof ClassOrInterfaceDeclaration
&& !((ClassOrInterfaceDeclaration) type).isInterface())
.findFirst()
.map(t -> (ClassOrInterfaceDeclaration) t);
}
/**
* Try to get all local class declarations ending by its name (top level or inner class)
*
* @param className the class name (case-sensitive)
*/
public List<ClassOrInterfaceDeclaration> getLocalDeclarationFromClassname(String className) {
return findAll(ClassOrInterfaceDeclaration.class).stream()
.filter(cid -> cid.getFullyQualifiedName().get().endsWith(className))
.collect(Collectors.toList());
}
/**
* Try to get a top level interface declaration by its name
*
* @param interfaceName the interface name (case-sensitive)
*/
public Optional<ClassOrInterfaceDeclaration> getInterfaceByName(String interfaceName) {
return getTypes().stream()
.filter(type -> type.getNameAsString().equals(interfaceName)
&& type instanceof ClassOrInterfaceDeclaration
&& ((ClassOrInterfaceDeclaration) type).isInterface())
.findFirst()
.map(t -> (ClassOrInterfaceDeclaration) t);
}
/**
* Try to get a top level enum declaration by its name
*
* @param enumName the enum name (case-sensitive)
*/
public Optional<EnumDeclaration> getEnumByName(String enumName) {
return getTypes().stream()
.filter(type -> type.getNameAsString().equals(enumName) && type instanceof EnumDeclaration)
.findFirst()
.map(t -> (EnumDeclaration) t);
}
/**
* @return the name that the primary type in this file should have, according to the filename in {@link Storage#getFileName()}.
* Empty if no file information is present (when this compilation unit wasn't parsed from a file.)
*/
public Optional<String> getPrimaryTypeName() {
return getStorage().map(Storage::getFileName).map(Utils::removeFileExtension);
}
/**
* @return the type whose name corresponds to the file name.
* Empty if no file information is present (when this compilation unit wasn't parsed from a file.)
* If for some strange reason there are multiple types of this name, the first one is returned.
*/
public Optional<TypeDeclaration<?>> getPrimaryType() {
return getPrimaryTypeName().flatMap(name -> getTypes().stream()
.filter(t -> t.getNameAsString().equals(name))
.findFirst());
}
/**
* Try to get a top level annotation type declaration by its name
*
* @param annotationName the annotation name (case-sensitive)
*/
public Optional<AnnotationDeclaration> getAnnotationDeclarationByName(String annotationName) {
return getTypes().stream()
.filter(type -> type.getNameAsString().equals(annotationName) && type instanceof AnnotationDeclaration)
.findFirst()
.map(t -> (AnnotationDeclaration) t);
}
/**
* Try to get a top level record declaration by its name
*
* @param recordName the enum name (case-sensitive)
*/
public Optional<RecordDeclaration> getRecordByName(String recordName) {
return getTypes().stream()
.filter(type -> type.getNameAsString().equals(recordName) && type instanceof RecordDeclaration)
.findFirst()
.map(t -> (RecordDeclaration) t);
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < imports.size(); i++) {
if (imports.get(i) == node) {
imports.remove(i);
return true;
}
}
if (module != null) {
if (node == module) {
removeModule();
return true;
}
}
if (packageDeclaration != null) {
if (node == packageDeclaration) {
removePackageDeclaration();
return true;
}
}
for (int i = 0; i < types.size(); i++) {
if (types.get(i) == node) {
types.remove(i);
return true;
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public CompilationUnit removePackageDeclaration() {
return setPackageDeclaration((PackageDeclaration) null);
}
/**
* @return the module declared in this compilation unit.
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<ModuleDeclaration> getModule() {
return Optional.ofNullable(module);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public CompilationUnit setModule(final ModuleDeclaration module) {
if (module == this.module) {
return this;
}
notifyPropertyChange(ObservableProperty.MODULE, this.module, module);
if (this.module != null) this.module.setParentNode(null);
this.module = module;
setAsParentNodeOf(module);
return this;
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public CompilationUnit removeModule() {
return setModule((ModuleDeclaration) null);
}
/**
* @return information about where this compilation unit was loaded from, or empty if it wasn't loaded from a file.
*/
public Optional<Storage> getStorage() {
return Optional.ofNullable(storage);
}
public CompilationUnit setStorage(Path path) {
this.storage = new Storage(this, path);
return this;
}
public CompilationUnit setStorage(Path path, Charset charset) {
this.storage = new Storage(this, path, charset);
return this;
}
/**
* Create (or overwrite) a module declaration in this compilation unit with name "name".
*
* @return the module
*/
public ModuleDeclaration setModule(String name) {
final ModuleDeclaration module = new ModuleDeclaration(parseName(name), false);
setModule(module);
return module;
}
/**
* Recalculates the ranges of all nodes by looking at the sizes of the tokens.
* This is useful when you have manually inserted or deleted tokens and still want to use the ranges.
*/
public void recalculatePositions() {
if (!getTokenRange().isPresent()) {
throw new IllegalStateException("Can't recalculate positions without tokens.");
}
Position cursor = Position.HOME;
for (JavaToken t : getTokenRange().get()) {
int tokenLength = t.getKind() == EOF.getKind() ? 0 : t.getText().length() - 1;
t.setRange(range(cursor, cursor.right(tokenLength)));
if (t.getCategory().isEndOfLine()) {
cursor = cursor.nextLine();
} else {
cursor = cursor.right(tokenLength + 1);
}
}
}
/**
* Information about where this compilation unit was loaded from.
* This class only stores the absolute location.
* For more flexibility use SourceRoot.
*/
public static class Storage {
private final CompilationUnit compilationUnit;
private final Path path;
private final Charset encoding;
private Storage(CompilationUnit compilationUnit, Path path) {
this(compilationUnit, path, UTF8);
}
private Storage(CompilationUnit compilationUnit, Path path, Charset encoding) {
this.compilationUnit = compilationUnit;
this.path = path.toAbsolutePath();
this.encoding = encoding;
}
/**
* @return the path to the source for this CompilationUnit
*/
public Path getPath() {
return path;
}
/**
* @return the CompilationUnit this Storage is about.
*/
public CompilationUnit getCompilationUnit() {
return compilationUnit;
}
/**
* @return the encoding used to read the file.
*/
public Charset getEncoding() {
return encoding;
}
/**
* @return the source root directory, calculated from the path of this compiation unit, and the package
* declaration of this compilation unit. If the package declaration is invalid (when it does not match the end
* of the path) a RuntimeException is thrown.
*/
public Path getSourceRoot() {
final Optional<String> pkgAsString =
compilationUnit.getPackageDeclaration().map(NodeWithName::getNameAsString);
return pkgAsString
.map(p -> Paths.get(CodeGenerationUtils.packageToPath(p)))
.map(pkg -> subtractPaths(getDirectory(), pkg))
.orElseGet(() -> getDirectory());
}
public String getFileName() {
return path.getFileName().toString();
}
public Path getDirectory() {
return path.getParent();
}
/**
* Saves the compilation unit to its original location
*/
public void save() {
save(cu -> compilationUnit.getPrinter().print(cu));
}
/**
* Saves a compilation unit to its original location with formatting according to the function passed as a
* parameter.
*
* @param makeOutput a function that formats the compilation unit
*/
public void save(Function<CompilationUnit, String> makeOutput) {
save(makeOutput, encoding);
}
/**
* Saves a compilation unit to its original location with formatting and encoding according to the function and
* encoding passed as a parameter.
*
* @param makeOutput a function that formats the compilation unit
* @param encoding the encoding to use for the saved file
*/
public void save(Function<CompilationUnit, String> makeOutput, Charset encoding) {
try {
Files.createDirectories(path.getParent());
final String code = makeOutput.apply(getCompilationUnit());
Files.write(path, code.getBytes(encoding));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public ParseResult<CompilationUnit> reparse(JavaParser javaParser) {
try {
return javaParser.parse(ParseStart.COMPILATION_UNIT, provider(getPath()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public CompilationUnit clone() {
return (CompilationUnit) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public CompilationUnitMetaModel getMetaModel() {
return JavaParserMetaModel.compilationUnitMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < imports.size(); i++) {
if (imports.get(i) == node) {
imports.set(i, (ImportDeclaration) replacementNode);
return true;
}
}
if (module != null) {
if (node == module) {
setModule((ModuleDeclaration) replacementNode);
return true;
}
}
if (packageDeclaration != null) {
if (node == packageDeclaration) {
setPackageDeclaration((PackageDeclaration) replacementNode);
return true;
}
}
for (int i = 0; i < types.size(); i++) {
if (types.get(i) == node) {
types.set(i, (TypeDeclaration) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
/**
* A key to a piece of data associated with a {@link Node} at runtime.
* The key contains type information that can be used to check the
* type of any user data value for the key when the value is set. DataKey is abstract in order to
* force the creation of a subtype. That subtype is used to test for identity when looking for the
* user data because actual object identity would suffer from problems under serialization.
* So, the correct way to declare a DataKey is like this:
* <p>
* <pre>
* {@code
* public static final DataKey<Role> ROLE = new DataKey<Role>() { };
* }
* </pre>
* <p>
* This code was taken from the <a href="http://wicket.apache.org/">Wicket project</a>.
*
* @param <T> The type of the object which is stored
* @see Node#getData(DataKey)
*/
public abstract class DataKey<T> {
@Override
public int hashCode() {
return getClass().hashCode();
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return obj != null && getClass().equals(obj.getClass());
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.SOURCE;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Copied from javax.annotation.Generated and reduced a bit.
* <p>
* Indicates a part of the code that was generated,
* and will be overwritten the next time the generators are run.
*/
@Retention(SOURCE)
@Target({PACKAGE, TYPE, ANNOTATION_TYPE, METHOD, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, PARAMETER})
public @interface Generated {
/**
* The value element must have the name of the code generator.
* The recommended convention is to use the fully qualified name of the
* code generator. For example: {@code com.acme.generator.CodeGen}.
*/
String[] value();
}

View File

@@ -0,0 +1,204 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.expr.Name;
import com.github.javaparser.ast.nodeTypes.NodeWithName;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.ImportDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
/**
* An import declaration.
* <br>{@code import com.github.javaparser.JavaParser;}
* <br>{@code import com.github.javaparser.*;}
* <br>{@code import com.github.javaparser.JavaParser.*; }
* <br>{@code import static com.github.javaparser.JavaParser.*;}
* <br>{@code import static com.github.javaparser.JavaParser.parse;}
*
* <p>The name does not include the asterisk or the static keyword.</p>
* @author Julio Vilmar Gesser
*/
public class ImportDeclaration extends Node implements NodeWithName<ImportDeclaration> {
private Name name;
private boolean isStatic;
private boolean isAsterisk;
private ImportDeclaration() {
this(null, new Name(), false, false);
}
public ImportDeclaration(String name, boolean isStatic, boolean isAsterisk) {
// If the value of the isAsterisk parameter is true, we consider that we deliberately wanted to create an import
// declaration of the form x.* by specifying only x.
// On the other hand, if the isAsterisk parameter is false, we can check that we haven't tried to directly
// create an import declaration of the form x.*.
this(null, getNameFromString(name), isStatic, isAsterisk ? isAsterisk : hasAsterisk(name));
}
@AllFieldsConstructor
public ImportDeclaration(Name name, boolean isStatic, boolean isAsterisk) {
this(null, name, isStatic, isAsterisk);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ImportDeclaration(TokenRange tokenRange, Name name, boolean isStatic, boolean isAsterisk) {
super(tokenRange);
setName(name);
setStatic(isStatic);
setAsterisk(isAsterisk);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* Returns true if the specified name is qualified
*/
private static boolean isQualified(String name) {
return name != null & name.indexOf(".") >= 0;
}
/**
* Returns true if the specified name has an asterisk
*/
private static boolean hasAsterisk(String name) {
return name != null & name.endsWith("*");
}
/**
* Returns the name of the import.
* The name can have a qualifier.
* For example, the java.util.Map class would have a qualifier java.util and an identifier name
* and the qualifier would have a qualifier java and an identifier util and so on.
*/
private static Name getNameFromString(String name) {
if (!isQualified(name)) {
return new Name(name);
}
if (hasAsterisk(name)) {
name = name.substring(0, name.length() - 2);
}
int lastSeparator = name.lastIndexOf(".");
return new Name(getNameFromString(name.substring(0, lastSeparator)), name.substring(lastSeparator + 1));
}
/**
* Retrieves the name of the import (.* is not included.)
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Name getName() {
return name;
}
/**
* Return if the import ends with "*".
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public boolean isAsterisk() {
return isAsterisk;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public boolean isStatic() {
return isStatic;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ImportDeclaration setAsterisk(final boolean isAsterisk) {
if (isAsterisk == this.isAsterisk) {
return this;
}
notifyPropertyChange(ObservableProperty.ASTERISK, this.isAsterisk, isAsterisk);
this.isAsterisk = isAsterisk;
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ImportDeclaration setName(final Name name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ImportDeclaration setStatic(final boolean isStatic) {
if (isStatic == this.isStatic) {
return this;
}
notifyPropertyChange(ObservableProperty.STATIC, this.isStatic, isStatic);
this.isStatic = isStatic;
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ImportDeclaration clone() {
return (ImportDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ImportDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.importDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == name) {
setName((Name) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
}

View File

@@ -0,0 +1,198 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.ast.NodeList.toNodeList;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.ModifierMetaModel;
import java.util.Arrays;
/**
* A modifier, like private, public, or volatile.
*/
public class Modifier extends Node {
public static Modifier publicModifier() {
return new Modifier(Keyword.PUBLIC);
}
public static Modifier protectedModifier() {
return new Modifier(Keyword.PROTECTED);
}
public static Modifier privateModifier() {
return new Modifier(Keyword.PRIVATE);
}
public static Modifier abstractModifier() {
return new Modifier(Keyword.ABSTRACT);
}
public static Modifier staticModifier() {
return new Modifier(Keyword.STATIC);
}
public static Modifier finalModifier() {
return new Modifier(Keyword.FINAL);
}
public static Modifier transientModifier() {
return new Modifier(Keyword.TRANSIENT);
}
public static Modifier volatileModifier() {
return new Modifier(Keyword.VOLATILE);
}
public static Modifier synchronizedModifier() {
return new Modifier(Keyword.SYNCHRONIZED);
}
public static Modifier nativeModifier() {
return new Modifier(Keyword.NATIVE);
}
public static Modifier strictfpModifier() {
return new Modifier(Keyword.STRICTFP);
}
public static Modifier transitiveModifier() {
return new Modifier(Keyword.TRANSITIVE);
}
public static Modifier sealedModifier() {
return new Modifier(Keyword.SEALED);
}
public static Modifier nonSealedModifier() {
return new Modifier(Keyword.NON_SEALED);
}
/**
* The Java modifier keywords.
*/
public enum Keyword {
DEFAULT("default"),
PUBLIC("public"),
PROTECTED("protected"),
PRIVATE("private"),
ABSTRACT("abstract"),
STATIC("static"),
FINAL("final"),
TRANSIENT("transient"),
VOLATILE("volatile"),
SYNCHRONIZED("synchronized"),
NATIVE("native"),
STRICTFP("strictfp"),
TRANSITIVE("transitive"),
SEALED("sealed"),
NON_SEALED("non-sealed");
private final String codeRepresentation;
Keyword(String codeRepresentation) {
this.codeRepresentation = codeRepresentation;
}
/**
* @return the Java keyword represented by this enum constant.
*/
public String asString() {
return codeRepresentation;
}
}
private Keyword keyword;
public Modifier() {
this(Keyword.PUBLIC);
}
@AllFieldsConstructor
public Modifier(Keyword keyword) {
this(null, keyword);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public Modifier(TokenRange tokenRange, Keyword keyword) {
super(tokenRange);
setKeyword(keyword);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Keyword getKeyword() {
return keyword;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Modifier setKeyword(final Keyword keyword) {
assertNotNull(keyword);
if (keyword == this.keyword) {
return this;
}
notifyPropertyChange(ObservableProperty.KEYWORD, this.keyword, keyword);
this.keyword = keyword;
return this;
}
/**
* Utility method that instantiaties "Modifier"s for the keywords,
* and puts them in a NodeList.
*/
public static NodeList<Modifier> createModifierList(Modifier.Keyword... modifiers) {
return Arrays.stream(modifiers).map(Modifier::new).collect(toNodeList());
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public Modifier clone() {
return (Modifier) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ModifierMetaModel getMetaModel() {
return JavaParserMetaModel.modifierMetaModel;
}
}

View File

@@ -0,0 +1,650 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import com.github.javaparser.HasParentNode;
import com.github.javaparser.ast.observer.AstObserver;
import com.github.javaparser.ast.observer.Observable;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.Visitable;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.InternalProperty;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A list of nodes.
* It usually has a parent node.
* Unlike normal Nodes, this does not mean that it is a child of that parent.
* Instead, this list will make every node it contains a child of its parent.
* This way, a NodeList does not create an extra level inside the AST.
*
* @param <N> the type of nodes contained.
*/
public class NodeList<N extends Node>
implements List<N>, Iterable<N>, HasParentNode<NodeList<N>>, Visitable, Observable {
@InternalProperty
private final List<N> innerList = new ArrayList<>(0);
private Node parentNode;
private final List<AstObserver> observers = new ArrayList<>();
public NodeList() {
parentNode = null;
}
public NodeList(Collection<N> n) {
this.addAll(n);
}
@SafeVarargs
public NodeList(N... n) {
this.addAll(Arrays.asList(n));
}
@Override
public boolean add(N node) {
notifyElementAdded(innerList.size(), node);
own(node);
return innerList.add(node);
}
private void own(N node) {
if (node == null) {
return;
}
setAsParentNodeOf(node);
}
public boolean remove(Node node) {
int index = innerList.indexOf(node);
if (index != -1) {
notifyElementRemoved(index, node);
node.setParentNode(null);
}
return innerList.remove(node);
}
public N removeFirst() {
return remove(0);
}
public N removeLast() {
return remove(innerList.size() - 1);
}
@SafeVarargs
public static <X extends Node> NodeList<X> nodeList(X... nodes) {
final NodeList<X> nodeList = new NodeList<>();
Collections.addAll(nodeList, nodes);
return nodeList;
}
public static <X extends Node> NodeList<X> nodeList(Collection<X> nodes) {
final NodeList<X> nodeList = new NodeList<>();
nodeList.addAll(nodes);
return nodeList;
}
public static <X extends Node> NodeList<X> nodeList(NodeList<X> nodes) {
final NodeList<X> nodeList = new NodeList<>();
nodeList.addAll(nodes);
return nodeList;
}
public boolean contains(N node) {
return innerList.contains(node);
}
@Override
public int size() {
return innerList.size();
}
@Override
public N get(int i) {
return innerList.get(i);
}
@Override
public Iterator<N> iterator() {
// Custom iterator required, to ensure that the relevant `notifyElement...` methods are called.
return new NodeListIterator(innerList);
}
@Override
public N set(int index, N element) {
if (index < 0 || index >= innerList.size()) {
throw new IllegalArgumentException("Illegal index. The index should be between 0 and " + innerList.size()
+ " excluded. It is instead " + index);
}
if (element == innerList.get(index)) {
return element;
}
notifyElementReplaced(index, element);
innerList.get(index).setParentNode(null);
setAsParentNodeOf(element);
return innerList.set(index, element);
}
@Override
public N remove(int index) {
notifyElementRemoved(index, innerList.get(index));
N remove = innerList.remove(index);
if (remove != null) remove.setParentNode(null);
return remove;
}
@Override
public boolean isEmpty() {
return innerList.isEmpty();
}
@Override
public void sort(Comparator<? super N> comparator) {
innerList.sort(comparator);
}
public void addAll(NodeList<N> otherList) {
for (N node : otherList) {
add(node);
}
}
@Override
public void add(int index, N node) {
notifyElementAdded(index, node);
own(node);
innerList.add(index, node);
}
/**
* Inserts the node before all other nodes.
*/
public NodeList<N> addFirst(N node) {
add(0, node);
return this;
}
/**
* Inserts the node after all other nodes. (This is simply an alias for add.)
*/
public NodeList<N> addLast(N node) {
add(node);
return this;
}
/**
* Inserts the node after afterThisNode.
*
* @throws IllegalArgumentException when afterThisNode is not in this list.
*/
public NodeList<N> addAfter(N node, N afterThisNode) {
int i = indexOf(afterThisNode);
if (i == -1) {
throw new IllegalArgumentException("Can't find node to insert after.");
}
add(i + 1, node);
return this;
}
/**
* Inserts the node before beforeThisNode.
*
* @throws IllegalArgumentException when beforeThisNode is not in this list.
*/
public NodeList<N> addBefore(N node, N beforeThisNode) {
int i = indexOf(beforeThisNode);
if (i == -1) {
throw new IllegalArgumentException("Can't find node to insert before.");
}
add(i, node);
return this;
}
/**
* @return the first node, or empty if the list is empty.
*/
public Optional<N> getFirst() {
if (isEmpty()) {
return Optional.empty();
}
return Optional.of(get(0));
}
/**
* @return the last node, or empty if the list is empty.
*/
public Optional<N> getLast() {
if (isEmpty()) {
return Optional.empty();
}
return Optional.of(get(size() - 1));
}
@Override
public Optional<Node> getParentNode() {
return Optional.ofNullable(parentNode);
}
/**
* Sets the parentNode
*
* @param parentNode the parentNode
* @return this, the NodeList
*/
@Override
public NodeList<N> setParentNode(Node parentNode) {
this.parentNode = parentNode;
setAsParentNodeOf(innerList);
return this;
}
@Override
public Node getParentNodeForChildren() {
return parentNode;
}
@Override
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* @see java.lang.Iterable#forEach(java.util.function.Consumer)
*/
@Override
public void forEach(Consumer<? super N> action) {
innerList.forEach(action);
}
/**
* @see java.util.List#contains(java.lang.Object)
*/
@Override
public boolean contains(Object o) {
return innerList.contains(o);
}
/**
* @see java.util.List#toArray()
*/
@Override
public Object[] toArray() {
return innerList.toArray();
}
/**
* @see java.util.List#toArray(java.lang.Object[])
*/
@Override
public <T> T[] toArray(T[] a) {
return innerList.toArray(a);
}
/**
* @see java.util.List#remove(java.lang.Object)
*/
@Override
public boolean remove(Object o) {
if (o instanceof Node) {
return remove((Node) o);
}
return false;
}
/**
* @see java.util.List#containsAll(java.util.Collection)
*/
@Override
public boolean containsAll(Collection<?> c) {
return innerList.containsAll(c);
}
/**
* @see java.util.List#addAll(java.util.Collection)
*/
@Override
public boolean addAll(Collection<? extends N> c) {
c.forEach(this::add);
return !c.isEmpty();
}
/**
* @see java.util.List#addAll(int, java.util.Collection)
*/
@Override
public boolean addAll(int index, Collection<? extends N> c) {
for (N e : c) {
add(index++, e);
}
return !c.isEmpty();
}
/**
* @see java.util.List#removeAll(java.util.Collection)
*/
@Override
public boolean removeAll(Collection<?> c) {
boolean changed = false;
for (Object e : c) {
changed = remove(e) || changed;
}
return changed;
}
/**
* @see java.util.List#retainAll(java.util.Collection)
*/
@Override
public boolean retainAll(Collection<?> c) {
boolean changed = false;
for (Object e : this.stream().filter(it -> !c.contains(it)).toArray()) {
if (!c.contains(e)) {
changed = remove(e) || changed;
}
}
return changed;
}
/**
* @see java.util.List#replaceAll(java.util.function.UnaryOperator)
*/
@Override
public void replaceAll(UnaryOperator<N> operator) {
for (int i = 0; i < this.size(); i++) {
set(i, operator.apply(this.get(i)));
}
}
/**
* @see java.util.Collection#removeIf(java.util.function.Predicate)
*/
@Override
public boolean removeIf(Predicate<? super N> filter) {
boolean changed = false;
for (Object e : this.stream().filter(filter).toArray()) {
changed = remove(e) || changed;
}
return changed;
}
/**
* @see java.util.List#clear()
*/
@Override
public void clear() {
while (!isEmpty()) {
remove(0);
}
}
/**
* @see java.util.List#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
return innerList.equals(o);
}
/**
* @see java.util.List#hashCode()
*/
@Override
public int hashCode() {
return innerList.hashCode();
}
/**
* @see java.util.List#indexOf(java.lang.Object)
*/
@Override
public int indexOf(Object o) {
return innerList.indexOf(o);
}
/**
* @see java.util.List#lastIndexOf(java.lang.Object)
*/
@Override
public int lastIndexOf(Object o) {
return innerList.lastIndexOf(o);
}
/**
* @see java.util.List#listIterator()
*/
@Override
public ListIterator<N> listIterator() {
// Custom iterator required, to ensure that the relevant `notifyElement...` methods are called.
return new NodeListIterator(innerList);
}
/**
* @see java.util.List#listIterator(int)
*/
@Override
public ListIterator<N> listIterator(int index) {
// Custom iterator required, to ensure that the relevant `notifyElement...` methods are called.
return new NodeListIterator(innerList, index);
}
/**
* @see java.util.Collection#parallelStream()
*/
@Override
public Stream<N> parallelStream() {
return innerList.parallelStream();
}
/**
* @see java.util.List#subList(int, int)
*/
@Override
public List<N> subList(int fromIndex, int toIndex) {
return innerList.subList(fromIndex, toIndex);
}
/**
* @see java.util.List#spliterator()
*/
@Override
public Spliterator<N> spliterator() {
return innerList.spliterator();
}
private void notifyElementAdded(int index, Node nodeAddedOrRemoved) {
this.observers.forEach(o -> o.listChange(this, AstObserver.ListChangeType.ADDITION, index, nodeAddedOrRemoved));
}
private void notifyElementRemoved(int index, Node nodeAddedOrRemoved) {
this.observers.forEach(o -> o.listChange(this, AstObserver.ListChangeType.REMOVAL, index, nodeAddedOrRemoved));
}
private void notifyElementReplaced(int index, Node nodeAddedOrRemoved) {
this.observers.forEach(o -> o.listReplacement(this, index, this.get(index), nodeAddedOrRemoved));
}
@Override
public void unregister(AstObserver observer) {
this.observers.remove(observer);
}
@Override
public void register(AstObserver observer) {
if (!this.observers.contains(observer)) {
this.observers.add(observer);
}
}
@Override
public boolean isRegistered(AstObserver observer) {
return this.observers.contains(observer);
}
/**
* Replaces the first node that is equal to "old" with "replacement".
*
* @return true if a replacement has happened.
*/
public boolean replace(N old, N replacement) {
int i = indexOf(old);
if (i == -1) {
return false;
}
set(i, replacement);
return true;
}
/**
* @return the opposite of isEmpty()
*/
public boolean isNonEmpty() {
return !isEmpty();
}
public void ifNonEmpty(Consumer<? super NodeList<N>> consumer) {
if (isNonEmpty()) consumer.accept(this);
}
public static <T extends Node> Collector<T, NodeList<T>, NodeList<T>> toNodeList() {
return Collector.of(NodeList::new, NodeList::add, (left, right) -> {
left.addAll(right);
return left;
});
}
private void setAsParentNodeOf(List<? extends Node> childNodes) {
if (childNodes != null) {
for (HasParentNode current : childNodes) {
current.setParentNode(getParentNodeForChildren());
}
}
}
private void setAsParentNodeOf(Node childNode) {
if (childNode != null) {
childNode.setParentNode(getParentNodeForChildren());
}
}
@Override
public String toString() {
return innerList.stream().map(Node::toString).collect(Collectors.joining(", ", "[", "]"));
}
protected class NodeListIterator implements ListIterator<N> {
ListIterator<N> iterator;
N current = null;
// initialize pointer to head of the list for iteration
public NodeListIterator(List<N> list) {
iterator = list.listIterator();
}
public NodeListIterator(List<N> list, int index) {
iterator = list.listIterator(index);
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public N next() {
current = iterator.next();
return current;
}
@Override
public boolean hasPrevious() {
return iterator.hasPrevious();
}
@Override
public N previous() {
current = iterator.previous();
return current;
}
@Override
public int nextIndex() {
return iterator.nextIndex();
}
@Override
public int previousIndex() {
return iterator.previousIndex();
}
@Override
public void remove() {
int index = innerList.indexOf(current);
if (index != -1) {
notifyElementRemoved(index, current);
current.setParentNode(null);
}
iterator.remove();
}
@Override
public void set(N n) {
int index = innerList.indexOf(current);
if (index < 0 || index >= innerList.size()) {
throw new IllegalArgumentException("Illegal index. The index should be between 0 and "
+ innerList.size() + " excluded. It is instead " + index);
}
if (n != innerList.get(index)) {
notifyElementReplaced(index, n);
innerList.get(index).setParentNode(null);
setAsParentNodeOf(n);
iterator.set(n);
}
}
@Override
public void add(N n) {
notifyElementAdded(innerList.size(), n);
own(n);
iterator.add(n);
}
@Override
public void forEachRemaining(Consumer<? super N> action) {
iterator.forEachRemaining(action);
}
}
}

View File

@@ -0,0 +1,187 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.Name;
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
import com.github.javaparser.ast.nodeTypes.NodeWithName;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.PackageDeclarationMetaModel;
/**
* A package declaration.
* <br>{@code package com.github.javaparser.ast;}
* <br>{@code @Wonderful package anything.can.be.annotated.nowadays;}
*
* @author Julio Vilmar Gesser
*/
public class PackageDeclaration extends Node
implements NodeWithAnnotations<PackageDeclaration>, NodeWithName<PackageDeclaration> {
private NodeList<AnnotationExpr> annotations = new NodeList<>();
private Name name;
public PackageDeclaration() {
this(null, new NodeList<>(), new Name());
}
public PackageDeclaration(Name name) {
this(null, new NodeList<>(), name);
}
@AllFieldsConstructor
public PackageDeclaration(NodeList<AnnotationExpr> annotations, Name name) {
this(null, annotations, name);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public PackageDeclaration(TokenRange tokenRange, NodeList<AnnotationExpr> annotations, Name name) {
super(tokenRange);
setAnnotations(annotations);
setName(name);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* Retrieves the list of annotations declared before the package
* declaration. Return {@code null} if there are no annotations.
*
* @return list of annotations or {@code null}
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<AnnotationExpr> getAnnotations() {
return annotations;
}
/**
* Return the name expression of the package.
*
* @return the name of the package
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Name getName() {
return name;
}
/**
* @param annotations the annotations to set
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public PackageDeclaration setAnnotations(final NodeList<AnnotationExpr> annotations) {
assertNotNull(annotations);
if (annotations == this.annotations) {
return this;
}
notifyPropertyChange(ObservableProperty.ANNOTATIONS, this.annotations, annotations);
if (this.annotations != null) this.annotations.setParentNode(null);
this.annotations = annotations;
setAsParentNodeOf(annotations);
return this;
}
/**
* Sets the name of this package declaration.
*
* @param name the name to set
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public PackageDeclaration setName(final Name name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public PackageDeclaration clone() {
return (PackageDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public PackageDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.packageDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.set(i, (AnnotationExpr) replacementNode);
return true;
}
}
if (node == name) {
setName((Name) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
}

View File

@@ -0,0 +1,138 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithAbstractModifier;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.AnnotationDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedAnnotationDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* An annotation type declaration.<br>{@code @interface X { ... }}
*
* @author Julio Vilmar Gesser
*/
public class AnnotationDeclaration extends TypeDeclaration<AnnotationDeclaration>
implements NodeWithAbstractModifier<AnnotationDeclaration>, Resolvable<ResolvedAnnotationDeclaration> {
public AnnotationDeclaration() {
this(null, new NodeList<>(), new NodeList<>(), new SimpleName(), new NodeList<>());
}
public AnnotationDeclaration(NodeList<Modifier> modifiers, String name) {
this(null, modifiers, new NodeList<>(), new SimpleName(name), new NodeList<>());
}
@AllFieldsConstructor
public AnnotationDeclaration(
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
SimpleName name,
NodeList<BodyDeclaration<?>> members) {
this(null, modifiers, annotations, name, members);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public AnnotationDeclaration(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
SimpleName name,
NodeList<BodyDeclaration<?>> members) {
super(tokenRange, modifiers, annotations, name, members);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public AnnotationDeclaration clone() {
return (AnnotationDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public AnnotationDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.annotationDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isAnnotationDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public AnnotationDeclaration asAnnotationDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifAnnotationDeclaration(Consumer<AnnotationDeclaration> action) {
action.accept(this);
}
@Override
public ResolvedAnnotationDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedAnnotationDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<AnnotationDeclaration> toAnnotationDeclaration() {
return Optional.of(this);
}
@Override
public FieldDeclaration addField(Type type, String name, Modifier.Keyword... modifiers) {
throw new IllegalStateException("Cannot add a field to an annotation declaration.");
}
}

View File

@@ -0,0 +1,301 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithJavadoc;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithAbstractModifier;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithPublicModifier;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.AnnotationMemberDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedAnnotationMemberDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* The "int id();" in {@code @interface X { int id(); }}
* <p>
* <br>All annotations preceding the type will be set on this object, not on the type. JavaParser doesn't know if it
* they are applicable to the method or the type.
*
* @author Julio Vilmar Gesser
*/
public class AnnotationMemberDeclaration extends BodyDeclaration<AnnotationMemberDeclaration>
implements NodeWithJavadoc<AnnotationMemberDeclaration>,
NodeWithSimpleName<AnnotationMemberDeclaration>,
NodeWithType<AnnotationMemberDeclaration, Type>,
NodeWithPublicModifier<AnnotationMemberDeclaration>,
NodeWithAbstractModifier<AnnotationMemberDeclaration>,
Resolvable<ResolvedAnnotationMemberDeclaration> {
private NodeList<Modifier> modifiers;
private Type type;
private SimpleName name;
@OptionalProperty
private Expression defaultValue;
public AnnotationMemberDeclaration() {
this(null, new NodeList<>(), new NodeList<>(), new ClassOrInterfaceType(), new SimpleName(), null);
}
public AnnotationMemberDeclaration(NodeList<Modifier> modifiers, Type type, String name, Expression defaultValue) {
this(null, modifiers, new NodeList<>(), type, new SimpleName(name), defaultValue);
}
@AllFieldsConstructor
public AnnotationMemberDeclaration(
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
Type type,
SimpleName name,
Expression defaultValue) {
this(null, modifiers, annotations, type, name, defaultValue);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public AnnotationMemberDeclaration(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
Type type,
SimpleName name,
Expression defaultValue) {
super(tokenRange, annotations);
setModifiers(modifiers);
setType(type);
setName(name);
setDefaultValue(defaultValue);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<Expression> getDefaultValue() {
return Optional.ofNullable(defaultValue);
}
/**
* Return the modifiers of this member declaration.
*
* @return modifiers
* @see Modifier
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Modifier> getModifiers() {
return modifiers;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Type getType() {
return type;
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public AnnotationMemberDeclaration removeDefaultValue() {
return setDefaultValue((Expression) null);
}
/**
* Sets the default value
*
* @param defaultValue the default value, can be null
* @return this, the AnnotationMemberDeclaration
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public AnnotationMemberDeclaration setDefaultValue(final Expression defaultValue) {
if (defaultValue == this.defaultValue) {
return this;
}
notifyPropertyChange(ObservableProperty.DEFAULT_VALUE, this.defaultValue, defaultValue);
if (this.defaultValue != null) this.defaultValue.setParentNode(null);
this.defaultValue = defaultValue;
setAsParentNodeOf(defaultValue);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public AnnotationMemberDeclaration setModifiers(final NodeList<Modifier> modifiers) {
assertNotNull(modifiers);
if (modifiers == this.modifiers) {
return this;
}
notifyPropertyChange(ObservableProperty.MODIFIERS, this.modifiers, modifiers);
if (this.modifiers != null) this.modifiers.setParentNode(null);
this.modifiers = modifiers;
setAsParentNodeOf(modifiers);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public AnnotationMemberDeclaration setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public AnnotationMemberDeclaration setType(final Type type) {
assertNotNull(type);
if (type == this.type) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE, this.type, type);
if (this.type != null) this.type.setParentNode(null);
this.type = type;
setAsParentNodeOf(type);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
if (defaultValue != null) {
if (node == defaultValue) {
removeDefaultValue();
return true;
}
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public AnnotationMemberDeclaration clone() {
return (AnnotationMemberDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public AnnotationMemberDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.annotationMemberDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (defaultValue != null) {
if (node == defaultValue) {
setDefaultValue((Expression) replacementNode);
return true;
}
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.set(i, (Modifier) replacementNode);
return true;
}
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
if (node == type) {
setType((Type) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isAnnotationMemberDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public AnnotationMemberDeclaration asAnnotationMemberDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifAnnotationMemberDeclaration(Consumer<AnnotationMemberDeclaration> action) {
action.accept(this);
}
@Override
public ResolvedAnnotationMemberDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedAnnotationMemberDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<AnnotationMemberDeclaration> toAnnotationMemberDeclaration() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,386 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.CodeGenerationUtils.f;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.metamodel.BodyDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* Any declaration that can appear between the { and } of a class, interface, enum, or record.
*
* @author Julio Vilmar Gesser
*/
public abstract class BodyDeclaration<T extends BodyDeclaration<?>> extends Node implements NodeWithAnnotations<T> {
private NodeList<AnnotationExpr> annotations;
public BodyDeclaration() {
this(null, new NodeList<>());
}
@AllFieldsConstructor
public BodyDeclaration(NodeList<AnnotationExpr> annotations) {
this(null, annotations);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public BodyDeclaration(TokenRange tokenRange, NodeList<AnnotationExpr> annotations) {
super(tokenRange);
setAnnotations(annotations);
customInitialization();
}
protected BodyDeclaration(TokenRange range) {
this(range, new NodeList<>());
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<AnnotationExpr> getAnnotations() {
return annotations;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
@SuppressWarnings("unchecked")
public T setAnnotations(final NodeList<AnnotationExpr> annotations) {
assertNotNull(annotations);
if (annotations == this.annotations) {
return (T) this;
}
notifyPropertyChange(ObservableProperty.ANNOTATIONS, this.annotations, annotations);
if (this.annotations != null) this.annotations.setParentNode(null);
this.annotations = annotations;
setAsParentNodeOf(annotations);
return (T) this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public BodyDeclaration<?> clone() {
return (BodyDeclaration<?>) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public BodyDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.bodyDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.set(i, (AnnotationExpr) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isAnnotationDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public AnnotationDeclaration asAnnotationDeclaration() {
throw new IllegalStateException(f(
"%s is not AnnotationDeclaration, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isAnnotationMemberDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public AnnotationMemberDeclaration asAnnotationMemberDeclaration() {
throw new IllegalStateException(f(
"%s is not AnnotationMemberDeclaration, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isCallableDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public CallableDeclaration asCallableDeclaration() {
throw new IllegalStateException(f(
"%s is not CallableDeclaration, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isClassOrInterfaceDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ClassOrInterfaceDeclaration asClassOrInterfaceDeclaration() {
throw new IllegalStateException(f(
"%s is not ClassOrInterfaceDeclaration, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isConstructorDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ConstructorDeclaration asConstructorDeclaration() {
throw new IllegalStateException(f(
"%s is not ConstructorDeclaration, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isCompactConstructorDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public CompactConstructorDeclaration asCompactConstructorDeclaration() {
throw new IllegalStateException(f(
"%s is not CompactConstructorDeclaration, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isEnumConstantDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public EnumConstantDeclaration asEnumConstantDeclaration() {
throw new IllegalStateException(f(
"%s is not EnumConstantDeclaration, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isEnumDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public EnumDeclaration asEnumDeclaration() {
throw new IllegalStateException(
f("%s is not EnumDeclaration, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isFieldDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public FieldDeclaration asFieldDeclaration() {
throw new IllegalStateException(
f("%s is not FieldDeclaration, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isInitializerDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public InitializerDeclaration asInitializerDeclaration() {
throw new IllegalStateException(f(
"%s is not InitializerDeclaration, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isMethodDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public MethodDeclaration asMethodDeclaration() {
throw new IllegalStateException(
f("%s is not MethodDeclaration, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isTypeDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public TypeDeclaration asTypeDeclaration() {
throw new IllegalStateException(
f("%s is not TypeDeclaration, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifAnnotationDeclaration(Consumer<AnnotationDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifAnnotationMemberDeclaration(Consumer<AnnotationMemberDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifCallableDeclaration(Consumer<CallableDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifClassOrInterfaceDeclaration(Consumer<ClassOrInterfaceDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifConstructorDeclaration(Consumer<ConstructorDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifEnumConstantDeclaration(Consumer<EnumConstantDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifEnumDeclaration(Consumer<EnumDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifFieldDeclaration(Consumer<FieldDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifInitializerDeclaration(Consumer<InitializerDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifMethodDeclaration(Consumer<MethodDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifTypeDeclaration(Consumer<TypeDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifRecordDeclaration(Consumer<RecordDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifCompactConstructorDeclaration(Consumer<CompactConstructorDeclaration> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<AnnotationDeclaration> toAnnotationDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<AnnotationMemberDeclaration> toAnnotationMemberDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<CallableDeclaration> toCallableDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ClassOrInterfaceDeclaration> toClassOrInterfaceDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ConstructorDeclaration> toConstructorDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<EnumConstantDeclaration> toEnumConstantDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<EnumDeclaration> toEnumDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<FieldDeclaration> toFieldDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<InitializerDeclaration> toInitializerDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<MethodDeclaration> toMethodDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<TypeDeclaration> toTypeDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isRecordDeclaration() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public RecordDeclaration asRecordDeclaration() {
throw new IllegalStateException(
f("%s is not RecordDeclaration, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<RecordDeclaration> toRecordDeclaration() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<CompactConstructorDeclaration> toCompactConstructorDeclaration() {
return Optional.empty();
}
}

View File

@@ -0,0 +1,468 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNotNull;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.*;
import com.github.javaparser.ast.nodeTypes.modifiers.*;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ArrayType;
import com.github.javaparser.ast.type.ReferenceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.metamodel.CallableDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
/**
* Represents a declaration which is callable eg. a method or a constructor.
*/
public abstract class CallableDeclaration<T extends CallableDeclaration<?>> extends BodyDeclaration<T>
implements NodeWithAccessModifiers<T>,
NodeWithDeclaration,
NodeWithSimpleName<T>,
NodeWithParameters<T>,
NodeWithThrownExceptions<T>,
NodeWithTypeParameters<T>,
NodeWithJavadoc<T>,
NodeWithAbstractModifier<T>,
NodeWithStaticModifier<T>,
NodeWithFinalModifier<T>,
NodeWithStrictfpModifier<T> {
private NodeList<Modifier> modifiers;
private NodeList<TypeParameter> typeParameters;
private SimpleName name;
private NodeList<Parameter> parameters;
private NodeList<ReferenceType> thrownExceptions;
@OptionalProperty
private ReceiverParameter receiverParameter;
@AllFieldsConstructor
CallableDeclaration(
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
NodeList<TypeParameter> typeParameters,
SimpleName name,
NodeList<Parameter> parameters,
NodeList<ReferenceType> thrownExceptions,
ReceiverParameter receiverParameter) {
this(null, modifiers, annotations, typeParameters, name, parameters, thrownExceptions, receiverParameter);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public CallableDeclaration(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
NodeList<TypeParameter> typeParameters,
SimpleName name,
NodeList<Parameter> parameters,
NodeList<ReferenceType> thrownExceptions,
ReceiverParameter receiverParameter) {
super(tokenRange, annotations);
setModifiers(modifiers);
setTypeParameters(typeParameters);
setName(name);
setParameters(parameters);
setThrownExceptions(thrownExceptions);
setReceiverParameter(receiverParameter);
customInitialization();
}
/**
* Return the modifiers of this member declaration.
*
* @return modifiers
* @see Modifier
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Modifier> getModifiers() {
return modifiers;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
@SuppressWarnings("unchecked")
public T setModifiers(final NodeList<Modifier> modifiers) {
assertNotNull(modifiers);
if (modifiers == this.modifiers) {
return (T) this;
}
notifyPropertyChange(ObservableProperty.MODIFIERS, this.modifiers, modifiers);
if (this.modifiers != null) this.modifiers.setParentNode(null);
this.modifiers = modifiers;
setAsParentNodeOf(modifiers);
return (T) this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
@SuppressWarnings("unchecked")
public T setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return (T) this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return (T) this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Parameter> getParameters() {
return parameters;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
@SuppressWarnings("unchecked")
public T setParameters(final NodeList<Parameter> parameters) {
assertNotNull(parameters);
if (parameters == this.parameters) {
return (T) this;
}
notifyPropertyChange(ObservableProperty.PARAMETERS, this.parameters, parameters);
if (this.parameters != null) this.parameters.setParentNode(null);
this.parameters = parameters;
setAsParentNodeOf(parameters);
return (T) this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<ReferenceType> getThrownExceptions() {
return thrownExceptions;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
@SuppressWarnings("unchecked")
public T setThrownExceptions(final NodeList<ReferenceType> thrownExceptions) {
assertNotNull(thrownExceptions);
if (thrownExceptions == this.thrownExceptions) {
return (T) this;
}
notifyPropertyChange(ObservableProperty.THROWN_EXCEPTIONS, this.thrownExceptions, thrownExceptions);
if (this.thrownExceptions != null) this.thrownExceptions.setParentNode(null);
this.thrownExceptions = thrownExceptions;
setAsParentNodeOf(thrownExceptions);
return (T) this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<TypeParameter> getTypeParameters() {
return typeParameters;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
@SuppressWarnings("unchecked")
public T setTypeParameters(final NodeList<TypeParameter> typeParameters) {
assertNotNull(typeParameters);
if (typeParameters == this.typeParameters) {
return (T) this;
}
notifyPropertyChange(ObservableProperty.TYPE_PARAMETERS, this.typeParameters, typeParameters);
if (this.typeParameters != null) this.typeParameters.setParentNode(null);
this.typeParameters = typeParameters;
setAsParentNodeOf(typeParameters);
return (T) this;
}
protected String appendThrowsIfRequested(boolean includingThrows) {
StringBuilder sb = new StringBuilder();
if (includingThrows) {
boolean firstThrow = true;
for (ReferenceType thr : getThrownExceptions()) {
if (firstThrow) {
firstThrow = false;
sb.append(" throws ");
} else {
sb.append(", ");
}
sb.append(thr.toString(prettyPrinterNoCommentsConfiguration));
}
}
return sb.toString();
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.remove(i);
return true;
}
}
for (int i = 0; i < parameters.size(); i++) {
if (parameters.get(i) == node) {
parameters.remove(i);
return true;
}
}
if (receiverParameter != null) {
if (node == receiverParameter) {
removeReceiverParameter();
return true;
}
}
for (int i = 0; i < thrownExceptions.size(); i++) {
if (thrownExceptions.get(i) == node) {
thrownExceptions.remove(i);
return true;
}
}
for (int i = 0; i < typeParameters.size(); i++) {
if (typeParameters.get(i) == node) {
typeParameters.remove(i);
return true;
}
}
return super.remove(node);
}
/**
* A method or constructor signature.
* <p/>Note that since JavaParser has no real knowledge of types - only the text found in the source file - using
* this will fail in some cases. (java.util.String != String for example, and generics are not taken into account.)
*/
public static class Signature {
private final String name;
private final List<Type> parameterTypes;
private Signature(String name, List<Type> parameterTypes) {
this.name = name;
this.parameterTypes = parameterTypes;
}
public String getName() {
return name;
}
public List<Type> getParameterTypes() {
return parameterTypes;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Signature signature = (Signature) o;
if (!name.equals(signature.name)) return false;
if (!parameterTypes.equals(signature.parameterTypes)) return false;
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + parameterTypes.hashCode();
return result;
}
public String asString() {
return parameterTypes.stream().map(Type::asString).collect(joining(", ", name + "(", ")"));
}
@Override
public String toString() {
return asString();
}
}
public Signature getSignature() {
return new Signature(
getName().getIdentifier(),
getParameters().stream()
.map(this::getTypeWithVarargsAsArray)
.map(this::stripGenerics)
.map(this::stripAnnotations)
.collect(toList()));
}
private Type stripAnnotations(Type type) {
if (type instanceof NodeWithAnnotations) {
((NodeWithAnnotations) type).setAnnotations(new NodeList<>());
}
return type;
}
private Type stripGenerics(Type type) {
if (type instanceof NodeWithTypeArguments) {
((NodeWithTypeArguments) type).setTypeArguments((NodeList<Type>) null);
}
return type;
}
private Type getTypeWithVarargsAsArray(Parameter p) {
/* A signature includes the varargs ellipsis.
This is a field on parameter which we lose when we only get the type,
so we represent it as an additional [] on the type. */
Type t = p.getType().clone();
if (p.isVarArgs()) {
t = new ArrayType(t);
}
return t;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public CallableDeclaration<?> clone() {
return (CallableDeclaration<?>) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public CallableDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.callableDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.set(i, (Modifier) replacementNode);
return true;
}
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
for (int i = 0; i < parameters.size(); i++) {
if (parameters.get(i) == node) {
parameters.set(i, (Parameter) replacementNode);
return true;
}
}
if (receiverParameter != null) {
if (node == receiverParameter) {
setReceiverParameter((ReceiverParameter) replacementNode);
return true;
}
}
for (int i = 0; i < thrownExceptions.size(); i++) {
if (thrownExceptions.get(i) == node) {
thrownExceptions.set(i, (ReferenceType) replacementNode);
return true;
}
}
for (int i = 0; i < typeParameters.size(); i++) {
if (typeParameters.get(i) == node) {
typeParameters.set(i, (TypeParameter) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isCallableDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public CallableDeclaration asCallableDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifCallableDeclaration(Consumer<CallableDeclaration> action) {
action.accept(this);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<ReceiverParameter> getReceiverParameter() {
return Optional.ofNullable(receiverParameter);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
@SuppressWarnings("unchecked")
public T setReceiverParameter(final ReceiverParameter receiverParameter) {
if (receiverParameter == this.receiverParameter) {
return (T) this;
}
notifyPropertyChange(ObservableProperty.RECEIVER_PARAMETER, this.receiverParameter, receiverParameter);
if (this.receiverParameter != null) this.receiverParameter.setParentNode(null);
this.receiverParameter = receiverParameter;
setAsParentNodeOf(receiverParameter);
return (T) this;
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public CallableDeclaration removeReceiverParameter() {
return setReceiverParameter((ReceiverParameter) null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<CallableDeclaration> toCallableDeclaration() {
return Optional.of(this);
}
/*
* Returns true if the method has a variable number of arguments
*/
public boolean isVariableArityMethod() {
return getParameters().size() > 0 && getParameters().getLast().get().isVarArgs();
}
/*
* Returns true if the method has a fixed number of arguments
*/
public boolean isFixedArityMethod() {
return !isVariableArityMethod();
}
}

View File

@@ -0,0 +1,377 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithExtends;
import com.github.javaparser.ast.nodeTypes.NodeWithImplements;
import com.github.javaparser.ast.nodeTypes.NodeWithTypeParameters;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithAbstractModifier;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithFinalModifier;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.LocalClassDeclarationStmt;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.ClassOrInterfaceDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A definition of a class or interface.<br>{@code class X { ... }}<br>{@code interface X { ... }}
*
* @author Julio Vilmar Gesser
*/
public class ClassOrInterfaceDeclaration extends TypeDeclaration<ClassOrInterfaceDeclaration>
implements NodeWithImplements<ClassOrInterfaceDeclaration>,
NodeWithExtends<ClassOrInterfaceDeclaration>,
NodeWithTypeParameters<ClassOrInterfaceDeclaration>,
NodeWithAbstractModifier<ClassOrInterfaceDeclaration>,
NodeWithFinalModifier<ClassOrInterfaceDeclaration>,
Resolvable<ResolvedReferenceTypeDeclaration> {
private boolean isInterface;
private NodeList<TypeParameter> typeParameters;
// Can contain more than one item if this is an interface
private NodeList<ClassOrInterfaceType> extendedTypes;
private NodeList<ClassOrInterfaceType> implementedTypes;
private NodeList<ClassOrInterfaceType> permittedTypes;
public ClassOrInterfaceDeclaration() {
this(
null,
new NodeList<>(),
new NodeList<>(),
false,
new SimpleName(),
new NodeList<>(),
new NodeList<>(),
new NodeList<>(),
new NodeList<>(),
new NodeList<>());
}
public ClassOrInterfaceDeclaration(
final NodeList<Modifier> modifiers, final boolean isInterface, final String name) {
this(
null,
modifiers,
new NodeList<>(),
isInterface,
new SimpleName(name),
new NodeList<>(),
new NodeList<>(),
new NodeList<>(),
new NodeList<>(),
new NodeList<>());
}
@AllFieldsConstructor
public ClassOrInterfaceDeclaration(
final NodeList<Modifier> modifiers,
final NodeList<AnnotationExpr> annotations,
final boolean isInterface,
final SimpleName name,
final NodeList<TypeParameter> typeParameters,
final NodeList<ClassOrInterfaceType> extendedTypes,
final NodeList<ClassOrInterfaceType> implementedTypes,
final NodeList<ClassOrInterfaceType> permittedTypes,
final NodeList<BodyDeclaration<?>> members) {
this(
null,
modifiers,
annotations,
isInterface,
name,
typeParameters,
extendedTypes,
implementedTypes,
permittedTypes,
members);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ClassOrInterfaceDeclaration(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
boolean isInterface,
SimpleName name,
NodeList<TypeParameter> typeParameters,
NodeList<ClassOrInterfaceType> extendedTypes,
NodeList<ClassOrInterfaceType> implementedTypes,
NodeList<ClassOrInterfaceType> permittedTypes,
NodeList<BodyDeclaration<?>> members) {
super(tokenRange, modifiers, annotations, name, members);
setInterface(isInterface);
setTypeParameters(typeParameters);
setExtendedTypes(extendedTypes);
setImplementedTypes(implementedTypes);
setPermittedTypes(permittedTypes);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<ClassOrInterfaceType> getExtendedTypes() {
return extendedTypes;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<ClassOrInterfaceType> getImplementedTypes() {
return implementedTypes;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<ClassOrInterfaceType> getPermittedTypes() {
return permittedTypes;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<TypeParameter> getTypeParameters() {
return typeParameters;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public boolean isInterface() {
return isInterface;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ClassOrInterfaceDeclaration setExtendedTypes(final NodeList<ClassOrInterfaceType> extendedTypes) {
assertNotNull(extendedTypes);
if (extendedTypes == this.extendedTypes) {
return this;
}
notifyPropertyChange(ObservableProperty.EXTENDED_TYPES, this.extendedTypes, extendedTypes);
if (this.extendedTypes != null) this.extendedTypes.setParentNode(null);
this.extendedTypes = extendedTypes;
setAsParentNodeOf(extendedTypes);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ClassOrInterfaceDeclaration setImplementedTypes(final NodeList<ClassOrInterfaceType> implementedTypes) {
assertNotNull(implementedTypes);
if (implementedTypes == this.implementedTypes) {
return this;
}
notifyPropertyChange(ObservableProperty.IMPLEMENTED_TYPES, this.implementedTypes, implementedTypes);
if (this.implementedTypes != null) this.implementedTypes.setParentNode(null);
this.implementedTypes = implementedTypes;
setAsParentNodeOf(implementedTypes);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ClassOrInterfaceDeclaration setPermittedTypes(final NodeList<ClassOrInterfaceType> permittedTypes) {
assertNotNull(permittedTypes);
if (permittedTypes == this.permittedTypes) {
return this;
}
notifyPropertyChange(ObservableProperty.PERMITTED_TYPES, this.permittedTypes, permittedTypes);
if (this.permittedTypes != null) this.permittedTypes.setParentNode(null);
this.permittedTypes = permittedTypes;
setAsParentNodeOf(permittedTypes);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ClassOrInterfaceDeclaration setInterface(final boolean isInterface) {
if (isInterface == this.isInterface) {
return this;
}
notifyPropertyChange(ObservableProperty.INTERFACE, this.isInterface, isInterface);
this.isInterface = isInterface;
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ClassOrInterfaceDeclaration setTypeParameters(final NodeList<TypeParameter> typeParameters) {
assertNotNull(typeParameters);
if (typeParameters == this.typeParameters) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE_PARAMETERS, this.typeParameters, typeParameters);
if (this.typeParameters != null) this.typeParameters.setParentNode(null);
this.typeParameters = typeParameters;
setAsParentNodeOf(typeParameters);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < extendedTypes.size(); i++) {
if (extendedTypes.get(i) == node) {
extendedTypes.remove(i);
return true;
}
}
for (int i = 0; i < implementedTypes.size(); i++) {
if (implementedTypes.get(i) == node) {
implementedTypes.remove(i);
return true;
}
}
for (int i = 0; i < permittedTypes.size(); i++) {
if (permittedTypes.get(i) == node) {
permittedTypes.remove(i);
return true;
}
}
for (int i = 0; i < typeParameters.size(); i++) {
if (typeParameters.get(i) == node) {
typeParameters.remove(i);
return true;
}
}
return super.remove(node);
}
/**
* @return is this class's parent a LocalClassDeclarationStmt ?
*/
public boolean isLocalClassDeclaration() {
return getParentNode().map(p -> p instanceof LocalClassDeclarationStmt).orElse(false);
}
@Override
public Optional<String> getFullyQualifiedName() {
if (isLocalClassDeclaration()) {
return Optional.empty();
}
return super.getFullyQualifiedName();
}
/**
* @return is this an inner class?
* NOTE: many people are confused over terminology. Refer to https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html .
*/
public boolean isInnerClass() {
return isNestedType() && !isInterface && !isStatic();
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ClassOrInterfaceDeclaration clone() {
return (ClassOrInterfaceDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ClassOrInterfaceDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.classOrInterfaceDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < extendedTypes.size(); i++) {
if (extendedTypes.get(i) == node) {
extendedTypes.set(i, (ClassOrInterfaceType) replacementNode);
return true;
}
}
for (int i = 0; i < implementedTypes.size(); i++) {
if (implementedTypes.get(i) == node) {
implementedTypes.set(i, (ClassOrInterfaceType) replacementNode);
return true;
}
}
for (int i = 0; i < permittedTypes.size(); i++) {
if (permittedTypes.get(i) == node) {
permittedTypes.set(i, (ClassOrInterfaceType) replacementNode);
return true;
}
}
for (int i = 0; i < typeParameters.size(); i++) {
if (typeParameters.get(i) == node) {
typeParameters.set(i, (TypeParameter) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isClassOrInterfaceDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ClassOrInterfaceDeclaration asClassOrInterfaceDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifClassOrInterfaceDeclaration(Consumer<ClassOrInterfaceDeclaration> action) {
action.accept(this);
}
@Override
public ResolvedReferenceTypeDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedReferenceTypeDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ClassOrInterfaceDeclaration> toClassOrInterfaceDeclaration() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,408 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.*;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithAccessModifiers;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.type.ReferenceType;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.CompactConstructorDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedConstructorDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* <h1>The record declaration's constructor</h1>
* <strong>WARNING: This implementation is subject to change.</strong>
*
* <h2>Java 1.0 to 13</h2>
* Not available.
* <br>
* <h2>Java 14 (preview), Java 15 (2nd preview), Java 16</h2>
* <p>
* A record "compact" constructor declaration: {@code class X(int a, int b) { public X{ } }} where {@code public X{}} is the compact record constructor declaration.
* <p>
* Note that the record constructor is distinct from a "standard" constructor as it does not permit arguments/parameters.
* </p>
* <p>
* All annotations preceding the name will be set on this object, not on the class.
* JavaParser doesn't know if it they are applicable to the method or the class.
* </p>
*
* @author Roger Howell
* @see <a href="https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-8.10">JLS 8.10 - Record Classes</a>
* @see <a href="https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-8.10.4">JLS 8.10.3 - Record Constructor Declarations</a>
* @since 3.22.0
*/
public class CompactConstructorDeclaration extends BodyDeclaration<CompactConstructorDeclaration>
implements NodeWithBlockStmt<CompactConstructorDeclaration>,
NodeWithAccessModifiers<CompactConstructorDeclaration>,
NodeWithJavadoc<CompactConstructorDeclaration>,
NodeWithSimpleName<CompactConstructorDeclaration>,
NodeWithThrownExceptions<CompactConstructorDeclaration>,
NodeWithTypeParameters<CompactConstructorDeclaration>,
Resolvable<ResolvedConstructorDeclaration> {
private NodeList<Modifier> modifiers;
private BlockStmt body;
private NodeList<TypeParameter> typeParameters;
private SimpleName name;
private NodeList<ReferenceType> thrownExceptions;
public CompactConstructorDeclaration() {
this(
null,
new NodeList<>(),
new NodeList<>(),
new NodeList<>(),
new SimpleName(),
new NodeList<>(),
new BlockStmt());
}
public CompactConstructorDeclaration(String name) {
this(
null,
new NodeList<>(new Modifier()),
new NodeList<>(),
new NodeList<>(),
new SimpleName(name),
new NodeList<>(),
new BlockStmt());
}
public CompactConstructorDeclaration(NodeList<Modifier> modifiers, String name) {
this(
null,
modifiers,
new NodeList<>(),
new NodeList<>(),
new SimpleName(name),
new NodeList<>(),
new BlockStmt());
}
@AllFieldsConstructor
public CompactConstructorDeclaration(
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
NodeList<TypeParameter> typeParameters,
SimpleName name,
NodeList<ReferenceType> thrownExceptions,
BlockStmt body) {
this(null, modifiers, annotations, typeParameters, name, thrownExceptions, body);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public CompactConstructorDeclaration(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
NodeList<TypeParameter> typeParameters,
SimpleName name,
NodeList<ReferenceType> thrownExceptions,
BlockStmt body) {
super(tokenRange, annotations);
setModifiers(modifiers);
setTypeParameters(typeParameters);
setName(name);
setThrownExceptions(thrownExceptions);
setBody(body);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public BlockStmt getBody() {
return body;
}
/**
* Sets the body
*
* @param body the body, can not be null
* @return this, the ConstructorDeclaration
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public CompactConstructorDeclaration setBody(final BlockStmt body) {
assertNotNull(body);
if (body == this.body) {
return this;
}
notifyPropertyChange(ObservableProperty.BODY, this.body, body);
if (this.body != null) this.body.setParentNode(null);
this.body = body;
setAsParentNodeOf(body);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Modifier> getModifiers() {
return modifiers;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public CompactConstructorDeclaration setModifiers(final NodeList<Modifier> modifiers) {
assertNotNull(modifiers);
if (modifiers == this.modifiers) {
return this;
}
notifyPropertyChange(ObservableProperty.MODIFIERS, this.modifiers, modifiers);
if (this.modifiers != null) this.modifiers.setParentNode(null);
this.modifiers = modifiers;
setAsParentNodeOf(modifiers);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public CompactConstructorDeclaration setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<ReferenceType> getThrownExceptions() {
return thrownExceptions;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public CompactConstructorDeclaration setThrownExceptions(final NodeList<ReferenceType> thrownExceptions) {
assertNotNull(thrownExceptions);
if (thrownExceptions == this.thrownExceptions) {
return this;
}
notifyPropertyChange(ObservableProperty.THROWN_EXCEPTIONS, this.thrownExceptions, thrownExceptions);
if (this.thrownExceptions != null) this.thrownExceptions.setParentNode(null);
this.thrownExceptions = thrownExceptions;
setAsParentNodeOf(thrownExceptions);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<TypeParameter> getTypeParameters() {
return typeParameters;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public CompactConstructorDeclaration setTypeParameters(final NodeList<TypeParameter> typeParameters) {
assertNotNull(typeParameters);
if (typeParameters == this.typeParameters) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE_PARAMETERS, this.typeParameters, typeParameters);
if (this.typeParameters != null) this.typeParameters.setParentNode(null);
this.typeParameters = typeParameters;
setAsParentNodeOf(typeParameters);
return this;
}
/**
* The declaration returned has this schema:
* <p>
* [accessSpecifier] className [throws exceptionsList]
*/
public String getDeclarationAsString(
boolean includingModifiers, boolean includingThrows, boolean includingParameterName) {
StringBuilder sb = new StringBuilder();
if (includingModifiers) {
AccessSpecifier accessSpecifier = getAccessSpecifier();
sb.append(accessSpecifier.asString()).append(" ");
}
sb.append(getName());
sb.append("(");
boolean firstParam = true;
sb.append(")");
sb.append(appendThrowsIfRequested(includingThrows));
return sb.toString();
}
protected String appendThrowsIfRequested(boolean includingThrows) {
StringBuilder sb = new StringBuilder();
if (includingThrows) {
boolean firstThrow = true;
for (ReferenceType thr : getThrownExceptions()) {
if (firstThrow) {
firstThrow = false;
sb.append(" throws ");
} else {
sb.append(", ");
}
sb.append(thr.toString(prettyPrinterNoCommentsConfiguration));
}
}
return sb.toString();
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.remove(i);
return true;
}
}
for (int i = 0; i < thrownExceptions.size(); i++) {
if (thrownExceptions.get(i) == node) {
thrownExceptions.remove(i);
return true;
}
}
for (int i = 0; i < typeParameters.size(); i++) {
if (typeParameters.get(i) == node) {
typeParameters.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public CompactConstructorDeclaration clone() {
return (CompactConstructorDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public CompactConstructorDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.compactConstructorDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == body) {
setBody((BlockStmt) replacementNode);
return true;
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.set(i, (Modifier) replacementNode);
return true;
}
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
for (int i = 0; i < thrownExceptions.size(); i++) {
if (thrownExceptions.get(i) == node) {
thrownExceptions.set(i, (ReferenceType) replacementNode);
return true;
}
}
for (int i = 0; i < typeParameters.size(); i++) {
if (typeParameters.get(i) == node) {
typeParameters.set(i, (TypeParameter) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isCompactConstructorDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public CompactConstructorDeclaration asCompactConstructorDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifCompactConstructorDeclaration(Consumer<CompactConstructorDeclaration> action) {
action.accept(this);
}
@Override
public ResolvedConstructorDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedConstructorDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<CompactConstructorDeclaration> toCompactConstructorDeclaration() {
return Optional.of(this);
}
/**
* This constructor is used by the parser and is considered private.
*/
public CompactConstructorDeclaration(TokenRange tokenRange, NodeList<AnnotationExpr> annotations, BlockStmt body) {
super(tokenRange, annotations);
setBody(body);
customInitialization();
}
}

View File

@@ -0,0 +1,315 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.*;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithAccessModifiers;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.type.ReferenceType;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.ConstructorDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedConstructorDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A constructor declaration: {@code class X { X() { } }} where X(){} is the constructor declaration.
* <p>
* <br>All annotations preceding the name will be set on this object, not on the class.
* JavaParser doesn't know if it they are applicable to the method or the class.
*
* @author Julio Vilmar Gesser
*/
public class ConstructorDeclaration extends CallableDeclaration<ConstructorDeclaration>
implements NodeWithBlockStmt<ConstructorDeclaration>,
NodeWithAccessModifiers<ConstructorDeclaration>,
NodeWithJavadoc<ConstructorDeclaration>,
NodeWithSimpleName<ConstructorDeclaration>,
NodeWithParameters<ConstructorDeclaration>,
NodeWithThrownExceptions<ConstructorDeclaration>,
NodeWithTypeParameters<ConstructorDeclaration>,
Resolvable<ResolvedConstructorDeclaration> {
private BlockStmt body;
public ConstructorDeclaration() {
this(
null,
new NodeList<>(),
new NodeList<>(),
new NodeList<>(),
new SimpleName(),
new NodeList<>(),
new NodeList<>(),
new BlockStmt(),
null);
}
public ConstructorDeclaration(String name) {
this(
null,
new NodeList<>(new Modifier()),
new NodeList<>(),
new NodeList<>(),
new SimpleName(name),
new NodeList<>(),
new NodeList<>(),
new BlockStmt(),
null);
}
public ConstructorDeclaration(NodeList<Modifier> modifiers, String name) {
this(
null,
modifiers,
new NodeList<>(),
new NodeList<>(),
new SimpleName(name),
new NodeList<>(),
new NodeList<>(),
new BlockStmt(),
null);
}
public ConstructorDeclaration(
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
NodeList<TypeParameter> typeParameters,
SimpleName name,
NodeList<Parameter> parameters,
NodeList<ReferenceType> thrownExceptions,
BlockStmt body) {
this(null, modifiers, annotations, typeParameters, name, parameters, thrownExceptions, body, null);
}
@AllFieldsConstructor
public ConstructorDeclaration(
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
NodeList<TypeParameter> typeParameters,
SimpleName name,
NodeList<Parameter> parameters,
NodeList<ReferenceType> thrownExceptions,
BlockStmt body,
ReceiverParameter receiverParameter) {
this(null, modifiers, annotations, typeParameters, name, parameters, thrownExceptions, body, receiverParameter);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ConstructorDeclaration(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
NodeList<TypeParameter> typeParameters,
SimpleName name,
NodeList<Parameter> parameters,
NodeList<ReferenceType> thrownExceptions,
BlockStmt body,
ReceiverParameter receiverParameter) {
super(
tokenRange,
modifiers,
annotations,
typeParameters,
name,
parameters,
thrownExceptions,
receiverParameter);
setBody(body);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public BlockStmt getBody() {
return body;
}
/**
* Sets the body
*
* @param body the body, can not be null
* @return this, the ConstructorDeclaration
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ConstructorDeclaration setBody(final BlockStmt body) {
assertNotNull(body);
if (body == this.body) {
return this;
}
notifyPropertyChange(ObservableProperty.BODY, this.body, body);
if (this.body != null) this.body.setParentNode(null);
this.body = body;
setAsParentNodeOf(body);
return this;
}
@Override
public ConstructorDeclaration setModifiers(final NodeList<Modifier> modifiers) {
return super.setModifiers(modifiers);
}
@Override
public ConstructorDeclaration setName(final SimpleName name) {
return super.setName(name);
}
@Override
public ConstructorDeclaration setParameters(final NodeList<Parameter> parameters) {
return super.setParameters(parameters);
}
@Override
public ConstructorDeclaration setThrownExceptions(final NodeList<ReferenceType> thrownExceptions) {
return super.setThrownExceptions(thrownExceptions);
}
@Override
public ConstructorDeclaration setTypeParameters(final NodeList<TypeParameter> typeParameters) {
return super.setTypeParameters(typeParameters);
}
/**
* The declaration returned has this schema:
* <p>
* [accessSpecifier] className ([paramType [paramName]])
* [throws exceptionsList]
*/
@Override
public String getDeclarationAsString(
boolean includingModifiers, boolean includingThrows, boolean includingParameterName) {
StringBuilder sb = new StringBuilder();
if (includingModifiers) {
AccessSpecifier accessSpecifier = getAccessSpecifier();
sb.append(accessSpecifier.asString()).append(" ");
}
sb.append(getName());
sb.append("(");
boolean firstParam = true;
for (Parameter param : getParameters()) {
if (firstParam) {
firstParam = false;
} else {
sb.append(", ");
}
if (includingParameterName) {
sb.append(param.toString(prettyPrinterNoCommentsConfiguration));
} else {
sb.append(param.getType().toString(prettyPrinterNoCommentsConfiguration));
}
}
sb.append(")");
sb.append(appendThrowsIfRequested(includingThrows));
return sb.toString();
}
/*
* Returns the constructor descriptor
*/
public String toDescriptor() {
StringBuilder sb = new StringBuilder();
sb.append('(');
for (int i = 0; i < getParameters().size(); i++) {
sb.append(getParameter(i).getType().toDescriptor());
}
return sb.append(")V").toString();
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ConstructorDeclaration clone() {
return (ConstructorDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ConstructorDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.constructorDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == body) {
setBody((BlockStmt) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isConstructorDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ConstructorDeclaration asConstructorDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifConstructorDeclaration(Consumer<ConstructorDeclaration> action) {
action.accept(this);
}
@Override
public ResolvedConstructorDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedConstructorDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ConstructorDeclaration> toConstructorDeclaration() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,250 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithArguments;
import com.github.javaparser.ast.nodeTypes.NodeWithJavadoc;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.EnumConstantDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedEnumConstantDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* One of the values an enum can take. A(1) and B(2) in this example: {@code enum X { A(1), B(2) }}
*
* @author Julio Vilmar Gesser
*/
public class EnumConstantDeclaration extends BodyDeclaration<EnumConstantDeclaration>
implements NodeWithJavadoc<EnumConstantDeclaration>,
NodeWithSimpleName<EnumConstantDeclaration>,
NodeWithArguments<EnumConstantDeclaration>,
Resolvable<ResolvedEnumConstantDeclaration> {
private SimpleName name;
private NodeList<Expression> arguments;
private NodeList<BodyDeclaration<?>> classBody;
public EnumConstantDeclaration() {
this(null, new NodeList<>(), new SimpleName(), new NodeList<>(), new NodeList<>());
}
public EnumConstantDeclaration(String name) {
this(null, new NodeList<>(), new SimpleName(name), new NodeList<>(), new NodeList<>());
}
@AllFieldsConstructor
public EnumConstantDeclaration(
NodeList<AnnotationExpr> annotations,
SimpleName name,
NodeList<Expression> arguments,
NodeList<BodyDeclaration<?>> classBody) {
this(null, annotations, name, arguments, classBody);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public EnumConstantDeclaration(
TokenRange tokenRange,
NodeList<AnnotationExpr> annotations,
SimpleName name,
NodeList<Expression> arguments,
NodeList<BodyDeclaration<?>> classBody) {
super(tokenRange, annotations);
setName(name);
setArguments(arguments);
setClassBody(classBody);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Expression> getArguments() {
return arguments;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<BodyDeclaration<?>> getClassBody() {
return classBody;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public EnumConstantDeclaration setArguments(final NodeList<Expression> arguments) {
assertNotNull(arguments);
if (arguments == this.arguments) {
return this;
}
notifyPropertyChange(ObservableProperty.ARGUMENTS, this.arguments, arguments);
if (this.arguments != null) this.arguments.setParentNode(null);
this.arguments = arguments;
setAsParentNodeOf(arguments);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public EnumConstantDeclaration setClassBody(final NodeList<BodyDeclaration<?>> classBody) {
assertNotNull(classBody);
if (classBody == this.classBody) {
return this;
}
notifyPropertyChange(ObservableProperty.CLASS_BODY, this.classBody, classBody);
if (this.classBody != null) this.classBody.setParentNode(null);
this.classBody = classBody;
setAsParentNodeOf(classBody);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public EnumConstantDeclaration setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < arguments.size(); i++) {
if (arguments.get(i) == node) {
arguments.remove(i);
return true;
}
}
for (int i = 0; i < classBody.size(); i++) {
if (classBody.get(i) == node) {
classBody.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public EnumConstantDeclaration clone() {
return (EnumConstantDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public EnumConstantDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.enumConstantDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < arguments.size(); i++) {
if (arguments.get(i) == node) {
arguments.set(i, (Expression) replacementNode);
return true;
}
}
for (int i = 0; i < classBody.size(); i++) {
if (classBody.get(i) == node) {
classBody.set(i, (BodyDeclaration) replacementNode);
return true;
}
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isEnumConstantDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public EnumConstantDeclaration asEnumConstantDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifEnumConstantDeclaration(Consumer<EnumConstantDeclaration> action) {
action.accept(this);
}
@Override
public ResolvedEnumConstantDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedEnumConstantDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<EnumConstantDeclaration> toEnumConstantDeclaration() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,257 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNonEmpty;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithImplements;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.EnumDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedEnumDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* The declaration of an enum.<br>{@code enum X { ... }}
*
* @author Julio Vilmar Gesser
*/
public class EnumDeclaration extends TypeDeclaration<EnumDeclaration>
implements NodeWithImplements<EnumDeclaration>, Resolvable<ResolvedEnumDeclaration> {
private NodeList<ClassOrInterfaceType> implementedTypes;
private NodeList<EnumConstantDeclaration> entries;
public EnumDeclaration() {
this(
null,
new NodeList<>(),
new NodeList<>(),
new SimpleName(),
new NodeList<>(),
new NodeList<>(),
new NodeList<>());
}
public EnumDeclaration(NodeList<Modifier> modifiers, String name) {
this(
null,
modifiers,
new NodeList<>(),
new SimpleName(name),
new NodeList<>(),
new NodeList<>(),
new NodeList<>());
}
@AllFieldsConstructor
public EnumDeclaration(
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
SimpleName name,
NodeList<ClassOrInterfaceType> implementedTypes,
NodeList<EnumConstantDeclaration> entries,
NodeList<BodyDeclaration<?>> members) {
this(null, modifiers, annotations, name, implementedTypes, entries, members);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public EnumDeclaration(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
SimpleName name,
NodeList<ClassOrInterfaceType> implementedTypes,
NodeList<EnumConstantDeclaration> entries,
NodeList<BodyDeclaration<?>> members) {
super(tokenRange, modifiers, annotations, name, members);
setImplementedTypes(implementedTypes);
setEntries(entries);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<EnumConstantDeclaration> getEntries() {
return entries;
}
public EnumConstantDeclaration getEntry(int i) {
return getEntries().get(i);
}
public EnumDeclaration setEntry(int i, EnumConstantDeclaration element) {
getEntries().set(i, element);
return this;
}
public EnumDeclaration addEntry(EnumConstantDeclaration element) {
getEntries().add(element);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<ClassOrInterfaceType> getImplementedTypes() {
return implementedTypes;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public EnumDeclaration setEntries(final NodeList<EnumConstantDeclaration> entries) {
assertNotNull(entries);
if (entries == this.entries) {
return this;
}
notifyPropertyChange(ObservableProperty.ENTRIES, this.entries, entries);
if (this.entries != null) this.entries.setParentNode(null);
this.entries = entries;
setAsParentNodeOf(entries);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public EnumDeclaration setImplementedTypes(final NodeList<ClassOrInterfaceType> implementedTypes) {
assertNotNull(implementedTypes);
if (implementedTypes == this.implementedTypes) {
return this;
}
notifyPropertyChange(ObservableProperty.IMPLEMENTED_TYPES, this.implementedTypes, implementedTypes);
if (this.implementedTypes != null) this.implementedTypes.setParentNode(null);
this.implementedTypes = implementedTypes;
setAsParentNodeOf(implementedTypes);
return this;
}
public EnumConstantDeclaration addEnumConstant(String name) {
assertNonEmpty(name);
EnumConstantDeclaration enumConstant = new EnumConstantDeclaration(name);
getEntries().add(enumConstant);
return enumConstant;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < entries.size(); i++) {
if (entries.get(i) == node) {
entries.remove(i);
return true;
}
}
for (int i = 0; i < implementedTypes.size(); i++) {
if (implementedTypes.get(i) == node) {
implementedTypes.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public EnumDeclaration clone() {
return (EnumDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public EnumDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.enumDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < entries.size(); i++) {
if (entries.get(i) == node) {
entries.set(i, (EnumConstantDeclaration) replacementNode);
return true;
}
}
for (int i = 0; i < implementedTypes.size(); i++) {
if (implementedTypes.get(i) == node) {
implementedTypes.set(i, (ClassOrInterfaceType) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isEnumDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public EnumDeclaration asEnumDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifEnumDeclaration(Consumer<EnumDeclaration> action) {
action.accept(this);
}
@Override
public ResolvedEnumDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedEnumDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<EnumDeclaration> toEnumDeclaration() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,373 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.ast.Modifier.Keyword.STATIC;
import static com.github.javaparser.ast.NodeList.nodeList;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.Modifier.Keyword;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.AssignExpr;
import com.github.javaparser.ast.expr.AssignExpr.Operator;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.nodeTypes.NodeWithJavadoc;
import com.github.javaparser.ast.nodeTypes.NodeWithVariables;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithAccessModifiers;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithFinalModifier;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithStaticModifier;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ReturnStmt;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.VoidType;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.FieldDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.NonEmptyProperty;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedFieldDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* The declaration of a field in a class. "private static int a=15*15;" in this example: {@code class X { private static
* int a=15*15; }}
*
* <br>All annotations preceding the type will be set on this object, not on the type.
* JavaParser doesn't know if it they are applicable to the method or the type.
*
* @author Julio Vilmar Gesser
*/
public class FieldDeclaration extends BodyDeclaration<FieldDeclaration>
implements NodeWithJavadoc<FieldDeclaration>,
NodeWithVariables<FieldDeclaration>,
NodeWithAccessModifiers<FieldDeclaration>,
NodeWithStaticModifier<FieldDeclaration>,
NodeWithFinalModifier<FieldDeclaration>,
Resolvable<ResolvedFieldDeclaration> {
private NodeList<Modifier> modifiers;
@NonEmptyProperty
private NodeList<VariableDeclarator> variables;
public FieldDeclaration() {
this(null, new NodeList<>(), new NodeList<>(), new NodeList<>());
}
public FieldDeclaration(NodeList<Modifier> modifiers, VariableDeclarator variable) {
this(null, modifiers, new NodeList<>(), nodeList(variable));
}
public FieldDeclaration(NodeList<Modifier> modifiers, NodeList<VariableDeclarator> variables) {
this(null, modifiers, new NodeList<>(), variables);
}
@AllFieldsConstructor
public FieldDeclaration(
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
NodeList<VariableDeclarator> variables) {
this(null, modifiers, annotations, variables);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public FieldDeclaration(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
NodeList<VariableDeclarator> variables) {
super(tokenRange, annotations);
setModifiers(modifiers);
setVariables(variables);
customInitialization();
}
/**
* Creates a {@link FieldDeclaration}.
*
* @param modifiers modifiers
* @param type type
* @param name field name
*/
public FieldDeclaration(NodeList<Modifier> modifiers, Type type, String name) {
this(assertNotNull(modifiers), new VariableDeclarator(type, assertNotNull(name)));
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* Return the modifiers of this member declaration.
*
* @return modifiers
* @see Modifier
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Modifier> getModifiers() {
return modifiers;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<VariableDeclarator> getVariables() {
return variables;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public FieldDeclaration setModifiers(final NodeList<Modifier> modifiers) {
assertNotNull(modifiers);
if (modifiers == this.modifiers) {
return this;
}
notifyPropertyChange(ObservableProperty.MODIFIERS, this.modifiers, modifiers);
if (this.modifiers != null) this.modifiers.setParentNode(null);
this.modifiers = modifiers;
setAsParentNodeOf(modifiers);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public FieldDeclaration setVariables(final NodeList<VariableDeclarator> variables) {
assertNotNull(variables);
if (variables == this.variables) {
return this;
}
notifyPropertyChange(ObservableProperty.VARIABLES, this.variables, variables);
if (this.variables != null) this.variables.setParentNode(null);
this.variables = variables;
setAsParentNodeOf(variables);
return this;
}
/**
* Create a getter for this field, <b>will only work if this field declares only 1 identifier and if this field is
* already added to a ClassOrInterfaceDeclaration</b>
*
* @return the {@link MethodDeclaration} created
* @throws IllegalStateException if there is more than 1 variable identifier or if this field isn't attached to a
* class or enum
*/
public MethodDeclaration createGetter() {
if (getVariables().size() != 1)
throw new IllegalStateException("You can use this only when the field declares only 1 variable name");
Optional<ClassOrInterfaceDeclaration> parentClass = findAncestor(ClassOrInterfaceDeclaration.class);
Optional<EnumDeclaration> parentEnum = findAncestor(EnumDeclaration.class);
if (!(parentClass.isPresent() || parentEnum.isPresent())
|| (parentClass.isPresent() && parentClass.get().isInterface()))
throw new IllegalStateException("You can use this only when the field is attached to a class or an enum");
VariableDeclarator variable = getVariable(0);
String fieldName = variable.getNameAsString();
String fieldNameUpper = fieldName.toUpperCase().substring(0, 1) + fieldName.substring(1, fieldName.length());
final MethodDeclaration getter;
getter = parentClass
.map(clazz -> clazz.addMethod("get" + fieldNameUpper, Modifier.Keyword.PUBLIC))
.orElseGet(() -> parentEnum.get().addMethod("get" + fieldNameUpper, Modifier.Keyword.PUBLIC));
getter.setType(variable.getType());
BlockStmt blockStmt = new BlockStmt();
getter.setBody(blockStmt);
blockStmt.addStatement(new ReturnStmt(fieldName));
return getter;
}
/**
* Create a setter for this field, <b>will only work if this field declares only 1 identifier and if this field is
* already added to a ClassOrInterfaceDeclaration</b>
*
* @return the {@link MethodDeclaration} created
* @throws IllegalStateException if there is more than 1 variable identifier or if this field isn't attached to a
* class or enum
*/
public MethodDeclaration createSetter() {
if (getVariables().size() != 1)
throw new IllegalStateException("You can use this only when the field declares only 1 variable name");
Optional<ClassOrInterfaceDeclaration> parentClass = findAncestor(ClassOrInterfaceDeclaration.class);
Optional<EnumDeclaration> parentEnum = findAncestor(EnumDeclaration.class);
if (!(parentClass.isPresent() || parentEnum.isPresent())
|| (parentClass.isPresent() && parentClass.get().isInterface()))
throw new IllegalStateException("You can use this only when the field is attached to a class or an enum");
VariableDeclarator variable = getVariable(0);
String fieldName = variable.getNameAsString();
String fieldNameUpper = fieldName.toUpperCase().substring(0, 1) + fieldName.substring(1, fieldName.length());
final MethodDeclaration setter;
setter = parentClass
.map(clazz -> clazz.addMethod("set" + fieldNameUpper, Modifier.Keyword.PUBLIC))
.orElseGet(() -> parentEnum.get().addMethod("set" + fieldNameUpper, Modifier.Keyword.PUBLIC));
setter.setType(new VoidType());
setter.getParameters().add(new Parameter(variable.getType(), fieldName));
BlockStmt blockStmt2 = new BlockStmt();
setter.setBody(blockStmt2);
blockStmt2.addStatement(
new AssignExpr(new NameExpr("this." + fieldName), new NameExpr(fieldName), Operator.ASSIGN));
return setter;
}
public boolean isTransient() {
return hasModifier(Modifier.Keyword.TRANSIENT);
}
public boolean isVolatile() {
return hasModifier(Modifier.Keyword.VOLATILE);
}
public FieldDeclaration setTransient(boolean set) {
return setModifier(Modifier.Keyword.TRANSIENT, set);
}
public FieldDeclaration setVolatile(boolean set) {
return setModifier(Modifier.Keyword.VOLATILE, set);
}
/*
* Every field declaration in the body of an interface is implicitly public, static, and final.
*/
@Override
public boolean isStatic() {
return hasModifier(STATIC) || isDeclaredInInterface();
}
/*
* Every field declaration in the body of an interface is implicitly public, static, and final.
*/
@Override
public boolean isFinal() {
return hasModifier(Keyword.FINAL) || isDeclaredInInterface();
}
/*
* Every field declaration in the body of an interface is implicitly public, static, and final.
*/
@Override
public boolean isPublic() {
return hasModifier(Keyword.PUBLIC) || isDeclaredInInterface();
}
/*
* Returns true if the field is declared in an interface
*/
private boolean isDeclaredInInterface() {
Optional<TypeDeclaration> parentType = findAncestor(TypeDeclaration.class);
return parentType
.filter(BodyDeclaration::isClassOrInterfaceDeclaration)
.map(BodyDeclaration::asClassOrInterfaceDeclaration)
.map(ClassOrInterfaceDeclaration::isInterface)
.orElse(false);
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.remove(i);
return true;
}
}
for (int i = 0; i < variables.size(); i++) {
if (variables.get(i) == node) {
variables.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public FieldDeclaration clone() {
return (FieldDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public FieldDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.fieldDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.set(i, (Modifier) replacementNode);
return true;
}
}
for (int i = 0; i < variables.size(); i++) {
if (variables.get(i) == node) {
variables.set(i, (VariableDeclarator) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isFieldDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public FieldDeclaration asFieldDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifFieldDeclaration(Consumer<FieldDeclaration> action) {
action.accept(this);
}
@Override
public ResolvedFieldDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedFieldDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<FieldDeclaration> toFieldDeclaration() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,166 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithBlockStmt;
import com.github.javaparser.ast.nodeTypes.NodeWithJavadoc;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.InitializerDeclarationMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A (possibly static) initializer body. "static { a=3; }" in this example: {@code class X { static { a=3; } } }
*
* @author Julio Vilmar Gesser
*/
public class InitializerDeclaration extends BodyDeclaration<InitializerDeclaration>
implements NodeWithJavadoc<InitializerDeclaration>, NodeWithBlockStmt<InitializerDeclaration> {
private boolean isStatic;
private BlockStmt body;
public InitializerDeclaration() {
this(null, false, new BlockStmt());
}
@AllFieldsConstructor
public InitializerDeclaration(boolean isStatic, BlockStmt body) {
this(null, isStatic, body);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public InitializerDeclaration(TokenRange tokenRange, boolean isStatic, BlockStmt body) {
super(tokenRange);
setStatic(isStatic);
setBody(body);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public BlockStmt getBody() {
return body;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public boolean isStatic() {
return isStatic;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public InitializerDeclaration setBody(final BlockStmt body) {
assertNotNull(body);
if (body == this.body) {
return this;
}
notifyPropertyChange(ObservableProperty.BODY, this.body, body);
if (this.body != null) this.body.setParentNode(null);
this.body = body;
setAsParentNodeOf(body);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public InitializerDeclaration setStatic(final boolean isStatic) {
if (isStatic == this.isStatic) {
return this;
}
notifyPropertyChange(ObservableProperty.STATIC, this.isStatic, isStatic);
this.isStatic = isStatic;
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public InitializerDeclaration clone() {
return (InitializerDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public InitializerDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.initializerDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == body) {
setBody((BlockStmt) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isInitializerDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public InitializerDeclaration asInitializerDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifInitializerDeclaration(Consumer<InitializerDeclaration> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<InitializerDeclaration> toInitializerDeclaration() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,481 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.ast.Modifier.Keyword.PUBLIC;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.Modifier.Keyword;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.*;
import com.github.javaparser.ast.nodeTypes.modifiers.*;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.ReferenceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.MethodDeclarationMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A method declaration. "public int abc() {return 1;}" in this example: {@code class X { public int abc() {return 1;}
* }}
* <p>
* <br>All annotations preceding the return type will be set on this object, not on the return type.
* JavaParser doesn't know if it they are applicable to the method or the type.
*
* @author Julio Vilmar Gesser
*/
public class MethodDeclaration extends CallableDeclaration<MethodDeclaration>
implements NodeWithType<MethodDeclaration, Type>,
NodeWithOptionalBlockStmt<MethodDeclaration>,
NodeWithJavadoc<MethodDeclaration>,
NodeWithDeclaration,
NodeWithSimpleName<MethodDeclaration>,
NodeWithParameters<MethodDeclaration>,
NodeWithThrownExceptions<MethodDeclaration>,
NodeWithTypeParameters<MethodDeclaration>,
NodeWithAccessModifiers<MethodDeclaration>,
NodeWithAbstractModifier<MethodDeclaration>,
NodeWithStaticModifier<MethodDeclaration>,
NodeWithFinalModifier<MethodDeclaration>,
NodeWithStrictfpModifier<MethodDeclaration>,
Resolvable<ResolvedMethodDeclaration> {
private Type type;
@OptionalProperty
private BlockStmt body;
public MethodDeclaration() {
this(
null,
new NodeList<>(),
new NodeList<>(),
new NodeList<>(),
new ClassOrInterfaceType(),
new SimpleName(),
new NodeList<>(),
new NodeList<>(),
new BlockStmt(),
null);
}
public MethodDeclaration(final NodeList<Modifier> modifiers, final Type type, final String name) {
this(
null,
modifiers,
new NodeList<>(),
new NodeList<>(),
type,
new SimpleName(name),
new NodeList<>(),
new NodeList<>(),
new BlockStmt(),
null);
}
public MethodDeclaration(
final NodeList<Modifier> modifiers,
final String name,
final Type type,
final NodeList<Parameter> parameters) {
this(
null,
modifiers,
new NodeList<>(),
new NodeList<>(),
type,
new SimpleName(name),
parameters,
new NodeList<>(),
new BlockStmt(),
null);
}
public MethodDeclaration(
final NodeList<Modifier> modifiers,
final NodeList<AnnotationExpr> annotations,
final NodeList<TypeParameter> typeParameters,
final Type type,
final SimpleName name,
final NodeList<Parameter> parameters,
final NodeList<ReferenceType> thrownExceptions,
final BlockStmt body) {
this(null, modifiers, annotations, typeParameters, type, name, parameters, thrownExceptions, body, null);
}
@AllFieldsConstructor
public MethodDeclaration(
final NodeList<Modifier> modifiers,
final NodeList<AnnotationExpr> annotations,
final NodeList<TypeParameter> typeParameters,
final Type type,
final SimpleName name,
final NodeList<Parameter> parameters,
final NodeList<ReferenceType> thrownExceptions,
final BlockStmt body,
ReceiverParameter receiverParameter) {
this(
null,
modifiers,
annotations,
typeParameters,
type,
name,
parameters,
thrownExceptions,
body,
receiverParameter);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public MethodDeclaration(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
NodeList<TypeParameter> typeParameters,
Type type,
SimpleName name,
NodeList<Parameter> parameters,
NodeList<ReferenceType> thrownExceptions,
BlockStmt body,
ReceiverParameter receiverParameter) {
super(
tokenRange,
modifiers,
annotations,
typeParameters,
name,
parameters,
thrownExceptions,
receiverParameter);
setType(type);
setBody(body);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<BlockStmt> getBody() {
return Optional.ofNullable(body);
}
/**
* Sets the body
*
* @param body the body, can be null
* @return this, the MethodDeclaration
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public MethodDeclaration setBody(final BlockStmt body) {
if (body == this.body) {
return this;
}
notifyPropertyChange(ObservableProperty.BODY, this.body, body);
if (this.body != null) this.body.setParentNode(null);
this.body = body;
setAsParentNodeOf(body);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Type getType() {
return type;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public MethodDeclaration setType(final Type type) {
assertNotNull(type);
if (type == this.type) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE, this.type, type);
if (this.type != null) this.type.setParentNode(null);
this.type = type;
setAsParentNodeOf(type);
return this;
}
@Override
public MethodDeclaration setModifiers(final NodeList<Modifier> modifiers) {
return super.setModifiers(modifiers);
}
@Override
public MethodDeclaration setName(final SimpleName name) {
return super.setName(name);
}
@Override
public MethodDeclaration setParameters(final NodeList<Parameter> parameters) {
return super.setParameters(parameters);
}
@Override
public MethodDeclaration setThrownExceptions(final NodeList<ReferenceType> thrownExceptions) {
return super.setThrownExceptions(thrownExceptions);
}
@Override
public MethodDeclaration setTypeParameters(final NodeList<TypeParameter> typeParameters) {
return super.setTypeParameters(typeParameters);
}
/**
* The declaration returned has this schema:
* <p>
* [accessSpecifier] [static] [abstract] [final] [native]
* [synchronized] returnType methodName ([paramType [paramName]])
* [throws exceptionsList]
*
* @return method declaration as String
*/
@Override
public String getDeclarationAsString(
boolean includingModifiers, boolean includingThrows, boolean includingParameterName) {
StringBuilder sb = new StringBuilder();
if (includingModifiers) {
AccessSpecifier accessSpecifier = getAccessSpecifier();
sb.append(accessSpecifier.asString()).append(" ");
if (isStatic()) {
sb.append("static ");
}
if (isAbstract()) {
sb.append("abstract ");
}
if (isFinal()) {
sb.append("final ");
}
if (isNative()) {
sb.append("native ");
}
if (isSynchronized()) {
sb.append("synchronized ");
}
}
sb.append(getType().toString(prettyPrinterNoCommentsConfiguration));
sb.append(" ");
sb.append(getName().toString(prettyPrinterNoCommentsConfiguration));
sb.append("(");
boolean firstParam = true;
for (Parameter param : getParameters()) {
if (firstParam) {
firstParam = false;
} else {
sb.append(", ");
}
if (includingParameterName) {
sb.append(param.toString(prettyPrinterNoCommentsConfiguration));
} else {
sb.append(param.getType().toString(prettyPrinterNoCommentsConfiguration));
if (param.isVarArgs()) {
sb.append("...");
}
}
}
sb.append(")");
sb.append(appendThrowsIfRequested(includingThrows));
return sb.toString();
}
/*
* Returns the method descriptor (https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3.3)
* The method descriptor for the method: {@code Object m(int i, double d, Thread t) {...}}
* is {@code (IDLjava/lang/Thread;)Ljava/lang/Object;}
* Note that the internal forms of the binary names of Thread and Object are used.
*/
public String toDescriptor() {
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < getParameters().size(); i++) {
sb.append(getParameter(i).getType().toDescriptor());
}
sb.append(")");
sb.append(getType().toDescriptor());
return sb.toString();
}
/*
* A method in the body of an interface may be declared public or private
* (§6.6). If no access modifier is given, the method is implicitly public.
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4
*/
@Override
public boolean isPublic() {
return hasModifier(PUBLIC) || isImplicitlyPublic();
}
private boolean isImplicitlyPublic() {
return getAccessSpecifier() == AccessSpecifier.NONE
&& hasParentNode()
&& getParentNode().get() instanceof ClassOrInterfaceDeclaration
&& ((ClassOrInterfaceDeclaration) getParentNode().get()).isInterface();
}
/*
* An interface method lacking a private, default, or static modifier is implicitly abstract.
* https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4
*/
@Override
public boolean isAbstract() {
return super.isAbstract() || isImplicitlyAbstract();
}
private boolean isImplicitlyAbstract() {
return hasParentNode()
&& getParentNode().get() instanceof ClassOrInterfaceDeclaration
&& ((ClassOrInterfaceDeclaration) getParentNode().get()).isInterface()
&& Arrays.asList(Keyword.STATIC, Keyword.DEFAULT, Keyword.PRIVATE).stream()
.noneMatch(modifier -> hasModifier(modifier));
}
public boolean isNative() {
return hasModifier(Modifier.Keyword.NATIVE);
}
public boolean isSynchronized() {
return hasModifier(Modifier.Keyword.SYNCHRONIZED);
}
public boolean isDefault() {
return hasModifier(Modifier.Keyword.DEFAULT);
}
public MethodDeclaration setNative(boolean set) {
return setModifier(Modifier.Keyword.NATIVE, set);
}
public MethodDeclaration setSynchronized(boolean set) {
return setModifier(Modifier.Keyword.SYNCHRONIZED, set);
}
public MethodDeclaration setDefault(boolean set) {
return setModifier(Modifier.Keyword.DEFAULT, set);
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
if (body != null) {
if (node == body) {
removeBody();
return true;
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public MethodDeclaration removeBody() {
return setBody((BlockStmt) null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public MethodDeclaration clone() {
return (MethodDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public MethodDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.methodDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (body != null) {
if (node == body) {
setBody((BlockStmt) replacementNode);
return true;
}
}
if (node == type) {
setType((Type) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isMethodDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public MethodDeclaration asMethodDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifMethodDeclaration(Consumer<MethodDeclaration> action) {
action.accept(this);
}
@Override
public ResolvedMethodDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedMethodDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<MethodDeclaration> toMethodDeclaration() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,366 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithFinalModifier;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.ParameterMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedParameterDeclaration;
/**
* The parameters to a method or lambda. Lambda parameters may have inferred types, in that case "type" is UnknownType.
* <br>Note that <a href="https://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments">parameters
* are different from arguments.</a> <br>"String x" and "float y" are the parameters in {@code int abc(String x, float
* y) {...}}
*
* <br>All annotations preceding the type will be set on this object, not on the type.
* JavaParser doesn't know if it they are applicable to the parameter or the type.
*
* @author Julio Vilmar Gesser
*/
public class Parameter extends Node
implements NodeWithType<Parameter, Type>,
NodeWithAnnotations<Parameter>,
NodeWithSimpleName<Parameter>,
NodeWithFinalModifier<Parameter>,
Resolvable<ResolvedParameterDeclaration> {
private Type type;
private boolean isVarArgs;
private NodeList<AnnotationExpr> varArgsAnnotations;
private NodeList<Modifier> modifiers;
private NodeList<AnnotationExpr> annotations;
private SimpleName name;
public Parameter() {
this(
null,
new NodeList<>(),
new NodeList<>(),
new ClassOrInterfaceType(),
false,
new NodeList<>(),
new SimpleName());
}
public Parameter(Type type, SimpleName name) {
this(null, new NodeList<>(), new NodeList<>(), type, false, new NodeList<>(), name);
}
/**
* Creates a new {@link Parameter}.
*
* @param type type of the parameter
* @param name name of the parameter
*/
public Parameter(Type type, String name) {
this(null, new NodeList<>(), new NodeList<>(), type, false, new NodeList<>(), new SimpleName(name));
}
public Parameter(NodeList<Modifier> modifiers, Type type, SimpleName name) {
this(null, modifiers, new NodeList<>(), type, false, new NodeList<>(), name);
}
@AllFieldsConstructor
public Parameter(
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
Type type,
boolean isVarArgs,
NodeList<AnnotationExpr> varArgsAnnotations,
SimpleName name) {
this(null, modifiers, annotations, type, isVarArgs, varArgsAnnotations, name);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public Parameter(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
Type type,
boolean isVarArgs,
NodeList<AnnotationExpr> varArgsAnnotations,
SimpleName name) {
super(tokenRange);
setModifiers(modifiers);
setAnnotations(annotations);
setType(type);
setVarArgs(isVarArgs);
setVarArgsAnnotations(varArgsAnnotations);
setName(name);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Type getType() {
return type;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public boolean isVarArgs() {
return isVarArgs;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Parameter setType(final Type type) {
assertNotNull(type);
if (type == this.type) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE, this.type, type);
if (this.type != null) this.type.setParentNode(null);
this.type = type;
setAsParentNodeOf(type);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Parameter setVarArgs(final boolean isVarArgs) {
if (isVarArgs == this.isVarArgs) {
return this;
}
notifyPropertyChange(ObservableProperty.VAR_ARGS, this.isVarArgs, isVarArgs);
this.isVarArgs = isVarArgs;
return this;
}
/**
* @return the list returned could be immutable (in that case it will be empty)
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<AnnotationExpr> getAnnotations() {
return annotations;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
/**
* Return the modifiers of this parameter declaration.
*
* @return modifiers
* @see Modifier
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Modifier> getModifiers() {
return modifiers;
}
/**
* @param annotations a null value is currently treated as an empty list. This behavior could change in the future,
* so please avoid passing null
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Parameter setAnnotations(final NodeList<AnnotationExpr> annotations) {
assertNotNull(annotations);
if (annotations == this.annotations) {
return this;
}
notifyPropertyChange(ObservableProperty.ANNOTATIONS, this.annotations, annotations);
if (this.annotations != null) this.annotations.setParentNode(null);
this.annotations = annotations;
setAsParentNodeOf(annotations);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Parameter setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Parameter setModifiers(final NodeList<Modifier> modifiers) {
assertNotNull(modifiers);
if (modifiers == this.modifiers) {
return this;
}
notifyPropertyChange(ObservableProperty.MODIFIERS, this.modifiers, modifiers);
if (this.modifiers != null) this.modifiers.setParentNode(null);
this.modifiers = modifiers;
setAsParentNodeOf(modifiers);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.remove(i);
return true;
}
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.remove(i);
return true;
}
}
for (int i = 0; i < varArgsAnnotations.size(); i++) {
if (varArgsAnnotations.get(i) == node) {
varArgsAnnotations.remove(i);
return true;
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<AnnotationExpr> getVarArgsAnnotations() {
return varArgsAnnotations;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Parameter setVarArgsAnnotations(final NodeList<AnnotationExpr> varArgsAnnotations) {
assertNotNull(varArgsAnnotations);
if (varArgsAnnotations == this.varArgsAnnotations) {
return this;
}
notifyPropertyChange(ObservableProperty.VAR_ARGS_ANNOTATIONS, this.varArgsAnnotations, varArgsAnnotations);
if (this.varArgsAnnotations != null) this.varArgsAnnotations.setParentNode(null);
this.varArgsAnnotations = varArgsAnnotations;
setAsParentNodeOf(varArgsAnnotations);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public Parameter clone() {
return (Parameter) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ParameterMetaModel getMetaModel() {
return JavaParserMetaModel.parameterMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.set(i, (AnnotationExpr) replacementNode);
return true;
}
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.set(i, (Modifier) replacementNode);
return true;
}
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
if (node == type) {
setType((Type) replacementNode);
return true;
}
for (int i = 0; i < varArgsAnnotations.size(); i++) {
if (varArgsAnnotations.get(i) == node) {
varArgsAnnotations.set(i, (AnnotationExpr) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
public ResolvedParameterDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedParameterDeclaration.class);
}
/**
* Record components (parameters here) are implicitly final, even without the explicitly-added modifier.
* https://openjdk.java.net/jeps/359#Restrictions-on-records
*
* If wanting to find out if the keyword {@code final} has been explicitly added to this parameter,
* you should use {@code node.hasModifier(Modifier.Keyword.FINAL)}
*
* @return true if the node parameter is explicitly final (keyword attached) or implicitly final (e.g. parameters to a record)
*/
@Override
public boolean isFinal() {
// RecordDeclaration-specific code
if (getParentNode().isPresent()) {
Node parentNode = getParentNode().get();
if (parentNode instanceof RecordDeclaration) {
return true;
}
}
// Otherwise use the default implementation.
return NodeWithFinalModifier.super.isFinal();
}
}

View File

@@ -0,0 +1,220 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.Name;
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
import com.github.javaparser.ast.nodeTypes.NodeWithName;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.ReceiverParameterMetaModel;
/**
* The <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.1-220">receiver parameter</a> feature of Java.
*
* <br>All annotations preceding the type will be set on this object, not on the type.
* JavaParser doesn't know if it they are applicable to the receiver parameter or the type.
*
* @author Julio Vilmar Gesser
*/
public class ReceiverParameter extends Node
implements NodeWithType<ReceiverParameter, Type>,
NodeWithAnnotations<ReceiverParameter>,
NodeWithName<ReceiverParameter> {
private Type type;
private NodeList<AnnotationExpr> annotations;
private Name name;
public ReceiverParameter() {
this(null, new NodeList<>(), new ClassOrInterfaceType(), new Name());
}
public ReceiverParameter(Type type, Name name) {
this(null, new NodeList<>(), type, name);
}
/**
* Creates a new {@link ReceiverParameter}.
*
* @param type type of the parameter
* @param name name of the parameter
*/
public ReceiverParameter(Type type, String name) {
this(null, new NodeList<>(), type, new Name(name));
}
@AllFieldsConstructor
public ReceiverParameter(NodeList<AnnotationExpr> annotations, Type type, Name name) {
this(null, annotations, type, name);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ReceiverParameter(TokenRange tokenRange, NodeList<AnnotationExpr> annotations, Type type, Name name) {
super(tokenRange);
setAnnotations(annotations);
setType(type);
setName(name);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Type getType() {
return type;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ReceiverParameter setType(final Type type) {
assertNotNull(type);
if (type == this.type) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE, this.type, type);
if (this.type != null) this.type.setParentNode(null);
this.type = type;
setAsParentNodeOf(type);
return this;
}
/**
* @return the list returned could be immutable (in that case it will be empty)
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<AnnotationExpr> getAnnotations() {
return annotations;
}
/**
* @param annotations a null value is currently treated as an empty list. This behavior could change in the future,
* so please avoid passing null
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ReceiverParameter setAnnotations(final NodeList<AnnotationExpr> annotations) {
assertNotNull(annotations);
if (annotations == this.annotations) {
return this;
}
notifyPropertyChange(ObservableProperty.ANNOTATIONS, this.annotations, annotations);
if (this.annotations != null) this.annotations.setParentNode(null);
this.annotations = annotations;
setAsParentNodeOf(annotations);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ReceiverParameter clone() {
return (ReceiverParameter) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ReceiverParameterMetaModel getMetaModel() {
return JavaParserMetaModel.receiverParameterMetaModel;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Name getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ReceiverParameter setName(final Name name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.set(i, (AnnotationExpr) replacementNode);
return true;
}
}
if (node == name) {
setName((Name) replacementNode);
return true;
}
if (node == type) {
setType((Type) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
}

View File

@@ -0,0 +1,440 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNotNull;
import static java.util.Collections.unmodifiableList;
import static java.util.stream.Collectors.toList;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithImplements;
import com.github.javaparser.ast.nodeTypes.NodeWithParameters;
import com.github.javaparser.ast.nodeTypes.NodeWithTypeParameters;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithFinalModifier;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.LocalRecordDeclarationStmt;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import com.github.javaparser.metamodel.RecordDeclarationMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
/**
* <h1>The record declaration</h1>
* <strong>WARNING: This implementation is subject to change.</strong>
*
* <h2>Java 1.0 to 13</h2>
* Not available.
* <br>
* <h2>Java 14 (preview), Java 15 (2nd preview), Java 16</h2>
* <p>
* A definition of a record.<br>
* {@code record X(...) { ... }}
* </p><p>
* Note that the syntax of records is substantively different to standard classes/interfaces/enums. Specifically, note
* that record header contains the component declarations - where a "component" is defined as a non-static field.
* </p><p>
* This is in contrast to "normal" classes, where fields declarations are within the class body (optionally then
* initialised
* within a constructor.
* </p><p>
* Also note that the constructor for records does not accept any parameters.
* </p>
*
* <p>
* Consider this example from https://openjdk.java.net/jeps/359
* <pre>{@code
* record Range(int lo, int hi) {
* public Range {
* if (lo > hi)
* throw new IllegalArgumentException(String.format("(%d,%d)",lo,hi));
* }
* }
* }</pre>
* </p><p>
* To access these non-static field declarations, use {@link RecordDeclaration#getParameters()}
* </p>
*
* @author Roger Howell
* @see <a href="https://openjdk.java.net/jeps/359">https://openjdk.java.net/jeps/395</a>
* @see <a href="https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-8.10">JLS 8.10 - Record Classes</a>
* @since 3.22.0
*/
public class RecordDeclaration extends TypeDeclaration<RecordDeclaration>
implements NodeWithParameters<RecordDeclaration>,
NodeWithImplements<RecordDeclaration>,
NodeWithTypeParameters<RecordDeclaration>,
NodeWithFinalModifier<RecordDeclaration>,
Resolvable<ResolvedReferenceTypeDeclaration> {
private NodeList<TypeParameter> typeParameters;
private NodeList<ClassOrInterfaceType> implementedTypes;
@OptionalProperty
private ReceiverParameter receiverParameter;
private NodeList<Parameter> parameters;
public RecordDeclaration() {
this(
null,
new NodeList<>(),
new NodeList<>(),
new SimpleName(),
new NodeList<>(),
new NodeList<>(),
new NodeList<>(),
new NodeList<>(),
null);
}
public RecordDeclaration(final NodeList<Modifier> modifiers, final String name) {
this(
null,
modifiers,
new NodeList<>(),
new SimpleName(name),
new NodeList<>(),
new NodeList<>(),
new NodeList<>(),
new NodeList<>(),
null);
}
@AllFieldsConstructor
public RecordDeclaration(
final NodeList<Modifier> modifiers,
final NodeList<AnnotationExpr> annotations,
final SimpleName name,
final NodeList<Parameter> parameters,
final NodeList<TypeParameter> typeParameters,
final NodeList<ClassOrInterfaceType> implementedTypes,
final NodeList<BodyDeclaration<?>> members,
final ReceiverParameter receiverParameter) {
this(
null,
modifiers,
annotations,
name,
parameters,
typeParameters,
implementedTypes,
members,
receiverParameter);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public RecordDeclaration(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
SimpleName name,
NodeList<Parameter> parameters,
NodeList<TypeParameter> typeParameters,
NodeList<ClassOrInterfaceType> implementedTypes,
NodeList<BodyDeclaration<?>> members,
ReceiverParameter receiverParameter) {
super(tokenRange, modifiers, annotations, name, members);
setParameters(parameters);
setTypeParameters(typeParameters);
setImplementedTypes(implementedTypes);
setReceiverParameter(receiverParameter);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<ClassOrInterfaceType> getImplementedTypes() {
return implementedTypes;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<TypeParameter> getTypeParameters() {
return typeParameters;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public RecordDeclaration setImplementedTypes(final NodeList<ClassOrInterfaceType> implementedTypes) {
assertNotNull(implementedTypes);
if (implementedTypes == this.implementedTypes) {
return this;
}
notifyPropertyChange(ObservableProperty.IMPLEMENTED_TYPES, this.implementedTypes, implementedTypes);
if (this.implementedTypes != null) this.implementedTypes.setParentNode(null);
this.implementedTypes = implementedTypes;
setAsParentNodeOf(implementedTypes);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public RecordDeclaration setTypeParameters(final NodeList<TypeParameter> typeParameters) {
assertNotNull(typeParameters);
if (typeParameters == this.typeParameters) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE_PARAMETERS, this.typeParameters, typeParameters);
if (this.typeParameters != null) this.typeParameters.setParentNode(null);
this.typeParameters = typeParameters;
setAsParentNodeOf(typeParameters);
return this;
}
// TODO document and remove duplication between here and com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
/**
* @return is this class's parent a LocalRecordDeclarationStmt ?
*/
public boolean isLocalRecordDeclaration() {
return getParentNode().map(p -> p instanceof LocalRecordDeclarationStmt).orElse(false);
}
// TODO document and remove duplication between here and com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
@Override
public Optional<String> getFullyQualifiedName() {
if (isLocalRecordDeclaration()) {
return Optional.empty();
}
return super.getFullyQualifiedName();
}
@Override
public ResolvedReferenceTypeDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedReferenceTypeDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isRecordDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public RecordDeclaration asRecordDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<RecordDeclaration> toRecordDeclaration() {
return Optional.of(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifRecordDeclaration(Consumer<RecordDeclaration> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < implementedTypes.size(); i++) {
if (implementedTypes.get(i) == node) {
implementedTypes.remove(i);
return true;
}
}
for (int i = 0; i < parameters.size(); i++) {
if (parameters.get(i) == node) {
parameters.remove(i);
return true;
}
}
if (receiverParameter != null) {
if (node == receiverParameter) {
removeReceiverParameter();
return true;
}
}
for (int i = 0; i < typeParameters.size(); i++) {
if (typeParameters.get(i) == node) {
typeParameters.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < implementedTypes.size(); i++) {
if (implementedTypes.get(i) == node) {
implementedTypes.set(i, (ClassOrInterfaceType) replacementNode);
return true;
}
}
for (int i = 0; i < parameters.size(); i++) {
if (parameters.get(i) == node) {
parameters.set(i, (Parameter) replacementNode);
return true;
}
}
if (receiverParameter != null) {
if (node == receiverParameter) {
setReceiverParameter((ReceiverParameter) replacementNode);
return true;
}
}
for (int i = 0; i < typeParameters.size(); i++) {
if (typeParameters.get(i) == node) {
typeParameters.set(i, (TypeParameter) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public RecordDeclaration clone() {
return (RecordDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public RecordDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.recordDeclarationMetaModel;
}
/**
* Type declarations do not normally have parameters - e.g. {@code class X {}} and {@code enum X {}}.
* Records are different, where the record declaration can include parameters e.g. {@code record X(int a) {}}.
* Additionally, note that the constructor for a record does not allow the declaration of parameters.
* See the JEP for details.
*
* @see <a href="https://openjdk.java.net/jeps/359">https://openjdk.java.net/jeps/359</a>
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Parameter> getParameters() {
return parameters;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public RecordDeclaration setParameters(final NodeList<Parameter> parameters) {
assertNotNull(parameters);
if (parameters == this.parameters) {
return this;
}
notifyPropertyChange(ObservableProperty.PARAMETERS, this.parameters, parameters);
if (this.parameters != null) this.parameters.setParentNode(null);
this.parameters = parameters;
setAsParentNodeOf(parameters);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<ReceiverParameter> getReceiverParameter() {
return Optional.ofNullable(receiverParameter);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public RecordDeclaration setReceiverParameter(final ReceiverParameter receiverParameter) {
if (receiverParameter == this.receiverParameter) {
return this;
}
notifyPropertyChange(ObservableProperty.RECEIVER_PARAMETER, this.receiverParameter, receiverParameter);
if (this.receiverParameter != null) this.receiverParameter.setParentNode(null);
this.receiverParameter = receiverParameter;
setAsParentNodeOf(receiverParameter);
return this;
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public RecordDeclaration removeReceiverParameter() {
return setReceiverParameter((ReceiverParameter) null);
}
/**
* Records are implicitly final, even without the explicit modifier.
* https://openjdk.java.net/jeps/359#Restrictions-on-records
*
* If wanting to find out if the keyword {@code final} is explicitly added to this parameter,
* you should use {@code node.hasModifier(Modifier.Keyword.FINAL)}
*
* @return always true -- Records are always implicitly final, therefore can never not be final.
*/
@Override
public boolean isFinal() {
return true;
}
/**
* Record components are implicitly static when nested (i.e. when the parent isn't a compilation unit).
* https://openjdk.java.net/jeps/359#Restrictions-on-records
*
* @return True if the record declaration is nested, otherwise use the default method implementation.
*/
@Override
public boolean isStatic() {
if (getParentNode().isPresent()) {
Node parentNode = getParentNode().get();
if (!(parentNode instanceof CompilationUnit)) {
return true;
}
}
// Otherwise use the default method.
return super.isStatic();
}
/**
* @return Only the "compact" constructors within this record,
* not "normal" constructors (which are obtainable via {@link #getConstructors()}).
*/
public List<CompactConstructorDeclaration> getCompactConstructors() {
return unmodifiableList(getMembers().stream()
.filter(m -> m instanceof CompactConstructorDeclaration)
.map(m -> (CompactConstructorDeclaration) m)
.collect(toList()));
}
}

View File

@@ -0,0 +1,301 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNotNull;
import static java.util.stream.Collectors.toList;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithJavadoc;
import com.github.javaparser.ast.nodeTypes.NodeWithMembers;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithAccessModifiers;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithStaticModifier;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithStrictfpModifier;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.TypeDeclarationMetaModel;
import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A base class for all types of type declarations.
*
* @author Julio Vilmar Gesser
*/
public abstract class TypeDeclaration<T extends TypeDeclaration<?>> extends BodyDeclaration<T>
implements NodeWithSimpleName<T>,
NodeWithJavadoc<T>,
NodeWithMembers<T>,
NodeWithAccessModifiers<T>,
NodeWithStaticModifier<T>,
NodeWithStrictfpModifier<T> {
private SimpleName name;
private NodeList<Modifier> modifiers;
private NodeList<BodyDeclaration<?>> members;
public TypeDeclaration() {
this(null, new NodeList<>(), new NodeList<>(), new SimpleName(), new NodeList<>());
}
public TypeDeclaration(NodeList<Modifier> modifiers, String name) {
this(null, modifiers, new NodeList<>(), new SimpleName(name), new NodeList<>());
}
@AllFieldsConstructor
public TypeDeclaration(
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
SimpleName name,
NodeList<BodyDeclaration<?>> members) {
this(null, modifiers, annotations, name, members);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public TypeDeclaration(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
SimpleName name,
NodeList<BodyDeclaration<?>> members) {
super(tokenRange, annotations);
setModifiers(modifiers);
setName(name);
setMembers(members);
customInitialization();
}
/**
* Adds the given declaration to the specified type.
*
* @param decl member declaration
*/
public T addMember(BodyDeclaration<?> decl) {
NodeList<BodyDeclaration<?>> members = getMembers();
members.add(decl);
return (T) this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<BodyDeclaration<?>> getMembers() {
return members;
}
/**
* Return the modifiers of this type declaration.
*
* @return modifiers
* @see Modifier
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Modifier> getModifiers() {
return modifiers;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
@SuppressWarnings("unchecked")
public T setMembers(final NodeList<BodyDeclaration<?>> members) {
assertNotNull(members);
if (members == this.members) {
return (T) this;
}
notifyPropertyChange(ObservableProperty.MEMBERS, this.members, members);
if (this.members != null) this.members.setParentNode(null);
this.members = members;
setAsParentNodeOf(members);
return (T) this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
@SuppressWarnings("unchecked")
public T setModifiers(final NodeList<Modifier> modifiers) {
assertNotNull(modifiers);
if (modifiers == this.modifiers) {
return (T) this;
}
notifyPropertyChange(ObservableProperty.MODIFIERS, this.modifiers, modifiers);
if (this.modifiers != null) this.modifiers.setParentNode(null);
this.modifiers = modifiers;
setAsParentNodeOf(modifiers);
return (T) this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
@SuppressWarnings("unchecked")
public T setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return (T) this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return (T) this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < members.size(); i++) {
if (members.get(i) == node) {
members.remove(i);
return true;
}
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.remove(i);
return true;
}
}
return super.remove(node);
}
/**
* @return is this type's parent a CompilationUnit?
*/
public boolean isTopLevelType() {
return getParentNode().map(p -> p instanceof CompilationUnit).orElse(false);
}
/**
* @return methods or constructors whose signatures match the passed signature.
*/
public List<CallableDeclaration<?>> getCallablesWithSignature(CallableDeclaration.Signature signature) {
return getMembers().stream()
.filter(m -> m instanceof CallableDeclaration)
.map(m -> ((CallableDeclaration<?>) m))
.filter(m -> m.getSignature().equals(signature))
.collect(toList());
}
/**
* Returns the fully qualified name of this type, derived only from information available in this compilation unit. (So no symbol solving happens.)
* If the declared type is a local class declaration, it will return Optional.empty().
* If the declared type is a local record declaration, it will return Optional.empty().
* If the declared type is not contained in a compilation unit, it will return Optional.empty().
* @see com.github.javaparser.ast.stmt.LocalClassDeclarationStmt
* @see com.github.javaparser.ast.stmt.LocalRecordDeclarationStmt
*/
public Optional<String> getFullyQualifiedName() {
if (isTopLevelType()) {
return findCompilationUnit().map(cu -> cu.getPackageDeclaration()
.map(pd -> pd.getNameAsString())
.map(pkg -> pkg + "." + getNameAsString())
.orElseGet(() -> getNameAsString()));
}
return findAncestor(TypeDeclaration.class)
.map(td -> (TypeDeclaration<?>) td)
.flatMap(td -> td.getFullyQualifiedName().map(fqn -> fqn + "." + getNameAsString()));
}
/**
* @return is this type's parent a TypeDeclaration?
* NOTE: many people are confused over terminology. Refer to https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html .
*/
public boolean isNestedType() {
return getParentNode().map(p -> p instanceof TypeDeclaration).orElse(false);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public TypeDeclaration<?> clone() {
return (TypeDeclaration<?>) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public TypeDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.typeDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < members.size(); i++) {
if (members.get(i) == node) {
members.set(i, (BodyDeclaration) replacementNode);
return true;
}
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.set(i, (Modifier) replacementNode);
return true;
}
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isTypeDeclaration() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public TypeDeclaration asTypeDeclaration() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifTypeDeclaration(Consumer<TypeDeclaration> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<TypeDeclaration> toTypeDeclaration() {
return Optional.of(this);
}
public abstract ResolvedReferenceTypeDeclaration resolve();
}

View File

@@ -0,0 +1,290 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.body;
import static com.github.javaparser.utils.Utils.assertNonEmpty;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.nodeTypes.NodeWithVariables;
import com.github.javaparser.ast.observer.AstObserverAdapter;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.NonEmptyProperty;
import com.github.javaparser.metamodel.OptionalProperty;
import com.github.javaparser.metamodel.VariableDeclaratorMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedValueDeclaration;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
/**
* The declaration of a variable.<br>In {@code int x = 14, y = 3;} "int x = 14" and "int y = 3" are
* VariableDeclarators.
* <p>The type is on all of the variable declarators because, thanks to array brackets, each variable can have a different type.
*
* @author Julio Vilmar Gesser
*/
public class VariableDeclarator extends Node
implements NodeWithType<VariableDeclarator, Type>,
NodeWithSimpleName<VariableDeclarator>,
Resolvable<ResolvedValueDeclaration> {
private SimpleName name;
@OptionalProperty
@NonEmptyProperty
private Expression initializer;
private Type type;
public VariableDeclarator() {
this(null, new ClassOrInterfaceType(), new SimpleName(), null);
}
public VariableDeclarator(Type type, String variableName) {
this(null, type, new SimpleName(variableName), null);
}
public VariableDeclarator(Type type, SimpleName name) {
this(null, type, name, null);
}
public VariableDeclarator(Type type, String variableName, Expression initializer) {
this(null, type, new SimpleName(variableName), initializer);
}
/**
* Defines the declaration of a variable.
*
* @param name The identifier for this variable. IE. The variables name.
* @param initializer What this variable should be initialized to. An {@link com.github.javaparser.ast.expr.AssignExpr}
* is unnecessary as the {@code =} operator is already added.
*/
@AllFieldsConstructor
public VariableDeclarator(Type type, SimpleName name, Expression initializer) {
this(null, type, name, initializer);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public VariableDeclarator(TokenRange tokenRange, Type type, SimpleName name, Expression initializer) {
super(tokenRange);
setType(type);
setName(name);
setInitializer(initializer);
customInitialization();
}
@Override
protected void customInitialization() {
// We register an observer on the type property. When it is changed the MaximumCommonType is changes as well,
// because it is derived from the type of the variables it contains, for this reason we notify about the change
register(new AstObserverAdapter() {
@Override
public void propertyChange(
Node observedNode, ObservableProperty property, Object oldValue, Object newValue) {
if (property == ObservableProperty.TYPE) {
VariableDeclarator vd = VariableDeclarator.this;
if (vd.getParentNode().isPresent() && vd.getParentNode().get() instanceof NodeWithVariables) {
NodeWithVariables<?> nodeWithVariables =
(NodeWithVariables<?>) vd.getParentNode().get();
// We calculate the value the property will assume after the change will be completed
Optional<Type> currentMaxCommonType = nodeWithVariables.getMaximumCommonType();
List<Type> types = new LinkedList<>();
int index = nodeWithVariables.getVariables().indexOf(vd);
for (int i = 0; i < nodeWithVariables.getVariables().size(); i++) {
if (i == index) {
types.add((Type) newValue);
} else {
types.add(nodeWithVariables.getVariable(i).getType());
}
}
Optional<Type> newMaxCommonType = NodeWithVariables.calculateMaximumCommonType(types);
((Node) nodeWithVariables)
.notifyPropertyChange(
ObservableProperty.MAXIMUM_COMMON_TYPE,
currentMaxCommonType.orElse(null),
newMaxCommonType.orElse(null));
}
}
}
});
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<Expression> getInitializer() {
return Optional.ofNullable(initializer);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public VariableDeclarator setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
/**
* Sets the initializer expression
*
* @param initializer the initializer expression, can be null
* @return this, the VariableDeclarator
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public VariableDeclarator setInitializer(final Expression initializer) {
if (initializer == this.initializer) {
return this;
}
notifyPropertyChange(ObservableProperty.INITIALIZER, this.initializer, initializer);
if (this.initializer != null) this.initializer.setParentNode(null);
this.initializer = initializer;
setAsParentNodeOf(initializer);
return this;
}
/**
* Will create a {@link NameExpr} with the initializer param
*
* @param init the initializer expression, can be null
* @return this, the VariableDeclarator
*/
public VariableDeclarator setInitializer(String init) {
return setInitializer(new NameExpr(assertNonEmpty(init)));
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Type getType() {
return type;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public VariableDeclarator setType(final Type type) {
assertNotNull(type);
if (type == this.type) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE, this.type, type);
if (this.type != null) this.type.setParentNode(null);
this.type = type;
setAsParentNodeOf(type);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
if (initializer != null) {
if (node == initializer) {
removeInitializer();
return true;
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public VariableDeclarator removeInitializer() {
return setInitializer((Expression) null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public VariableDeclarator clone() {
return (VariableDeclarator) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public VariableDeclaratorMetaModel getMetaModel() {
return JavaParserMetaModel.variableDeclaratorMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (initializer != null) {
if (node == initializer) {
setInitializer((Expression) replacementNode);
return true;
}
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
if (node == type) {
setType((Type) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
public ResolvedValueDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedValueDeclaration.class);
}
}

View File

@@ -0,0 +1,120 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.comments;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.BlockCommentMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* <p>
* AST node that represent block comments.
* </p>
* Block comments can have multi lines and are delimited by "/&#42;" and
* "&#42;/".
*
* @author Julio Vilmar Gesser
*/
public class BlockComment extends Comment {
public BlockComment() {
this(null, "empty");
}
@AllFieldsConstructor
public BlockComment(String content) {
this(null, content);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public BlockComment(TokenRange tokenRange, String content) {
super(tokenRange, content);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public BlockComment clone() {
return (BlockComment) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public BlockCommentMetaModel getMetaModel() {
return JavaParserMetaModel.blockCommentMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isBlockComment() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public BlockComment asBlockComment() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifBlockComment(Consumer<BlockComment> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<BlockComment> toBlockComment() {
return Optional.of(this);
}
@Override
public String getHeader() {
return "/*";
}
@Override
public String getFooter() {
return "*/";
}
}

View File

@@ -0,0 +1,240 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.comments;
import static com.github.javaparser.utils.CodeGenerationUtils.f;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.metamodel.CommentMetaModel;
import com.github.javaparser.metamodel.InternalProperty;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* Abstract class for all AST nodes that represent comments.
*
* @author Julio Vilmar Gesser
* @see BlockComment
* @see LineComment
* @see JavadocComment
*/
public abstract class Comment extends Node {
private String content;
@InternalProperty
private Node commentedNode;
@AllFieldsConstructor
public Comment(String content) {
this(null, content);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public Comment(TokenRange tokenRange, String content) {
super(tokenRange);
setContent(content);
customInitialization();
}
/**
* Return the text of the comment.
*
* @return text of the comment
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public String getContent() {
return content;
}
/**
* Sets the text of the comment.
*
* @param content the text of the comment to set
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Comment setContent(final String content) {
assertNotNull(content);
if (content == this.content) {
return this;
}
notifyPropertyChange(ObservableProperty.CONTENT, this.content, content);
this.content = content;
return this;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isLineComment() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public LineComment asLineComment() {
throw new IllegalStateException(
f("%s is not LineComment, it is %s", this, this.getClass().getSimpleName()));
}
public Optional<Node> getCommentedNode() {
return Optional.ofNullable(this.commentedNode);
}
/**
* Sets the commentedNode
*
* @param commentedNode the commentedNode, can be null
* @return this, the Comment
*/
public Comment setCommentedNode(Node commentedNode) {
notifyPropertyChange(ObservableProperty.COMMENTED_NODE, this.commentedNode, commentedNode);
if (commentedNode == null) {
this.commentedNode = null;
return this;
}
if (commentedNode == this) {
throw new IllegalArgumentException();
}
if (commentedNode instanceof Comment) {
throw new IllegalArgumentException();
}
this.commentedNode = commentedNode;
return this;
}
public boolean isOrphan() {
return this.commentedNode == null;
}
@Override
public Node setComment(final Comment comment) {
// comments on comments are not allowed, so we override setComment(Comment) here
if (comment != null) {
throw new IllegalArgumentException("A comment cannot be commented.");
}
return super.setComment(comment);
}
@Override
public boolean remove() {
if (this.commentedNode != null) {
this.commentedNode.setComment(null);
return true;
}
if (this.getParentNode().isPresent()) {
return this.getParentNode().get().removeOrphanComment(this);
}
return false;
}
@Override
public Node findRootNode() {
// (Non-orphan) comments are not integrated into the normal AST; we need to get the commented node first.
Node n = getCommentedNode().orElse(this);
while (n.getParentNode().isPresent()) {
n = n.getParentNode().get();
}
return n;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public Comment clone() {
return (Comment) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public CommentMetaModel getMetaModel() {
return JavaParserMetaModel.commentMetaModel;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isBlockComment() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public BlockComment asBlockComment() {
throw new IllegalStateException(
f("%s is not BlockComment, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isJavadocComment() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public JavadocComment asJavadocComment() {
throw new IllegalStateException(
f("%s is not JavadocComment, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifBlockComment(Consumer<BlockComment> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifJavadocComment(Consumer<JavadocComment> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifLineComment(Consumer<LineComment> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<BlockComment> toBlockComment() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<JavadocComment> toJavadocComment() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<LineComment> toLineComment() {
return Optional.empty();
}
/*
* Header is "//" for line comment
*/
public abstract String getHeader();
/*
*
*/
public abstract String getFooter();
/*
* Returns the content of the comment with header and footer
*/
public String asString() {
return getHeader() + getContent() + getFooter();
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.comments;
import static com.github.javaparser.ast.Node.NODE_BY_BEGIN_POSITION;
import com.github.javaparser.Range;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
/**
* The comments contained in a certain parsed piece of source code.
*/
public class CommentsCollection {
private final TreeSet<Comment> comments = new TreeSet<>(NODE_BY_BEGIN_POSITION);
public CommentsCollection() {}
public CommentsCollection(Collection<Comment> commentsToCopy) {
comments.addAll(commentsToCopy);
}
public Set<LineComment> getLineComments() {
return comments.stream()
.filter(comment -> comment instanceof LineComment)
.map(comment -> (LineComment) comment)
.collect(Collectors.toCollection(() -> new TreeSet<>(NODE_BY_BEGIN_POSITION)));
}
public Set<BlockComment> getBlockComments() {
return comments.stream()
.filter(comment -> comment instanceof BlockComment)
.map(comment -> (BlockComment) comment)
.collect(Collectors.toCollection(() -> new TreeSet<>(NODE_BY_BEGIN_POSITION)));
}
public Set<JavadocComment> getJavadocComments() {
return comments.stream()
.filter(comment -> comment instanceof JavadocComment)
.map(comment -> (JavadocComment) comment)
.collect(Collectors.toCollection(() -> new TreeSet<>(NODE_BY_BEGIN_POSITION)));
}
public void addComment(Comment comment) {
comments.add(comment);
}
public boolean contains(Comment comment) {
if (!comment.hasRange()) {
return false;
}
Range commentRange = comment.getRange().get();
for (Comment c : getComments()) {
if (!c.hasRange()) {
return false;
}
Range cRange = c.getRange().get();
// we tolerate a difference of one element in the end column:
// it depends how \r and \n are calculated...
if (cRange.begin.equals(commentRange.begin)
&& cRange.end.line == commentRange.end.line
&& Math.abs(cRange.end.column - commentRange.end.column) < 2) {
return true;
}
}
return false;
}
public TreeSet<Comment> getComments() {
return comments;
}
public int size() {
return comments.size();
}
public CommentsCollection minus(CommentsCollection other) {
CommentsCollection result = new CommentsCollection();
result.comments.addAll(
comments.stream().filter(comment -> !other.contains(comment)).collect(Collectors.toList()));
return result;
}
public CommentsCollection copy() {
return new CommentsCollection(comments);
}
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.comments;
import static com.github.javaparser.StaticJavaParser.parseJavadoc;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.javadoc.Javadoc;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.JavadocCommentMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A Javadoc comment. {@code / a comment /}
*
* @author Julio Vilmar Gesser
*/
public class JavadocComment extends Comment {
public JavadocComment() {
this(null, "empty");
}
@AllFieldsConstructor
public JavadocComment(String content) {
this(null, content);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public JavadocComment(TokenRange tokenRange, String content) {
super(tokenRange, content);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
public Javadoc parse() {
return parseJavadoc(getContent());
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public JavadocComment clone() {
return (JavadocComment) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public JavadocCommentMetaModel getMetaModel() {
return JavaParserMetaModel.javadocCommentMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isJavadocComment() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public JavadocComment asJavadocComment() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifJavadocComment(Consumer<JavadocComment> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<JavadocComment> toJavadocComment() {
return Optional.of(this);
}
@Override
public String getHeader() {
return "/**";
}
@Override
public String getFooter() {
return "*/";
}
}

View File

@@ -0,0 +1,119 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.comments;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.LineCommentMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* <p>
* AST node that represent line comments.
* </p>
* Line comments start with "//" and finish at the end of the line ("\n").
*
* @author Julio Vilmar Gesser
*/
public class LineComment extends Comment {
public LineComment() {
this(null, "empty");
}
@AllFieldsConstructor
public LineComment(String content) {
this(null, content);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public LineComment(TokenRange tokenRange, String content) {
super(tokenRange, content);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isLineComment() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public LineComment clone() {
return (LineComment) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public LineCommentMetaModel getMetaModel() {
return JavaParserMetaModel.lineCommentMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public LineComment asLineComment() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifLineComment(Consumer<LineComment> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<LineComment> toLineComment() {
return Optional.of(this);
}
@Override
public String getHeader() {
return "//";
}
@Override
public String getFooter() {
return "";
}
}

View File

@@ -0,0 +1,149 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithName;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.metamodel.AnnotationExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.UnsolvedSymbolException;
import com.github.javaparser.resolution.declarations.ResolvedAnnotationDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A base class for the different types of annotations.
*
* @author Julio Vilmar Gesser
*/
public abstract class AnnotationExpr extends Expression
implements NodeWithName<AnnotationExpr>, Resolvable<ResolvedAnnotationDeclaration> {
protected Name name;
public AnnotationExpr() {
this(null, new Name());
}
@AllFieldsConstructor
public AnnotationExpr(Name name) {
this(null, name);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public AnnotationExpr(TokenRange tokenRange, Name name) {
super(tokenRange);
setName(name);
customInitialization();
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Name getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public AnnotationExpr setName(final Name name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public AnnotationExpr clone() {
return (AnnotationExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public AnnotationExprMetaModel getMetaModel() {
return JavaParserMetaModel.annotationExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == name) {
setName((Name) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isAnnotationExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public AnnotationExpr asAnnotationExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifAnnotationExpr(Consumer<AnnotationExpr> action) {
action.accept(this);
}
/**
* Attempts to resolve the declaration corresponding to the annotation expression. If successful, a
* {@link ResolvedAnnotationDeclaration} representing the declaration of the annotation referenced by this
* {@code AnnotationExpr} is returned. Otherwise, an {@link UnsolvedSymbolException} is thrown.
*
* @return a {@link ResolvedAnnotationDeclaration} representing the declaration of the annotation expression.
* @throws UnsolvedSymbolException if the declaration corresponding to the annotation expression could not be
* resolved.
*/
@Override
public ResolvedAnnotationDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedAnnotationDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<AnnotationExpr> toAnnotationExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,170 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.ArrayAccessExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* Array brackets [] being used to get a value from an array.
* In <br>{@code getNames()[15*15]} the name expression is getNames() and the index expression is 15*15.
*
* @author Julio Vilmar Gesser
*/
public class ArrayAccessExpr extends Expression {
private Expression name;
private Expression index;
public ArrayAccessExpr() {
this(null, new NameExpr(), new IntegerLiteralExpr());
}
@AllFieldsConstructor
public ArrayAccessExpr(Expression name, Expression index) {
this(null, name, index);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ArrayAccessExpr(TokenRange tokenRange, Expression name, Expression index) {
super(tokenRange);
setName(name);
setIndex(index);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getIndex() {
return index;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ArrayAccessExpr setIndex(final Expression index) {
assertNotNull(index);
if (index == this.index) {
return this;
}
notifyPropertyChange(ObservableProperty.INDEX, this.index, index);
if (this.index != null) this.index.setParentNode(null);
this.index = index;
setAsParentNodeOf(index);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ArrayAccessExpr setName(final Expression name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ArrayAccessExpr clone() {
return (ArrayAccessExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ArrayAccessExprMetaModel getMetaModel() {
return JavaParserMetaModel.arrayAccessExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == index) {
setIndex((Expression) replacementNode);
return true;
}
if (node == name) {
setName((Expression) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isArrayAccessExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ArrayAccessExpr asArrayAccessExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifArrayAccessExpr(Consumer<ArrayAccessExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ArrayAccessExpr> toArrayAccessExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,272 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.parseType;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ArrayType;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.ArrayCreationExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.NonEmptyProperty;
import com.github.javaparser.metamodel.OptionalProperty;
import java.util.Optional;
import java.util.function.Consumer;
/**
* {@code new int[5][4][][]} or {@code new int[][]{{1},{2,3}}}.
*
* <br>"int" is the element type.
* <br>All the brackets are stored in the levels field, from left to right.
*
* @author Julio Vilmar Gesser
*/
public class ArrayCreationExpr extends Expression {
@NonEmptyProperty
private NodeList<ArrayCreationLevel> levels;
private Type elementType;
@OptionalProperty
private ArrayInitializerExpr initializer;
public ArrayCreationExpr() {
this(null, new ClassOrInterfaceType(), new NodeList<>(new ArrayCreationLevel()), new ArrayInitializerExpr());
}
@AllFieldsConstructor
public ArrayCreationExpr(Type elementType, NodeList<ArrayCreationLevel> levels, ArrayInitializerExpr initializer) {
this(null, elementType, levels, initializer);
}
public ArrayCreationExpr(Type elementType) {
this(null, elementType, new NodeList<>(new ArrayCreationLevel()), new ArrayInitializerExpr());
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ArrayCreationExpr(
TokenRange tokenRange,
Type elementType,
NodeList<ArrayCreationLevel> levels,
ArrayInitializerExpr initializer) {
super(tokenRange);
setElementType(elementType);
setLevels(levels);
setInitializer(initializer);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<ArrayInitializerExpr> getInitializer() {
return Optional.ofNullable(initializer);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Type getElementType() {
return elementType;
}
/**
* Sets the initializer
*
* @param initializer the initializer, can be null
* @return this, the ArrayCreationExpr
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ArrayCreationExpr setInitializer(final ArrayInitializerExpr initializer) {
if (initializer == this.initializer) {
return this;
}
notifyPropertyChange(ObservableProperty.INITIALIZER, this.initializer, initializer);
if (this.initializer != null) this.initializer.setParentNode(null);
this.initializer = initializer;
setAsParentNodeOf(initializer);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ArrayCreationExpr setElementType(final Type elementType) {
assertNotNull(elementType);
if (elementType == this.elementType) {
return this;
}
notifyPropertyChange(ObservableProperty.ELEMENT_TYPE, this.elementType, elementType);
if (this.elementType != null) this.elementType.setParentNode(null);
this.elementType = elementType;
setAsParentNodeOf(elementType);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<ArrayCreationLevel> getLevels() {
return levels;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ArrayCreationExpr setLevels(final NodeList<ArrayCreationLevel> levels) {
assertNotNull(levels);
if (levels == this.levels) {
return this;
}
notifyPropertyChange(ObservableProperty.LEVELS, this.levels, levels);
if (this.levels != null) this.levels.setParentNode(null);
this.levels = levels;
setAsParentNodeOf(levels);
return this;
}
/**
* Takes the element type and wraps it in an ArrayType for every array creation level.
*/
public Type createdType() {
Type result = elementType;
for (int i = 0; i < levels.size(); i++) {
result = new ArrayType(result, ArrayType.Origin.TYPE, new NodeList<>());
}
return result;
}
/**
* Sets this type to this class and try to import it to the {@link CompilationUnit} if needed
*
* @param typeClass the type
* @return this
*/
public ArrayCreationExpr setElementType(Class<?> typeClass) {
tryAddImportToParentCompilationUnit(typeClass);
return setElementType(parseType(typeClass.getSimpleName()));
}
public ArrayCreationExpr setElementType(final String type) {
return setElementType(parseType(type));
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
if (initializer != null) {
if (node == initializer) {
removeInitializer();
return true;
}
}
for (int i = 0; i < levels.size(); i++) {
if (levels.get(i) == node) {
levels.remove(i);
return true;
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public ArrayCreationExpr removeInitializer() {
return setInitializer((ArrayInitializerExpr) null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ArrayCreationExpr clone() {
return (ArrayCreationExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ArrayCreationExprMetaModel getMetaModel() {
return JavaParserMetaModel.arrayCreationExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == elementType) {
setElementType((Type) replacementNode);
return true;
}
if (initializer != null) {
if (node == initializer) {
setInitializer((ArrayInitializerExpr) replacementNode);
return true;
}
}
for (int i = 0; i < levels.size(); i++) {
if (levels.get(i) == node) {
levels.set(i, (ArrayCreationLevel) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isArrayCreationExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ArrayCreationExpr asArrayCreationExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifArrayCreationExpr(Consumer<ArrayCreationExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ArrayCreationExpr> toArrayCreationExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,165 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.ArrayInitializerExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* The initialization of an array. In the following sample, the outer { } is an ArrayInitializerExpr.
* It has two expressions inside: two ArrayInitializerExprs.
* These have two expressions each, one has 1 and 1, the other two and two.
* <br>{@code new int[][]{{1, 1}, {2, 2}};}
*
* @author Julio Vilmar Gesser
*/
public class ArrayInitializerExpr extends Expression {
private NodeList<Expression> values;
public ArrayInitializerExpr() {
this(null, new NodeList<>());
}
@AllFieldsConstructor
public ArrayInitializerExpr(NodeList<Expression> values) {
this(null, values);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ArrayInitializerExpr(TokenRange tokenRange, NodeList<Expression> values) {
super(tokenRange);
setValues(values);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Expression> getValues() {
return values;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ArrayInitializerExpr setValues(final NodeList<Expression> values) {
assertNotNull(values);
if (values == this.values) {
return this;
}
notifyPropertyChange(ObservableProperty.VALUES, this.values, values);
if (this.values != null) this.values.setParentNode(null);
this.values = values;
setAsParentNodeOf(values);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < values.size(); i++) {
if (values.get(i) == node) {
values.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ArrayInitializerExpr clone() {
return (ArrayInitializerExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ArrayInitializerExprMetaModel getMetaModel() {
return JavaParserMetaModel.arrayInitializerExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < values.size(); i++) {
if (values.get(i) == node) {
values.set(i, (Expression) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isArrayInitializerExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ArrayInitializerExpr asArrayInitializerExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifArrayInitializerExpr(Consumer<ArrayInitializerExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ArrayInitializerExpr> toArrayInitializerExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,258 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.AssignExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.printer.Stringable;
import java.util.Optional;
import java.util.function.Consumer;
/**
* An assignment expression. It supports the operators that are found the AssignExpr.Operator enum.
* <br>{@code a=5}
* <br>{@code time+=500}
* <br>{@code watch.time+=500}
* <br>{@code (((time)))=100*60}
* <br>{@code peanut[a]=true}
*
* @author Julio Vilmar Gesser
*/
public class AssignExpr extends Expression {
public enum Operator implements Stringable {
ASSIGN("="),
PLUS("+="),
MINUS("-="),
MULTIPLY("*="),
DIVIDE("/="),
BINARY_AND("&="),
BINARY_OR("|="),
XOR("^="),
REMAINDER("%="),
LEFT_SHIFT("<<="),
SIGNED_RIGHT_SHIFT(">>="),
UNSIGNED_RIGHT_SHIFT(">>>=");
private final String codeRepresentation;
Operator(String codeRepresentation) {
this.codeRepresentation = codeRepresentation;
}
public String asString() {
return codeRepresentation;
}
public Optional<BinaryExpr.Operator> toBinaryOperator() {
switch (this) {
case PLUS:
return Optional.of(BinaryExpr.Operator.PLUS);
case MINUS:
return Optional.of(BinaryExpr.Operator.MINUS);
case MULTIPLY:
return Optional.of(BinaryExpr.Operator.MULTIPLY);
case DIVIDE:
return Optional.of(BinaryExpr.Operator.DIVIDE);
case BINARY_AND:
return Optional.of(BinaryExpr.Operator.BINARY_AND);
case BINARY_OR:
return Optional.of(BinaryExpr.Operator.BINARY_OR);
case XOR:
return Optional.of(BinaryExpr.Operator.XOR);
case REMAINDER:
return Optional.of(BinaryExpr.Operator.REMAINDER);
case LEFT_SHIFT:
return Optional.of(BinaryExpr.Operator.LEFT_SHIFT);
case SIGNED_RIGHT_SHIFT:
return Optional.of(BinaryExpr.Operator.SIGNED_RIGHT_SHIFT);
case UNSIGNED_RIGHT_SHIFT:
return Optional.of(BinaryExpr.Operator.UNSIGNED_RIGHT_SHIFT);
default:
return Optional.empty();
}
}
}
private Expression target;
private Expression value;
private Operator operator;
public AssignExpr() {
this(null, new NameExpr(), new StringLiteralExpr(), Operator.ASSIGN);
}
@AllFieldsConstructor
public AssignExpr(Expression target, Expression value, Operator operator) {
this(null, target, value, operator);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public AssignExpr(TokenRange tokenRange, Expression target, Expression value, Operator operator) {
super(tokenRange);
setTarget(target);
setValue(value);
setOperator(operator);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Operator getOperator() {
return operator;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getTarget() {
return target;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getValue() {
return value;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public AssignExpr setOperator(final Operator operator) {
assertNotNull(operator);
if (operator == this.operator) {
return this;
}
notifyPropertyChange(ObservableProperty.OPERATOR, this.operator, operator);
this.operator = operator;
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public AssignExpr setTarget(final Expression target) {
assertNotNull(target);
if (target == this.target) {
return this;
}
notifyPropertyChange(ObservableProperty.TARGET, this.target, target);
if (this.target != null) this.target.setParentNode(null);
this.target = target;
setAsParentNodeOf(target);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public AssignExpr setValue(final Expression value) {
assertNotNull(value);
if (value == this.value) {
return this;
}
notifyPropertyChange(ObservableProperty.VALUE, this.value, value);
if (this.value != null) this.value.setParentNode(null);
this.value = value;
setAsParentNodeOf(value);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public AssignExpr clone() {
return (AssignExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public AssignExprMetaModel getMetaModel() {
return JavaParserMetaModel.assignExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == target) {
setTarget((Expression) replacementNode);
return true;
}
if (node == value) {
setValue((Expression) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isAssignExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public AssignExpr asAssignExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifAssignExpr(Consumer<AssignExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<AssignExpr> toAssignExpr() {
return Optional.of(this);
}
/*
* Returns true if the expression is an assignment context
* https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.2
* 5.2. Assignment Contexts: Assignment contexts allow the value of an expression to be assigned (§15.26) to a variable;...
*/
@Override
protected boolean isAssignmentContext() {
return true;
}
}

View File

@@ -0,0 +1,253 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.BinaryExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.printer.Stringable;
import java.util.Optional;
import java.util.function.Consumer;
/**
* An expression with an expression on the left, an expression on the right, and an operator in the middle.
* It supports the operators that are found the BinaryExpr.Operator enum.
* <br>{@code a && b}
* <br>{@code 155 * 33}
*
* @author Julio Vilmar Gesser
*/
public class BinaryExpr extends Expression {
public enum Operator implements Stringable {
OR("||"),
AND("&&"),
BINARY_OR("|"),
BINARY_AND("&"),
XOR("^"),
EQUALS("=="),
NOT_EQUALS("!="),
LESS("<"),
GREATER(">"),
LESS_EQUALS("<="),
GREATER_EQUALS(">="),
LEFT_SHIFT("<<"),
SIGNED_RIGHT_SHIFT(">>"),
UNSIGNED_RIGHT_SHIFT(">>>"),
PLUS("+"),
MINUS("-"),
MULTIPLY("*"),
DIVIDE("/"),
REMAINDER("%");
private final String codeRepresentation;
Operator(String codeRepresentation) {
this.codeRepresentation = codeRepresentation;
}
public String asString() {
return codeRepresentation;
}
public Optional<AssignExpr.Operator> toAssignOperator() {
switch (this) {
case BINARY_OR:
return Optional.of(AssignExpr.Operator.BINARY_OR);
case BINARY_AND:
return Optional.of(AssignExpr.Operator.BINARY_AND);
case XOR:
return Optional.of(AssignExpr.Operator.XOR);
case LEFT_SHIFT:
return Optional.of(AssignExpr.Operator.LEFT_SHIFT);
case SIGNED_RIGHT_SHIFT:
return Optional.of(AssignExpr.Operator.SIGNED_RIGHT_SHIFT);
case UNSIGNED_RIGHT_SHIFT:
return Optional.of(AssignExpr.Operator.UNSIGNED_RIGHT_SHIFT);
case PLUS:
return Optional.of(AssignExpr.Operator.PLUS);
case MINUS:
return Optional.of(AssignExpr.Operator.MINUS);
case MULTIPLY:
return Optional.of(AssignExpr.Operator.MULTIPLY);
case DIVIDE:
return Optional.of(AssignExpr.Operator.DIVIDE);
case REMAINDER:
return Optional.of(AssignExpr.Operator.REMAINDER);
default:
return Optional.empty();
}
}
}
private Expression left;
private Expression right;
private Operator operator;
public BinaryExpr() {
this(null, new BooleanLiteralExpr(), new BooleanLiteralExpr(), Operator.EQUALS);
}
@AllFieldsConstructor
public BinaryExpr(Expression left, Expression right, Operator operator) {
this(null, left, right, operator);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public BinaryExpr(TokenRange tokenRange, Expression left, Expression right, Operator operator) {
super(tokenRange);
setLeft(left);
setRight(right);
setOperator(operator);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getLeft() {
return left;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Operator getOperator() {
return operator;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getRight() {
return right;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public BinaryExpr setLeft(final Expression left) {
assertNotNull(left);
if (left == this.left) {
return this;
}
notifyPropertyChange(ObservableProperty.LEFT, this.left, left);
if (this.left != null) this.left.setParentNode(null);
this.left = left;
setAsParentNodeOf(left);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public BinaryExpr setOperator(final Operator operator) {
assertNotNull(operator);
if (operator == this.operator) {
return this;
}
notifyPropertyChange(ObservableProperty.OPERATOR, this.operator, operator);
this.operator = operator;
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public BinaryExpr setRight(final Expression right) {
assertNotNull(right);
if (right == this.right) {
return this;
}
notifyPropertyChange(ObservableProperty.RIGHT, this.right, right);
if (this.right != null) this.right.setParentNode(null);
this.right = right;
setAsParentNodeOf(right);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public BinaryExpr clone() {
return (BinaryExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public BinaryExprMetaModel getMetaModel() {
return JavaParserMetaModel.binaryExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == left) {
setLeft((Expression) replacementNode);
return true;
}
if (node == right) {
setRight((Expression) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isBinaryExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public BinaryExpr asBinaryExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifBinaryExpr(Consumer<BinaryExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<BinaryExpr> toBinaryExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,135 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.BooleanLiteralExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* The boolean literals.
* <br>{@code true}
* <br>{@code false}
*
* @author Julio Vilmar Gesser
*/
public class BooleanLiteralExpr extends LiteralExpr {
private boolean value;
public BooleanLiteralExpr() {
this(null, false);
}
@AllFieldsConstructor
public BooleanLiteralExpr(boolean value) {
this(null, value);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public BooleanLiteralExpr(TokenRange tokenRange, boolean value) {
super(tokenRange);
setValue(value);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* The code generator likes to generate an "is" getter for boolean, so this here is the generated version,
* but "getValue" does the same and makes more sense.
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public boolean isValue() {
return value;
}
public boolean getValue() {
return isValue();
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public BooleanLiteralExpr setValue(final boolean value) {
if (value == this.value) {
return this;
}
notifyPropertyChange(ObservableProperty.VALUE, this.value, value);
this.value = value;
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public BooleanLiteralExpr clone() {
return (BooleanLiteralExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public BooleanLiteralExprMetaModel getMetaModel() {
return JavaParserMetaModel.booleanLiteralExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isBooleanLiteralExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public BooleanLiteralExpr asBooleanLiteralExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifBooleanLiteralExpr(Consumer<BooleanLiteralExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<BooleanLiteralExpr> toBooleanLiteralExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,173 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithExpression;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.CastExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A typecast. The (long) in {@code (long)15}
*
* @author Julio Vilmar Gesser
*/
public class CastExpr extends Expression implements NodeWithType<CastExpr, Type>, NodeWithExpression<CastExpr> {
private Type type;
private Expression expression;
public CastExpr() {
this(null, new ClassOrInterfaceType(), new NameExpr());
}
@AllFieldsConstructor
public CastExpr(Type type, Expression expression) {
this(null, type, expression);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public CastExpr(TokenRange tokenRange, Type type, Expression expression) {
super(tokenRange);
setType(type);
setExpression(expression);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getExpression() {
return expression;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Type getType() {
return type;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public CastExpr setExpression(final Expression expression) {
assertNotNull(expression);
if (expression == this.expression) {
return this;
}
notifyPropertyChange(ObservableProperty.EXPRESSION, this.expression, expression);
if (this.expression != null) this.expression.setParentNode(null);
this.expression = expression;
setAsParentNodeOf(expression);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public CastExpr setType(final Type type) {
assertNotNull(type);
if (type == this.type) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE, this.type, type);
if (this.type != null) this.type.setParentNode(null);
this.type = type;
setAsParentNodeOf(type);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public CastExpr clone() {
return (CastExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public CastExprMetaModel getMetaModel() {
return JavaParserMetaModel.castExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == expression) {
setExpression((Expression) replacementNode);
return true;
}
if (node == type) {
setType((Type) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isCastExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public CastExpr asCastExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifCastExpr(Consumer<CastExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<CastExpr> toCastExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,147 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.CharLiteralExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.utils.StringEscapeUtils;
import com.github.javaparser.utils.Utils;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A literal character.
* <br>{@code 'a'}
* <br>{@code '\t'}
* <br>{@code 'Ω'}
* <br>{@code '\177'}
* <br>{@code '💩'}
*
* @author Julio Vilmar Gesser
*/
public class CharLiteralExpr extends LiteralStringValueExpr {
public CharLiteralExpr() {
this(null, "?");
}
@AllFieldsConstructor
public CharLiteralExpr(String value) {
this(null, value);
}
/**
* Constructs a CharLiteralExpr with given escaped character.
*
* @param value a char
*/
public CharLiteralExpr(char value) {
this(null, StringEscapeUtils.escapeJava(String.valueOf(value)));
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public CharLiteralExpr(TokenRange tokenRange, String value) {
super(tokenRange, value);
customInitialization();
}
/**
* Utility method that creates a new StringLiteralExpr. Escapes EOL characters.
*/
public static CharLiteralExpr escape(String string) {
return new CharLiteralExpr(Utils.escapeEndOfLines(string));
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* @return the unescaped value character of this literal
*/
public char asChar() {
return StringEscapeUtils.unescapeJava(value).charAt(0);
}
/**
* Sets the given char as the literal value
*
* @param value a char
* @return this expression
*/
public CharLiteralExpr setChar(char value) {
this.value = String.valueOf(value);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public CharLiteralExpr clone() {
return (CharLiteralExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public CharLiteralExprMetaModel getMetaModel() {
return JavaParserMetaModel.charLiteralExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isCharLiteralExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public CharLiteralExpr asCharLiteralExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifCharLiteralExpr(Consumer<CharLiteralExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<CharLiteralExpr> toCharLiteralExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,148 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.ClassExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* Defines an expression that accesses the class of a type.
* <br>{@code Object.class}
*
* @author Julio Vilmar Gesser
*/
public class ClassExpr extends Expression implements NodeWithType<ClassExpr, Type> {
private Type type;
public ClassExpr() {
this(null, new ClassOrInterfaceType());
}
@AllFieldsConstructor
public ClassExpr(Type type) {
this(null, type);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ClassExpr(TokenRange tokenRange, Type type) {
super(tokenRange);
setType(type);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Type getType() {
return type;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ClassExpr setType(final Type type) {
assertNotNull(type);
if (type == this.type) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE, this.type, type);
if (this.type != null) this.type.setParentNode(null);
this.type = type;
setAsParentNodeOf(type);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ClassExpr clone() {
return (ClassExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ClassExprMetaModel getMetaModel() {
return JavaParserMetaModel.classExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == type) {
setType((Type) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isClassExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ClassExpr asClassExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifClassExpr(Consumer<ClassExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ClassExpr> toClassExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,205 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithCondition;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.ConditionalExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* The ternary conditional expression.
* In {@code b==0?x:y}, b==0 is the condition, x is thenExpr, and y is elseExpr.
*
* @author Julio Vilmar Gesser
*/
public class ConditionalExpr extends Expression implements NodeWithCondition<ConditionalExpr> {
private Expression condition;
private Expression thenExpr;
private Expression elseExpr;
public ConditionalExpr() {
this(null, new BooleanLiteralExpr(), new StringLiteralExpr(), new StringLiteralExpr());
}
@AllFieldsConstructor
public ConditionalExpr(Expression condition, Expression thenExpr, Expression elseExpr) {
this(null, condition, thenExpr, elseExpr);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ConditionalExpr(TokenRange tokenRange, Expression condition, Expression thenExpr, Expression elseExpr) {
super(tokenRange);
setCondition(condition);
setThenExpr(thenExpr);
setElseExpr(elseExpr);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getCondition() {
return condition;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getElseExpr() {
return elseExpr;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getThenExpr() {
return thenExpr;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ConditionalExpr setCondition(final Expression condition) {
assertNotNull(condition);
if (condition == this.condition) {
return this;
}
notifyPropertyChange(ObservableProperty.CONDITION, this.condition, condition);
if (this.condition != null) this.condition.setParentNode(null);
this.condition = condition;
setAsParentNodeOf(condition);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ConditionalExpr setElseExpr(final Expression elseExpr) {
assertNotNull(elseExpr);
if (elseExpr == this.elseExpr) {
return this;
}
notifyPropertyChange(ObservableProperty.ELSE_EXPR, this.elseExpr, elseExpr);
if (this.elseExpr != null) this.elseExpr.setParentNode(null);
this.elseExpr = elseExpr;
setAsParentNodeOf(elseExpr);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ConditionalExpr setThenExpr(final Expression thenExpr) {
assertNotNull(thenExpr);
if (thenExpr == this.thenExpr) {
return this;
}
notifyPropertyChange(ObservableProperty.THEN_EXPR, this.thenExpr, thenExpr);
if (this.thenExpr != null) this.thenExpr.setParentNode(null);
this.thenExpr = thenExpr;
setAsParentNodeOf(thenExpr);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ConditionalExpr clone() {
return (ConditionalExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ConditionalExprMetaModel getMetaModel() {
return JavaParserMetaModel.conditionalExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == condition) {
setCondition((Expression) replacementNode);
return true;
}
if (node == elseExpr) {
setElseExpr((Expression) replacementNode);
return true;
}
if (node == thenExpr) {
setThenExpr((Expression) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isConditionalExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ConditionalExpr asConditionalExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifConditionalExpr(Consumer<ConditionalExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ConditionalExpr> toConditionalExpr() {
return Optional.of(this);
}
/*
* A reference conditional expression is a poly expression if it appears in an assignment context or an invocation context (§5.2. §5.3).
* Otherwise, it is a standalone expression.
*/
@Override
public boolean isPolyExpression() {
return appearsInAssignmentContext() || appearsInInvocationContext();
}
}

View File

@@ -0,0 +1,129 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.DoubleLiteralExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A float or a double constant. This value is stored exactly as found in the source.
* <br>{@code 100.1f}
* <br>{@code 23958D}
* <br>{@code 0x4.5p1f}
*
* @author Julio Vilmar Gesser
*/
public class DoubleLiteralExpr extends LiteralStringValueExpr {
public DoubleLiteralExpr() {
this(null, "0");
}
@AllFieldsConstructor
public DoubleLiteralExpr(final String value) {
this(null, value);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public DoubleLiteralExpr(TokenRange tokenRange, String value) {
super(tokenRange, value);
customInitialization();
}
public DoubleLiteralExpr(final double value) {
this(null, String.valueOf(value));
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* @return the literal value as a double
*/
public double asDouble() {
// Underscores are allowed in number literals for readability reasons but cause a NumberFormatException if
// passed along to Double#parseDouble. Hence, we apply a simple filter to remove all underscores.
// See https://github.com/javaparser/javaparser/issues/1980 for more information.
String noUnderscoreValue = value.replaceAll("_", "");
return Double.parseDouble(noUnderscoreValue);
}
public DoubleLiteralExpr setDouble(double value) {
this.value = String.valueOf(value);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public DoubleLiteralExpr clone() {
return (DoubleLiteralExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public DoubleLiteralExprMetaModel getMetaModel() {
return JavaParserMetaModel.doubleLiteralExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isDoubleLiteralExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public DoubleLiteralExpr asDoubleLiteralExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifDoubleLiteralExpr(Consumer<DoubleLiteralExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<DoubleLiteralExpr> toDoubleLiteralExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,160 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.EnclosedExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* An expression between ( ).
* <br>{@code (1+1)}
*
* @author Julio Vilmar Gesser
*/
public class EnclosedExpr extends Expression {
private Expression inner;
public EnclosedExpr() {
this(null, new StringLiteralExpr());
}
@AllFieldsConstructor
public EnclosedExpr(final Expression inner) {
this(null, inner);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public EnclosedExpr(TokenRange tokenRange, Expression inner) {
super(tokenRange);
setInner(inner);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getInner() {
return inner;
}
/**
* Sets the inner expression
*
* @param inner the inner expression, can be null
* @return this, the EnclosedExpr
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public EnclosedExpr setInner(final Expression inner) {
assertNotNull(inner);
if (inner == this.inner) {
return this;
}
notifyPropertyChange(ObservableProperty.INNER, this.inner, inner);
if (this.inner != null) this.inner.setParentNode(null);
this.inner = inner;
setAsParentNodeOf(inner);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public EnclosedExpr clone() {
return (EnclosedExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public EnclosedExprMetaModel getMetaModel() {
return JavaParserMetaModel.enclosedExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == inner) {
setInner((Expression) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isEnclosedExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public EnclosedExpr asEnclosedExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifEnclosedExpr(Consumer<EnclosedExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<EnclosedExpr> toEnclosedExpr() {
return Optional.of(this);
}
/*
* On Parenthesized Expressions, if the contained expression is a poly expression (§15.2), the parenthesized expression is also a poly expression. Otherwise, it is a standalone expression.
* (https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.5)
*/
@Override
public boolean isPolyExpression() {
return getInner().isPolyExpression();
}
}

View File

@@ -0,0 +1,927 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.CodeGenerationUtils.f;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithOptionalScope;
import com.github.javaparser.ast.nodeTypes.NodeWithTypeArguments;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.metamodel.ExpressionMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.resolution.types.ResolvedType;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* A base class for all expressions.
*
* @author Julio Vilmar Gesser
*/
public abstract class Expression extends Node {
/**
* Returns {@code true} when the Node to be tested is not an
* {@link EnclosedExpr}, {@code false} otherwise.
*/
public static final Predicate<Node> IS_NOT_ENCLOSED_EXPR = n -> !(n instanceof EnclosedExpr);
/**
* A {@link Function} that returns its argument (an {@link Expression}) when
* the argument is not an {@link EnclosedExpr}, otherwise the first
* {@link Expression} down the argument's 'inner' path that is not an
* {@link EnclosedExpr}.
*/
public static final Function<Expression, Expression> EXCLUDE_ENCLOSED_EXPR = expr -> {
while (expr.isEnclosedExpr()) {
expr = expr.asEnclosedExpr().getInner();
}
return expr;
};
@AllFieldsConstructor
public Expression() {
this(null);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public Expression(TokenRange tokenRange) {
super(tokenRange);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public Expression clone() {
return (Expression) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ExpressionMetaModel getMetaModel() {
return JavaParserMetaModel.expressionMetaModel;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isAnnotationExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public AnnotationExpr asAnnotationExpr() {
throw new IllegalStateException(
f("%s is not AnnotationExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isArrayAccessExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ArrayAccessExpr asArrayAccessExpr() {
throw new IllegalStateException(
f("%s is not ArrayAccessExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isArrayCreationExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ArrayCreationExpr asArrayCreationExpr() {
throw new IllegalStateException(
f("%s is not ArrayCreationExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isArrayInitializerExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ArrayInitializerExpr asArrayInitializerExpr() {
throw new IllegalStateException(f(
"%s is not ArrayInitializerExpr, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isAssignExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public AssignExpr asAssignExpr() {
throw new IllegalStateException(
f("%s is not AssignExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isBinaryExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public BinaryExpr asBinaryExpr() {
throw new IllegalStateException(
f("%s is not BinaryExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isBooleanLiteralExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public BooleanLiteralExpr asBooleanLiteralExpr() {
throw new IllegalStateException(f(
"%s is not BooleanLiteralExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isCastExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public CastExpr asCastExpr() {
throw new IllegalStateException(
f("%s is not CastExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isCharLiteralExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public CharLiteralExpr asCharLiteralExpr() {
throw new IllegalStateException(
f("%s is not CharLiteralExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isClassExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ClassExpr asClassExpr() {
throw new IllegalStateException(
f("%s is not ClassExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isConditionalExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ConditionalExpr asConditionalExpr() {
throw new IllegalStateException(
f("%s is not ConditionalExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isDoubleLiteralExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public DoubleLiteralExpr asDoubleLiteralExpr() {
throw new IllegalStateException(
f("%s is not DoubleLiteralExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isEnclosedExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public EnclosedExpr asEnclosedExpr() {
throw new IllegalStateException(
f("%s is not EnclosedExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isFieldAccessExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public FieldAccessExpr asFieldAccessExpr() {
throw new IllegalStateException(
f("%s is not FieldAccessExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isInstanceOfExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public InstanceOfExpr asInstanceOfExpr() {
throw new IllegalStateException(
f("%s is not InstanceOfExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isIntegerLiteralExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public IntegerLiteralExpr asIntegerLiteralExpr() {
throw new IllegalStateException(f(
"%s is not IntegerLiteralExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isLambdaExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public LambdaExpr asLambdaExpr() {
throw new IllegalStateException(
f("%s is not LambdaExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isLiteralExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public LiteralExpr asLiteralExpr() {
throw new IllegalStateException(
f("%s is not LiteralExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isLiteralStringValueExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public LiteralStringValueExpr asLiteralStringValueExpr() {
throw new IllegalStateException(f(
"%s is not LiteralStringValueExpr, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isLongLiteralExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public LongLiteralExpr asLongLiteralExpr() {
throw new IllegalStateException(
f("%s is not LongLiteralExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isMarkerAnnotationExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public MarkerAnnotationExpr asMarkerAnnotationExpr() {
throw new IllegalStateException(f(
"%s is not MarkerAnnotationExpr, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isMethodCallExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public MethodCallExpr asMethodCallExpr() {
throw new IllegalStateException(
f("%s is not MethodCallExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isMethodReferenceExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public MethodReferenceExpr asMethodReferenceExpr() {
throw new IllegalStateException(f(
"%s is not MethodReferenceExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isNameExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public NameExpr asNameExpr() {
throw new IllegalStateException(
f("%s is not NameExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isNormalAnnotationExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public NormalAnnotationExpr asNormalAnnotationExpr() {
throw new IllegalStateException(f(
"%s is not NormalAnnotationExpr, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isNullLiteralExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public NullLiteralExpr asNullLiteralExpr() {
throw new IllegalStateException(
f("%s is not NullLiteralExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isObjectCreationExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ObjectCreationExpr asObjectCreationExpr() {
throw new IllegalStateException(f(
"%s is not ObjectCreationExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isSingleMemberAnnotationExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public SingleMemberAnnotationExpr asSingleMemberAnnotationExpr() {
throw new IllegalStateException(f(
"%s is not SingleMemberAnnotationExpr, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isStringLiteralExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public StringLiteralExpr asStringLiteralExpr() {
throw new IllegalStateException(
f("%s is not StringLiteralExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isSuperExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public SuperExpr asSuperExpr() {
throw new IllegalStateException(
f("%s is not SuperExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isThisExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ThisExpr asThisExpr() {
throw new IllegalStateException(
f("%s is not ThisExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isTypeExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public TypeExpr asTypeExpr() {
throw new IllegalStateException(
f("%s is not TypeExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isUnaryExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public UnaryExpr asUnaryExpr() {
throw new IllegalStateException(
f("%s is not UnaryExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isVariableDeclarationExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public VariableDeclarationExpr asVariableDeclarationExpr() {
throw new IllegalStateException(f(
"%s is not VariableDeclarationExpr, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifAnnotationExpr(Consumer<AnnotationExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifArrayAccessExpr(Consumer<ArrayAccessExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifArrayCreationExpr(Consumer<ArrayCreationExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifArrayInitializerExpr(Consumer<ArrayInitializerExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifAssignExpr(Consumer<AssignExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifBinaryExpr(Consumer<BinaryExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifBooleanLiteralExpr(Consumer<BooleanLiteralExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifCastExpr(Consumer<CastExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifCharLiteralExpr(Consumer<CharLiteralExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifClassExpr(Consumer<ClassExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifConditionalExpr(Consumer<ConditionalExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifDoubleLiteralExpr(Consumer<DoubleLiteralExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifEnclosedExpr(Consumer<EnclosedExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifFieldAccessExpr(Consumer<FieldAccessExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifInstanceOfExpr(Consumer<InstanceOfExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifIntegerLiteralExpr(Consumer<IntegerLiteralExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifLambdaExpr(Consumer<LambdaExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifLiteralExpr(Consumer<LiteralExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifLiteralStringValueExpr(Consumer<LiteralStringValueExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifLongLiteralExpr(Consumer<LongLiteralExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifMarkerAnnotationExpr(Consumer<MarkerAnnotationExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifMethodCallExpr(Consumer<MethodCallExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifMethodReferenceExpr(Consumer<MethodReferenceExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifNameExpr(Consumer<NameExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifNormalAnnotationExpr(Consumer<NormalAnnotationExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifNullLiteralExpr(Consumer<NullLiteralExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifObjectCreationExpr(Consumer<ObjectCreationExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifSingleMemberAnnotationExpr(Consumer<SingleMemberAnnotationExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifStringLiteralExpr(Consumer<StringLiteralExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifSuperExpr(Consumer<SuperExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifThisExpr(Consumer<ThisExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifTypeExpr(Consumer<TypeExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifUnaryExpr(Consumer<UnaryExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifVariableDeclarationExpr(Consumer<VariableDeclarationExpr> action) {}
/**
* returns the type associated with the node.
*/
public ResolvedType calculateResolvedType() {
return getSymbolResolver().calculateType(this);
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<AnnotationExpr> toAnnotationExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ArrayAccessExpr> toArrayAccessExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ArrayCreationExpr> toArrayCreationExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ArrayInitializerExpr> toArrayInitializerExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<AssignExpr> toAssignExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<BinaryExpr> toBinaryExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<BooleanLiteralExpr> toBooleanLiteralExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<CastExpr> toCastExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<CharLiteralExpr> toCharLiteralExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ClassExpr> toClassExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ConditionalExpr> toConditionalExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<DoubleLiteralExpr> toDoubleLiteralExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<EnclosedExpr> toEnclosedExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<FieldAccessExpr> toFieldAccessExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<InstanceOfExpr> toInstanceOfExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<IntegerLiteralExpr> toIntegerLiteralExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<LambdaExpr> toLambdaExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<LiteralExpr> toLiteralExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<LiteralStringValueExpr> toLiteralStringValueExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<LongLiteralExpr> toLongLiteralExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<MarkerAnnotationExpr> toMarkerAnnotationExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<MethodCallExpr> toMethodCallExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<MethodReferenceExpr> toMethodReferenceExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<NameExpr> toNameExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<NormalAnnotationExpr> toNormalAnnotationExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<NullLiteralExpr> toNullLiteralExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ObjectCreationExpr> toObjectCreationExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<SingleMemberAnnotationExpr> toSingleMemberAnnotationExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<StringLiteralExpr> toStringLiteralExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<SuperExpr> toSuperExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ThisExpr> toThisExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<TypeExpr> toTypeExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<UnaryExpr> toUnaryExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<VariableDeclarationExpr> toVariableDeclarationExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isSwitchExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public SwitchExpr asSwitchExpr() {
throw new IllegalStateException(
f("%s is not SwitchExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<SwitchExpr> toSwitchExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifSwitchExpr(Consumer<SwitchExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isTextBlockLiteralExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public TextBlockLiteralExpr asTextBlockLiteralExpr() {
throw new IllegalStateException(f(
"%s is not TextBlockLiteralExpr, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<TextBlockLiteralExpr> toTextBlockLiteralExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifTextBlockLiteralExpr(Consumer<TextBlockLiteralExpr> action) {}
/**
* See https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.2
* @return true if the expression is a standalone expression
*/
public boolean isStandaloneExpression() {
return !isPolyExpression();
}
/**
* See https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.2
* @return true if the expression is a poly expression
*/
public boolean isPolyExpression() {
return false;
}
/*
* 6.5.6.2. Qualified Expression Names
* https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.5.6.2
*/
public boolean isQualified() {
return hasScope();
}
/*
* Verify if the parent node is an assignment context.
*/
public final boolean appearsInAssignmentContext() {
if (getParentNode().isPresent() && getParentNode().get() instanceof Expression) {
return ((Expression) getParentNode().get()).isAssignmentContext();
}
return false;
}
/*
* Returns true if the expression is an assignment context. Default is false.
* https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.2
* 5.2. Assignment Contexts: Assignment contexts allow the value of an expression to be assigned (§15.26) to a variable;...
*/
protected boolean isAssignmentContext() {
return false;
}
/*
* Verify if the parent node is an invocation context.
*/
public final boolean appearsInInvocationContext() {
if (getParentNode().isPresent() && getParentNode().get() instanceof Expression) {
return ((Expression) getParentNode().get()).isInvocationContext();
}
return false;
}
/*
* Returns true if the expression is an invocation context. Default is false.
* https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.3
* 5.3. Invocation Contexts
*/
protected boolean isInvocationContext() {
return false;
}
/*
* returns true if the scope of this expression does not define an type argument or if the expression has not a scope (the expression is not qualified)
* or if there is a scope it uses <> to elide class type arguments
* For exemple :
* m() ==> true because there is no scope
* a.m() ==> true because the scope has no type arguments
* a<>.m() ==> true because the type argument is elided
* a<T>.m() ==> false because the type argument is not elided
*/
public final boolean elidesTypeArguments() {
if (!(hasScope() && this instanceof NodeWithTypeArguments)) {
return true;
}
Expression scope =
(Expression) ((NodeWithOptionalScope) this).getScope().get();
NodeWithTypeArguments nwta = (NodeWithTypeArguments) this;
return scope.elidesTypeArguments() && (!nwta.getTypeArguments().isPresent() || nwta.isUsingDiamondOperator());
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isTypePatternExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public TypePatternExpr asTypePatternExpr() {
throw new IllegalStateException(
f("%s is not TypePatternExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<TypePatternExpr> toTypePatternExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifTypePatternExpr(Consumer<TypePatternExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isPatternExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public PatternExpr asPatternExpr() {
throw new IllegalStateException(
f("%s is not PatternExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<PatternExpr> toPatternExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifPatternExpr(Consumer<PatternExpr> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isRecordPatternExpr() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public RecordPatternExpr asRecordPatternExpr() {
throw new IllegalStateException(
f("%s is not RecordPatternExpr, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<RecordPatternExpr> toRecordPatternExpr() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifRecordPatternExpr(Consumer<RecordPatternExpr> action) {}
}

View File

@@ -0,0 +1,278 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.nodeTypes.NodeWithScope;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithTypeArguments;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.FieldAccessExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.UnsolvedSymbolException;
import com.github.javaparser.resolution.declarations.ResolvedValueDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* Access of a field of an object or a class.
* <br>In {@code person.name} "name" is the name and "person" is the scope.
*
* @author Julio Vilmar Gesser
*/
public class FieldAccessExpr extends Expression
implements NodeWithSimpleName<FieldAccessExpr>,
NodeWithTypeArguments<FieldAccessExpr>,
NodeWithScope<FieldAccessExpr>,
Resolvable<ResolvedValueDeclaration> {
private Expression scope;
@OptionalProperty
private NodeList<Type> typeArguments;
private SimpleName name;
public FieldAccessExpr() {
this(null, new ThisExpr(), null, new SimpleName());
}
public FieldAccessExpr(final Expression scope, final String name) {
this(null, scope, null, new SimpleName(name));
}
@AllFieldsConstructor
public FieldAccessExpr(final Expression scope, final NodeList<Type> typeArguments, final SimpleName name) {
this(null, scope, typeArguments, name);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public FieldAccessExpr(TokenRange tokenRange, Expression scope, NodeList<Type> typeArguments, SimpleName name) {
super(tokenRange);
setScope(scope);
setTypeArguments(typeArguments);
setName(name);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public FieldAccessExpr setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getScope() {
return scope;
}
/**
* Sets the scope
*
* @param scope the scope, can not be null
* @return this, the FieldAccessExpr
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public FieldAccessExpr setScope(final Expression scope) {
assertNotNull(scope);
if (scope == this.scope) {
return this;
}
notifyPropertyChange(ObservableProperty.SCOPE, this.scope, scope);
if (this.scope != null) this.scope.setParentNode(null);
this.scope = scope;
setAsParentNodeOf(scope);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<NodeList<Type>> getTypeArguments() {
return Optional.ofNullable(typeArguments);
}
/**
* Sets the type arguments
*
* @param typeArguments the type arguments, can be null
* @return this, the FieldAccessExpr
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public FieldAccessExpr setTypeArguments(final NodeList<Type> typeArguments) {
if (typeArguments == this.typeArguments) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE_ARGUMENTS, this.typeArguments, typeArguments);
if (this.typeArguments != null) this.typeArguments.setParentNode(null);
this.typeArguments = typeArguments;
setAsParentNodeOf(typeArguments);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public FieldAccessExpr clone() {
return (FieldAccessExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public FieldAccessExprMetaModel getMetaModel() {
return JavaParserMetaModel.fieldAccessExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
if (typeArguments != null) {
for (int i = 0; i < typeArguments.size(); i++) {
if (typeArguments.get(i) == node) {
typeArguments.remove(i);
return true;
}
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
if (node == scope) {
setScope((Expression) replacementNode);
return true;
}
if (typeArguments != null) {
for (int i = 0; i < typeArguments.size(); i++) {
if (typeArguments.get(i) == node) {
typeArguments.set(i, (Type) replacementNode);
return true;
}
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isFieldAccessExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public FieldAccessExpr asFieldAccessExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifFieldAccessExpr(Consumer<FieldAccessExpr> action) {
action.accept(this);
}
/**
* Attempts to resolve the declaration corresponding to the accessed field. If successful, a
* {@link ResolvedValueDeclaration} representing the declaration of the value accessed by this
* {@code FieldAccessExpr} is returned. Otherwise, an {@link UnsolvedSymbolException} is thrown.
*
* @return a {@link ResolvedValueDeclaration} representing the declaration of the accessed value.
* @throws UnsolvedSymbolException if the declaration corresponding to the field access expression could not be
* resolved.
* @see NameExpr#resolve()
* @see MethodCallExpr#resolve()
* @see ObjectCreationExpr#resolve()
* @see ExplicitConstructorInvocationStmt#resolve()
*/
@Override
public ResolvedValueDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedValueDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<FieldAccessExpr> toFieldAccessExpr() {
return Optional.of(this);
}
/**
* Indicate if this FieldAccessExpr is an element directly contained in a larger FieldAccessExpr.
*/
public boolean isInternal() {
return this.getParentNode().isPresent() && this.getParentNode().get() instanceof FieldAccessExpr;
}
/**
* Indicate if this FieldAccessExpr is top level, i.e., it is not directly contained in a larger FieldAccessExpr.
*/
public boolean isTopLevel() {
return !isInternal();
}
}

View File

@@ -0,0 +1,294 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithExpression;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.ReferenceType;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.InstanceOfExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import java.util.Optional;
import java.util.function.Consumer;
/**
* <h1>The instanceof statement</h1>
*
* <h2>Java ?? to 13</h2>
* The {@code instanceof} expression is a
* <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.20">relational operator</a>,
* evaluating to true if the object on the left hand side
* is an instance of the type ({@link ReferenceType}) on the right hand side.
* <br>
* <br>
* Example:
* <br>{@code tool instanceof Drill}
* <br>
* <br>This is then used wherever a conditional/boolean value can be used. For example:
* <br>
* <pre>{@code if (obj instanceof String) {
* String s = (String) obj;
* // use s
* }}</pre>
* <br>
* <h2>Java 14</h2>
* Since JDK14, it is possible to bind a variable that is cast to the type being tested against.
* This is referred to as a {@code Pattern} within <a href="https://bugs.openjdk.java.net/browse/JDK-8181287">JEP305</a>,
* and avoids the need to cast to the desired type.
* <br>
* Example:
* <br>{@code tool instanceof Drill d}
* <br>
* <br>This is then used wherever a conditional/boolean value can be used. The scope of the variable created can vary, and is defined further within
* <a href="https://bugs.openjdk.java.net/browse/JDK-8181287">JEP305</a>.
* <br>
* <pre>{@code if (obj instanceof String s) {
* // can use s here
* } else {
* // can't use s here
* }}</pre>
* <br>
* <br>
* <h3>JDK14 Grammar</h3>
* Per JEP305:
* <br>
* <pre>{@code RelationalExpression:
* ...
* RelationalExpression instanceof ReferenceType
* RelationalExpression instanceof Pattern
*
* Pattern:
* ReferenceType Identifier}</pre>
*
* @author Julio Vilmar Gesser
*
* @see PatternExpr
* @see <a href="https://bugs.openjdk.java.net/browse/JDK-8181287">JEP305: https://bugs.openjdk.java.net/browse/JDK-8181287</a>
* @see <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.20">https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.20</a>
*/
public class InstanceOfExpr extends Expression
implements NodeWithType<InstanceOfExpr, ReferenceType>, NodeWithExpression<InstanceOfExpr> {
private Expression expression;
@OptionalProperty
private PatternExpr pattern;
private ReferenceType type;
public InstanceOfExpr() {
this(null, new NameExpr(), new ClassOrInterfaceType(), null);
}
public InstanceOfExpr(final Expression expression, final ReferenceType type) {
this(null, expression, type, null);
}
@AllFieldsConstructor
public InstanceOfExpr(final Expression expression, final ReferenceType type, final PatternExpr pattern) {
this(null, expression, type, pattern);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public InstanceOfExpr(TokenRange tokenRange, Expression expression, ReferenceType type, PatternExpr pattern) {
super(tokenRange);
setExpression(expression);
setType(type);
setPattern(pattern);
customInitialization();
}
/**
* Helper method which, if this is an expression with a type pattern, returns the identifier/name.
* <br>
* <br>For example:
* <br>{@code obj instanceof String stringName}
* <br>
* <br>In this example, {@code getName()} returns {@code stringName}
*/
public Optional<SimpleName> getName() {
if (pattern == null) {
return Optional.empty();
}
if (!pattern.isTypePatternExpr()) {
return Optional.empty();
}
return Optional.of(pattern.asTypePatternExpr().getName());
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public InstanceOfExpr asInstanceOfExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public InstanceOfExpr clone() {
return (InstanceOfExpr) accept(new CloneVisitor(), null);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getExpression() {
return expression;
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public InstanceOfExprMetaModel getMetaModel() {
return JavaParserMetaModel.instanceOfExprMetaModel;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<PatternExpr> getPattern() {
return Optional.ofNullable(pattern);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ReferenceType getType() {
return type;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifInstanceOfExpr(Consumer<InstanceOfExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isInstanceOfExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
if (pattern != null) {
if (node == pattern) {
removePattern();
return true;
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public InstanceOfExpr removePattern() {
return setPattern((PatternExpr) null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == expression) {
setExpression((Expression) replacementNode);
return true;
}
if (pattern != null) {
if (node == pattern) {
setPattern((PatternExpr) replacementNode);
return true;
}
}
if (node == type) {
setType((ReferenceType) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public InstanceOfExpr setExpression(final Expression expression) {
assertNotNull(expression);
if (expression == this.expression) {
return this;
}
notifyPropertyChange(ObservableProperty.EXPRESSION, this.expression, expression);
if (this.expression != null) this.expression.setParentNode(null);
this.expression = expression;
setAsParentNodeOf(expression);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public InstanceOfExpr setPattern(final PatternExpr pattern) {
if (pattern == this.pattern) {
return this;
}
notifyPropertyChange(ObservableProperty.PATTERN, this.pattern, pattern);
if (this.pattern != null) this.pattern.setParentNode(null);
this.pattern = pattern;
setAsParentNodeOf(pattern);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public InstanceOfExpr setType(final ReferenceType type) {
assertNotNull(type);
if (type == this.type) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE, this.type, type);
if (this.type != null) this.type.setParentNode(null);
this.type = type;
setAsParentNodeOf(type);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<InstanceOfExpr> toInstanceOfExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,181 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.hasUnaryMinusAsParent;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.IntegerLiteralExprMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
/**
* All ways to specify an int literal.
*
* <ul>
* <li>{@code 8934}</li>
* <li>{@code 0x01}</li>
* <li>{@code 022}</li>
* <li>{@code 0B10101010}</li>
* </ul>
*
* @author Julio Vilmar Gesser
*/
public class IntegerLiteralExpr extends LiteralStringValueExpr {
public static final String MAX_31_BIT_UNSIGNED_VALUE_AS_STRING = "2147483648";
public static final long MAX_31_BIT_UNSIGNED_VALUE_AS_LONG = 2147483648L;
public IntegerLiteralExpr() {
this(null, "0");
}
@AllFieldsConstructor
public IntegerLiteralExpr(final String value) {
this(null, value);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public IntegerLiteralExpr(TokenRange tokenRange, String value) {
super(tokenRange, value);
customInitialization();
}
/**
* @deprecated This function is deprecated in favor of {@link #IntegerLiteralExpr(String)}. Please refer to the
* {@link #asNumber()} function for valid formats and how to construct literals holding negative values.
*/
@Deprecated
public IntegerLiteralExpr(final int value) {
this(null, String.valueOf(value));
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* @return the literal value as an integer while respecting different number representations
* @deprecated This function has issues with corner cases, such as 2147483648, so please use {@link
* IntegerLiteralExpr#asNumber()}. It will be made private or merged with {@link IntegerLiteralExpr#asNumber()} in
* future releases
*/
@Deprecated
public int asInt() {
String result = value.replaceAll("_", "");
if (result.startsWith("0x") || result.startsWith("0X")) {
return Integer.parseUnsignedInt(result.substring(2), 16);
}
if (result.startsWith("0b") || result.startsWith("0B")) {
return Integer.parseUnsignedInt(result.substring(2), 2);
}
if (result.length() > 1 && result.startsWith("0")) {
return Integer.parseUnsignedInt(result.substring(1), 8);
}
return Integer.parseInt(result);
}
/**
* This function returns a representation of the literal value as a number. This will return an integer, except for
* the case when the literal has the value {@code 2147483648}. This special literal is only allowed in the
* expression {@code -2147483648} which represents <code>Integer.MIN_VALUE</code>). However 2147483648 (2^31)
* is out of range of int, which is -(2^31) to (2^31)-1 and thus a long must be returned.
*
* <p>Note, that this function will NOT return a negative number if the literal was specified in decimal, since
* according to the language specification (chapter 3.10.1) an expression such as {@code -1} is represented by
* a unary expression with a minus operator and the literal {@code 1}. It is however possible to represent
* negative numbers in a literal directly, i.e. by using the binary or hexadecimal representation. For example
* {@code 0xffff_ffff} represents the value <code> -1</code>.
*
* @return the literal value as a number while respecting different number representations
*/
public Number asNumber() {
if (Objects.equals(value, MAX_31_BIT_UNSIGNED_VALUE_AS_STRING) && hasUnaryMinusAsParent(this)) {
return MAX_31_BIT_UNSIGNED_VALUE_AS_LONG;
}
return asInt();
}
/**
* @deprecated This function is deprecated in favor of {@link #setValue(String)}. Please refer to the {@link
* #asNumber()} function for valid formats and how to construct literals holding negative values.
*/
@Deprecated
public IntegerLiteralExpr setInt(int value) {
this.value = String.valueOf(value);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public IntegerLiteralExpr clone() {
return (IntegerLiteralExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public IntegerLiteralExprMetaModel getMetaModel() {
return JavaParserMetaModel.integerLiteralExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isIntegerLiteralExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public IntegerLiteralExpr asIntegerLiteralExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifIntegerLiteralExpr(Consumer<IntegerLiteralExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<IntegerLiteralExpr> toIntegerLiteralExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,283 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.nodeTypes.NodeWithParameters;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ExpressionStmt;
import com.github.javaparser.ast.stmt.ReturnStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.DerivedProperty;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.LambdaExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* <h1>A lambda expression</h1>
* <h2>Java 1-7</h2>
* Does not exist.
* <h2>Java 8+</h2>
* {@code (a, b) -> a + b}
* <br>{@code a -> ...}
* <br>{@code (Long a) -> { println(a); }}
* <p>The parameters are on the left side of the -&gt;.
* If a parameter uses type inference (it has no type specified) then its type is set to {@code UnknownType}.
* If they are in ( ), "isEnclosingParameters" is true.
* <br>The body is to the right of the -&gt;.
* The body is either a BlockStmt when it is in { } braces, or an ExpressionStmt when it is not in braces.
*
* @author Raquel Pau
*/
public class LambdaExpr extends Expression implements NodeWithParameters<LambdaExpr> {
private NodeList<Parameter> parameters;
private boolean isEnclosingParameters;
private Statement body;
public LambdaExpr() {
this(null, new NodeList<>(), new ReturnStmt(), false);
}
/**
* Creates a single parameter lambda expression.
*/
public LambdaExpr(Parameter parameter, BlockStmt body) {
this(null, new NodeList<>(parameter), body, false);
}
/**
* Creates a zero or multi-parameter lambda expression with its parameters wrapped in ( ).
*/
public LambdaExpr(NodeList<Parameter> parameters, BlockStmt body) {
this(null, parameters, body, true);
}
/**
* Creates a single parameter lambda expression.
*/
public LambdaExpr(Parameter parameter, Expression body) {
this(null, new NodeList<>(parameter), new ExpressionStmt(body), false);
}
/**
* Creates a zero or multi-parameter lambda expression with its parameters wrapped in ( ).
*/
public LambdaExpr(NodeList<Parameter> parameters, Expression body) {
this(null, parameters, new ExpressionStmt(body), true);
}
@AllFieldsConstructor
public LambdaExpr(NodeList<Parameter> parameters, Statement body, boolean isEnclosingParameters) {
this(null, parameters, body, isEnclosingParameters);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public LambdaExpr(
TokenRange tokenRange, NodeList<Parameter> parameters, Statement body, boolean isEnclosingParameters) {
super(tokenRange);
setParameters(parameters);
setBody(body);
setEnclosingParameters(isEnclosingParameters);
customInitialization();
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Parameter> getParameters() {
return parameters;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public LambdaExpr setParameters(final NodeList<Parameter> parameters) {
assertNotNull(parameters);
if (parameters == this.parameters) {
return this;
}
notifyPropertyChange(ObservableProperty.PARAMETERS, this.parameters, parameters);
if (this.parameters != null) this.parameters.setParentNode(null);
this.parameters = parameters;
setAsParentNodeOf(parameters);
return this;
}
/**
* @return a BlockStatement or an ExpressionStatement. See class Javadoc.
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Statement getBody() {
return body;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public LambdaExpr setBody(final Statement body) {
assertNotNull(body);
if (body == this.body) {
return this;
}
notifyPropertyChange(ObservableProperty.BODY, this.body, body);
if (this.body != null) this.body.setParentNode(null);
this.body = body;
setAsParentNodeOf(body);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public boolean isEnclosingParameters() {
return isEnclosingParameters;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public LambdaExpr setEnclosingParameters(final boolean isEnclosingParameters) {
if (isEnclosingParameters == this.isEnclosingParameters) {
return this;
}
notifyPropertyChange(
ObservableProperty.ENCLOSING_PARAMETERS, this.isEnclosingParameters, isEnclosingParameters);
this.isEnclosingParameters = isEnclosingParameters;
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < parameters.size(); i++) {
if (parameters.get(i) == node) {
parameters.remove(i);
return true;
}
}
return super.remove(node);
}
/**
* @return if the body of this lambda is a simple expression, return that expression.
* Otherwise (when the body is a block) return Optional.empty().
*/
@DerivedProperty
public Optional<Expression> getExpressionBody() {
if (body.isExpressionStmt()) {
return Optional.of(body.asExpressionStmt().getExpression());
}
return Optional.empty();
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public LambdaExpr clone() {
return (LambdaExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public LambdaExprMetaModel getMetaModel() {
return JavaParserMetaModel.lambdaExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == body) {
setBody((Statement) replacementNode);
return true;
}
for (int i = 0; i < parameters.size(); i++) {
if (parameters.get(i) == node) {
parameters.set(i, (Parameter) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isLambdaExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public LambdaExpr asLambdaExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifLambdaExpr(Consumer<LambdaExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<LambdaExpr> toLambdaExpr() {
return Optional.of(this);
}
/*
* Lambda expressions are always poly expressions
*/
@Override
public boolean isPolyExpression() {
return true;
}
/*
* Returns true if no type parameter has been defined
*/
public boolean isExplicitlyTyped() {
return getParameters().stream().allMatch(p -> !(p.getType().isUnknownType()));
}
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.LiteralExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A base class for all literal expressions.
*
* @author Julio Vilmar Gesser
*/
public abstract class LiteralExpr extends Expression {
@AllFieldsConstructor
public LiteralExpr() {
this(null);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public LiteralExpr(TokenRange tokenRange) {
super(tokenRange);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public LiteralExpr clone() {
return (LiteralExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public LiteralExprMetaModel getMetaModel() {
return JavaParserMetaModel.literalExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isLiteralExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public LiteralExpr asLiteralExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifLiteralExpr(Consumer<LiteralExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<LiteralExpr> toLiteralExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.LiteralStringValueExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* Any literal value that is stored internally as a String.
*/
public abstract class LiteralStringValueExpr extends LiteralExpr {
protected String value;
@AllFieldsConstructor
public LiteralStringValueExpr(final String value) {
this(null, value);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public LiteralStringValueExpr(TokenRange tokenRange, String value) {
super(tokenRange);
setValue(value);
customInitialization();
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public String getValue() {
return value;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public LiteralStringValueExpr setValue(final String value) {
assertNotNull(value);
if (value == this.value) {
return this;
}
notifyPropertyChange(ObservableProperty.VALUE, this.value, value);
this.value = value;
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public LiteralStringValueExpr clone() {
return (LiteralStringValueExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public LiteralStringValueExprMetaModel getMetaModel() {
return JavaParserMetaModel.literalStringValueExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isLiteralStringValueExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public LiteralStringValueExpr asLiteralStringValueExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifLiteralStringValueExpr(Consumer<LiteralStringValueExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<LiteralStringValueExpr> toLiteralStringValueExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,188 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.hasUnaryMinusAsParent;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.LongLiteralExprMetaModel;
import java.math.BigInteger;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
/**
* All ways to specify a long literal.
*
* <ul>
* <li>{@code 8934l}</li>
* <li>{@code 0x01L}</li>
* <li>{@code 022l}</li>
* <li>{@code 0B10101010L}</li>
* <li>{@code 99999999L}</li>
* </ul>
*
* @author Julio Vilmar Gesser
*/
public class LongLiteralExpr extends LiteralStringValueExpr {
public static final String MAX_63_BIT_UNSIGNED_VALUE_AS_STRING = "9223372036854775808L";
public static final BigInteger MAX_63_BIT_UNSIGNED_VALUE_AS_BIG_INTEGER = new BigInteger("9223372036854775808");
public LongLiteralExpr() {
this(null, "0");
}
@AllFieldsConstructor
public LongLiteralExpr(final String value) {
this(null, value);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public LongLiteralExpr(TokenRange tokenRange, String value) {
super(tokenRange, value);
customInitialization();
}
/**
* @deprecated This function is deprecated in favor of {@link #LongLiteralExpr(String)}. Please refer to the {@link
* #asNumber()} function for valid formats and how to construct literals holding negative values.
*/
@Deprecated
public LongLiteralExpr(final long value) {
this(null, String.valueOf(value));
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* @return the literal value as an long while respecting different number representations
* @deprecated This function has issues with corner cases, such as 9223372036854775808L, so please use {@link
* LongLiteralExpr#asNumber()}. It will be made private or merged with {@link LongLiteralExpr#asNumber()} in future
* releases
*/
@Deprecated
public long asLong() {
String result = value.replaceAll("_", "");
char lastChar = result.charAt(result.length() - 1);
if (lastChar == 'l' || lastChar == 'L') {
result = result.substring(0, result.length() - 1);
}
if (result.startsWith("0x") || result.startsWith("0X")) {
return Long.parseUnsignedLong(result.substring(2), 16);
}
if (result.startsWith("0b") || result.startsWith("0B")) {
return Long.parseUnsignedLong(result.substring(2), 2);
}
if (result.length() > 1 && result.startsWith("0")) {
return Long.parseUnsignedLong(result.substring(1), 8);
}
return Long.parseLong(result);
}
/**
* This function returns a representation of the literal value as a number. This will return a long, except for the
* case when the literal has the value {@code 9223372036854775808L}. This special literal is only allowed in
* the expression {@code -9223372036854775808L} which represents <code>Long.MIN_VALUE</code>). However
* 9223372036854775808 (2^63) is out of range of long, which is -(2^63) to (2^63)-1 and thus a BigInteger must be
* returned.
*
* <p>Note, that this function will NOT return a negative number if the literal was specified in decimal, since
* according to the language specification (chapter 3.10.1) an expression such as {@code -1L} is represented by
* a unary * expression with a minus operator and the literal {@code 1L}. It is however possible to represent
* negative * numbers in a literal directly, i.e. by using the binary or hexadecimal representation. For example
* {@code 0xffff_ffff_ffff_ffffL} represents the value <code>-1L</code>.
*
* @return the literal value as a number while respecting different number representations
*/
public Number asNumber() {
if (Objects.equals(value, MAX_63_BIT_UNSIGNED_VALUE_AS_STRING) && hasUnaryMinusAsParent(this)) {
return MAX_63_BIT_UNSIGNED_VALUE_AS_BIG_INTEGER;
}
return asLong();
}
/**
* @deprecated This function is deprecated in favor of {@link #setValue(String)}. Please refer to the {@link
* #asNumber()} function for valid formats and how to construct literals holding negative values.
*/
@Deprecated
public LongLiteralExpr setLong(long value) {
this.value = String.valueOf(value);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public LongLiteralExpr clone() {
return (LongLiteralExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public LongLiteralExprMetaModel getMetaModel() {
return JavaParserMetaModel.longLiteralExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isLongLiteralExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public LongLiteralExpr asLongLiteralExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifLongLiteralExpr(Consumer<LongLiteralExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<LongLiteralExpr> toLongLiteralExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.StaticJavaParser.parseName;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.MarkerAnnotationExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* An annotation that uses only the annotation type name.
* <br>{@code @Override}
*
* @author Julio Vilmar Gesser
*/
public class MarkerAnnotationExpr extends AnnotationExpr {
public MarkerAnnotationExpr() {
this(null, new Name());
}
public MarkerAnnotationExpr(final String name) {
this(null, parseName(name));
}
@AllFieldsConstructor
public MarkerAnnotationExpr(final Name name) {
this(null, name);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public MarkerAnnotationExpr(TokenRange tokenRange, Name name) {
super(tokenRange, name);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public MarkerAnnotationExpr clone() {
return (MarkerAnnotationExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public MarkerAnnotationExprMetaModel getMetaModel() {
return JavaParserMetaModel.markerAnnotationExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isMarkerAnnotationExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public MarkerAnnotationExpr asMarkerAnnotationExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifMarkerAnnotationExpr(Consumer<MarkerAnnotationExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<MarkerAnnotationExpr> toMarkerAnnotationExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,149 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.MemberValuePairMetaModel;
/**
* A value for a member of an annotation.
* In {@code @Counters(a=15)} a=15 is a MemberValuePair. Its name is a, and its value is 15.
*
* @author Julio Vilmar Gesser
*/
public class MemberValuePair extends Node implements NodeWithSimpleName<MemberValuePair> {
private SimpleName name;
private Expression value;
public MemberValuePair() {
this(null, new SimpleName(), new StringLiteralExpr());
}
public MemberValuePair(final String name, final Expression value) {
this(null, new SimpleName(name), value);
}
@AllFieldsConstructor
public MemberValuePair(final SimpleName name, final Expression value) {
this(null, name, value);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public MemberValuePair(TokenRange tokenRange, SimpleName name, Expression value) {
super(tokenRange);
setName(name);
setValue(value);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getValue() {
return value;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public MemberValuePair setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public MemberValuePair setValue(final Expression value) {
assertNotNull(value);
if (value == this.value) {
return this;
}
notifyPropertyChange(ObservableProperty.VALUE, this.value, value);
if (this.value != null) this.value.setParentNode(null);
this.value = value;
setAsParentNodeOf(value);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public MemberValuePair clone() {
return (MemberValuePair) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public MemberValuePairMetaModel getMetaModel() {
return JavaParserMetaModel.memberValuePairMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
if (node == value) {
setValue((Expression) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
}

View File

@@ -0,0 +1,401 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.nodeTypes.NodeWithArguments;
import com.github.javaparser.ast.nodeTypes.NodeWithOptionalScope;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.nodeTypes.NodeWithTypeArguments;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.MethodCallExprMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.UnsolvedSymbolException;
import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration;
import com.github.javaparser.resolution.types.ResolvedType;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A method call on an object or a class. <br>{@code circle.circumference()} <br>In {@code a.<String>bb(15);}, a
* is the scope, String is a type argument, bb is the name and 15 is an argument.
*
* @author Julio Vilmar Gesser
*/
public class MethodCallExpr extends Expression
implements NodeWithTypeArguments<MethodCallExpr>,
NodeWithArguments<MethodCallExpr>,
NodeWithSimpleName<MethodCallExpr>,
NodeWithOptionalScope<MethodCallExpr>,
Resolvable<ResolvedMethodDeclaration> {
@OptionalProperty
private Expression scope;
@OptionalProperty
private NodeList<Type> typeArguments;
private SimpleName name;
private NodeList<Expression> arguments;
public MethodCallExpr() {
this(null, null, null, new SimpleName(), new NodeList<>());
}
public MethodCallExpr(String name, Expression... arguments) {
this(null, null, null, new SimpleName(name), new NodeList<>(arguments));
}
public MethodCallExpr(final Expression scope, final String name) {
this(null, scope, null, new SimpleName(name), new NodeList<>());
}
public MethodCallExpr(final Expression scope, final SimpleName name) {
this(null, scope, null, name, new NodeList<>());
}
public MethodCallExpr(final Expression scope, final String name, final NodeList<Expression> arguments) {
this(null, scope, null, new SimpleName(name), arguments);
}
public MethodCallExpr(
final Expression scope,
final NodeList<Type> typeArguments,
final String name,
final NodeList<Expression> arguments) {
this(null, scope, typeArguments, new SimpleName(name), arguments);
}
public MethodCallExpr(final Expression scope, final SimpleName name, final NodeList<Expression> arguments) {
this(null, scope, null, name, arguments);
}
@AllFieldsConstructor
public MethodCallExpr(
final Expression scope,
final NodeList<Type> typeArguments,
final SimpleName name,
final NodeList<Expression> arguments) {
this(null, scope, typeArguments, name, arguments);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public MethodCallExpr(
TokenRange tokenRange,
Expression scope,
NodeList<Type> typeArguments,
SimpleName name,
NodeList<Expression> arguments) {
super(tokenRange);
setScope(scope);
setTypeArguments(typeArguments);
setName(name);
setArguments(arguments);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Expression> getArguments() {
return arguments;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<Expression> getScope() {
return Optional.ofNullable(scope);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public MethodCallExpr setArguments(final NodeList<Expression> arguments) {
assertNotNull(arguments);
if (arguments == this.arguments) {
return this;
}
notifyPropertyChange(ObservableProperty.ARGUMENTS, this.arguments, arguments);
if (this.arguments != null) this.arguments.setParentNode(null);
this.arguments = arguments;
setAsParentNodeOf(arguments);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public MethodCallExpr setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public MethodCallExpr setScope(final Expression scope) {
if (scope == this.scope) {
return this;
}
notifyPropertyChange(ObservableProperty.SCOPE, this.scope, scope);
if (this.scope != null) this.scope.setParentNode(null);
this.scope = scope;
setAsParentNodeOf(scope);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<NodeList<Type>> getTypeArguments() {
return Optional.ofNullable(typeArguments);
}
/**
* Sets the typeArguments
*
* @param typeArguments the typeArguments, can be null
* @return this, the MethodCallExpr
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public MethodCallExpr setTypeArguments(final NodeList<Type> typeArguments) {
if (typeArguments == this.typeArguments) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE_ARGUMENTS, this.typeArguments, typeArguments);
if (this.typeArguments != null) this.typeArguments.setParentNode(null);
this.typeArguments = typeArguments;
setAsParentNodeOf(typeArguments);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < arguments.size(); i++) {
if (arguments.get(i) == node) {
arguments.remove(i);
return true;
}
}
if (scope != null) {
if (node == scope) {
removeScope();
return true;
}
}
if (typeArguments != null) {
for (int i = 0; i < typeArguments.size(); i++) {
if (typeArguments.get(i) == node) {
typeArguments.remove(i);
return true;
}
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public MethodCallExpr removeScope() {
return setScope((Expression) null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public MethodCallExpr clone() {
return (MethodCallExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public MethodCallExprMetaModel getMetaModel() {
return JavaParserMetaModel.methodCallExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < arguments.size(); i++) {
if (arguments.get(i) == node) {
arguments.set(i, (Expression) replacementNode);
return true;
}
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
if (scope != null) {
if (node == scope) {
setScope((Expression) replacementNode);
return true;
}
}
if (typeArguments != null) {
for (int i = 0; i < typeArguments.size(); i++) {
if (typeArguments.get(i) == node) {
typeArguments.set(i, (Type) replacementNode);
return true;
}
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isMethodCallExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public MethodCallExpr asMethodCallExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifMethodCallExpr(Consumer<MethodCallExpr> action) {
action.accept(this);
}
/**
* Attempts to resolve the declaration corresponding to the invoked method. If successful, a
* {@link ResolvedMethodDeclaration} representing the declaration of the constructor invoked by this
* {@code MethodCallExpr} is returned. Otherwise, an {@link UnsolvedSymbolException} is thrown.
*
* @return a {@link ResolvedMethodDeclaration} representing the declaration of the invoked method.
* @throws UnsolvedSymbolException if the declaration corresponding to the method call expression could not be
* resolved.
* @see NameExpr#resolve()
* @see FieldAccessExpr#resolve()
* @see ObjectCreationExpr#resolve()
* @see ExplicitConstructorInvocationStmt#resolve()
*/
@Override
public ResolvedMethodDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedMethodDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<MethodCallExpr> toMethodCallExpr() {
return Optional.of(this);
}
/*
* A method invocation expression is a poly expression if all of the following are true:
* 1. The invocation appears in an assignment context or an invocation context (§5.2, §5.3).
* 2. If the invocation is qualified (that is, any form of MethodInvocation except for the first), then
* the invocation elides TypeArguments to the left of the Identifier.
* 3. The method to be invoked, as determined by the following subsections, is generic (§8.4.4) and has a
* return type that mentions at least one of the method's type parameters.
* Otherwise, the method invocation expression is a standalone expression.
*/
@Override
public boolean isPolyExpression() {
// A method invocation expression is a poly expression if all of the following are true:
//
// 1. The invocation appears in an assignment context or an invocation context (§5.2, §5.3).
if (!(appearsInAssignmentContext() || appearsInInvocationContext())) {
return false;
}
// 2. If the invocation is qualified (that is, any form of MethodInvocation except for the form [MethodName (
// [ArgumentList] )]), then the invocation elides TypeArguments to the left of the Identifier.
if (isQualified() && !elidesTypeArguments()) {
return false;
}
// 3. The method to be invoked, as determined by the following subsections, is generic (§8.4.4) and has a
// return type that mentions at least one of the method's type parameters.
// A method is generic if it declares one or more type variables (§4.4).
if (isGenericMethod()
&& hasParameterwithSameTypeThanResultType(resolve().getReturnType())) {
// it's a poly expression
return true;
}
// Otherwise, the method invocation expression is a standalone expression.
return false;
}
/*
* A method is generic if it declares one or more type variables (§4.4).
* Not sure it's enough to verify that the type arguments list is empty or not.
*/
private boolean isGenericMethod() {
return getTypeArguments().isPresent() && !getTypeArguments().get().isEmpty();
}
/*
* return true if at least one of the method's type parameters has the same type as the specified type .
*/
private boolean hasParameterwithSameTypeThanResultType(ResolvedType resolvedReturnType) {
return getTypeArguments().isPresent()
&& getTypeArguments().get().stream()
.anyMatch(argType -> argType.resolve().isAssignableBy(resolvedReturnType));
}
/*
* Returns true if the expression is an invocation context.
* https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.3
* 5.3. Invocation Contexts
*/
@Override
protected boolean isInvocationContext() {
return true;
}
}

View File

@@ -0,0 +1,252 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNonEmpty;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.nodeTypes.NodeWithIdentifier;
import com.github.javaparser.ast.nodeTypes.NodeWithTypeArguments;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.MethodReferenceExprMetaModel;
import com.github.javaparser.metamodel.NonEmptyProperty;
import com.github.javaparser.metamodel.OptionalProperty;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* Method reference expressions introduced in Java 8 specifically designed to simplify lambda Expressions.
* Note that the field "identifier", indicating the word to the right of the ::, is not always a method name,
* it can be "new".
* <br>In {@code System.out::println;} the scope is System.out and the identifier is "println"
* <br>{@code (test ? stream.map(String::trim) : stream)::toArray;}
* <br>In {@code Bar<String>::<Integer>new} the String type argument is on the scope,
* and the Integer type argument is on this MethodReferenceExpr.
*
* @author Raquel Pau
*/
public class MethodReferenceExpr extends Expression
implements NodeWithTypeArguments<MethodReferenceExpr>,
NodeWithIdentifier<MethodReferenceExpr>,
Resolvable<ResolvedMethodDeclaration> {
private Expression scope;
@OptionalProperty
private NodeList<Type> typeArguments;
@NonEmptyProperty
private String identifier;
public MethodReferenceExpr() {
this(null, new ClassExpr(), null, "empty");
}
@AllFieldsConstructor
public MethodReferenceExpr(Expression scope, NodeList<Type> typeArguments, String identifier) {
this(null, scope, typeArguments, identifier);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public MethodReferenceExpr(
TokenRange tokenRange, Expression scope, NodeList<Type> typeArguments, String identifier) {
super(tokenRange);
setScope(scope);
setTypeArguments(typeArguments);
setIdentifier(identifier);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getScope() {
return scope;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public MethodReferenceExpr setScope(final Expression scope) {
assertNotNull(scope);
if (scope == this.scope) {
return this;
}
notifyPropertyChange(ObservableProperty.SCOPE, this.scope, scope);
if (this.scope != null) this.scope.setParentNode(null);
this.scope = scope;
setAsParentNodeOf(scope);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<NodeList<Type>> getTypeArguments() {
return Optional.ofNullable(typeArguments);
}
/**
* Sets the typeArguments
*
* @param typeArguments the typeArguments, can be null
* @return this, the MethodReferenceExpr
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public MethodReferenceExpr setTypeArguments(final NodeList<Type> typeArguments) {
if (typeArguments == this.typeArguments) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE_ARGUMENTS, this.typeArguments, typeArguments);
if (this.typeArguments != null) this.typeArguments.setParentNode(null);
this.typeArguments = typeArguments;
setAsParentNodeOf(typeArguments);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public String getIdentifier() {
return identifier;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public MethodReferenceExpr setIdentifier(final String identifier) {
assertNonEmpty(identifier);
if (identifier == this.identifier) {
return this;
}
notifyPropertyChange(ObservableProperty.IDENTIFIER, this.identifier, identifier);
this.identifier = identifier;
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
if (typeArguments != null) {
for (int i = 0; i < typeArguments.size(); i++) {
if (typeArguments.get(i) == node) {
typeArguments.remove(i);
return true;
}
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public MethodReferenceExpr clone() {
return (MethodReferenceExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public MethodReferenceExprMetaModel getMetaModel() {
return JavaParserMetaModel.methodReferenceExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == scope) {
setScope((Expression) replacementNode);
return true;
}
if (typeArguments != null) {
for (int i = 0; i < typeArguments.size(); i++) {
if (typeArguments.get(i) == node) {
typeArguments.set(i, (Type) replacementNode);
return true;
}
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isMethodReferenceExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public MethodReferenceExpr asMethodReferenceExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifMethodReferenceExpr(Consumer<MethodReferenceExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<MethodReferenceExpr> toMethodReferenceExpr() {
return Optional.of(this);
}
/**
* @return the method declaration this method reference is referencing.
*/
@Override
public ResolvedMethodDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedMethodDeclaration.class);
}
/*
* Method reference expressions are always poly expressions
* (https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html 15.13. Method Reference Expressions)
*/
@Override
public boolean isPolyExpression() {
return true;
}
}

View File

@@ -0,0 +1,203 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNonEmpty;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithIdentifier;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.NameMetaModel;
import com.github.javaparser.metamodel.NonEmptyProperty;
import com.github.javaparser.metamodel.OptionalProperty;
import java.util.Optional;
/**
* A name that may consist of multiple identifiers.
* In other words: it.may.contain.dots.
* <p>
* The rightmost identifier is "identifier",
* The one to the left of it is "qualifier.identifier", etc.
* <p>
* You can construct one from a String with the name(...) method.
*
* @author Julio Vilmar Gesser
* @see SimpleName
*/
public class Name extends Node implements NodeWithIdentifier<Name> {
@NonEmptyProperty
private String identifier;
@OptionalProperty
private Name qualifier;
public Name() {
this(null, null, "empty");
}
public Name(final String identifier) {
this(null, null, identifier);
}
@AllFieldsConstructor
public Name(Name qualifier, final String identifier) {
this(null, qualifier, identifier);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public Name(TokenRange tokenRange, Name qualifier, String identifier) {
super(tokenRange);
setQualifier(qualifier);
setIdentifier(identifier);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public String getIdentifier() {
return identifier;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Name setIdentifier(final String identifier) {
assertNonEmpty(identifier);
if (identifier == this.identifier) {
return this;
}
notifyPropertyChange(ObservableProperty.IDENTIFIER, this.identifier, identifier);
this.identifier = identifier;
return this;
}
/**
* @return the complete qualified name. Only the identifiers and the dots, so no comments or whitespace.
*/
public String asString() {
if (qualifier != null) {
return qualifier.asString() + "." + identifier;
}
return identifier;
}
public boolean hasQualifier() {
return qualifier != null;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<Name> getQualifier() {
return Optional.ofNullable(qualifier);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Name setQualifier(final Name qualifier) {
if (qualifier == this.qualifier) {
return this;
}
notifyPropertyChange(ObservableProperty.QUALIFIER, this.qualifier, qualifier);
if (this.qualifier != null) this.qualifier.setParentNode(null);
this.qualifier = qualifier;
setAsParentNodeOf(qualifier);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
if (qualifier != null) {
if (node == qualifier) {
removeQualifier();
return true;
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public Name removeQualifier() {
return setQualifier((Name) null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public Name clone() {
return (Name) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public NameMetaModel getMetaModel() {
return JavaParserMetaModel.nameMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (qualifier != null) {
if (node == qualifier) {
setQualifier((Name) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
/**
* A top level name is a name that is not contained in a larger Name instance.
*/
public boolean isTopLevel() {
return !isInternal();
}
/**
* An internal name is a name that constitutes a part of a larger Name instance.
*/
public boolean isInternal() {
return getParentNode().filter(parent -> parent instanceof Name).isPresent();
}
}

View File

@@ -0,0 +1,172 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.NameExprMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.UnsolvedSymbolException;
import com.github.javaparser.resolution.declarations.ResolvedValueDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* Whenever a SimpleName is used in an expression, it is wrapped in NameExpr.
* <br>In {@code int x = a + 3;} a is a SimpleName inside a NameExpr.
*
* @author Julio Vilmar Gesser
*/
public class NameExpr extends Expression implements NodeWithSimpleName<NameExpr>, Resolvable<ResolvedValueDeclaration> {
private SimpleName name;
public NameExpr() {
this(null, new SimpleName());
}
public NameExpr(final String name) {
this(null, new SimpleName(name));
}
@AllFieldsConstructor
public NameExpr(final SimpleName name) {
this(name.getTokenRange().orElse(null), name);
setRange(name.getRange().orElse(null));
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public NameExpr(TokenRange tokenRange, SimpleName name) {
super(tokenRange);
setName(name);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NameExpr setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public NameExpr clone() {
return (NameExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public NameExprMetaModel getMetaModel() {
return JavaParserMetaModel.nameExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isNameExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public NameExpr asNameExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifNameExpr(Consumer<NameExpr> action) {
action.accept(this);
}
/**
* Attempts to resolve the declaration corresponding to the accessed name. If successful, a
* {@link ResolvedValueDeclaration} representing the declaration of the value accessed by this {@code NameExpr} is
* returned. Otherwise, an {@link UnsolvedSymbolException} is thrown.
*
* @return a {@link ResolvedValueDeclaration} representing the declaration of the accessed value.
* @throws UnsolvedSymbolException if the declaration corresponding to the name expression could not be resolved.
* @see FieldAccessExpr#resolve()
* @see MethodCallExpr#resolve()
* @see ObjectCreationExpr#resolve()
* @see ExplicitConstructorInvocationStmt#resolve()
*/
@Override
public ResolvedValueDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedValueDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<NameExpr> toNameExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,181 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.NormalAnnotationExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* An annotation that has zero or more key-value pairs.<br>{@code @Mapping(a=5, d=10)}
* @author Julio Vilmar Gesser
*/
public class NormalAnnotationExpr extends AnnotationExpr {
private NodeList<MemberValuePair> pairs;
public NormalAnnotationExpr() {
this(null, new Name(), new NodeList<>());
}
@AllFieldsConstructor
public NormalAnnotationExpr(final Name name, final NodeList<MemberValuePair> pairs) {
this(null, name, pairs);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public NormalAnnotationExpr(TokenRange tokenRange, Name name, NodeList<MemberValuePair> pairs) {
super(tokenRange, name);
setPairs(pairs);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<MemberValuePair> getPairs() {
return pairs;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NormalAnnotationExpr setPairs(final NodeList<MemberValuePair> pairs) {
assertNotNull(pairs);
if (pairs == this.pairs) {
return this;
}
notifyPropertyChange(ObservableProperty.PAIRS, this.pairs, pairs);
if (this.pairs != null) this.pairs.setParentNode(null);
this.pairs = pairs;
setAsParentNodeOf(pairs);
return this;
}
/**
* adds a pair to this annotation
*
* @return this, the {@link NormalAnnotationExpr}
*/
public NormalAnnotationExpr addPair(String key, String value) {
return addPair(key, new NameExpr(value));
}
/**
* adds a pair to this annotation
*
* @return this, the {@link NormalAnnotationExpr}
*/
public NormalAnnotationExpr addPair(String key, Expression value) {
MemberValuePair memberValuePair = new MemberValuePair(key, value);
getPairs().add(memberValuePair);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < pairs.size(); i++) {
if (pairs.get(i) == node) {
pairs.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public NormalAnnotationExpr clone() {
return (NormalAnnotationExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public NormalAnnotationExprMetaModel getMetaModel() {
return JavaParserMetaModel.normalAnnotationExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < pairs.size(); i++) {
if (pairs.get(i) == node) {
pairs.set(i, (MemberValuePair) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isNormalAnnotationExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public NormalAnnotationExpr asNormalAnnotationExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifNormalAnnotationExpr(Consumer<NormalAnnotationExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<NormalAnnotationExpr> toNormalAnnotationExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.NullLiteralExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A literal "null".
* <br>{@code null}
*
* @author Julio Vilmar Gesser
*/
public class NullLiteralExpr extends LiteralExpr {
@AllFieldsConstructor
public NullLiteralExpr() {
this(null);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public NullLiteralExpr(TokenRange tokenRange) {
super(tokenRange);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public NullLiteralExpr clone() {
return (NullLiteralExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public NullLiteralExprMetaModel getMetaModel() {
return JavaParserMetaModel.nullLiteralExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isNullLiteralExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public NullLiteralExpr asNullLiteralExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifNullLiteralExpr(Consumer<NullLiteralExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<NullLiteralExpr> toNullLiteralExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,397 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.nodeTypes.NodeWithArguments;
import com.github.javaparser.ast.nodeTypes.NodeWithOptionalScope;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.nodeTypes.NodeWithTypeArguments;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.ObjectCreationExprMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.UnsolvedSymbolException;
import com.github.javaparser.resolution.declarations.ResolvedConstructorDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A constructor call.
* <br>In {@code new HashMap.Entry<String, Long>(15) {public String getKey() {return null;}};}
* HashMap.Entry is the type, String and Long are type arguments, 15 is an argument, and everything in { }
* is the anonymous class body.
* <p/>In {@code class B { class C { public void a() { new B().new C(); } } }} the scope is {@code new B()}
* of ObjectCreationExpr {@code new B().new C()}
*
* @author Julio Vilmar Gesser
*/
public class ObjectCreationExpr extends Expression
implements NodeWithTypeArguments<ObjectCreationExpr>,
NodeWithType<ObjectCreationExpr, ClassOrInterfaceType>,
NodeWithArguments<ObjectCreationExpr>,
NodeWithOptionalScope<ObjectCreationExpr>,
Resolvable<ResolvedConstructorDeclaration> {
@OptionalProperty
private Expression scope;
private ClassOrInterfaceType type;
@OptionalProperty
private NodeList<Type> typeArguments;
private NodeList<Expression> arguments;
@OptionalProperty
private NodeList<BodyDeclaration<?>> anonymousClassBody;
public ObjectCreationExpr() {
this(null, null, new ClassOrInterfaceType(), new NodeList<>(), new NodeList<>(), null);
}
/**
* Defines a call to a constructor.
*
* @param scope may be null
* @param type this is the class that the constructor is being called for.
* @param arguments Any arguments to pass to the constructor
*/
public ObjectCreationExpr(
final Expression scope, final ClassOrInterfaceType type, final NodeList<Expression> arguments) {
this(null, scope, type, null, arguments, null);
}
@AllFieldsConstructor
public ObjectCreationExpr(
final Expression scope,
final ClassOrInterfaceType type,
final NodeList<Type> typeArguments,
final NodeList<Expression> arguments,
final NodeList<BodyDeclaration<?>> anonymousClassBody) {
this(null, scope, type, typeArguments, arguments, anonymousClassBody);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ObjectCreationExpr(
TokenRange tokenRange,
Expression scope,
ClassOrInterfaceType type,
NodeList<Type> typeArguments,
NodeList<Expression> arguments,
NodeList<BodyDeclaration<?>> anonymousClassBody) {
super(tokenRange);
setScope(scope);
setType(type);
setTypeArguments(typeArguments);
setArguments(arguments);
setAnonymousClassBody(anonymousClassBody);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<NodeList<BodyDeclaration<?>>> getAnonymousClassBody() {
return Optional.ofNullable(anonymousClassBody);
}
public void addAnonymousClassBody(BodyDeclaration<?> body) {
if (anonymousClassBody == null) anonymousClassBody = new NodeList<>();
anonymousClassBody.add(body);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Expression> getArguments() {
return arguments;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<Expression> getScope() {
return Optional.ofNullable(scope);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ClassOrInterfaceType getType() {
return type;
}
/**
* Sets the anonymousClassBody<br>
* Null means no class body<br>
* Empty NodeList means new ClassName(){ }
*
* @param anonymousClassBody the anonymousClassBody, can be null or empty
* @return this, the ObjectCreationExpr
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ObjectCreationExpr setAnonymousClassBody(final NodeList<BodyDeclaration<?>> anonymousClassBody) {
if (anonymousClassBody == this.anonymousClassBody) {
return this;
}
notifyPropertyChange(ObservableProperty.ANONYMOUS_CLASS_BODY, this.anonymousClassBody, anonymousClassBody);
if (this.anonymousClassBody != null) this.anonymousClassBody.setParentNode(null);
this.anonymousClassBody = anonymousClassBody;
setAsParentNodeOf(anonymousClassBody);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ObjectCreationExpr setArguments(final NodeList<Expression> arguments) {
assertNotNull(arguments);
if (arguments == this.arguments) {
return this;
}
notifyPropertyChange(ObservableProperty.ARGUMENTS, this.arguments, arguments);
if (this.arguments != null) this.arguments.setParentNode(null);
this.arguments = arguments;
setAsParentNodeOf(arguments);
return this;
}
/**
* Sets the scope
*
* @param scope the scope, can be null
* @return this, the ObjectCreationExpr
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ObjectCreationExpr setScope(final Expression scope) {
if (scope == this.scope) {
return this;
}
notifyPropertyChange(ObservableProperty.SCOPE, this.scope, scope);
if (this.scope != null) this.scope.setParentNode(null);
this.scope = scope;
setAsParentNodeOf(scope);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ObjectCreationExpr setType(final ClassOrInterfaceType type) {
assertNotNull(type);
if (type == this.type) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE, this.type, type);
if (this.type != null) this.type.setParentNode(null);
this.type = type;
setAsParentNodeOf(type);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<NodeList<Type>> getTypeArguments() {
return Optional.ofNullable(typeArguments);
}
/**
* Sets the typeArguments
*
* @param typeArguments the typeArguments, can be null
* @return this, the ObjectCreationExpr
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ObjectCreationExpr setTypeArguments(final NodeList<Type> typeArguments) {
if (typeArguments == this.typeArguments) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE_ARGUMENTS, this.typeArguments, typeArguments);
if (this.typeArguments != null) this.typeArguments.setParentNode(null);
this.typeArguments = typeArguments;
setAsParentNodeOf(typeArguments);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
if (anonymousClassBody != null) {
for (int i = 0; i < anonymousClassBody.size(); i++) {
if (anonymousClassBody.get(i) == node) {
anonymousClassBody.remove(i);
return true;
}
}
}
for (int i = 0; i < arguments.size(); i++) {
if (arguments.get(i) == node) {
arguments.remove(i);
return true;
}
}
if (scope != null) {
if (node == scope) {
removeScope();
return true;
}
}
if (typeArguments != null) {
for (int i = 0; i < typeArguments.size(); i++) {
if (typeArguments.get(i) == node) {
typeArguments.remove(i);
return true;
}
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public ObjectCreationExpr removeScope() {
return setScope((Expression) null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ObjectCreationExpr clone() {
return (ObjectCreationExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ObjectCreationExprMetaModel getMetaModel() {
return JavaParserMetaModel.objectCreationExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (anonymousClassBody != null) {
for (int i = 0; i < anonymousClassBody.size(); i++) {
if (anonymousClassBody.get(i) == node) {
anonymousClassBody.set(i, (BodyDeclaration) replacementNode);
return true;
}
}
}
for (int i = 0; i < arguments.size(); i++) {
if (arguments.get(i) == node) {
arguments.set(i, (Expression) replacementNode);
return true;
}
}
if (scope != null) {
if (node == scope) {
setScope((Expression) replacementNode);
return true;
}
}
if (node == type) {
setType((ClassOrInterfaceType) replacementNode);
return true;
}
if (typeArguments != null) {
for (int i = 0; i < typeArguments.size(); i++) {
if (typeArguments.get(i) == node) {
typeArguments.set(i, (Type) replacementNode);
return true;
}
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isObjectCreationExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ObjectCreationExpr asObjectCreationExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifObjectCreationExpr(Consumer<ObjectCreationExpr> action) {
action.accept(this);
}
/**
* Attempts to resolve the declaration corresponding to the invoked constructor. If successful, a
* {@link ResolvedConstructorDeclaration} representing the declaration of the constructor invoked by this
* {@code ObjectCreationExpr} is returned. Otherwise, an {@link UnsolvedSymbolException} is thrown.
*
* @return a {@link ResolvedConstructorDeclaration} representing the declaration of the invoked constructor.
* @throws UnsolvedSymbolException if the declaration corresponding to the object creation expression could not be
* resolved.
* @see NameExpr#resolve()
* @see FieldAccessExpr#resolve()
* @see MethodCallExpr#resolve()
* @see ExplicitConstructorInvocationStmt#resolve()
*/
@Override
public ResolvedConstructorDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedConstructorDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ObjectCreationExpr> toObjectCreationExpr() {
return Optional.of(this);
}
/*
* A class instance creation expression is a poly expression (§15.2) if it uses the diamond form for type
* arguments to the class, and it appears in an assignment context or an invocation context (§5.2, §5.3).
* Otherwise, it is a standalone expression.
*/
@Override
public boolean isPolyExpression() {
return isUsingDiamondOperator() && (appearsInInvocationContext() || appearsInAssignmentContext());
}
}

View File

@@ -0,0 +1,165 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.PatternExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* <h1>Pattern Matching in Java</h1>
*
* <h2>Java 1.0 to 13</h2>
* Not available.
* <br>
* <h2>Java 14</h2>
* Java 14 introduced TypePatterns with simple pattern matching in {@code instanceof} expressions.
* @see com.github.javaparser.ast.expr.TypePatternExpr
* <h2>Java 21</h2>
* In Java 21, support for pattern matching was extended to switch expressions and {@code Record Patterns}
* were introduced. Since {@code Record Patterns} and {@code TypePatterns} can be used interchangeably, the
* {@code PatternExpr} class is used as a common parent for both in the JavaParser AST.
*
* <h3>JDK21 Grammar</h3>
* <br>
* <pre><code>Pattern:
* TypePattern
* RecordPattern
* TypePattern:
* LocalVariableDeclaration
* RecordPattern:
* ReferenceType ( [PatternList] )
* PatternList:
* Pattern {, Pattern }</code></pre>
*
* @author Johannes Coetzee
*
* @see <a href="https://bugs.openjdk.java.net/browse/JDK-8181287">JEP305: https://bugs.openjdk.java.net/browse/JDK-8181287</a>
* @see <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.20">https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.20</a>
*/
public abstract class PatternExpr extends Expression implements NodeWithType<PatternExpr, Type> {
private Type type;
@AllFieldsConstructor
public PatternExpr(final Type type) {}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isPatternExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public PatternExpr asPatternExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<PatternExpr> toPatternExpr() {
return Optional.of(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifPatternExpr(Consumer<PatternExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public PatternExpr clone() {
return (PatternExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public PatternExprMetaModel getMetaModel() {
return JavaParserMetaModel.patternExprMetaModel;
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public PatternExpr(TokenRange tokenRange) {
super(tokenRange);
customInitialization();
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public PatternExpr setType(final Type type) {
assertNotNull(type);
if (type == this.type) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE, this.type, type);
if (this.type != null) this.type.setParentNode(null);
this.type = type;
setAsParentNodeOf(type);
return this;
}
/**
* The types of record patters and top-level type patterns must be reference types, but nested type patterns
* can also have primitive types.
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Type getType() {
return type;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == type) {
setType((Type) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public PatternExpr(TokenRange tokenRange, Type type) {
super(tokenRange);
setType(type);
customInitialization();
}
}

View File

@@ -0,0 +1,241 @@
/*
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithFinalModifier;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.ReferenceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.RecordPatternExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* <h1>Record Patterns</h1>
* Record patterns were officially added in Java 21 to allow the deconstruction of
* record values and provide convenient access to inner fields through pattern matching.
* <br>
* <br>
* <h3>JDK 21 Grammar</h3>
* <pre><code>Pattern
* TypePattern
* RecordPattern
*
* RecordPattern:
* ReferenceType ( [PatternList] )
*
* PatternList
* Pattern {, Pattern }
* </code></pre>
*
* <h3>Example</h3>
* Example taken from <a href="https://openjdk.org/jeps/440">JEP440: RecordPatterns</a>
* <pre><code>
* record Pair(Object x, Object y) {}
*
* Pair p = new Pair(42, 42);
*
* if (p instanceof Pair(String s, String t)) {
* System.out.println(s + ", " + t);
* } else {
* System.out.println("Not a pair of strings");
* }
* </code></pre>
*
* @see com.github.javaparser.ast.expr.PatternExpr
* @see com.github.javaparser.ast.expr.TypePatternExpr
* @see <a href="https://openjdk.org/jeps/440">JEP 440: Record Patterns</a>
*/
public class RecordPatternExpr extends PatternExpr implements NodeWithFinalModifier<RecordPatternExpr> {
private NodeList<Modifier> modifiers;
private NodeList<PatternExpr> patternList;
public RecordPatternExpr() {
this(new NodeList<>(), new ClassOrInterfaceType(), new NodeList<>());
}
@AllFieldsConstructor
public RecordPatternExpr(
final NodeList<Modifier> modifiers, final Type type, final NodeList<PatternExpr> patternList) {
this(null, modifiers, type, patternList);
}
/**
* The type of RecordPatternExpr must always be a reference type. Only nested TypePatternExprs may have primitive
* types.
*/
@Override
public ReferenceType getType() {
return super.getType().asReferenceType();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Modifier> getModifiers() {
return modifiers;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public RecordPatternExpr setModifiers(final NodeList<Modifier> modifiers) {
assertNotNull(modifiers);
if (modifiers == this.modifiers) {
return this;
}
notifyPropertyChange(ObservableProperty.MODIFIERS, this.modifiers, modifiers);
if (this.modifiers != null) this.modifiers.setParentNode(null);
this.modifiers = modifiers;
setAsParentNodeOf(modifiers);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isRecordPatternExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public RecordPatternExpr asRecordPatternExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<RecordPatternExpr> toRecordPatternExpr() {
return Optional.of(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifRecordPatternExpr(Consumer<RecordPatternExpr> action) {
action.accept(this);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<PatternExpr> getPatternList() {
return patternList;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public RecordPatternExpr setPatternList(final NodeList<PatternExpr> patternList) {
assertNotNull(patternList);
if (patternList == this.patternList) {
return this;
}
notifyPropertyChange(ObservableProperty.PATTERN_LIST, this.patternList, patternList);
if (this.patternList != null) this.patternList.setParentNode(null);
this.patternList = patternList;
setAsParentNodeOf(patternList);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.remove(i);
return true;
}
}
for (int i = 0; i < patternList.size(); i++) {
if (patternList.get(i) == node) {
patternList.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.set(i, (Modifier) replacementNode);
return true;
}
}
for (int i = 0; i < patternList.size(); i++) {
if (patternList.get(i) == node) {
patternList.set(i, (PatternExpr) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public RecordPatternExpr clone() {
return (RecordPatternExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public RecordPatternExprMetaModel getMetaModel() {
return JavaParserMetaModel.recordPatternExprMetaModel;
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public RecordPatternExpr(
TokenRange tokenRange, NodeList<Modifier> modifiers, Type type, NodeList<PatternExpr> patternList) {
super(tokenRange, type);
setModifiers(modifiers);
setPatternList(patternList);
customInitialization();
}
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNonEmpty;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithIdentifier;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.NonEmptyProperty;
import com.github.javaparser.metamodel.SimpleNameMetaModel;
/**
* A name that consists of a single identifier.
* In other words: it.does.NOT.contain.dots.
*
* @see Name
*/
public class SimpleName extends Node implements NodeWithIdentifier<SimpleName> {
@NonEmptyProperty
private String identifier;
public SimpleName() {
this(null, "empty");
}
@AllFieldsConstructor
public SimpleName(final String identifier) {
this(null, identifier);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public SimpleName(TokenRange tokenRange, String identifier) {
super(tokenRange);
setIdentifier(identifier);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public String getIdentifier() {
return identifier;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName setIdentifier(final String identifier) {
assertNonEmpty(identifier);
if (identifier == this.identifier) {
return this;
}
notifyPropertyChange(ObservableProperty.IDENTIFIER, this.identifier, identifier);
this.identifier = identifier;
return this;
}
public String asString() {
return identifier;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public SimpleName clone() {
return (SimpleName) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public SimpleNameMetaModel getMetaModel() {
return JavaParserMetaModel.simpleNameMetaModel;
}
}

View File

@@ -0,0 +1,144 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.SingleMemberAnnotationExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* An annotation that has a single value. <br>{@code @Count(15)}
*
* @author Julio Vilmar Gesser
*/
public class SingleMemberAnnotationExpr extends AnnotationExpr {
private Expression memberValue;
public SingleMemberAnnotationExpr() {
this(null, new Name(), new StringLiteralExpr());
}
@AllFieldsConstructor
public SingleMemberAnnotationExpr(final Name name, final Expression memberValue) {
this(null, name, memberValue);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public SingleMemberAnnotationExpr(TokenRange tokenRange, Name name, Expression memberValue) {
super(tokenRange, name);
setMemberValue(memberValue);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getMemberValue() {
return memberValue;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SingleMemberAnnotationExpr setMemberValue(final Expression memberValue) {
assertNotNull(memberValue);
if (memberValue == this.memberValue) {
return this;
}
notifyPropertyChange(ObservableProperty.MEMBER_VALUE, this.memberValue, memberValue);
if (this.memberValue != null) this.memberValue.setParentNode(null);
this.memberValue = memberValue;
setAsParentNodeOf(memberValue);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public SingleMemberAnnotationExpr clone() {
return (SingleMemberAnnotationExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public SingleMemberAnnotationExprMetaModel getMetaModel() {
return JavaParserMetaModel.singleMemberAnnotationExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == memberValue) {
setMemberValue((Expression) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isSingleMemberAnnotationExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public SingleMemberAnnotationExpr asSingleMemberAnnotationExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifSingleMemberAnnotationExpr(Consumer<SingleMemberAnnotationExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<SingleMemberAnnotationExpr> toSingleMemberAnnotationExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,149 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.StringEscapeUtils.escapeJava;
import static com.github.javaparser.utils.StringEscapeUtils.unescapeJava;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.StringLiteralExprMetaModel;
import com.github.javaparser.utils.Utils;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A literal string.
* <br>{@code "Hello World!"}
* <br>{@code "\"\n"}
* <br>{@code "\u2122"}
* <br>{@code "™"}
* <br>{@code "💩"}
*
* @author Julio Vilmar Gesser
*/
public class StringLiteralExpr extends LiteralStringValueExpr {
public StringLiteralExpr() {
this(null, "empty");
}
/**
* Creates a string literal expression from given string. Escapes EOL characters.
*
* @param value the value of the literal
*/
@AllFieldsConstructor
public StringLiteralExpr(final String value) {
this(null, Utils.escapeEndOfLines(value));
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public StringLiteralExpr(TokenRange tokenRange, String value) {
super(tokenRange, value);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
/**
* Sets the content of this expressions to given value. Escapes EOL characters.
*
* @param value the new literal value
* @return self
*/
public StringLiteralExpr setEscapedValue(String value) {
this.value = Utils.escapeEndOfLines(value);
return this;
}
/**
* @return the unescaped literal value
*/
public String asString() {
return unescapeJava(value);
}
/**
* Escapes the given string from special characters and uses it as the literal value.
*
* @param value unescaped string
* @return this literal expression
*/
public StringLiteralExpr setString(String value) {
this.value = escapeJava(value);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public StringLiteralExpr clone() {
return (StringLiteralExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public StringLiteralExprMetaModel getMetaModel() {
return JavaParserMetaModel.stringLiteralExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isStringLiteralExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public StringLiteralExpr asStringLiteralExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifStringLiteralExpr(Consumer<StringLiteralExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<StringLiteralExpr> toStringLiteralExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,176 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import com.github.javaparser.metamodel.SuperExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* An occurrence of the "super" keyword. <br>
* {@code World.super.greet()} is a MethodCallExpr of method name greet,
* and scope "World.super" which is a SuperExpr with typeName "World". <br>
* {@code super.name} is a FieldAccessExpr of field greet, and a SuperExpr as its scope.
* This SuperExpr has no typeName.
*
* @author Julio Vilmar Gesser
* @see com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt
* @see ThisExpr
*/
public class SuperExpr extends Expression {
@OptionalProperty
private Name typeName;
public SuperExpr() {
this(null, null);
}
@AllFieldsConstructor
public SuperExpr(final Name typeName) {
this(null, typeName);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public SuperExpr(TokenRange tokenRange, Name typeName) {
super(tokenRange);
setTypeName(typeName);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<Name> getTypeName() {
return Optional.ofNullable(typeName);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SuperExpr setTypeName(final Name typeName) {
if (typeName == this.typeName) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE_NAME, this.typeName, typeName);
if (this.typeName != null) this.typeName.setParentNode(null);
this.typeName = typeName;
setAsParentNodeOf(typeName);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
if (typeName != null) {
if (node == typeName) {
removeTypeName();
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public SuperExpr clone() {
return (SuperExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public SuperExprMetaModel getMetaModel() {
return JavaParserMetaModel.superExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isSuperExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public SuperExpr asSuperExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifSuperExpr(Consumer<SuperExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<SuperExpr> toSuperExpr() {
return Optional.of(this);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public SuperExpr removeClassName() {
return setTypeName((Name) null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (typeName != null) {
if (node == typeName) {
setTypeName((Name) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public SuperExpr removeTypeName() {
return setTypeName((Name) null);
}
}

View File

@@ -0,0 +1,208 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.nodeTypes.SwitchNode;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.stmt.SwitchEntry;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.SwitchExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* <h1>The switch expression</h1>
* <h2>Java 1.0-11</h2>
* Not available.
* <h2>Java 12</h2>
* Like {@link com.github.javaparser.ast.stmt.SwitchStmt},
* but can also be used as an expression.
* <br>
* <br>{@code int a = switch(x) { case 5,6 -> 20; case 9 -> 30; default -> 40; };}
* <br>{@code int a = switch(x) { case 5,6: break 20; default: break 5+5; };}
* <h2>Java 13</h2>
* The break statement has been reverted to what it was before Java 12, and break-with-value is now the YieldStatement.
* <br>{@code int a = switch(x) { case 5,6: yield 20; default: yield 5+5; };}
*
* @see SwitchEntry
* @see com.github.javaparser.ast.stmt.SwitchStmt
* @see SwitchNode
* @see com.github.javaparser.ast.stmt.BreakStmt
* @see com.github.javaparser.ast.stmt.YieldStmt
*/
public class SwitchExpr extends Expression implements SwitchNode {
private Expression selector;
private NodeList<SwitchEntry> entries;
public SwitchExpr() {
this(null, new NameExpr(), new NodeList<>());
}
@AllFieldsConstructor
public SwitchExpr(final Expression selector, final NodeList<SwitchEntry> entries) {
this(null, selector, entries);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public SwitchExpr(TokenRange tokenRange, Expression selector, NodeList<SwitchEntry> entries) {
super(tokenRange);
setSelector(selector);
setEntries(entries);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<SwitchEntry> getEntries() {
return entries;
}
public SwitchEntry getEntry(int i) {
return getEntries().get(i);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getSelector() {
return selector;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SwitchExpr setEntries(final NodeList<SwitchEntry> entries) {
assertNotNull(entries);
if (entries == this.entries) {
return this;
}
notifyPropertyChange(ObservableProperty.ENTRIES, this.entries, entries);
if (this.entries != null) this.entries.setParentNode(null);
this.entries = entries;
setAsParentNodeOf(entries);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SwitchExpr setSelector(final Expression selector) {
assertNotNull(selector);
if (selector == this.selector) {
return this;
}
notifyPropertyChange(ObservableProperty.SELECTOR, this.selector, selector);
if (this.selector != null) this.selector.setParentNode(null);
this.selector = selector;
setAsParentNodeOf(selector);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < entries.size(); i++) {
if (entries.get(i) == node) {
entries.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public SwitchExpr clone() {
return (SwitchExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < entries.size(); i++) {
if (entries.get(i) == node) {
entries.set(i, (SwitchEntry) replacementNode);
return true;
}
}
if (node == selector) {
setSelector((Expression) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isSwitchExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public SwitchExpr asSwitchExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<SwitchExpr> toSwitchExpr() {
return Optional.of(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifSwitchExpr(Consumer<SwitchExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public SwitchExprMetaModel getMetaModel() {
return JavaParserMetaModel.switchExprMetaModel;
}
}

View File

@@ -0,0 +1,207 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.StringEscapeUtils.unescapeJavaTextBlock;
import static java.util.stream.Collectors.joining;
import static java.util.stream.IntStream.range;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.TextBlockLiteralExprMetaModel;
import com.github.javaparser.utils.Pair;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Stream;
/**
* <h1>A text block</h1>
* <h2>Java 13-</h2>
* A text block is a multi-line string. It was introduced in JEP 355.
* The content of "value" is byte-for-byte exactly what is in the source code.
*/
public class TextBlockLiteralExpr extends LiteralStringValueExpr {
public TextBlockLiteralExpr() {
this(null, "empty");
}
/**
* Creates a text block literal expression from given string.
*
* @param value the value of the literal
*/
@AllFieldsConstructor
public TextBlockLiteralExpr(final String value) {
this(null, value);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public TextBlockLiteralExpr(TokenRange tokenRange, String value) {
super(tokenRange, value);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isTextBlockLiteralExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public TextBlockLiteralExpr asTextBlockLiteralExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<TextBlockLiteralExpr> toTextBlockLiteralExpr() {
return Optional.of(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifTextBlockLiteralExpr(Consumer<TextBlockLiteralExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public TextBlockLiteralExpr clone() {
return (TextBlockLiteralExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public TextBlockLiteralExprMetaModel getMetaModel() {
return JavaParserMetaModel.textBlockLiteralExprMetaModel;
}
/**
* Most of the algorithm for stripIndent, stopping just before concatenating all the lines into a single string.
* Useful for tools.
*/
public Stream<String> stripIndentOfLines() {
/* Split the content of the text block at every LF, producing a list of individual lines.
Note that any line in the content which was just an LF will become an empty line in the list of individual lines. */
String[] rawLines = getValue().split("\\R", -1);
/* Add all non-blank lines from the list of individual lines into a set of determining lines.
(Blank lines -- lines that are empty or are composed wholly of white space -- have no visible influence on the indentation.
Excluding blank lines from the set of determining lines avoids throwing off step 4 of the algorithm.) */
/* If the last line in the list of individual lines (i.e., the line with the closing delimiter) is blank, then add it to the set of determining lines.
(The indentation of the closing delimiter should influence the indentation of the content as a whole -- a "significant trailing line" policy.) */
/* Compute the common white space prefix of the set of determining lines, by counting the number of leading white space characters on each line and taking the minimum count. */
int commonWhiteSpacePrefixSize = range(0, rawLines.length)
.mapToObj(nr -> new Pair<>(nr, rawLines[nr]))
.filter(l -> !emptyOrWhitespace(l.b) || isLastLine(rawLines, l.a))
.map(l -> indentSize(l.b))
.min(Integer::compare)
.orElse(0);
/* Remove the common white space prefix from each non-blank line in the list of individual lines. */
/* Remove all trailing white space from all lines in the modified list of individual lines from step 5.
This step collapses wholly-whitespace lines in the modified list so that they are empty, but does not discard them. */
return Arrays.stream(rawLines)
.map(l -> l.length() < commonWhiteSpacePrefixSize ? l : l.substring(commonWhiteSpacePrefixSize))
.map(this::trimTrailing);
}
/**
* @return The algorithm from String::stripIndent in JDK 13.
*/
public String stripIndent() {
/* Construct the result string by joining all the lines in the modified list of individual lines from step 6, using LF as the separator between lines.
If the final line in the list from step 6 is empty, then the joining LF from the previous line will be the last character in the result string. */
return stripIndentOfLines().collect(joining("\n"));
}
/**
* @return The algorithm from String::translateEscapes in JDK 13.
*/
public String translateEscapes() {
return unescapeJavaTextBlock(stripIndent());
}
/**
* @return the final string value of this text block after all processing.
*/
public String asString() {
return translateEscapes();
}
/**
* @return is the line with index lineNr the last line in rawLines?
*/
private boolean isLastLine(String[] rawLines, Integer lineNr) {
return lineNr == rawLines.length - 1;
}
/**
* @return is this string empty or filled only with whitespace?
*/
private boolean emptyOrWhitespace(String rawLine) {
return rawLine.trim().isEmpty();
}
/**
* @return the amount of leading whitespaces.
*/
private int indentSize(String s) {
String content = s.trim();
if (content.isEmpty()) {
return s.length();
}
return s.indexOf(content);
}
/**
* Can be replaced when moving to JDK 11
*/
private String trimTrailing(String source) {
int pos = source.length() - 1;
while ((pos >= 0) && Character.isWhitespace(source.charAt(pos))) {
pos--;
}
pos++;
return (pos < source.length()) ? source.substring(0, pos) : source;
}
}

View File

@@ -0,0 +1,183 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.OptionalProperty;
import com.github.javaparser.metamodel.ThisExprMetaModel;
import com.github.javaparser.resolution.Resolvable;
import com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration;
import java.util.Optional;
import java.util.function.Consumer;
/**
* An occurrence of the "this" keyword. <br>
* {@code World.this.greet()} is a MethodCallExpr of method name greet,
* and scope "World.this" which is a ThisExpr with typeName "World". <br>
* {@code this.name} is a FieldAccessExpr of field greet, and a ThisExpr as its scope.
* This ThisExpr has no typeName.
*
* @author Julio Vilmar Gesser
* @see com.github.javaparser.ast.stmt.ExplicitConstructorInvocationStmt
* @see SuperExpr
*/
public class ThisExpr extends Expression implements Resolvable<ResolvedTypeDeclaration> {
@OptionalProperty
private Name typeName;
public ThisExpr() {
this(null, null);
}
@AllFieldsConstructor
public ThisExpr(final Name typeName) {
this(null, typeName);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ThisExpr(TokenRange tokenRange, Name typeName) {
super(tokenRange);
setTypeName(typeName);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Optional<Name> getTypeName() {
return Optional.ofNullable(typeName);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ThisExpr setTypeName(final Name typeName) {
if (typeName == this.typeName) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE_NAME, this.typeName, typeName);
if (this.typeName != null) this.typeName.setParentNode(null);
this.typeName = typeName;
setAsParentNodeOf(typeName);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
if (typeName != null) {
if (node == typeName) {
removeTypeName();
return true;
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public ThisExpr removeClassName() {
return setTypeName((Name) null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ThisExpr clone() {
return (ThisExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ThisExprMetaModel getMetaModel() {
return JavaParserMetaModel.thisExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (typeName != null) {
if (node == typeName) {
setTypeName((Name) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isThisExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ThisExpr asThisExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifThisExpr(Consumer<ThisExpr> action) {
action.accept(this);
}
@Override
public ResolvedTypeDeclaration resolve() {
return getSymbolResolver().resolveDeclaration(this, ResolvedTypeDeclaration.class);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ThisExpr> toThisExpr() {
return Optional.of(this);
}
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public ThisExpr removeTypeName() {
return setTypeName((Name) null);
}
}

View File

@@ -0,0 +1,149 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithType;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.TypeExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* This class is just instantiated as scopes for MethodReferenceExpr nodes to encapsulate Types.
* <br>In {@code World::greet} the ClassOrInterfaceType "World" is wrapped in a TypeExpr
* before it is set as the scope of the MethodReferenceExpr.
*
* @author Raquel Pau
*/
public class TypeExpr extends Expression implements NodeWithType<TypeExpr, Type> {
private Type type;
public TypeExpr() {
this(null, new ClassOrInterfaceType());
}
@AllFieldsConstructor
public TypeExpr(Type type) {
this(null, type);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public TypeExpr(TokenRange tokenRange, Type type) {
super(tokenRange);
setType(type);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Type getType() {
return type;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public TypeExpr setType(final Type type) {
assertNotNull(type);
if (type == this.type) {
return this;
}
notifyPropertyChange(ObservableProperty.TYPE, this.type, type);
if (this.type != null) this.type.setParentNode(null);
this.type = type;
setAsParentNodeOf(type);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public TypeExpr clone() {
return (TypeExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public TypeExprMetaModel getMetaModel() {
return JavaParserMetaModel.typeExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == type) {
setType((Type) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isTypeExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public TypeExpr asTypeExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifTypeExpr(Consumer<TypeExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<TypeExpr> toTypeExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,218 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithFinalModifier;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.TypePatternExprMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* <h1>The instanceof statement</h1>
*
* <h2>Java 1.0 to 13</h2>
* Not available.
* <br>
* <h2>Java 14</h2>
* Since JDK14, it is possible to bind a variable that is cast to the type being tested against.
* This is referred to as a {@code Pattern} within <a href="https://bugs.openjdk.java.net/browse/JDK-8181287">JEP305</a>,
* and avoids the need to cast to the desired type.
* <br>
* Example:
* <br>
* <pre>{@code
* tool instanceof Drill d
* ^^^^^^^
* Pattern
* }</pre>
* <br>Note: While this is exclusively used within {@code instanceof} operators for now, JEP305 suggests this might
* be used more widely in the future (e.g. in switch expressions/statements).
* <br>
* <br>
* <h3>JDK14 Grammar</h3>
* Per JEP305 (not currently listed within the JLS):
* <br>
* <pre>{@code Pattern:
* Type Identifier}</pre>
*
* @author Roger Howell
*
* @see com.github.javaparser.ast.expr.InstanceOfExpr
* @see <a href="https://bugs.openjdk.java.net/browse/JDK-8181287">JEP305: https://bugs.openjdk.java.net/browse/JDK-8181287</a>
* @see <a href="https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.20">https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.20</a>
*/
public class TypePatternExpr extends PatternExpr
implements NodeWithSimpleName<TypePatternExpr>, NodeWithFinalModifier<TypePatternExpr> {
private NodeList<Modifier> modifiers;
private SimpleName name;
public TypePatternExpr() {
this(null, new NodeList<>(), new ClassOrInterfaceType(), new SimpleName());
}
@AllFieldsConstructor
public TypePatternExpr(final NodeList<Modifier> modifiers, final Type type, SimpleName name) {
this(null, modifiers, type, name);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public TypePatternExpr(TokenRange tokenRange, NodeList<Modifier> modifiers, Type type, SimpleName name) {
super(tokenRange, type);
setModifiers(modifiers);
setName(name);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public SimpleName getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public TypePatternExpr setName(final SimpleName name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.set(i, (Modifier) replacementNode);
return true;
}
}
if (node == name) {
setName((SimpleName) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public TypePatternExpr clone() {
return (TypePatternExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public TypePatternExprMetaModel getMetaModel() {
return JavaParserMetaModel.typePatternExprMetaModel;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Modifier> getModifiers() {
return modifiers;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public TypePatternExpr setModifiers(final NodeList<Modifier> modifiers) {
assertNotNull(modifiers);
if (modifiers == this.modifiers) {
return this;
}
notifyPropertyChange(ObservableProperty.MODIFIERS, this.modifiers, modifiers);
if (this.modifiers != null) this.modifiers.setParentNode(null);
this.modifiers = modifiers;
setAsParentNodeOf(modifiers);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isTypePatternExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public TypePatternExpr asTypePatternExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<TypePatternExpr> toTypePatternExpr() {
return Optional.of(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifTypePatternExpr(Consumer<TypePatternExpr> action) {
action.accept(this);
}
}

View File

@@ -0,0 +1,213 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.nodeTypes.NodeWithExpression;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.DerivedProperty;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.UnaryExprMetaModel;
import com.github.javaparser.printer.Stringable;
import java.util.Optional;
import java.util.function.Consumer;
/**
* An expression where an operator is applied to a single expression.
* It supports the operators that are found in the UnaryExpr.Operator enum.
* <br>{@code 11++}
* <br>{@code ++11}
* <br>{@code ~1}
* <br>{@code -333}
*
* @author Julio Vilmar Gesser
*/
public class UnaryExpr extends Expression implements NodeWithExpression<UnaryExpr> {
public enum Operator implements Stringable {
PLUS("+", false),
MINUS("-", false),
PREFIX_INCREMENT("++", false),
PREFIX_DECREMENT("--", false),
LOGICAL_COMPLEMENT("!", false),
BITWISE_COMPLEMENT("~", false),
POSTFIX_INCREMENT("++", true),
POSTFIX_DECREMENT("--", true);
private final String codeRepresentation;
private final boolean isPostfix;
Operator(String codeRepresentation, boolean isPostfix) {
this.codeRepresentation = codeRepresentation;
this.isPostfix = isPostfix;
}
public String asString() {
return codeRepresentation;
}
public boolean isPostfix() {
return isPostfix;
}
public boolean isPrefix() {
return !isPostfix();
}
}
private Expression expression;
private Operator operator;
public UnaryExpr() {
this(null, new IntegerLiteralExpr(), Operator.POSTFIX_INCREMENT);
}
@AllFieldsConstructor
public UnaryExpr(final Expression expression, final Operator operator) {
this(null, expression, operator);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public UnaryExpr(TokenRange tokenRange, Expression expression, Operator operator) {
super(tokenRange);
setExpression(expression);
setOperator(operator);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Expression getExpression() {
return expression;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Operator getOperator() {
return operator;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public UnaryExpr setExpression(final Expression expression) {
assertNotNull(expression);
if (expression == this.expression) {
return this;
}
notifyPropertyChange(ObservableProperty.EXPRESSION, this.expression, expression);
if (this.expression != null) this.expression.setParentNode(null);
this.expression = expression;
setAsParentNodeOf(expression);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public UnaryExpr setOperator(final Operator operator) {
assertNotNull(operator);
if (operator == this.operator) {
return this;
}
notifyPropertyChange(ObservableProperty.OPERATOR, this.operator, operator);
this.operator = operator;
return this;
}
@DerivedProperty
public boolean isPostfix() {
return operator.isPostfix();
}
@DerivedProperty
public boolean isPrefix() {
return !isPostfix();
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public UnaryExpr clone() {
return (UnaryExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public UnaryExprMetaModel getMetaModel() {
return JavaParserMetaModel.unaryExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
if (node == expression) {
setExpression((Expression) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isUnaryExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public UnaryExpr asUnaryExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifUnaryExpr(Consumer<UnaryExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<UnaryExpr> toUnaryExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,289 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.expr;
import static com.github.javaparser.ast.NodeList.nodeList;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
import com.github.javaparser.ast.nodeTypes.NodeWithVariables;
import com.github.javaparser.ast.nodeTypes.modifiers.NodeWithFinalModifier;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.NonEmptyProperty;
import com.github.javaparser.metamodel.VariableDeclarationExprMetaModel;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* A declaration of variables.
* It is an expression, so it can be put in places like the initializer of a for loop,
* or the resources part of the try statement.
* <br>{@code final int x=3, y=55}
*
* <br>All annotations preceding the type will be set on this object, not on the type.
* JavaParser doesn't know if it they are applicable to the method or the type.
*
* @author Julio Vilmar Gesser
*/
public class VariableDeclarationExpr extends Expression
implements NodeWithFinalModifier<VariableDeclarationExpr>,
NodeWithAnnotations<VariableDeclarationExpr>,
NodeWithVariables<VariableDeclarationExpr> {
private NodeList<Modifier> modifiers;
private NodeList<AnnotationExpr> annotations;
@NonEmptyProperty
private NodeList<VariableDeclarator> variables;
public VariableDeclarationExpr() {
this(null, new NodeList<>(), new NodeList<>(), new NodeList<>());
}
public VariableDeclarationExpr(final Type type, String variableName) {
this(null, new NodeList<>(), new NodeList<>(), nodeList(new VariableDeclarator(type, variableName)));
}
public VariableDeclarationExpr(VariableDeclarator var) {
this(null, new NodeList<>(), new NodeList<>(), nodeList(var));
}
public VariableDeclarationExpr(final Type type, String variableName, Modifier... modifiers) {
this(
null,
Arrays.stream(modifiers).collect(Collectors.toCollection(() -> new NodeList<>())),
new NodeList<>(),
nodeList(new VariableDeclarator(type, variableName)));
}
public VariableDeclarationExpr(VariableDeclarator var, Modifier... modifiers) {
this(
null,
Arrays.stream(modifiers).collect(Collectors.toCollection(() -> new NodeList<>())),
new NodeList<>(),
nodeList(var));
}
public VariableDeclarationExpr(final NodeList<VariableDeclarator> variables) {
this(null, new NodeList<>(), new NodeList<>(), variables);
}
public VariableDeclarationExpr(final NodeList<Modifier> modifiers, final NodeList<VariableDeclarator> variables) {
this(null, modifiers, new NodeList<>(), variables);
}
@AllFieldsConstructor
public VariableDeclarationExpr(
final NodeList<Modifier> modifiers,
final NodeList<AnnotationExpr> annotations,
final NodeList<VariableDeclarator> variables) {
this(null, modifiers, annotations, variables);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public VariableDeclarationExpr(
TokenRange tokenRange,
NodeList<Modifier> modifiers,
NodeList<AnnotationExpr> annotations,
NodeList<VariableDeclarator> variables) {
super(tokenRange);
setModifiers(modifiers);
setAnnotations(annotations);
setVariables(variables);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<AnnotationExpr> getAnnotations() {
return annotations;
}
/**
* Return the modifiers of this variable declaration.
*
* @return modifiers
* @see Modifier
*/
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Modifier> getModifiers() {
return modifiers;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<VariableDeclarator> getVariables() {
return variables;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public VariableDeclarationExpr setAnnotations(final NodeList<AnnotationExpr> annotations) {
assertNotNull(annotations);
if (annotations == this.annotations) {
return this;
}
notifyPropertyChange(ObservableProperty.ANNOTATIONS, this.annotations, annotations);
if (this.annotations != null) this.annotations.setParentNode(null);
this.annotations = annotations;
setAsParentNodeOf(annotations);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public VariableDeclarationExpr setModifiers(final NodeList<Modifier> modifiers) {
assertNotNull(modifiers);
if (modifiers == this.modifiers) {
return this;
}
notifyPropertyChange(ObservableProperty.MODIFIERS, this.modifiers, modifiers);
if (this.modifiers != null) this.modifiers.setParentNode(null);
this.modifiers = modifiers;
setAsParentNodeOf(modifiers);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public VariableDeclarationExpr setVariables(final NodeList<VariableDeclarator> variables) {
assertNotNull(variables);
if (variables == this.variables) {
return this;
}
notifyPropertyChange(ObservableProperty.VARIABLES, this.variables, variables);
if (this.variables != null) this.variables.setParentNode(null);
this.variables = variables;
setAsParentNodeOf(variables);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.remove(i);
return true;
}
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.remove(i);
return true;
}
}
for (int i = 0; i < variables.size(); i++) {
if (variables.get(i) == node) {
variables.remove(i);
return true;
}
}
return super.remove(node);
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public VariableDeclarationExpr clone() {
return (VariableDeclarationExpr) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public VariableDeclarationExprMetaModel getMetaModel() {
return JavaParserMetaModel.variableDeclarationExprMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.set(i, (AnnotationExpr) replacementNode);
return true;
}
}
for (int i = 0; i < modifiers.size(); i++) {
if (modifiers.get(i) == node) {
modifiers.set(i, (Modifier) replacementNode);
return true;
}
}
for (int i = 0; i < variables.size(); i++) {
if (variables.get(i) == node) {
variables.set(i, (VariableDeclarator) replacementNode);
return true;
}
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isVariableDeclarationExpr() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public VariableDeclarationExpr asVariableDeclarationExpr() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifVariableDeclarationExpr(Consumer<VariableDeclarationExpr> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<VariableDeclarationExpr> toVariableDeclarationExpr() {
return Optional.of(this);
}
}

View File

@@ -0,0 +1,238 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.modules;
import static com.github.javaparser.StaticJavaParser.parseModuleDirective;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.Name;
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
import com.github.javaparser.ast.nodeTypes.NodeWithName;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.ModuleDeclarationMetaModel;
/**
* A Java 9 Jigsaw module declaration. {@code @Foo module com.github.abc { requires a.B; }}
*/
public class ModuleDeclaration extends Node
implements NodeWithName<ModuleDeclaration>, NodeWithAnnotations<ModuleDeclaration> {
private Name name;
private NodeList<AnnotationExpr> annotations;
private boolean isOpen;
private NodeList<ModuleDirective> directives;
public ModuleDeclaration() {
this(null, new NodeList<>(), new Name(), false, new NodeList<>());
}
public ModuleDeclaration(Name name, boolean isOpen) {
this(null, new NodeList<>(), name, isOpen, new NodeList<>());
}
@AllFieldsConstructor
public ModuleDeclaration(
NodeList<AnnotationExpr> annotations, Name name, boolean isOpen, NodeList<ModuleDirective> directives) {
this(null, annotations, name, isOpen, directives);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ModuleDeclaration(
TokenRange tokenRange,
NodeList<AnnotationExpr> annotations,
Name name,
boolean isOpen,
NodeList<ModuleDirective> directives) {
super(tokenRange);
setAnnotations(annotations);
setName(name);
setOpen(isOpen);
setDirectives(directives);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Name getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ModuleDeclaration setName(final Name name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<AnnotationExpr> getAnnotations() {
return annotations;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ModuleDeclaration setAnnotations(final NodeList<AnnotationExpr> annotations) {
assertNotNull(annotations);
if (annotations == this.annotations) {
return this;
}
notifyPropertyChange(ObservableProperty.ANNOTATIONS, this.annotations, annotations);
if (this.annotations != null) this.annotations.setParentNode(null);
this.annotations = annotations;
setAsParentNodeOf(annotations);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.remove(i);
return true;
}
}
for (int i = 0; i < directives.size(); i++) {
if (directives.get(i) == node) {
directives.remove(i);
return true;
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public boolean isOpen() {
return isOpen;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ModuleDeclaration setOpen(final boolean isOpen) {
if (isOpen == this.isOpen) {
return this;
}
notifyPropertyChange(ObservableProperty.OPEN, this.isOpen, isOpen);
this.isOpen = isOpen;
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<ModuleDirective> getDirectives() {
return directives;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ModuleDeclaration setDirectives(final NodeList<ModuleDirective> directives) {
assertNotNull(directives);
if (directives == this.directives) {
return this;
}
notifyPropertyChange(ObservableProperty.DIRECTIVES, this.directives, directives);
if (this.directives != null) this.directives.setParentNode(null);
this.directives = directives;
setAsParentNodeOf(directives);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ModuleDeclaration clone() {
return (ModuleDeclaration) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ModuleDeclarationMetaModel getMetaModel() {
return JavaParserMetaModel.moduleDeclarationMetaModel;
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i) == node) {
annotations.set(i, (AnnotationExpr) replacementNode);
return true;
}
}
for (int i = 0; i < directives.size(); i++) {
if (directives.get(i) == node) {
directives.set(i, (ModuleDirective) replacementNode);
return true;
}
}
if (node == name) {
setName((Name) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
/**
* Add a directive to the module, like "exports R.S to T1.U1, T2.U2;"
*/
public ModuleDeclaration addDirective(String directive) {
return addDirective(parseModuleDirective(directive));
}
public ModuleDeclaration addDirective(ModuleDirective directive) {
getDirectives().add(directive);
return this;
}
}

View File

@@ -0,0 +1,254 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.modules;
import static com.github.javaparser.utils.CodeGenerationUtils.f;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.ModuleDirectiveMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* A module directive.
*/
public abstract class ModuleDirective extends Node {
@AllFieldsConstructor
public ModuleDirective() {
this(null);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ModuleDirective(TokenRange tokenRange) {
super(tokenRange);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ModuleDirective clone() {
return (ModuleDirective) accept(new CloneVisitor(), null);
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleExportsStmt() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleExportsDirective asModuleExportsStmt() {
throw new IllegalStateException(f("%s is not an ModuleExportsDirective", this));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleOpensStmt() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleOpensDirective asModuleOpensStmt() {
throw new IllegalStateException(f("%s is not an ModuleOpensDirective", this));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleProvidesStmt() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleProvidesDirective asModuleProvidesStmt() {
throw new IllegalStateException(f("%s is not an ModuleProvidesDirective", this));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleRequiresStmt() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleRequiresDirective asModuleRequiresStmt() {
throw new IllegalStateException(f("%s is not an ModuleRequiresDirective", this));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleUsesStmt() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleUsesDirective asModuleUsesStmt() {
throw new IllegalStateException(f("%s is not an ModuleUsesDirective", this));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleExportsStmt(Consumer<ModuleExportsDirective> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleOpensStmt(Consumer<ModuleOpensDirective> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleProvidesStmt(Consumer<ModuleProvidesDirective> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleRequiresStmt(Consumer<ModuleRequiresDirective> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleUsesStmt(Consumer<ModuleUsesDirective> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleExportsDirective> toModuleExportsStmt() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleOpensDirective> toModuleOpensStmt() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleProvidesDirective> toModuleProvidesStmt() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleRequiresDirective> toModuleRequiresStmt() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleUsesDirective> toModuleUsesStmt() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleExportsDirective() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleExportsDirective asModuleExportsDirective() {
throw new IllegalStateException(f(
"%s is not ModuleExportsDirective, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleExportsDirective> toModuleExportsDirective() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleExportsDirective(Consumer<ModuleExportsDirective> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleOpensDirective() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleOpensDirective asModuleOpensDirective() {
throw new IllegalStateException(f(
"%s is not ModuleOpensDirective, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleOpensDirective> toModuleOpensDirective() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleOpensDirective(Consumer<ModuleOpensDirective> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleProvidesDirective() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleProvidesDirective asModuleProvidesDirective() {
throw new IllegalStateException(f(
"%s is not ModuleProvidesDirective, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleProvidesDirective> toModuleProvidesDirective() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleProvidesDirective(Consumer<ModuleProvidesDirective> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleRequiresDirective() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleRequiresDirective asModuleRequiresDirective() {
throw new IllegalStateException(f(
"%s is not ModuleRequiresDirective, it is %s",
this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleRequiresDirective> toModuleRequiresDirective() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleRequiresDirective(Consumer<ModuleRequiresDirective> action) {}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleUsesDirective() {
return false;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleUsesDirective asModuleUsesDirective() {
throw new IllegalStateException(f(
"%s is not ModuleUsesDirective, it is %s", this, this.getClass().getSimpleName()));
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleUsesDirective> toModuleUsesDirective() {
return Optional.empty();
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleUsesDirective(Consumer<ModuleUsesDirective> action) {}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ModuleDirectiveMetaModel getMetaModel() {
return JavaParserMetaModel.moduleDirectiveMetaModel;
}
}

View File

@@ -0,0 +1,216 @@
/*
* Copyright (C) 2007-2010 Júlio Vilmar Gesser.
* Copyright (C) 2011, 2013-2024 The JavaParser Team.
*
* This file is part of JavaParser.
*
* JavaParser can be used either under the terms of
* a) the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* b) the terms of the Apache License
*
* You should have received a copy of both licenses in LICENCE.LGPL and
* LICENCE.APACHE. Please refer to those files for details.
*
* JavaParser 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
* GNU Lesser General Public License for more details.
*/
package com.github.javaparser.ast.modules;
import static com.github.javaparser.StaticJavaParser.parseName;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.TokenRange;
import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Generated;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.expr.Name;
import com.github.javaparser.ast.nodeTypes.NodeWithName;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.ModuleExportsDirectiveMetaModel;
import java.util.Optional;
import java.util.function.Consumer;
/**
* An exports directive in module-info.java. {@code exports R.S to T1.U1, T2.U2;}
*/
public class ModuleExportsDirective extends ModuleDirective implements NodeWithName<ModuleExportsDirective> {
private Name name;
private NodeList<Name> moduleNames;
public ModuleExportsDirective() {
this(null, new Name(), new NodeList<>());
}
@AllFieldsConstructor
public ModuleExportsDirective(Name name, NodeList<Name> moduleNames) {
this(null, name, moduleNames);
}
/**
* This constructor is used by the parser and is considered private.
*/
@Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
public ModuleExportsDirective(TokenRange tokenRange, Name name, NodeList<Name> moduleNames) {
super(tokenRange);
setName(name);
setModuleNames(moduleNames);
customInitialization();
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
return v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
public <A> void accept(final VoidVisitor<A> v, final A arg) {
v.visit(this, arg);
}
@Override
@Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
public boolean remove(Node node) {
if (node == null) {
return false;
}
for (int i = 0; i < moduleNames.size(); i++) {
if (moduleNames.get(i) == node) {
moduleNames.remove(i);
return true;
}
}
return super.remove(node);
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public Name getName() {
return name;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ModuleExportsDirective setName(final Name name) {
assertNotNull(name);
if (name == this.name) {
return this;
}
notifyPropertyChange(ObservableProperty.NAME, this.name, name);
if (this.name != null) this.name.setParentNode(null);
this.name = name;
setAsParentNodeOf(name);
return this;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public NodeList<Name> getModuleNames() {
return moduleNames;
}
@Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
public ModuleExportsDirective setModuleNames(final NodeList<Name> moduleNames) {
assertNotNull(moduleNames);
if (moduleNames == this.moduleNames) {
return this;
}
notifyPropertyChange(ObservableProperty.MODULE_NAMES, this.moduleNames, moduleNames);
if (this.moduleNames != null) this.moduleNames.setParentNode(null);
this.moduleNames = moduleNames;
setAsParentNodeOf(moduleNames);
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.CloneGenerator")
public ModuleExportsDirective clone() {
return (ModuleExportsDirective) accept(new CloneVisitor(), null);
}
@Override
@Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
public boolean replace(Node node, Node replacementNode) {
if (node == null) {
return false;
}
for (int i = 0; i < moduleNames.size(); i++) {
if (moduleNames.get(i) == node) {
moduleNames.set(i, (Name) replacementNode);
return true;
}
}
if (node == name) {
setName((Name) replacementNode);
return true;
}
return super.replace(node, replacementNode);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleExportsStmt() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleExportsDirective asModuleExportsStmt() {
return this;
}
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleExportsStmt(Consumer<ModuleExportsDirective> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleExportsDirective> toModuleExportsStmt() {
return Optional.of(this);
}
public ModuleExportsDirective addModuleName(String name) {
moduleNames.add(parseName(name));
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public boolean isModuleExportsDirective() {
return true;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public ModuleExportsDirective asModuleExportsDirective() {
return this;
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public Optional<ModuleExportsDirective> toModuleExportsDirective() {
return Optional.of(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
public void ifModuleExportsDirective(Consumer<ModuleExportsDirective> action) {
action.accept(this);
}
@Override
@Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
public ModuleExportsDirectiveMetaModel getMetaModel() {
return JavaParserMetaModel.moduleExportsDirectiveMetaModel;
}
}

Some files were not shown because too many files have changed in this diff Show More