use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock in project intellij-community by JetBrains.
the class GroovyFoldingBuilder method collapseBlock.
private static void collapseBlock(List<FoldingDescriptor> descriptors, PsiElement psi) {
if (psi instanceof GrCodeBlock) {
final int lineFeedCount = StringUtil.countChars(psi.getText(), '\n');
if (lineFeedCount <= 2) {
final PsiElement lbrace = ((GrCodeBlock) psi).getLBrace();
final PsiElement rbrace = ((GrCodeBlock) psi).getRBrace();
if (lbrace != null && rbrace != null) {
final PsiElement next = lbrace.getNextSibling();
final PsiElement prev = rbrace.getPrevSibling();
if (next != null && PsiImplUtil.isWhiteSpaceOrNls(next) && prev != null && PsiImplUtil.isWhiteSpaceOrNls(prev)) {
final FoldingGroup group = FoldingGroup.newGroup("block_group");
descriptors.add(new NamedFoldingDescriptor(psi, lbrace.getTextRange().getStartOffset(), next.getTextRange().getEndOffset(), group, "{"));
descriptors.add(new NamedFoldingDescriptor(psi, prev.getTextRange().getStartOffset(), rbrace.getTextRange().getEndOffset(), group, "}"));
return;
}
}
}
}
descriptors.add(new FoldingDescriptor(psi, psi.getTextRange()));
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock in project intellij-community by JetBrains.
the class PsiImplUtil method replaceExpression.
@Nullable
public static GrExpression replaceExpression(GrExpression oldExpr, GrExpression newExpr, boolean removeUnnecessaryParentheses) {
PsiElement oldParent = oldExpr.getParent();
if (oldParent == null)
throw new PsiInvalidElementAccessException(oldExpr);
if (!(oldExpr instanceof GrApplicationStatement)) {
newExpr = ApplicationStatementUtil.convertToMethodCallExpression(newExpr);
}
// Remove unnecessary parentheses
if (removeUnnecessaryParentheses && oldParent instanceof GrParenthesizedExpression && !(oldParent.getParent() instanceof GrArgumentLabel)) {
return ((GrExpression) oldParent).replaceWithExpression(newExpr, true);
}
//regexes cannot be after identifier , try to replace it with simple string
if (getRegexAtTheBeginning(newExpr) != null && isAfterIdentifier(oldExpr)) {
final PsiElement copy = newExpr.copy();
final GrLiteral regex = getRegexAtTheBeginning(copy);
LOG.assertTrue(regex != null);
final GrLiteral stringLiteral = GrStringUtil.createStringFromRegex(regex);
if (regex == copy) {
return oldExpr.replaceWithExpression(stringLiteral, removeUnnecessaryParentheses);
} else {
regex.replace(stringLiteral);
return oldExpr.replaceWithExpression((GrExpression) copy, removeUnnecessaryParentheses);
}
}
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(oldExpr.getProject());
if (oldParent instanceof GrStringInjection) {
if (newExpr instanceof GrString || newExpr instanceof GrLiteral && ((GrLiteral) newExpr).getValue() instanceof String) {
return GrStringUtil.replaceStringInjectionByLiteral((GrStringInjection) oldParent, (GrLiteral) newExpr);
} else {
GrClosableBlock block = factory.createClosureFromText("{foo}");
oldParent.getNode().replaceChild(oldExpr.getNode(), block.getNode());
GrStatement[] statements = block.getStatements();
return ((GrExpression) statements[0]).replaceWithExpression(newExpr, removeUnnecessaryParentheses);
}
}
if (PsiTreeUtil.getParentOfType(oldExpr, GrStringInjection.class, false, GrCodeBlock.class) != null) {
final GrStringInjection stringInjection = PsiTreeUtil.getParentOfType(oldExpr, GrStringInjection.class);
GrStringUtil.wrapInjection(stringInjection);
assert stringInjection != null;
final PsiElement replaced = oldExpr.replaceWithExpression(newExpr, removeUnnecessaryParentheses);
return (GrExpression) replaced;
}
//check priorities
if (oldParent instanceof GrExpression && !(oldParent instanceof GrParenthesizedExpression)) {
GrExpression addedParenth = checkPrecedence(newExpr, oldExpr) ? parenthesize(newExpr) : newExpr;
if (newExpr != addedParenth) {
return oldExpr.replaceWithExpression(addedParenth, removeUnnecessaryParentheses);
}
}
//we should add the expression in arg list
if (oldExpr instanceof GrClosableBlock && !(newExpr instanceof GrClosableBlock) && oldParent instanceof GrMethodCallExpression && ArrayUtil.contains(oldExpr, ((GrMethodCallExpression) oldParent).getClosureArguments())) {
return ((GrMethodCallExpression) oldParent).replaceClosureArgument((GrClosableBlock) oldExpr, newExpr);
}
newExpr = (GrExpression) oldExpr.replace(newExpr);
// to find target parenthesised expression.
if (newExpr instanceof GrParenthesizedExpression && isFirstChild(newExpr)) {
int parentCount = 0;
PsiElement element = oldParent;
while (element != null && !(element instanceof GrCommandArgumentList)) {
if (element instanceof GrCodeBlock || element instanceof GrParenthesizedExpression)
break;
if (element instanceof PsiFile)
break;
final PsiElement parent = element.getParent();
if (parent == null)
break;
if (!isFirstChild(element))
break;
element = parent;
parentCount++;
}
if (element instanceof GrCommandArgumentList) {
final GrCommandArgumentList commandArgList = (GrCommandArgumentList) element;
final PsiElement parent = commandArgList.getParent();
LOG.assertTrue(parent instanceof GrApplicationStatement);
final GrMethodCall methodCall = factory.createMethodCallByAppCall((GrApplicationStatement) parent);
final GrMethodCall newCall = (GrMethodCall) parent.replace(methodCall);
PsiElement result = newCall.getArgumentList().getAllArguments()[0];
for (int i = 0; i < parentCount; i++) {
result = PsiUtil.skipWhitespacesAndComments(result.getFirstChild(), true);
}
LOG.assertTrue(result instanceof GrParenthesizedExpression);
return (GrExpression) result;
}
}
return newExpr;
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock in project intellij-community by JetBrains.
the class GroovyPropertyUtils method generateSetterPrototype.
public static GrMethod generateSetterPrototype(PsiField field) {
Project project = field.getProject();
JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
String name = field.getName();
boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
VariableKind kind = codeStyleManager.getVariableKind(field);
String propertyName = codeStyleManager.variableNameToPropertyName(name, kind);
String setName = getSetterName(field.getName());
final PsiClass containingClass = field.getContainingClass();
try {
GrMethod setMethod = factory.createMethod(setName, PsiType.VOID);
String parameterName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);
final PsiType type = field instanceof GrField ? ((GrField) field).getDeclaredType() : field.getType();
GrParameter param = factory.createParameter(parameterName, type);
annotateWithNullableStuff(field, param);
setMethod.getParameterList().add(param);
PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic);
@NonNls StringBuilder builder = new StringBuilder();
if (name.equals(parameterName)) {
if (!isStatic) {
builder.append("this.");
} else {
String className = containingClass.getName();
if (className != null) {
builder.append(className);
builder.append(".");
}
}
}
builder.append(name);
builder.append("=");
builder.append(parameterName);
builder.append("\n");
GrCodeBlock body = factory.createMethodBodyFromText(builder.toString());
setMethod.getBlock().replace(body);
return setMethod;
} catch (IncorrectOperationException e) {
LOG.error(e);
return null;
}
}
use of org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock 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.GrCodeBlock in project intellij-community by JetBrains.
the class GroovyStatementMover method allRanges.
private List<LineRange> allRanges(final GroovyPsiElement scope, final boolean stmtLevel, final boolean topLevel) {
final ArrayList<LineRange> result = new ArrayList<>();
scope.accept(new PsiRecursiveElementVisitor() {
int lastStart = -1;
private void addRange(int endLine) {
if (lastStart >= 0) {
result.add(new LineRange(lastStart, endLine));
}
lastStart = endLine;
}
@Override
public void visitElement(PsiElement element) {
if (stmtLevel && element instanceof GrCodeBlock) {
final PsiElement lBrace = ((GrCodeBlock) element).getLBrace();
if (nlsAfter(lBrace)) {
assert lBrace != null;
addRange(new LineRange(lBrace).endLine);
}
addChildRanges(((GrCodeBlock) element).getStatements());
final PsiElement rBrace = ((GrCodeBlock) element).getRBrace();
if (nlsAfter(rBrace)) {
assert rBrace != null;
final int endLine = new LineRange(rBrace).endLine;
if (lastStart >= 0) {
for (int i = lastStart + 1; i < endLine; i++) {
addRange(i);
}
}
}
} else if (stmtLevel && element instanceof GrCaseSection) {
final GrCaseLabel[] allLabels = ((GrCaseSection) element).getCaseLabels();
final GrCaseLabel label = allLabels[0];
if (nlsAfter(label)) {
addRange(new LineRange(label).endLine);
}
addChildRanges(((GrCaseSection) element).getStatements());
} else if (element instanceof GroovyFileBase) {
addChildRanges(((GroovyFileBase) element).getTopStatements());
} else if (!stmtLevel && !topLevel && element instanceof GrTypeDefinitionBody) {
addChildRanges(((GrTypeDefinitionBody) element).getMemberDeclarations());
} else {
super.visitElement(element);
}
}
private boolean shouldDigInside(GroovyPsiElement statement) {
if (stmtLevel && (statement instanceof GrMethod || statement instanceof GrTypeDefinition)) {
return false;
}
if (statement instanceof GrVariableDeclaration && !stmtLevel) {
return false;
}
return true;
}
private void addChildRanges(GroovyPsiElement[] statements) {
for (int i = 0; i < statements.length; i++) {
GroovyPsiElement statement = statements[i];
if (nlsAfter(statement)) {
final LineRange range = getLineRange(statement);
if ((i == 0 || isStatement(statements[i - 1])) && isStatement(statement)) {
for (int j = lastStart; j < range.startLine; j++) {
addRange(j + 1);
}
}
lastStart = range.startLine;
if (shouldDigInside(statement)) {
statement.accept(this);
}
addRange(range.endLine);
}
}
}
});
return result;
}
Aggregations