private List<Block> generateForMultiLineGStringBegin() { final ArrayList<Block> subBlocks = new ArrayList<Block>(); final int start = myNode.getTextRange().getStartOffset(); final int end = myNode.getTextRange().getEndOffset(); subBlocks.add( new GroovyBlock( myNode, myAlignment, Indent.getNoneIndent(), myWrap, mySettings, myGroovySettings, myInnerAlignments) { @NotNull public TextRange getTextRange() { return new TextRange(start, start + 3); } }); subBlocks.add( new GroovyBlock( myNode, myAlignment, Indent.getAbsoluteNoneIndent(), myWrap, mySettings, myGroovySettings, myInnerAlignments) { @NotNull public TextRange getTextRange() { return new TextRange(start + 3, end); } }); return subBlocks; }
@NotNull public Block create( @NotNull final List<ASTNode> subNodes, final Wrap wrap, @Nullable final Alignment alignment) { final ArrayList<Block> subBlocks = new ArrayList<Block>(); final ASTNode firstNode = subNodes.get(0); if (firstNode.getElementType() == JavaTokenType.DOT) { AlignmentStrategy strategy = AlignmentStrategy.getNullStrategy(); Block block = createJavaBlock( firstNode, mySettings, myJavaSettings, Indent.getNoneIndent(), null, strategy); subBlocks.add(block); subNodes.remove(0); if (!subNodes.isEmpty()) { subBlocks.add(create(subNodes, wrap, null)); } return new SyntheticCodeBlock( subBlocks, alignment, mySettings, myJavaSettings, Indent.getContinuationIndent(myIndentSettings.USE_RELATIVE_INDENTS), wrap); } return new SyntheticCodeBlock( createJavaBlocks(subNodes), alignment, mySettings, myJavaSettings, Indent.getContinuationWithoutFirstIndent(myIndentSettings.USE_RELATIVE_INDENTS), null); }
private void replaceDocComment( @Nullable String newCommentText, @NotNull final PsiDocCommentOwner psiDocCommentOwner) { final PsiDocComment oldComment = psiDocCommentOwner.getDocComment(); if (newCommentText != null) newCommentText = stripSpaces(newCommentText); if (newCommentText == null || oldComment == null || newCommentText.equals(oldComment.getText())) { return; } try { PsiComment newComment = JavaPsiFacade.getInstance(myProject) .getElementFactory() .createCommentFromText(newCommentText, null); final ASTNode oldNode = oldComment.getNode(); final ASTNode newNode = newComment.getNode(); assert oldNode != null && newNode != null; final ASTNode parent = oldNode.getTreeParent(); parent.replaceChild( oldNode, newNode); // important to replace with tree operation to avoid resolve and repository // update } catch (IncorrectOperationException e) { LOG.error(e); } }
private static void replaceByTagContent(Project project, XmlTag tagToReplace, XmlTag tagToInline) throws AndroidRefactoringErrorException { final ASTNode node = tagToInline.getNode(); if (node == null) { throw new AndroidRefactoringErrorException(); } final ASTNode startTagEnd = XmlChildRole.START_TAG_END_FINDER.findChild(node); final ASTNode closingTagStart = XmlChildRole.CLOSING_TAG_START_FINDER.findChild(node); if (startTagEnd == null || closingTagStart == null) { throw new AndroidRefactoringErrorException(); } final int contentStart = startTagEnd.getTextRange().getEndOffset(); final int contentEnd = closingTagStart.getTextRange().getStartOffset(); if (contentStart < 0 || contentEnd < 0 || contentStart >= contentEnd) { throw new AndroidRefactoringErrorException(); } final PsiFile file = tagToInline.getContainingFile(); if (file == null) { throw new AndroidRefactoringErrorException(); } final String textToInline = file.getText().substring(contentStart, contentEnd).trim(); final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); final Document document = documentManager.getDocument(tagToReplace.getContainingFile()); if (document == null) { throw new AndroidRefactoringErrorException(); } final TextRange range = tagToReplace.getTextRange(); document.replaceString(range.getStartOffset(), range.getEndOffset(), textToInline); documentManager.commitDocument(document); }
@Nullable public PsiElement getPsiOperator() { ASTNode node = getNode(); final ASTNode child = node.findChildByType(PyElementTypes.BINARY_OPS); if (child != null) return child.getPsi(); return null; }
private static void addNewLineToTag(CompositeElement tag, Project project) { LOG.assertTrue(tag != null && tag.getElementType() == DOC_TAG); ASTNode current = tag.getLastChildNode(); while (current != null && current.getElementType() == DOC_COMMENT_DATA && isWhitespaceCommentData(current)) { current = current.getTreePrev(); } if (current != null && current.getElementType() == DOC_COMMENT_LEADING_ASTERISKS) return; final CharTable treeCharTab = SharedImplUtil.findCharTableByTree(tag); final ASTNode newLine = Factory.createSingleLeafElement( DOC_COMMENT_DATA, "\n", 0, 1, treeCharTab, SharedImplUtil.getManagerByTree(tag)); tag.addChild(newLine, null); ASTNode leadingWhitespaceAnchor = null; if (JavaCodeStyleSettingsFacade.getInstance(project).isJavaDocLeadingAsterisksEnabled()) { final TreeElement leadingAsterisk = Factory.createSingleLeafElement( DOC_COMMENT_LEADING_ASTERISKS, "*", 0, 1, treeCharTab, SharedImplUtil.getManagerByTree(tag)); leadingWhitespaceAnchor = tag.addInternal(leadingAsterisk, leadingAsterisk, null, Boolean.TRUE); } final TreeElement commentData = Factory.createSingleLeafElement( DOC_COMMENT_DATA, " ", 0, 1, treeCharTab, SharedImplUtil.getManagerByTree(tag)); tag.addInternal(commentData, commentData, leadingWhitespaceAnchor, Boolean.TRUE); }
@Override public void visitPyStringLiteralExpression(PyStringLiteralExpression node) { final Pair<PsiElement, TextRange> data = node.getUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE); if (data != null) { final PsiElement parent = data.getFirst(); final String text = parent.getText(); final Pair<String, String> detectedQuotes = PythonStringUtil.getQuotes(text); final Pair<String, String> quotes = detectedQuotes != null ? detectedQuotes : Pair.create("'", "'"); final TextRange range = data.getSecond(); final String substring = range.substring(text); myResult.append(quotes.getFirst() + substring + quotes.getSecond()); } else { ASTNode child = node.getNode().getFirstChildNode(); while (child != null) { String text = child.getText(); if (child.getElementType() == TokenType.WHITE_SPACE) { if (text.contains("\n")) { if (!text.contains("\\")) { myResult.append("\\"); } myResult.append(text); } } else { myResult.append(text); } child = child.getTreeNext(); } } }
@NotNull public PsiReference[] getReferences() { ProgressManager.checkCanceled(); final ASTNode startTagName = XmlChildRole.START_TAG_NAME_FINDER.findChild(this); if (startTagName == null) return PsiReference.EMPTY_ARRAY; final ASTNode endTagName = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(this); List<PsiReference> refs = new ArrayList<PsiReference>(); String prefix = getNamespacePrefix(); TagNameReference startTagRef = TagNameReference.createTagNameReference(this, startTagName, true); refs.add(startTagRef); if (prefix.length() > 0) { refs.add(createPrefixReference(startTagName, prefix, startTagRef)); } if (endTagName != null) { TagNameReference endTagRef = TagNameReference.createTagNameReference(this, endTagName, false); refs.add(endTagRef); prefix = XmlUtil.findPrefixByQualifiedName(endTagName.getText()); if (StringUtil.isNotEmpty(prefix)) { refs.add(createPrefixReference(endTagName, prefix, endTagRef)); } } // ArrayList.addAll() makes a clone of the collection //noinspection ManualArrayToCollectionCopy for (PsiReference ref : ReferenceProvidersRegistry.getReferencesFromProviders(this, XmlTag.class)) { refs.add(ref); } return ContainerUtil.toArray(refs, new PsiReference[refs.size()]); }
@NotNull public GrAnnotation addAnnotation(@NotNull @NonNls String qualifiedName) { final PsiClass psiClass = JavaPsiFacade.getInstance(getProject()).findClass(qualifiedName, getResolveScope()); final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(getProject()); GrAnnotation annotation; if (psiClass != null && psiClass.isAnnotationType()) { annotation = (GrAnnotation) addAfter(factory.createModifierFromText("@xxx"), null); annotation.getClassReference().bindToElement(psiClass); } else { annotation = (GrAnnotation) addAfter(factory.createModifierFromText("@" + qualifiedName), null); } final PsiElement parent = getParent(); if (!(parent instanceof GrParameter)) { final ASTNode node = annotation.getNode(); final ASTNode treeNext = node.getTreeNext(); if (treeNext != null) { getNode().addLeaf(TokenType.WHITE_SPACE, "\n", treeNext); } else { parent.getNode().addLeaf(TokenType.WHITE_SPACE, "\n", getNode().getTreeNext()); } } return annotation; }
void addNestedChildrenSuffix( List<Block> list, @Nullable AlignmentProvider.Aligner aligner, boolean topLevel, List<ASTNode> children, int limit) { for (int i = 1; i < limit; i++) { ASTNode childNode = children.get(i); if (canBeCorrectBlock(childNode)) { IElementType type = childNode.getElementType(); Indent indent = topLevel || NESTED.contains(type) || type == mIDENT || TokenSets.DOTS.contains(type) ? Indent.getContinuationWithoutFirstIndent() : Indent.getNoneIndent(); if (aligner != null && TokenSets.DOTS.contains(type)) { aligner.append(childNode.getPsi()); } list.add( new GroovyBlock( childNode, indent, myWrap, mySettings, myGroovySettings, myAlignmentProvider)); } } }
/** * Adds all children of specified element to given list * * @param elem * @param list * @param indent * @param alignment */ private void addBinaryChildrenRecursively( PsiElement elem, List<Block> list, Indent indent, Alignment alignment) { if (elem == null) return; // For binary expressions if ((elem instanceof GrBinaryExpression)) { GrBinaryExpression myExpr = ((GrBinaryExpression) elem); if (myExpr.getLeftOperand() instanceof GrBinaryExpression) { addBinaryChildrenRecursively( myExpr.getLeftOperand(), list, Indent.getContinuationWithoutFirstIndent(), alignment); } PsiElement op = ((GrBinaryExpression) elem).getOperationToken(); for (ASTNode childNode : visibleChildren(elem.getNode())) { PsiElement psi = childNode.getPsi(); if (!(psi instanceof GrBinaryExpression)) { Alignment alignmentToUse = op == psi ? myInnerAlignments.get(op) : alignment; list.add( new GroovyBlock( childNode, alignmentToUse, indent, myWrap, mySettings, myGroovySettings, myInnerAlignments)); } } if (myExpr.getRightOperand() instanceof GrBinaryExpression) { addBinaryChildrenRecursively( myExpr.getRightOperand(), list, Indent.getContinuationWithoutFirstIndent(), alignment); } } }
@NotNull public IElementType getOperationTokenType() { PsiElement opElement = getOperationToken(); ASTNode node = opElement.getNode(); assert node != null; return node.getElementType(); }
private static void reportInconsistentLength( PsiFile file, CharSequence newFileText, ASTNode node, int start, int end) { String message = "Index out of bounds: type=" + node.getElementType() + "; file=" + file + "; file.class=" + file.getClass() + "; start=" + start + "; end=" + end + "; length=" + node.getTextLength(); String newTextBefore = newFileText.subSequence(0, start).toString(); String oldTextBefore = file.getText().subSequence(0, start).toString(); if (oldTextBefore.equals(newTextBefore)) { message += "; oldTextBefore==newTextBefore"; } LOG.error( message, new Attachment(file.getName() + "_oldNodeText.txt", node.getText()), new Attachment(file.getName() + "_oldFileText.txt", file.getText()), new Attachment(file.getName() + "_newFileText.txt", newFileText.toString())); }
/** * Adds all children of specified element to given list * * @param elem * @param list * @param indent * @param aligner */ private void addBinaryChildrenRecursively( PsiElement elem, List<Block> list, Indent indent, @Nullable AlignmentProvider.Aligner aligner) { if (elem == null) return; // For binary expressions if ((elem instanceof GrBinaryExpression)) { GrBinaryExpression myExpr = ((GrBinaryExpression) elem); if (myExpr.getLeftOperand() instanceof GrBinaryExpression) { addBinaryChildrenRecursively( myExpr.getLeftOperand(), list, Indent.getContinuationWithoutFirstIndent(), aligner); } PsiElement op = ((GrBinaryExpression) elem).getOperationToken(); for (ASTNode childNode : visibleChildren(elem.getNode())) { PsiElement psi = childNode.getPsi(); if (!(psi instanceof GrBinaryExpression)) { if (op != psi && aligner != null) { aligner.append(psi); } list.add( new GroovyBlock( childNode, indent, myWrap, mySettings, myGroovySettings, myAlignmentProvider)); } } if (myExpr.getRightOperand() instanceof GrBinaryExpression) { addBinaryChildrenRecursively( myExpr.getRightOperand(), list, Indent.getContinuationWithoutFirstIndent(), aligner); } } }
@NotNull public static DiffLog mergeTrees( @NotNull final PsiFileImpl fileImpl, @NotNull final ASTNode oldRoot, @NotNull final ASTNode newRoot, @NotNull ProgressIndicator indicator) { if (newRoot instanceof FileElement) { ((FileElement) newRoot).setCharTable(fileImpl.getTreeElement().getCharTable()); } try { newRoot.putUserData(TREE_TO_BE_REPARSED, oldRoot); if (isReplaceWholeNode(fileImpl, newRoot)) { DiffLog treeChangeEvent = replaceElementWithEvents((CompositeElement) oldRoot, (CompositeElement) newRoot); fileImpl.putUserData(TREE_DEPTH_LIMIT_EXCEEDED, Boolean.TRUE); return treeChangeEvent; } newRoot .getFirstChildNode(); // maybe reparsed in PsiBuilderImpl and have thrown exception here } catch (ReparsedSuccessfullyException e) { // reparsed in PsiBuilderImpl return e.getDiffLog(); } finally { newRoot.putUserData(TREE_TO_BE_REPARSED, null); } final ASTShallowComparator comparator = new ASTShallowComparator(indicator); final ASTStructure treeStructure = createInterruptibleASTStructure(newRoot, indicator); DiffLog diffLog = new DiffLog(); diffTrees(oldRoot, diffLog, comparator, treeStructure, indicator); return diffLog; }
private void calculateAlignments(List<ASTNode> children, boolean classLevel) { List<GrStatement> currentGroup = null; boolean spock = true; for (ASTNode child : children) { PsiElement psi = child.getPsi(); if (psi instanceof GrLabeledStatement) { alignGroup(currentGroup, spock, classLevel); currentGroup = ContainerUtil.newArrayList((GrStatement) psi); spock = true; } else if (currentGroup != null && spock && isTablePart(psi)) { currentGroup.add((GrStatement) psi); } else if (psi instanceof GrVariableDeclaration) { GrVariable[] variables = ((GrVariableDeclaration) psi).getVariables(); if (variables.length > 0) { if (!classLevel || currentGroup == null || fieldGroupEnded(psi) || spock) { alignGroup(currentGroup, spock, classLevel); currentGroup = ContainerUtil.newArrayList(); spock = false; } currentGroup.add((GrStatement) psi); } } else { if (psi instanceof PsiComment) { PsiElement prev = psi.getPrevSibling(); if (prev != null && prev.getNode().getElementType() != mNLS || classLevel && !fieldGroupEnded(psi)) { continue; } } alignGroup(currentGroup, spock, classLevel); currentGroup = null; } } }
private void checkAccessors( @NotNull JetProperty property, @NotNull PropertyDescriptor propertyDescriptor) { for (JetPropertyAccessor accessor : property.getAccessors()) { PropertyAccessorDescriptor propertyAccessorDescriptor = accessor.isGetter() ? propertyDescriptor.getGetter() : propertyDescriptor.getSetter(); assert propertyAccessorDescriptor != null : "No property accessor descriptor for " + property.getText(); modifiersChecker.checkModifiersForDeclaration(accessor, propertyAccessorDescriptor); modifiersChecker.reportIllegalModalityModifiers(accessor); } JetPropertyAccessor getter = property.getGetter(); PropertyGetterDescriptor getterDescriptor = propertyDescriptor.getGetter(); JetModifierList getterModifierList = getter != null ? getter.getModifierList() : null; if (getterModifierList != null && getterDescriptor != null) { Map<JetModifierKeywordToken, ASTNode> nodes = ModifiersChecker.getNodesCorrespondingToModifiers( getterModifierList, Sets.newHashSet( JetTokens.PUBLIC_KEYWORD, JetTokens.PROTECTED_KEYWORD, JetTokens.PRIVATE_KEYWORD, JetTokens.INTERNAL_KEYWORD)); if (getterDescriptor.getVisibility() != propertyDescriptor.getVisibility()) { for (ASTNode node : nodes.values()) { trace.report(Errors.GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY.on(node.getPsi())); } } else { for (ASTNode node : nodes.values()) { trace.report(Errors.REDUNDANT_MODIFIER_IN_GETTER.on(node.getPsi())); } } } }
@Override protected PsiElement getInternalNavigationElement() { List<INode> _findNodesForFeature = NodeModelUtils.findNodesForFeature(this.owner, this.feature); final Function1<INode, Iterable<ILeafNode>> _function = new Function1<INode, Iterable<ILeafNode>>() { @Override public Iterable<ILeafNode> apply(final INode it) { return it.getLeafNodes(); } }; List<Iterable<ILeafNode>> _map = ListExtensions.<INode, Iterable<ILeafNode>>map(_findNodesForFeature, _function); Iterable<ILeafNode> _flatten = Iterables.<ILeafNode>concat(_map); final Function1<ILeafNode, Boolean> _function_1 = new Function1<ILeafNode, Boolean>() { @Override public Boolean apply(final ILeafNode it) { boolean _isHidden = it.isHidden(); return Boolean.valueOf((!_isHidden)); } }; Iterable<ILeafNode> _filter = IterableExtensions.<ILeafNode>filter(_flatten, _function_1); ILeafNode _head = IterableExtensions.<ILeafNode>head(_filter); ASTNode _aSTNode = this.xtextFile.getASTNode(_head); return _aSTNode.getPsi(); }
private void changeParameter( int parameterIndex, JetParameter parameter, JetParameterInfo parameterInfo) { ASTNode valOrVarAstNode = parameter.getValOrVarNode(); PsiElement valOrVarNode = valOrVarAstNode != null ? valOrVarAstNode.getPsi() : null; JetValVar valOrVar = parameterInfo.getValOrVar(); JetPsiFactory psiFactory = JetPsiFactory(getProject()); if (valOrVarNode != null) { if (valOrVar == JetValVar.None) { valOrVarNode.delete(); } else { valOrVarNode.replace(psiFactory.createValOrVarNode(valOrVar.toString()).getPsi()); } } else if (valOrVar != JetValVar.None) { PsiElement firstChild = parameter.getFirstChild(); parameter.addBefore(psiFactory.createValOrVarNode(valOrVar.toString()).getPsi(), firstChild); parameter.addBefore(psiFactory.createWhiteSpace(), firstChild); } if (parameterInfo.getIsTypeChanged() && parameter.getTypeReference() != null) { String renderedType = parameterInfo.renderType(parameterIndex, this); parameter.setTypeReference(psiFactory.createType(renderedType)); } PsiElement identifier = parameter.getNameIdentifier(); if (identifier != null) { //noinspection unchecked String newName = parameterInfo.getInheritedName((JetFunctionDefinitionUsage<PsiElement>) this); identifier.replace(psiFactory.createIdentifier(newName)); } }
private void checkClass( BodiesResolveContext c, JetClass aClass, ClassDescriptorWithResolutionScopes classDescriptor) { checkOpenMembers(classDescriptor); checkTypeParameters(aClass); if (aClass.isInterface()) { ASTNode traitKeyword = aClass.getNode().findChildByType(JetTokens.TRAIT_KEYWORD); if (traitKeyword != null) { trace.report(Errors.DEPRECATED_TRAIT_KEYWORD.on(traitKeyword.getPsi())); } checkTraitModifiers(aClass); checkConstructorInTrait(aClass); } else if (aClass.isAnnotation()) { checkAnnotationClassWithBody(aClass); checkValOnAnnotationParameter(aClass); } else if (aClass.isEnum()) { checkEnumModifiers(aClass); if (aClass.isLocal()) { trace.report(LOCAL_ENUM_NOT_ALLOWED.on(aClass, classDescriptor)); } } else if (aClass.hasModifier(JetTokens.SEALED_KEYWORD)) { checkSealedModifiers(aClass); } else if (aClass instanceof JetEnumEntry) { checkEnumEntry((JetEnumEntry) aClass, classDescriptor); } }
public static void deleteStatementTail(PsiElement container, @NotNull PsiElement statement) { PsiElement next = statement.getNextSibling(); while (next != null) { final ASTNode node = next.getNode(); final IElementType type = node.getElementType(); if (type == mSEMI) { final PsiElement nnext = next.getNextSibling(); container.deleteChildRange(next, next); next = nnext; } else if (type == mNLS || type == TokenType.WHITE_SPACE && next.getText().contains("\n")) { final String text = next.getText(); final int first = text.indexOf("\n"); final int second = text.indexOf("\n", first + 1); if (second < 0) { container.deleteChildRange(next, next); return; } final String substring = text.substring(second); container .getNode() .replaceChild( node, createSingleLeafElement( type, substring, 0, substring.length(), null, container.getManager())); return; } else { break; } } }
@Override public int getTextLength() { final ASTNode tree = derefTreeElement(); if (tree != null) return tree.getTextLength(); return getViewProvider().getContents().length(); }
/** * Indent for common block * * @param psiBlock * @param child * @return */ private static Indent indentForBlock(PsiElement psiBlock, ASTNode child) { // Common case if (mLCURLY.equals(child.getElementType()) || mRCURLY.equals(child.getElementType())) { return Indent.getNoneIndent(); } return Indent.getNormalIndent(); }
public static void removeNewLineAfter(@NotNull GrStatement statement) { ASTNode parentNode = statement.getParent().getNode(); ASTNode next = statement.getNode().getTreeNext(); if (parentNode != null && next != null && mNLS == next.getElementType()) { parentNode.removeChild(next); } }
public static String getName(X816SymbolAffectation element) { ASTNode symbol = element.getNode().findChildByType(X816Types.SYMBOL); if (symbol != null) { return symbol.getText(); } return null; }
@Nullable public static ASTNode getPreviousNonWhitespaceSibling(@Nullable ASTNode node) { ASTNode prevNode = node == null ? null : node.getTreePrev(); while (prevNode != null && isWhitespaceOrEmpty(prevNode)) { prevNode = prevNode.getTreePrev(); } return prevNode; }
@Nullable public static ASTNode getNextNonWhitespaceSibling(@Nullable ASTNode node) { ASTNode next = node == null ? null : node.getTreeNext(); while (next != null && isWhitespaceOrEmpty(next)) { next = next.getTreeNext(); } return next; }
public static PsiElement getNameIdentifier(X816SymbolAffectation element) { ASTNode keyNode = element.getNode().findChildByType(X816Types.SYMBOL); if (keyNode != null) { return keyNode.getPsi(); } else { return null; } }
public static PsiElement getNameIdentifier(X816LabelDef element) { ASTNode keyNode = element.getNode().findChildByType(X816Types.LABEL); if (keyNode != null) { return keyNode.getPsi(); } else { return null; } }
@Nullable public String getActualStepPrefix() { ASTNode keyword = getKeyword(); if (keyword == null) { // that's weird! return null; } return keyword.getText(); }