use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression in project intellij-community by JetBrains.
the class ImportMavenRepositoriesTask method findMavenRemoteRepositories.
@NotNull
private Collection<? extends MavenRemoteRepository> findMavenRemoteRepositories(@Nullable GrClosableBlock repositoriesBlock) {
Set<MavenRemoteRepository> myRemoteRepositories = ContainerUtil.newHashSet();
for (GrMethodCall repo : PsiTreeUtil.getChildrenOfTypeAsList(repositoriesBlock, GrMethodCall.class)) {
final String expressionText = repo.getInvokedExpression().getText();
if ("mavenCentral".equals(expressionText)) {
myRemoteRepositories.add(mavenCentralRemoteRepository);
} else if ("mavenRepo".equals(expressionText)) {
for (GrNamedArgument namedArgument : repo.getNamedArguments()) {
if ("url".equals(namedArgument.getLabelName())) {
URI urlArgumentValue = resolveUriFromSimpleExpression(namedArgument.getExpression());
if (urlArgumentValue != null) {
String textUri = urlArgumentValue.toString();
myRemoteRepositories.add(new MavenRemoteRepository(textUri, null, textUri, null, null, null));
}
break;
}
}
} else if ("maven".equals(expressionText) && repo.getClosureArguments().length > 0) {
List<GrApplicationStatement> applicationStatementList = PsiTreeUtil.getChildrenOfTypeAsList(repo.getClosureArguments()[0], GrApplicationStatement.class);
if (!applicationStatementList.isEmpty()) {
GrApplicationStatement statement = applicationStatementList.get(0);
if (statement == null)
continue;
GrExpression expression = statement.getInvokedExpression();
if ("url".equals(expression.getText())) {
URI urlArgumentValue = resolveUriFromSimpleExpression(statement.getExpressionArguments()[0]);
if (urlArgumentValue != null) {
String textUri = urlArgumentValue.toString();
myRemoteRepositories.add(new MavenRemoteRepository(textUri, null, textUri, null, null, null));
}
}
}
List<GrAssignmentExpression> assignmentExpressionList = PsiTreeUtil.getChildrenOfTypeAsList(repo.getClosureArguments()[0], GrAssignmentExpression.class);
if (!assignmentExpressionList.isEmpty()) {
GrAssignmentExpression statement = assignmentExpressionList.get(0);
if (statement == null)
continue;
GrExpression expression = statement.getLValue();
if ("url".equals(expression.getText())) {
URI urlArgumentValue = resolveUriFromSimpleExpression(statement.getRValue());
if (urlArgumentValue != null) {
String textUri = urlArgumentValue.toString();
myRemoteRepositories.add(new MavenRemoteRepository(textUri, null, textUri, null, null, null));
}
}
}
}
}
return myRemoteRepositories;
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression in project intellij-community by JetBrains.
the class GroovyExtractChooser method buildInfo.
@NotNull
private static InitialInfo buildInfo(@NotNull Project project, @NotNull PsiFile file, int start, int end, boolean forceStatements, @NotNull SelectionModel selectionModel, @Nullable GrVariable variable) throws GrRefactoringError {
PsiElement[] elements = getElementsInOffset(file, start, end, forceStatements);
//if (elements.length == 1 && elements[0] instanceof GrExpression) {
// selectionModel.setSelection(start, elements[0].getTextRange().getEndOffset());
//}
GrStatement[] statements = getStatementsByElements(elements);
if (statements.length == 0) {
throw new GrRefactoringError(GroovyRefactoringBundle.message("selected.block.should.represent.a.statement.set"));
}
for (GrStatement statement : statements) {
if (GroovyRefactoringUtil.isSuperOrThisCall(statement, true, true)) {
throw new GrRefactoringError(GroovyRefactoringBundle.message("selected.block.contains.invocation.of.another.class.constructor"));
}
}
GrStatement statement0 = statements[0];
PsiClass owner = PsiUtil.getContextClass(statement0);
GrStatementOwner declarationOwner = GroovyRefactoringUtil.getDeclarationOwner(statement0);
if (owner == null || declarationOwner == null && !ExtractUtil.isSingleExpression(statements)) {
throw new GrRefactoringError(GroovyRefactoringBundle.message("refactoring.is.not.supported.in.the.current.context"));
}
if (declarationOwner == null && ExtractUtil.isSingleExpression(statements) && statement0 instanceof GrExpression && PsiType.VOID.equals(((GrExpression) statement0).getType())) {
throw new GrRefactoringError(GroovyRefactoringBundle.message("selected.expression.has.void.type"));
}
if (ExtractUtil.isSingleExpression(statements) && GrIntroduceHandlerBase.expressionIsIncorrect((GrExpression) statement0, true)) {
throw new GrRefactoringError(GroovyRefactoringBundle.message("selected.block.should.represent.an.expression"));
}
if (ExtractUtil.isSingleExpression(statements) && statement0.getParent() instanceof GrAssignmentExpression && ((GrAssignmentExpression) statement0.getParent()).getLValue() == statement0) {
throw new GrRefactoringError(GroovyRefactoringBundle.message("selected.expression.should.not.be.lvalue"));
}
// collect information about return statements in selected statement set
Set<GrStatement> allReturnStatements = new HashSet<>();
GrControlFlowOwner controlFlowOwner = ControlFlowUtils.findControlFlowOwner(statement0);
LOG.assertTrue(controlFlowOwner != null);
final Instruction[] flow = new ControlFlowBuilder(project, GrAllVarsInitializedPolicy.getInstance()).buildControlFlow(controlFlowOwner);
allReturnStatements.addAll(ControlFlowUtils.collectReturns(flow, true));
ArrayList<GrStatement> returnStatements = new ArrayList<>();
for (GrStatement returnStatement : allReturnStatements) {
for (GrStatement statement : statements) {
if (PsiTreeUtil.isAncestor(statement, returnStatement, false)) {
returnStatements.add(returnStatement);
break;
}
}
}
// collect information about variables in selected block
FragmentVariableInfos fragmentVariableInfos = ReachingDefinitionsCollector.obtainVariableFlowInformation(statement0, statements[statements.length - 1], controlFlowOwner, flow);
VariableInfo[] inputInfos = fragmentVariableInfos.getInputVariableNames();
VariableInfo[] outputInfos = fragmentVariableInfos.getOutputVariableNames();
if (outputInfos.length == 1 && !returnStatements.isEmpty()) {
throw new GrRefactoringError(GroovyRefactoringBundle.message("multiple.output.values"));
}
boolean hasInterruptingStatements = false;
for (GrStatement statement : statements) {
hasInterruptingStatements = GroovyRefactoringUtil.hasWrongBreakStatements(statement) || GroovyRefactoringUtil.hasWrongContinueStatements(statement);
if (hasInterruptingStatements)
break;
}
// must be replaced by return statement
boolean hasReturns = !returnStatements.isEmpty();
List<GrStatement> returnStatementsCopy = new ArrayList<>(returnStatements.size());
returnStatementsCopy.addAll(returnStatements);
boolean isReturnStatement = isReturnStatement(statements[statements.length - 1], returnStatementsCopy);
boolean isLastStatementOfMethod = isLastStatementOfMethodOrClosure(statements);
if (hasReturns && !isLastStatementOfMethod && !isReturnStatement || hasInterruptingStatements) {
throw new GrRefactoringError(GroovyRefactoringBundle.message("refactoring.is.not.supported.when.return.statement.interrupts.the.execution.flow"));
}
return new InitialInfo(inputInfos, outputInfos, elements, statements, returnStatements, null, project, variable);
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression in project android by JetBrains.
the class GradleEditorModelParserFacade method fillContext.
/**
* Processes given PSI file and fills given context
* by {@link GradleEditorModelParseContext#getAssignments(Variable) corresponding assignments}.
*
* @param context context to fill
* @param psiFile psi file to parse
*/
private static void fillContext(@NotNull final GradleEditorModelParseContext context, @NotNull PsiFile psiFile) {
psiFile.acceptChildren(new GroovyPsiElementVisitor(new GroovyRecursiveElementVisitor() {
@Override
public void visitMethodCallExpression(GrMethodCallExpression methodCallExpression) {
Pair<String, TextRange> pair = GradleEditorValueExtractor.extractMethodName(methodCallExpression);
GrClosableBlock[] closureArguments = methodCallExpression.getClosureArguments();
if (pair == null || closureArguments.length > 1) {
super.visitMethodCallExpression(methodCallExpression);
return;
}
if (closureArguments.length == 0) {
if (methodCallExpression.getArgumentList().getAllArguments().length == 0) {
// This is a no-args method, so, we just register it for cases like 'mavenCentral()' or 'jcenter()'.
context.addCachedValue(NO_ARGS_METHOD_ASSIGNMENT_VALUE, TextRange.create(pair.second.getEndOffset(), methodCallExpression.getTextRange().getEndOffset()));
context.registerAssignmentFromCachedData(pair.first, pair.second, methodCallExpression);
}
return;
}
context.onMethodEnter(pair.getFirst());
try {
super.visitClosure(closureArguments[0]);
} finally {
context.onMethodExit();
}
}
@Override
public void visitApplicationStatement(GrApplicationStatement applicationStatement) {
Pair<String, TextRange> methodName = GradleEditorValueExtractor.extractMethodName(applicationStatement);
if (methodName == null) {
return;
}
GroovyPsiElement[] allArguments = applicationStatement.getArgumentList().getAllArguments();
if (allArguments.length == 1) {
context.resetCaches();
extractValueOrVariable(allArguments[0], context);
context.registerAssignmentFromCachedData(methodName.getFirst(), methodName.getSecond(), applicationStatement.getArgumentList());
}
}
@Override
public void visitAssignmentExpression(GrAssignmentExpression expression) {
// General idea is to try to extract variable from the given expression and, in case of success, try to extract rvalue and
// register corresponding assignment with them.
context.resetCaches();
extractValueOrVariable(expression.getLValue(), context);
Multimap<Variable, Location> vars = context.getCachedVariables();
if (vars.size() != 1) {
context.resetCaches();
return;
}
Map.Entry<Variable, Location> entry = vars.entries().iterator().next();
Variable lVariable = entry.getKey();
Location lVariableLocation = entry.getValue();
context.resetCaches();
GrExpression rValue = expression.getRValue();
if (rValue == null) {
return;
}
extractValueOrVariable(rValue, context);
if (context.getCachedValues().size() > 1) {
Value value = new Value("", new Location(context.getCurrentFile(), GradleEditorModelUtil.interestedRange(rValue)));
context.setCachedValues(Collections.singletonList(value));
}
context.registerAssignmentFromCachedData(lVariable, lVariableLocation, rValue);
context.resetCaches();
}
@Override
public void visitVariable(GrVariable variable) {
TextRange nameRange = null;
boolean lookForInitializer = false;
ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.findSingle(GroovyLanguage.INSTANCE);
for (PsiElement e = variable.getFirstChild(); e != null; e = e.getNextSibling()) {
ASTNode node = e.getNode();
if (node == null) {
continue;
}
if (!lookForInitializer) {
if (node.getElementType() == GroovyTokenTypes.mIDENT) {
nameRange = e.getTextRange();
} else if (node.getElementType() == GroovyTokenTypes.mASSIGN) {
if (nameRange == null) {
return;
}
lookForInitializer = true;
}
continue;
}
if (node.getElementType() == GroovyTokenTypes.mNLS || node.getElementType() == GroovyTokenTypes.mSEMI) {
break;
}
if (parserDefinition.getWhitespaceTokens().contains(node.getElementType())) {
continue;
}
extractValueOrVariable(e, context);
if (context.getCachedValues().size() > 1) {
Value value = new Value("", new Location(context.getCurrentFile(), GradleEditorModelUtil.interestedRange(e)));
context.setCachedValues(Collections.singletonList(value));
}
if (context.registerAssignmentFromCachedData(variable.getName(), nameRange, e)) {
return;
}
}
}
}));
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression in project android by JetBrains.
the class GradleDslElement method deleteIfEmpty.
protected static void deleteIfEmpty(@Nullable PsiElement element) {
if (element == null || !element.isValid()) {
return;
}
PsiElement parent = element.getParent();
if (element instanceof GrAssignmentExpression) {
if (((GrAssignmentExpression) element).getRValue() == null) {
element.delete();
}
} else if (element instanceof GrApplicationStatement) {
if (((GrApplicationStatement) element).getArgumentList() == null) {
element.delete();
}
} else if (element instanceof GrClosableBlock) {
final Boolean[] isEmpty = new Boolean[] { true };
((GrClosableBlock) element).acceptChildren(new GroovyElementVisitor() {
@Override
public void visitElement(GroovyPsiElement child) {
if (child instanceof GrParameterList) {
if (((GrParameterList) child).getParameters().length == 0) {
// Ignore the empty parameter list.
return;
}
}
isEmpty[0] = false;
}
});
if (isEmpty[0]) {
element.delete();
}
} else if (element instanceof GrMethodCallExpression) {
GrMethodCallExpression call = ((GrMethodCallExpression) element);
GrArgumentList argumentList;
try {
argumentList = call.getArgumentList();
} catch (AssertionError e) {
// We will get this exception if the argument list is already deleted.
argumentList = null;
}
GrClosableBlock[] closureArguments = call.getClosureArguments();
if ((argumentList == null || argumentList.getAllArguments().length == 0) && closureArguments.length == 0) {
element.delete();
}
} else if (element instanceof GrCommandArgumentList) {
GrCommandArgumentList commandArgumentList = (GrCommandArgumentList) element;
if (commandArgumentList.getAllArguments().length == 0) {
commandArgumentList.delete();
}
} else if (element instanceof GrListOrMap) {
GrListOrMap listOrMap = (GrListOrMap) element;
if ((listOrMap.isMap() && listOrMap.getNamedArguments().length == 0) || (!listOrMap.isMap() && listOrMap.getInitializers().length == 0)) {
listOrMap.delete();
}
}
if (!element.isValid()) {
// If this element is deleted, also delete the parent if it is empty.
deleteIfEmpty(parent);
}
}
Aggregations