use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression in project intellij-community by JetBrains.
the class ConvertClosureToMethodIntention method processIntention.
@Override
protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) throws IncorrectOperationException {
final GrField field;
if (element.getParent() instanceof GrField) {
field = (GrField) element.getParent();
} else {
final PsiReference ref = element.getReference();
LOG.assertTrue(ref != null);
PsiElement resolved = ref.resolve();
if (resolved instanceof GrAccessorMethod) {
resolved = ((GrAccessorMethod) resolved).getProperty();
}
LOG.assertTrue(resolved instanceof GrField);
field = (GrField) resolved;
}
final HashSet<PsiReference> usages = new HashSet<>();
usages.addAll(ReferencesSearch.search(field).findAll());
final GrAccessorMethod[] getters = field.getGetters();
for (GrAccessorMethod getter : getters) {
usages.addAll(MethodReferencesSearch.search(getter).findAll());
}
final GrAccessorMethod setter = field.getSetter();
if (setter != null) {
usages.addAll(MethodReferencesSearch.search(setter).findAll());
}
final String fieldName = field.getName();
LOG.assertTrue(fieldName != null);
final Collection<PsiElement> fieldUsages = new HashSet<>();
MultiMap<PsiElement, String> conflicts = new MultiMap<>();
for (PsiReference usage : usages) {
final PsiElement psiElement = usage.getElement();
if (PsiUtil.isMethodUsage(psiElement))
continue;
if (!GroovyLanguage.INSTANCE.equals(psiElement.getLanguage())) {
conflicts.putValue(psiElement, GroovyIntentionsBundle.message("closure.is.accessed.outside.of.groovy", fieldName));
} else {
if (psiElement instanceof GrReferenceExpression) {
fieldUsages.add(psiElement);
if (PsiUtil.isAccessedForWriting((GrExpression) psiElement)) {
conflicts.putValue(psiElement, GroovyIntentionsBundle.message("write.access.to.closure.variable", fieldName));
}
} else if (psiElement instanceof GrArgumentLabel) {
conflicts.putValue(psiElement, GroovyIntentionsBundle.message("field.is.used.in.argument.label", fieldName));
}
}
}
final PsiClass containingClass = field.getContainingClass();
final GrExpression initializer = field.getInitializerGroovy();
LOG.assertTrue(initializer != null);
final PsiType type = initializer.getType();
LOG.assertTrue(type instanceof GrClosureType);
final GrSignature signature = ((GrClosureType) type).getSignature();
final List<MethodSignature> signatures = GrClosureSignatureUtil.generateAllMethodSignaturesBySignature(fieldName, signature);
for (MethodSignature s : signatures) {
final PsiMethod method = MethodSignatureUtil.findMethodBySignature(containingClass, s, true);
if (method != null) {
conflicts.putValue(method, GroovyIntentionsBundle.message("method.with.signature.already.exists", GroovyPresentationUtil.getSignaturePresentation(s)));
}
}
if (!conflicts.isEmpty()) {
final ConflictsDialog conflictsDialog = new ConflictsDialog(project, conflicts, () -> execute(field, fieldUsages));
conflictsDialog.show();
if (conflictsDialog.getExitCode() != DialogWrapper.OK_EXIT_CODE)
return;
}
execute(field, fieldUsages);
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression in project intellij-community by JetBrains.
the class IndexingMethodConversionPredicate method satisfiedBy.
@Override
public boolean satisfiedBy(PsiElement element) {
if (!(element instanceof GrMethodCallExpression)) {
return false;
}
if (ErrorUtil.containsError(element)) {
return false;
}
final GrMethodCallExpression callExpression = (GrMethodCallExpression) element;
final GrArgumentList argList = callExpression.getArgumentList();
final GrExpression[] arguments = argList.getExpressionArguments();
final GrExpression invokedExpression = callExpression.getInvokedExpression();
if (!(invokedExpression instanceof GrReferenceExpression)) {
return false;
}
final GrReferenceExpression referenceExpression = (GrReferenceExpression) invokedExpression;
final GrExpression qualifier = referenceExpression.getQualifierExpression();
if (qualifier == null) {
return false;
}
final IElementType referenceType = referenceExpression.getDotTokenType();
if (!GroovyTokenTypes.mDOT.equals(referenceType)) {
return false;
}
final String methodName = referenceExpression.getReferenceName();
if ("getAt".equals(methodName)) {
return arguments.length == 1;
}
if ("get".equals(methodName)) {
final PsiType qualifierType = qualifier.getType();
if (!isMap(qualifierType)) {
return false;
}
return arguments.length == 1;
} else if ("setAt".equals(methodName)) {
return arguments.length == 2;
} else if ("put".equals(methodName)) {
final PsiType qualifierType = qualifier.getType();
if (!isMap(qualifierType)) {
return false;
}
return arguments.length == 2;
}
return false;
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression in project intellij-community by JetBrains.
the class GroovyInsertHandler method handleInsert.
@Override
public void handleInsert(InsertionContext context, LookupElement item) {
@NonNls Object obj = item.getObject();
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
if (obj instanceof GroovyResolveResult) {
substitutor = ((GroovyResolveResult) obj).getSubstitutor();
obj = ((GroovyResolveResult) obj).getElement();
}
if (obj instanceof PsiMethod) {
final PsiMethod method = (PsiMethod) obj;
PsiParameter[] parameters = method.getParameterList().getParameters();
Editor editor = context.getEditor();
Document document = editor.getDocument();
if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
handleOverwrite(editor.getCaretModel().getOffset(), document);
}
CaretModel caretModel = editor.getCaretModel();
int offset = context.getTailOffset();
PsiFile file = context.getFile();
PsiElement elementAt = file.findElementAt(context.getStartOffset());
assert elementAt != null;
PsiElement parent = elementAt.getParent();
if (parent instanceof GrReferenceExpression && ((GrReferenceExpression) parent).getDotTokenType() == GroovyTokenTypes.mMEMBER_POINTER) {
return;
}
CharSequence charsSequence = document.getCharsSequence();
if (isAnnotationNameValuePair(obj, parent)) {
int endOffset = offset;
if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
endOffset = CharArrayUtil.shiftForward(charsSequence, offset, " \t");
if (charsSequence.length() > endOffset && charsSequence.charAt(endOffset) == '=') {
endOffset++;
endOffset = CharArrayUtil.shiftForward(charsSequence, endOffset, " \t");
}
}
document.replaceString(offset, endOffset, " = ");
caretModel.moveToOffset(offset + 3);
return;
}
if (PsiTreeUtil.getParentOfType(elementAt, GrImportStatement.class) != null)
return;
if (parameters.length == 1) {
if ((context.getCompletionChar() != '(' && context.getCompletionChar() != ' ') && TypesUtil.isClassType(parameters[0].getType(), GroovyCommonClassNames.GROOVY_LANG_CLOSURE)) {
int afterBrace;
final int nonWs = CharArrayUtil.shiftForward(charsSequence, offset, " \t");
if (nonWs < document.getTextLength() && charsSequence.charAt(nonWs) == '{') {
afterBrace = nonWs + 1;
} else {
if (isSpaceBeforeClosure(file)) {
document.insertString(offset, " ");
offset++;
}
if (ClosureCompleter.runClosureCompletion(context, method, substitutor, document, offset, parent))
return;
if (context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
//smart enter invoked
document.insertString(offset, "{\n}");
//position caret before '{' for smart enter
afterBrace = offset + 1;
context.setTailOffset(afterBrace);
} else {
document.insertString(offset, "{}");
afterBrace = offset + 1;
}
}
caretModel.moveToOffset(afterBrace);
return;
}
}
context.commitDocument();
if (context.getCompletionChar() == ' ' && MethodParenthesesHandler.hasParams(item, context.getElements(), true, method)) {
return;
}
CommonCodeStyleSettings settings = context.getCodeStyleSettings();
ParenthesesInsertHandler.getInstance(MethodParenthesesHandler.hasParams(item, context.getElements(), true, method), settings.SPACE_BEFORE_METHOD_CALL_PARENTHESES, settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES, true, true).handleInsert(context, item);
AutoPopupController.getInstance(context.getProject()).autoPopupParameterInfo(editor, method);
return;
}
if (obj instanceof PsiClass) {
final PsiClass clazz = (PsiClass) obj;
Editor editor = context.getEditor();
Document document = editor.getDocument();
PsiFile file = PsiDocumentManager.getInstance(clazz.getProject()).getPsiFile(document);
assert file != null;
PsiElement elementAt = file.findElementAt(context.getStartOffset());
assert elementAt != null;
CaretModel caretModel = editor.getCaretModel();
int offset = context.getStartOffset() + elementAt.getTextLength();
final String text = document.getText();
final PsiElement parent = elementAt.getParent();
if (parent instanceof GrCodeReferenceElement && parent.getParent() instanceof GrNewExpression && (offset == text.length() || !text.substring(offset).trim().startsWith("("))) {
document.insertString(offset, "()");
if (GroovyCompletionUtil.hasConstructorParameters(clazz, parent)) {
caretModel.moveToOffset(offset + 1);
return;
}
caretModel.moveToOffset(offset + 2);
return;
}
}
if (context.getCompletionChar() == '=') {
context.setAddCompletionChar(false);
TailType.EQ.processTail(context.getEditor(), context.getTailOffset());
return;
}
if (obj instanceof PsiPackage) {
AutoPopupController.getInstance(context.getProject()).scheduleAutoPopup(context.getEditor());
}
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression in project intellij-community by JetBrains.
the class GroovyExtractMethodHandler method renameParameterOccurrences.
private static void renameParameterOccurrences(GrMethod method, ExtractMethodInfoHelper helper) throws IncorrectOperationException {
GrOpenBlock block = method.getBlock();
if (block == null)
return;
GrStatement[] statements = block.getStatements();
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(helper.getProject());
for (ParameterInfo info : helper.getParameterInfos()) {
final String oldName = info.getOriginalName();
final String newName = info.getName();
final ArrayList<GrExpression> result = new ArrayList<>();
if (!oldName.equals(newName)) {
for (final GrStatement statement : statements) {
statement.accept(new PsiRecursiveElementVisitor() {
@Override
public void visitElement(final PsiElement element) {
super.visitElement(element);
if (element instanceof GrReferenceExpression) {
GrReferenceExpression expr = (GrReferenceExpression) element;
if (!expr.isQualified() && oldName.equals(expr.getReferenceName())) {
result.add(expr);
}
}
}
});
for (GrExpression expr : result) {
expr.replaceWithExpression(factory.createExpressionFromText(newName), false);
}
}
}
}
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression in project intellij-community by JetBrains.
the class GrVariableInliner method inlineReference.
static void inlineReference(UsageInfo usage, PsiElement referenced, GrExpression initializer) {
if (initializer == null)
return;
GrExpression exprToBeReplaced = (GrExpression) usage.getElement();
if (exprToBeReplaced == null)
return;
if ((referenced instanceof GrAccessorMethod || referenced instanceof GrField) && exprToBeReplaced instanceof GrReferenceExpression) {
final GroovyResolveResult resolveResult = ((GrReferenceExpression) exprToBeReplaced).advancedResolve();
if (resolveResult.getElement() instanceof GrAccessorMethod && !resolveResult.isInvokedOnProperty()) {
final PsiElement parent = exprToBeReplaced.getParent();
if (parent instanceof GrCall && parent instanceof GrExpression) {
exprToBeReplaced = (GrExpression) parent;
} else {
return;
}
}
}
GrExpression newExpr = exprToBeReplaced.replaceWithExpression((GrExpression) initializer.copy(), true);
final Project project = usage.getProject();
JavaCodeStyleManager.getInstance(project).shortenClassReferences(newExpr);
Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
GroovyRefactoringUtil.highlightOccurrences(project, editor, new PsiElement[] { newExpr });
WindowManager.getInstance().getStatusBar(project).setInfo(GroovyRefactoringBundle.message("press.escape.to.remove.the.highlighting"));
}
Aggregations