use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock in project intellij-community by JetBrains.
the class GroovyBlockGenerator method isAfterMultiLineClosure.
private static boolean isAfterMultiLineClosure(ASTNode dot) {
PsiElement dotPsi = dot.getPsi();
PsiElement prev = PsiUtil.skipWhitespaces(dotPsi.getPrevSibling(), false);
if (prev != null) {
if (prev instanceof GrMethodCall) {
final PsiElement last = prev.getLastChild();
if (last instanceof GrClosableBlock) {
return last.getText().contains("\n");
}
}
}
return false;
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock in project intellij-community by JetBrains.
the class GroovyBlockGenerator method generateSubBlocks.
public List<Block> generateSubBlocks() {
//For binary expressions
PsiElement blockPsi = myNode.getPsi();
IElementType elementType = myNode.getElementType();
if (blockPsi instanceof GrBinaryExpression && !(blockPsi.getParent() instanceof GrBinaryExpression)) {
return generateForBinaryExpr();
}
//For multiline strings
if ((elementType == GroovyTokenTypes.mSTRING_LITERAL || elementType == GroovyTokenTypes.mGSTRING_LITERAL) && myBlock.getTextRange().equals(myNode.getTextRange())) {
String text = myNode.getText();
if (text.length() > 6) {
if (text.substring(0, 3).equals("'''") && text.substring(text.length() - 3).equals("'''") || text.substring(0, 3).equals("\"\"\"") & text.substring(text.length() - 3).equals("\"\"\"")) {
return generateForMultiLineString();
}
}
}
//for gstrings
if (elementType == GroovyElementTypes.GSTRING || elementType == GroovyElementTypes.REGEX || elementType == GroovyTokenTypes.mREGEX_LITERAL || elementType == GroovyTokenTypes.mDOLLAR_SLASH_REGEX_LITERAL) {
final FormattingContext context = myNode.getPsi() instanceof GrString && ((GrString) myNode.getPsi()).isPlainString() ? myContext.createContext(true) : myContext;
final ArrayList<Block> subBlocks = new ArrayList<>();
ASTNode[] children = getGroovyChildren(myNode);
for (ASTNode childNode : children) {
if (childNode.getTextRange().getLength() > 0) {
subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), Wrap.createWrap(WrapType.NONE, false), context));
}
}
return subBlocks;
}
// chained properties, calls, indexing, etc
if (NESTED.contains(elementType) && blockPsi.getParent() != null && !NESTED.contains(blockPsi.getParent().getNode().getElementType())) {
final List<Block> subBlocks = new ArrayList<>();
AlignmentProvider.Aligner dotsAligner = myContext.getSettings().ALIGN_MULTILINE_CHAINED_METHODS ? myAlignmentProvider.createAligner(false) : null;
final Wrap wrap = myWrappingProcessor.getChainedMethodCallWrap();
addNestedChildren(myNode.getPsi(), subBlocks, dotsAligner, true, wrap);
return subBlocks;
}
if (blockPsi instanceof GrListOrMap && ((GrListOrMap) blockPsi).isMap() && myContext.getGroovySettings().ALIGN_NAMED_ARGS_IN_MAP) {
AlignmentProvider.Aligner labels = myAlignmentProvider.createAligner(false);
AlignmentProvider.Aligner exprs = myAlignmentProvider.createAligner(true);
GrNamedArgument[] namedArgs = ((GrListOrMap) blockPsi).getNamedArguments();
for (GrNamedArgument arg : namedArgs) {
GrArgumentLabel label = arg.getLabel();
if (label != null)
labels.append(label);
PsiElement colon = arg.getColon();
if (colon == null)
colon = arg.getExpression();
if (colon != null)
exprs.append(colon);
}
}
// For Parameter lists
if (isListLikeClause(blockPsi)) {
final ArrayList<Block> subBlocks = new ArrayList<>();
List<ASTNode> astNodes = visibleChildren(myNode);
if (mustAlign(blockPsi, astNodes)) {
final AlignmentProvider.Aligner aligner = myAlignmentProvider.createAligner(false);
for (ASTNode node : astNodes) {
if (!isKeyword(node))
aligner.append(node.getPsi());
}
}
for (ASTNode childNode : astNodes) {
subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), getChildWrap(childNode), myContext));
}
return subBlocks;
}
boolean classLevel = blockPsi instanceof GrTypeDefinitionBody;
if (blockPsi instanceof GrClosableBlock && ((GrClosableBlock) blockPsi).getArrow() != null && ((GrClosableBlock) blockPsi).getParameters().length > 0 && !getClosureBodyVisibleChildren(myNode).isEmpty()) {
GrClosableBlock closableBlock = (GrClosableBlock) blockPsi;
ArrayList<Block> blocks = new ArrayList<>();
PsiElement lbrace = closableBlock.getLBrace();
if (lbrace != null) {
ASTNode node = lbrace.getNode();
blocks.add(new GroovyBlock(node, getIndent(node), Wrap.createWrap(WrapType.NONE, false), myContext));
}
/* {
Indent indent = GroovyIndentProcessor.getChildIndent(myBlock, parameterListNode);
GroovyBlock block = new GroovyBlock(parameterListNode, indent, myWrap, mySettings, myGroovySettings, myAlignmentProvider);
blocks.add(block);
}
{
PsiElement arrow = closableBlock.getArrow();
ASTNode node = arrow.getNode();
Indent indent = GroovyIndentProcessor.getChildIndent(myBlock, node);
GroovyBlock block = new GroovyBlock(node, indent, myWrap, mySettings, myGroovySettings, myAlignmentProvider);
blocks.add(block);
}*/
{
Indent indent = Indent.getNormalIndent();
ASTNode parameterListNode = closableBlock.getParameterList().getNode();
ClosureBodyBlock bodyBlock = new ClosureBodyBlock(parameterListNode, indent, Wrap.createWrap(WrapType.NONE, false), myContext);
blocks.add(bodyBlock);
}
PsiElement rbrace = closableBlock.getRBrace();
if (rbrace != null) {
ASTNode node = rbrace.getNode();
blocks.add(new GroovyBlock(node, getIndent(node), Wrap.createWrap(WrapType.NONE, false), myContext));
}
return blocks;
}
if (blockPsi instanceof GrCodeBlock || blockPsi instanceof GroovyFile || classLevel) {
return generateSubBlockForCodeBlocks(classLevel, visibleChildren(myNode), myContext.getGroovySettings().INDENT_LABEL_BLOCKS);
}
if (blockPsi instanceof GrMethod) {
final ArrayList<Block> subBlocks = new ArrayList<>();
for (ASTNode childNode : getGroovyChildren(myNode)) {
if (childNode.getElementType() == GroovyTokenTypes.mLPAREN)
continue;
if (childNode.getElementType() == GroovyTokenTypes.mRPAREN)
continue;
if (childNode.getElementType() == GroovyElementTypes.PARAMETERS_LIST) {
subBlocks.add(new ParameterListBlock(((GrMethod) blockPsi), Indent.getNoneIndent(), Wrap.createWrap(WrapType.NONE, false), myContext));
} else if (canBeCorrectBlock(childNode)) {
subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), getChildWrap(childNode), myContext));
}
}
return subBlocks;
} else if (blockPsi instanceof GrTraditionalForClause) {
if (myContext.getSettings().ALIGN_MULTILINE_FOR) {
final GrTraditionalForClause clause = (GrTraditionalForClause) blockPsi;
final AlignmentProvider.Aligner parenthesesAligner = myAlignmentProvider.createAligner(false);
parenthesesAligner.append(clause.getInitialization());
parenthesesAligner.append(clause.getCondition());
parenthesesAligner.append(clause.getUpdate());
}
} else if (blockPsi instanceof GrBinaryExpression) {
if (myContext.getSettings().ALIGN_MULTILINE_BINARY_OPERATION) {
final GrBinaryExpression binary = (GrBinaryExpression) blockPsi;
final GrExpression left = binary.getLeftOperand();
final GrExpression right = binary.getRightOperand();
if (left != null && right != null) {
myAlignmentProvider.addPair(left, right, false);
}
}
} else if (blockPsi instanceof GrAssignmentExpression) {
if (myContext.getSettings().ALIGN_MULTILINE_ASSIGNMENT) {
final GrAssignmentExpression assignment = (GrAssignmentExpression) blockPsi;
final GrExpression lValue = assignment.getLValue();
final GrExpression rValue = assignment.getRValue();
if (lValue != null && rValue != null) {
myAlignmentProvider.addPair(lValue, rValue, false);
}
}
} else if (blockPsi instanceof GrConditionalExpression) {
if (myContext.getSettings().ALIGN_MULTILINE_TERNARY_OPERATION) {
final GrConditionalExpression conditional = (GrConditionalExpression) blockPsi;
final AlignmentProvider.Aligner exprAligner = myAlignmentProvider.createAligner(false);
exprAligner.append(conditional.getCondition());
if (!(conditional instanceof GrElvisExpression)) {
exprAligner.append(conditional.getThenBranch());
}
exprAligner.append(conditional.getElseBranch());
ASTNode question = conditional.getNode().findChildByType(GroovyTokenTypes.mQUESTION);
ASTNode colon = conditional.getNode().findChildByType(GroovyTokenTypes.mCOLON);
if (question != null && colon != null) {
AlignmentProvider.Aligner questionColonAligner = myAlignmentProvider.createAligner(false);
questionColonAligner.append(question.getPsi());
questionColonAligner.append(colon.getPsi());
}
}
}
// For other cases
final ArrayList<Block> subBlocks = new ArrayList<>();
for (ASTNode childNode : visibleChildren(myNode)) {
subBlocks.add(new GroovyBlock(childNode, getIndent(childNode), getChildWrap(childNode), myContext));
}
return subBlocks;
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock in project intellij-community by JetBrains.
the class GeeseUtil method getClosureRBraceAtTheEnd.
@Nullable
public static ASTNode getClosureRBraceAtTheEnd(ASTNode node) {
IElementType elementType = node.getElementType();
if (elementType == GroovyElementTypes.CLOSABLE_BLOCK) {
PsiElement rBrace = ((GrClosableBlock) node.getPsi()).getRBrace();
return rBrace != null ? rBrace.getNode() : null;
}
ASTNode lastChild = node.getLastChildNode();
while (lastChild != null && PsiImplUtil.isWhiteSpaceOrNls(lastChild)) {
lastChild = lastChild.getTreePrev();
}
if (lastChild == null)
return null;
return getClosureRBraceAtTheEnd(lastChild);
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock in project intellij-community by JetBrains.
the class GrIntroduceClosureParameterProcessor method processExternalUsage.
private static void processExternalUsage(UsageInfo usage, GrIntroduceParameterSettings settings, PsiElement expression) {
final PsiElement element = usage.getElement();
GrCall callExpression = GroovyRefactoringUtil.getCallExpressionByMethodReference(element);
if (callExpression == null) {
final PsiElement parent = element.getParent();
if (parent instanceof GrReferenceExpression && element == ((GrReferenceExpression) parent).getQualifier() && "call".equals(((GrReferenceExpression) parent).getReferenceName())) {
callExpression = GroovyRefactoringUtil.getCallExpressionByMethodReference(parent);
}
}
if (callExpression == null)
return;
//check for x.getFoo()(args)
if (callExpression instanceof GrMethodCall) {
final GrExpression invoked = ((GrMethodCall) callExpression).getInvokedExpression();
if (invoked instanceof GrReferenceExpression) {
final GroovyResolveResult result = ((GrReferenceExpression) invoked).advancedResolve();
final PsiElement resolved = result.getElement();
if (resolved instanceof GrAccessorMethod && !result.isInvokedOnProperty()) {
PsiElement actualCallExpression = callExpression.getParent();
if (actualCallExpression instanceof GrCall) {
callExpression = (GrCall) actualCallExpression;
}
}
}
}
GrArgumentList argList = callExpression.getArgumentList();
LOG.assertTrue(argList != null);
GrExpression[] oldArgs = argList.getExpressionArguments();
GrClosableBlock toReplaceIn = (GrClosableBlock) settings.getToReplaceIn();
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(settings.getProject());
final GrExpression anchor = getAnchorForArgument(oldArgs, toReplaceIn.isVarArgs(), toReplaceIn.getParameterList());
GrClosureSignature signature = GrClosureSignatureUtil.createSignature(callExpression);
if (signature == null)
signature = GrClosureSignatureUtil.createSignature(toReplaceIn);
final GrClosureSignatureUtil.ArgInfo<PsiElement>[] actualArgs = GrClosureSignatureUtil.mapParametersToArguments(signature, callExpression.getNamedArguments(), callExpression.getExpressionArguments(), callExpression.getClosureArguments(), callExpression, true, true);
if (PsiTreeUtil.isAncestor(toReplaceIn, callExpression, false)) {
argList.addAfter(factory.createExpressionFromText(settings.getName()), anchor);
} else {
PsiElement initializer = ExpressionConverter.getExpression(expression, GroovyLanguage.INSTANCE, settings.getProject());
LOG.assertTrue(initializer instanceof GrExpression);
GrExpression newArg = GroovyIntroduceParameterUtil.addClosureToCall(initializer, argList);
if (newArg == null) {
final PsiElement dummy = argList.addAfter(factory.createExpressionFromText("1"), anchor);
newArg = ((GrExpression) dummy).replaceWithExpression((GrExpression) initializer, true);
}
new OldReferencesResolver(callExpression, newArg, toReplaceIn, settings.replaceFieldsWithGetters(), initializer, signature, actualArgs, toReplaceIn.getParameters()).resolve();
ChangeContextUtil.clearContextInfo(initializer);
//newarg can be replaced by OldReferenceResolve
if (newArg.isValid()) {
JavaCodeStyleManager.getInstance(newArg.getProject()).shortenClassReferences(newArg);
CodeStyleManager.getInstance(settings.getProject()).reformat(newArg);
}
}
if (actualArgs == null) {
GroovyIntroduceParameterUtil.removeParamsFromUnresolvedCall(callExpression, toReplaceIn.getParameters(), settings.parametersToRemove());
} else {
GroovyIntroduceParameterUtil.removeParametersFromCall(actualArgs, settings.parametersToRemove());
}
if (argList.getAllArguments().length == 0 && PsiImplUtil.hasClosureArguments(callExpression)) {
final GrArgumentList emptyArgList = ((GrMethodCallExpression) factory.createExpressionFromText("foo{}")).getArgumentList();
argList.replace(emptyArgList);
}
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock in project intellij-community by JetBrains.
the class GroovyInlineLocalProcessor method collectRefs.
private static void collectRefs(final GrVariable variable, Instruction[] flow, final List<BitSet> writes, final int writeInstructionNumber, final ArrayList<UsageInfo> toInline) {
for (Instruction instruction : flow) {
final PsiElement element = instruction.getElement();
if (instruction instanceof ReadWriteVariableInstruction) {
if (((ReadWriteVariableInstruction) instruction).isWrite())
continue;
if (element instanceof GrVariable && element != variable)
continue;
if (!(element instanceof GrReferenceExpression))
continue;
final GrReferenceExpression ref = (GrReferenceExpression) element;
if (ref.isQualified() || ref.resolve() != variable)
continue;
final BitSet prev = writes.get(instruction.num());
if (writeInstructionNumber >= 0 && prev.cardinality() == 1 && prev.get(writeInstructionNumber)) {
toInline.add(new UsageInfo(ref));
} else if (writeInstructionNumber == -1 && prev.cardinality() == 0) {
toInline.add(new ClosureUsage(ref));
}
} else if (element instanceof GrClosableBlock) {
final BitSet prev = writes.get(instruction.num());
if (writeInstructionNumber >= 0 && prev.cardinality() == 1 && prev.get(writeInstructionNumber) || writeInstructionNumber == -1 && prev.cardinality() == 0) {
final Instruction[] closureFlow = ((GrClosableBlock) element).getControlFlow();
collectRefs(variable, closureFlow, ControlFlowUtils.inferWriteAccessMap(closureFlow, variable), -1, toInline);
}
} else if (element instanceof GrAnonymousClassDefinition) {
final BitSet prev = writes.get(instruction.num());
if (writeInstructionNumber >= 0 && prev.cardinality() == 1 && prev.get(writeInstructionNumber) || writeInstructionNumber == -1 && prev.cardinality() == 0) {
((GrAnonymousClassDefinition) element).acceptChildren(new GroovyRecursiveElementVisitor() {
@Override
public void visitField(@NotNull GrField field) {
GrExpression initializer = field.getInitializerGroovy();
if (initializer != null) {
Instruction[] flow = new ControlFlowBuilder(field.getProject()).buildControlFlow(initializer);
collectRefs(variable, flow, ControlFlowUtils.inferWriteAccessMap(flow, variable), -1, toInline);
}
}
@Override
public void visitMethod(@NotNull GrMethod method) {
GrOpenBlock block = method.getBlock();
if (block != null) {
Instruction[] flow = block.getControlFlow();
collectRefs(variable, flow, ControlFlowUtils.inferWriteAccessMap(flow, variable), -1, toInline);
}
}
@Override
public void visitClassInitializer(@NotNull GrClassInitializer initializer) {
GrOpenBlock block = initializer.getBlock();
Instruction[] flow = block.getControlFlow();
collectRefs(variable, flow, ControlFlowUtils.inferWriteAccessMap(flow, variable), -1, toInline);
}
});
}
}
}
}
Aggregations