use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression in project intellij-community by JetBrains.
the class GrRefactoringConflictsUtil method checkUsedElements.
public static void checkUsedElements(PsiMember member, PsiElement scope, @NotNull Set<GrMember> membersToMove, @Nullable Set<PsiMethod> abstractMethods, @Nullable PsiClass targetClass, @NotNull PsiElement context, MultiMap<PsiElement, String> conflicts) {
final Set<PsiMember> moving = new HashSet<>(membersToMove);
if (abstractMethods != null) {
moving.addAll(abstractMethods);
}
if (scope instanceof GrReferenceExpression) {
GrReferenceExpression refExpr = (GrReferenceExpression) scope;
PsiElement refElement = refExpr.resolve();
if (refElement instanceof PsiMember) {
if (!RefactoringHierarchyUtil.willBeInTargetClass(refElement, moving, targetClass, false)) {
GrExpression qualifier = refExpr.getQualifierExpression();
PsiClass accessClass = (PsiClass) (qualifier != null ? PsiUtil.getAccessObjectClass(qualifier).getElement() : null);
RefactoringConflictsUtil.checkAccessibility((PsiMember) refElement, context, accessClass, member, conflicts);
}
}
} else if (scope instanceof GrNewExpression) {
final GrNewExpression newExpression = (GrNewExpression) scope;
final GrAnonymousClassDefinition anonymousClass = newExpression.getAnonymousClassDefinition();
if (anonymousClass != null) {
if (!RefactoringHierarchyUtil.willBeInTargetClass(anonymousClass, moving, targetClass, false)) {
RefactoringConflictsUtil.checkAccessibility(anonymousClass, context, anonymousClass, member, conflicts);
}
} else {
final PsiMethod refElement = newExpression.resolveMethod();
if (refElement != null) {
if (!RefactoringHierarchyUtil.willBeInTargetClass(refElement, moving, targetClass, false)) {
RefactoringConflictsUtil.checkAccessibility(refElement, context, null, member, conflicts);
}
}
}
} else if (scope instanceof GrCodeReferenceElement) {
GrCodeReferenceElement refExpr = (GrCodeReferenceElement) scope;
PsiElement refElement = refExpr.resolve();
if (refElement instanceof PsiMember) {
if (!RefactoringHierarchyUtil.willBeInTargetClass(refElement, moving, targetClass, false)) {
RefactoringConflictsUtil.checkAccessibility((PsiMember) refElement, context, null, member, conflicts);
}
}
}
for (PsiElement child : scope.getChildren()) {
if (child instanceof PsiWhiteSpace || child instanceof PsiComment)
continue;
checkUsedElements(member, child, membersToMove, abstractMethods, targetClass, context, conflicts);
}
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression 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.GrNewExpression in project intellij-community by JetBrains.
the class GroovySpacingProcessorBasic method getSpacing.
public static Spacing getSpacing(GroovyBlock child1, GroovyBlock child2, FormattingContext context) {
ASTNode leftNode = child1.getNode();
ASTNode rightNode = child2.getNode();
final PsiElement left = leftNode.getPsi();
final PsiElement right = rightNode.getPsi();
IElementType leftType = leftNode.getElementType();
IElementType rightType = rightNode.getElementType();
final CommonCodeStyleSettings settings = context.getSettings();
final GroovyCodeStyleSettings groovySettings = context.getGroovySettings();
if (!(mirrorsAst(child1) && mirrorsAst(child2))) {
return NO_SPACING;
}
if (child2 instanceof ClosureBodyBlock) {
return settings.SPACE_WITHIN_BRACES ? COMMON_SPACING : NO_SPACING_WITH_NEWLINE;
}
if (child1 instanceof ClosureBodyBlock) {
return createDependentSpacingForClosure(settings, groovySettings, (GrClosableBlock) left.getParent(), false);
}
if (leftType == GroovyDocElementTypes.GROOVY_DOC_COMMENT) {
return COMMON_SPACING_WITH_NL;
}
if (right instanceof GrTypeArgumentList) {
return NO_SPACING_WITH_NEWLINE;
}
/********** punctuation marks ************/
if (GroovyTokenTypes.mCOMMA == leftType) {
return settings.SPACE_AFTER_COMMA ? COMMON_SPACING : NO_SPACING_WITH_NEWLINE;
}
if (GroovyTokenTypes.mCOMMA == rightType) {
return settings.SPACE_BEFORE_COMMA ? COMMON_SPACING : NO_SPACING_WITH_NEWLINE;
}
if (GroovyTokenTypes.mSEMI == leftType) {
return settings.SPACE_AFTER_SEMICOLON ? COMMON_SPACING : NO_SPACING_WITH_NEWLINE;
}
if (GroovyTokenTypes.mSEMI == rightType) {
return settings.SPACE_BEFORE_SEMICOLON ? COMMON_SPACING : NO_SPACING_WITH_NEWLINE;
}
// For dots, commas etc.
if ((TokenSets.DOTS.contains(rightType)) || (GroovyTokenTypes.mCOLON.equals(rightType) && !(right.getParent() instanceof GrConditionalExpression))) {
return NO_SPACING_WITH_NEWLINE;
}
if (TokenSets.DOTS.contains(leftType)) {
return NO_SPACING_WITH_NEWLINE;
}
//todo:check it for multiple assignments
if ((GroovyElementTypes.VARIABLE_DEFINITION.equals(leftType) || GroovyElementTypes.VARIABLE_DEFINITION.equals(rightType)) && !(leftNode.getTreeNext() instanceof PsiErrorElement)) {
return Spacing.createSpacing(0, 0, 1, false, 100);
}
// For regexes
if (leftNode.getTreeParent().getElementType() == GroovyTokenTypes.mREGEX_LITERAL || leftNode.getTreeParent().getElementType() == GroovyTokenTypes.mDOLLAR_SLASH_REGEX_LITERAL) {
return NO_SPACING;
}
// For << and >> ...
if ((GroovyTokenTypes.mLT.equals(leftType) && GroovyTokenTypes.mLT.equals(rightType)) || (GroovyTokenTypes.mGT.equals(leftType) && GroovyTokenTypes.mGT.equals(rightType))) {
return NO_SPACING_WITH_NEWLINE;
}
// Unary and postfix expressions
if (SpacingTokens.PREFIXES.contains(leftType) || SpacingTokens.POSTFIXES.contains(rightType) || (SpacingTokens.PREFIXES_OPTIONAL.contains(leftType) && left.getParent() instanceof GrUnaryExpression)) {
return NO_SPACING_WITH_NEWLINE;
}
if (SpacingTokens.RANGES.contains(leftType) || SpacingTokens.RANGES.contains(rightType)) {
return NO_SPACING_WITH_NEWLINE;
}
if (GroovyDocTokenTypes.mGDOC_ASTERISKS == leftType && GroovyDocTokenTypes.mGDOC_COMMENT_DATA == rightType) {
String text = rightNode.getText();
if (!text.isEmpty() && !StringUtil.startsWithChar(text, ' ')) {
return COMMON_SPACING;
}
return NO_SPACING;
}
if (leftType == GroovyDocTokenTypes.mGDOC_TAG_VALUE_TOKEN && rightType == GroovyDocTokenTypes.mGDOC_COMMENT_DATA) {
return LAZY_SPACING;
}
if (left instanceof GrStatement && right instanceof GrStatement && left.getParent() instanceof GrStatementOwner && right.getParent() instanceof GrStatementOwner) {
return COMMON_SPACING_WITH_NL;
}
if (rightType == GroovyDocTokenTypes.mGDOC_INLINE_TAG_END || leftType == GroovyDocTokenTypes.mGDOC_INLINE_TAG_START || rightType == GroovyDocTokenTypes.mGDOC_INLINE_TAG_START || leftType == GroovyDocTokenTypes.mGDOC_INLINE_TAG_END) {
return NO_SPACING;
}
if ((leftType == GroovyDocElementTypes.GDOC_INLINED_TAG && rightType == GroovyDocTokenTypes.mGDOC_COMMENT_DATA) || (leftType == GroovyDocTokenTypes.mGDOC_COMMENT_DATA && rightType == GroovyDocElementTypes.GDOC_INLINED_TAG)) {
// Keep formatting between groovy doc text and groovy doc reference tag as is.
return NO_SPACING;
}
if (leftType == GroovyElementTypes.CLASS_TYPE_ELEMENT && rightType == GroovyTokenTypes.mTRIPLE_DOT) {
return NO_SPACING;
}
// diamonds
if (rightType == GroovyTokenTypes.mLT || rightType == GroovyTokenTypes.mGT) {
if (right.getParent() instanceof GrCodeReferenceElement) {
PsiElement p = right.getParent().getParent();
if (p instanceof GrNewExpression || p instanceof GrAnonymousClassDefinition) {
return NO_SPACING;
}
}
}
return COMMON_SPACING;
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression in project intellij-community by JetBrains.
the class ReplaceAbstractClassInstanceByMapIntention method processIntention.
@Override
protected void processIntention(@NotNull PsiElement psiElement, @NotNull Project project, Editor editor) throws IncorrectOperationException {
PsiDocumentManager.getInstance(project).commitAllDocuments();
GrCodeReferenceElement ref = (GrCodeReferenceElement) psiElement;
final GrAnonymousClassDefinition anonymous = (GrAnonymousClassDefinition) ref.getParent();
final GrNewExpression newExpr = (GrNewExpression) anonymous.getParent();
final PsiElement resolved = ref.resolve();
// && ((PsiClass)resolved).isInterface();
assert resolved instanceof PsiClass;
GrTypeDefinitionBody body = anonymous.getBody();
assert body != null;
List<Pair<PsiMethod, GrOpenBlock>> methods = new ArrayList<>();
for (GrMethod method : body.getMethods()) {
methods.add(new Pair<>(method, method.getBlock()));
}
final PsiClass iface = (PsiClass) resolved;
final Collection<CandidateInfo> collection = OverrideImplementExploreUtil.getMethodsToOverrideImplement(anonymous, true);
for (CandidateInfo info : collection) {
methods.add(new Pair<>((PsiMethod) info.getElement(), null));
}
StringBuilder buffer = new StringBuilder();
if (methods.size() == 1) {
final Pair<PsiMethod, GrOpenBlock> pair = methods.get(0);
appendClosureTextByMethod(pair.getFirst(), buffer, pair.getSecond(), newExpr);
if (!GroovyConfigUtils.getInstance().isVersionAtLeast(psiElement, GroovyConfigUtils.GROOVY2_2)) {
buffer.append(" as ").append(iface.getQualifiedName());
}
} else {
buffer.append("[");
buffer.append("\n");
for (Pair<PsiMethod, GrOpenBlock> pair : methods) {
final PsiMethod method = pair.getFirst();
final GrOpenBlock block = pair.getSecond();
buffer.append(method.getName()).append(": ");
appendClosureTextByMethod(method, buffer, block, newExpr);
buffer.append(",\n");
}
if (!methods.isEmpty()) {
buffer.delete(buffer.length() - 2, buffer.length());
buffer.append('\n');
}
buffer.append("]");
buffer.append(" as ").append(iface.getQualifiedName());
}
createAndAdjustNewExpression(project, newExpr, buffer);
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression in project intellij-community by JetBrains.
the class GroovyConstructorUsagesSearcher method processConstructorUsages.
static void processConstructorUsages(final PsiMethod constructor, final SearchScope searchScope, final Processor<PsiReference> consumer, final SearchRequestCollector collector, final boolean includeOverloads) {
if (!constructor.isConstructor())
return;
final PsiClass clazz = constructor.getContainingClass();
if (clazz == null)
return;
SearchScope onlyGroovy = GroovyScopeUtil.restrictScopeToGroovyFiles(searchScope, GroovyScopeUtil.getEffectiveScope(constructor));
Set<PsiClass> processed = collector.getSearchSession().getUserData(LITERALLY_CONSTRUCTED_CLASSES);
if (processed == null) {
collector.getSearchSession().putUserData(LITERALLY_CONSTRUCTED_CLASSES, processed = ContainerUtil.newConcurrentSet());
}
if (!processed.add(clazz))
return;
if (clazz.isEnum() && clazz instanceof GroovyPsiElement) {
for (PsiField field : clazz.getFields()) {
if (field instanceof GrEnumConstant) {
final PsiReference ref = field.getReference();
if (ref != null && ref.isReferenceTo(constructor)) {
if (!consumer.process(ref))
return;
}
}
}
}
final LiteralConstructorSearcher literalProcessor = new LiteralConstructorSearcher(constructor, consumer, includeOverloads);
final Processor<GrNewExpression> newExpressionProcessor = grNewExpression -> {
final PsiMethod resolvedConstructor = grNewExpression.resolveMethod();
if (includeOverloads || constructor.getManager().areElementsEquivalent(resolvedConstructor, constructor)) {
return consumer.process(grNewExpression.getReferenceElement());
}
return true;
};
processGroovyClassUsages(clazz, searchScope, collector, newExpressionProcessor, literalProcessor);
//this()
if (clazz instanceof GrTypeDefinition) {
if (!processConstructors(constructor, consumer, clazz, true)) {
return;
}
}
//super()
DirectClassInheritorsSearch.search(clazz, onlyGroovy).forEach(new ReadActionProcessor<PsiClass>() {
@Override
public boolean processInReadAction(PsiClass inheritor) {
if (inheritor instanceof GrTypeDefinition) {
if (!processConstructors(constructor, consumer, inheritor, false))
return false;
}
return true;
}
});
}
Aggregations