public void setMirror(@NotNull TreeElement element) { setMirrorCheckingType(element, null); PsiAnnotation mirror = (PsiAnnotation) SourceTreeToPsiMap.treeElementToPsi(element); ((ClsElementImpl) getParameterList()) .setMirror((TreeElement) SourceTreeToPsiMap.psiElementToTree(mirror.getParameterList())); ((ClsElementImpl) getNameReferenceElement()) .setMirror( (TreeElement) SourceTreeToPsiMap.psiElementToTree(mirror.getNameReferenceElement())); }
private void checkDuplicateAttribute(XmlTag tag, final XmlAttribute attribute) { if (skipValidation(tag)) { return; } final XmlAttribute[] attributes = tag.getAttributes(); final PsiFile containingFile = tag.getContainingFile(); final XmlExtension extension = containingFile instanceof XmlFile ? XmlExtension.getExtension(containingFile) : XmlExtension.DEFAULT_EXTENSION; for (XmlAttribute tagAttribute : attributes) { ProgressManager.checkCanceled(); if (attribute != tagAttribute && Comparing.strEqual(attribute.getName(), tagAttribute.getName())) { final String localName = attribute.getLocalName(); if (extension.canBeDuplicated(tagAttribute)) continue; // multiple import attributes are allowed in jsp directive HighlightInfo highlightInfo = HighlightInfo.createHighlightInfo( getTagProblemInfoType(tag), XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild( SourceTreeToPsiMap.psiElementToTree(attribute)), XmlErrorMessages.message("duplicate.attribute", localName)); addToResults(highlightInfo); IntentionAction intentionAction = new RemoveAttributeIntentionFix(localName, attribute); QuickFixAction.registerQuickFixAction(highlightInfo, intentionAction); } } }
@NotNull @Override public PsiCatchSection createCatchSection( @NotNull final PsiType exceptionType, @NotNull final String exceptionName, @Nullable final PsiElement context) throws IncorrectOperationException { if (!(exceptionType instanceof PsiClassType || exceptionType instanceof PsiDisjunctionType)) { throw new IncorrectOperationException("Unexpected type:" + exceptionType); } @NonNls final String text = "catch (" + exceptionType.getCanonicalText() + " " + exceptionName + ") {}"; final DummyHolder holder = DummyHolderFactory.createHolder( myManager, new JavaDummyElement(text, CATCH_SECTION, level(context)), context); final PsiElement element = SourceTreeToPsiMap.treeElementToPsi(holder.getTreeElement().getFirstChildNode()); if (!(element instanceof PsiCatchSection)) { throw new IncorrectOperationException( "Incorrect catch section '" + text + "'. Parsed element: " + element); } final Project project = myManager.getProject(); final JavaPsiImplementationHelper helper = JavaPsiImplementationHelper.getInstance(project); helper.setupCatchBlock(exceptionName, exceptionType, context, (PsiCatchSection) element); final CodeStyleManager styleManager = CodeStyleManager.getInstance(project); final PsiCatchSection catchSection = (PsiCatchSection) styleManager.reformat(element); GeneratedMarkerVisitor.markGenerated(catchSection); return catchSection; }
@Override public void setMirror(@NotNull TreeElement element) { setMirrorCheckingType(element, null); PsiTypeElement[] typeElements = getTypeParameterElements(); PsiTypeElement[] typeMirrors = ((PsiReferenceParameterList) SourceTreeToPsiMap.treeElementToPsi(element)) .getTypeParameterElements(); LOG.assertTrue(typeElements.length == typeMirrors.length); if (typeElements.length == typeMirrors.length) { for (int i = 0; i < typeElements.length; i++) { ((ClsElementImpl) typeElements[i]) .setMirror((TreeElement) SourceTreeToPsiMap.psiElementToTree(typeMirrors[i])); } } }
@Nullable private HighlightInfo reportAttributeProblem( final XmlTag tag, final String localName, final XmlAttribute attribute, final String localizedMessage) { final RemoveAttributeIntentionFix removeAttributeIntention = new RemoveAttributeIntentionFix(localName, attribute); if (!(tag instanceof HtmlTag)) { final HighlightInfoType tagProblemInfoType = HighlightInfoType.WRONG_REF; final ASTNode node = SourceTreeToPsiMap.psiElementToTree(attribute); assert node != null; final ASTNode child = XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(node); assert child != null; final HighlightInfo highlightInfo = HighlightInfo.createHighlightInfo(tagProblemInfoType, child, localizedMessage); addToResults(highlightInfo); QuickFixAction.registerQuickFixAction(highlightInfo, removeAttributeIntention); return highlightInfo; } return null; }
public ASTNode getDefaultAnchor( @NotNull PsiImportList list, @NotNull PsiImportStatementBase statement) { PsiJavaCodeReferenceElement ref = statement.getImportReference(); if (ref == null) return null; int entryIndex = findEntryIndex(statement); PsiImportStatementBase[] allStatements = list.getAllImportStatements(); int[] entries = ArrayUtil.newIntArray(allStatements.length); List<PsiImportStatementBase> statements = new ArrayList<PsiImportStatementBase>(); for (int i = 0; i < allStatements.length; i++) { PsiImportStatementBase statement1 = allStatements[i]; int entryIndex1 = findEntryIndex(statement1); entries[i] = entryIndex1; if (entryIndex1 == entryIndex) { statements.add(statement1); } } if (statements.isEmpty()) { int index; for (index = entries.length - 1; index >= 0; index--) { if (entries[index] < entryIndex) break; } index++; return index < entries.length ? SourceTreeToPsiMap.psiElementToTree(allStatements[index]) : null; } else { String refText = ref.getCanonicalText(); if (statement.isOnDemand()) { refText += "."; } PsiImportStatementBase insertBefore = null; PsiImportStatementBase insertAfter = null; for (PsiImportStatementBase statement1 : statements) { PsiJavaCodeReferenceElement ref1 = statement1.getImportReference(); if (ref1 == null) { continue; } String refTextThis = ref1.getCanonicalText(); if (statement1.isOnDemand()) { refTextThis += "."; } int comp = Comparing.compare(refText, refTextThis); if (comp < 0 && insertBefore == null) { insertBefore = statement1; } if (comp > 0) { insertAfter = statement1; } } if (insertBefore != null) return insertBefore.getNode(); if (insertAfter != null) return insertAfter.getNode().getTreeNext(); return null; } }
public void processRange(TreeElement element, int startOffset, int endOffset) { ArrayList<ASTNode> array = new ArrayList<ASTNode>(); addReferencesInRange(array, element, startOffset, endOffset); for (ASTNode ref : array) { if (SourceTreeToPsiMap.treeElementToPsi(ref).isValid()) { process((TreeElement) ref, true, true); } } }
@Override public PsiElement shortenClassReferences(@NotNull PsiElement element, int flags) throws IncorrectOperationException { CheckUtil.checkWritable(element); if (!SourceTreeToPsiMap.hasTreeElement(element)) return element; final boolean addImports = (flags & DO_NOT_ADD_IMPORTS) == 0; final boolean incompleteCode = (flags & UNCOMPLETE_CODE) != 0; final ReferenceAdjuster adjuster = ReferenceAdjuster.Extension.getReferenceAdjuster(element.getLanguage()); if (adjuster != null) { final ASTNode reference = adjuster.process(element.getNode(), addImports, incompleteCode, myProject); return SourceTreeToPsiMap.treeToPsiNotNull(reference); } else { return element; } }
public void deleteChildInternal(@NotNull ASTNode child) { if (child.getElementType() == JavaElementType.CLASS) { PsiJavaFile file = SourceTreeToPsiMap.treeToPsiNotNull(this); if (file.getClasses().length == 1) { file.delete(); return; } } super.deleteChildInternal(child); }
@Override public PsiElement qualifyClassReferences(@NotNull PsiElement element) { final ReferenceAdjuster adjuster = ReferenceAdjuster.Extension.getReferenceAdjuster(element.getLanguage()); if (adjuster != null) { final ASTNode reference = adjuster.process(element.getNode(), false, false, true, true); return SourceTreeToPsiMap.treeToPsiNotNull(reference); } return element; }
@Override public void setMirror(@NotNull TreeElement element) throws InvalidMirrorException { PsiElement mirrorElement = SourceTreeToPsiMap.treeToPsiNotNull(element); if (!(mirrorElement instanceof PsiJavaFile)) { throw new InvalidMirrorException("Unexpected mirror file: " + mirrorElement); } PsiJavaFile mirrorFile = (PsiJavaFile) mirrorElement; setMirrorIfPresent(getPackageStatement(), mirrorFile.getPackageStatement()); setMirrors(getClasses(), mirrorFile.getClasses()); }
@Override public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException { LOG.assertTrue(getTreeParent() != null); CheckUtil.checkWritable(this); TreeElement elementCopy = ChangeUtil.copyToElement(newElement); getTreeParent().replaceChildInternal(this, elementCopy); elementCopy = ChangeUtil.decodeInformation(elementCopy); final PsiElement result = SourceTreeToPsiMap.treeElementToPsi(elementCopy); this.invalidate(); return result; }
@Override public void shortenClassReferences(@NotNull PsiElement element, int startOffset, int endOffset) throws IncorrectOperationException { CheckUtil.checkWritable(element); if (SourceTreeToPsiMap.hasTreeElement(element)) { final ReferenceAdjuster adjuster = ReferenceAdjuster.Extension.getReferenceAdjuster(element.getLanguage()); if (adjuster != null) { adjuster.processRange(element.getNode(), startOffset, endOffset, myProject); } } }
private void init(final ASTNode child) { if (child == null) return; ASTNode treePrev = child.getTreePrev(); while (treePrev != null && SpacingUtil.isWhiteSpace(treePrev)) { treePrev = treePrev.getTreePrev(); } if (treePrev == null) { init(child.getTreeParent()); } else { myChild2 = child; myChild1 = treePrev; final CompositeElement parent = (CompositeElement) treePrev.getTreeParent(); myParent = SourceTreeToPsiMap.treeElementToPsi(parent); } }
@Nullable private static ASTNode findPreviousWhiteSpace( final ASTNode leafElement, final IElementType whiteSpaceTokenType) { final int offset = leafElement.getTextRange().getStartOffset() - 1; if (offset < 0) return null; final PsiElement psiElement = SourceTreeToPsiMap.treeElementToPsi(leafElement); if (psiElement == null) { return null; } final PsiElement found = psiElement.getContainingFile().findElementAt(offset); if (found == null) return null; final ASTNode treeElement = found.getNode(); if (treeElement != null && treeElement.getElementType() == whiteSpaceTokenType) return treeElement; return null; }
@Override public PsiElement getMirror() { TreeElement mirrorTreeElement = myMirrorFileElement; if (mirrorTreeElement == null) { synchronized (myMirrorLock) { mirrorTreeElement = myMirrorFileElement; if (mirrorTreeElement == null) { VirtualFile file = getVirtualFile(); PsiClass[] classes = getClasses(); String fileName = (classes.length > 0 ? classes[0].getName() : file.getNameWithoutExtension()) + JavaFileType.DOT_DEFAULT_EXTENSION; final Document document = FileDocumentManager.getInstance().getDocument(file); assert document != null : file.getUrl(); CharSequence mirrorText = document.getImmutableCharSequence(); boolean internalDecompiler = StringUtil.startsWith(mirrorText, BANNER); PsiFileFactory factory = PsiFileFactory.getInstance(getManager().getProject()); PsiFile mirror = factory.createFileFromText(fileName, JavaLanguage.INSTANCE, mirrorText, false, false); mirror.putUserData(PsiUtil.FILE_LANGUAGE_LEVEL_KEY, getLanguageLevel()); mirrorTreeElement = SourceTreeToPsiMap.psiToTreeNotNull(mirror); try { final TreeElement finalMirrorTreeElement = mirrorTreeElement; ProgressManager.getInstance() .executeNonCancelableSection( new Runnable() { @Override public void run() { setMirror(finalMirrorTreeElement); putUserData(CLS_DOCUMENT_LINK_KEY, document); } }); } catch (InvalidMirrorException e) { //noinspection ThrowableResultOfMethodCallIgnored LOG.error(file.getUrl(), internalDecompiler ? e : wrapException(e, file)); } ((PsiFileImpl) mirror).setOriginalFile(this); myMirrorFileElement = mirrorTreeElement; } } } return mirrorTreeElement.getPsi(); }
@NotNull static PsiModifierListOwner getAnnotationOwner(@NotNull PsiElement element) { PsiModifierListOwner annotationOwner = element.getOriginalElement() instanceof PsiModifierListOwner ? (PsiModifierListOwner) element.getOriginalElement() : (PsiModifierListOwner) element; if (!annotationOwner.isPhysical()) { // this is fake PsiFile which is mirror for ClsFile without sources ASTNode node = SourceTreeToPsiMap.psiElementToTree(element); if (node != null) { PsiCompiledElement compiledElement = node.getUserData(ClsElementImpl.COMPILED_ELEMENT); if (compiledElement instanceof PsiModifierListOwner) { return (PsiModifierListOwner) compiledElement; } } } return annotationOwner; }
@NotNull private PsiAnnotation createAnnotationFromText(@NotNull final String text) throws IncorrectOperationException { // synchronize during interning in charTable synchronized (charTable) { final DummyHolder holder = DummyHolderFactory.createHolder( myPsiManager, new JavaDummyElement(text, ANNOTATION, LanguageLevel.HIGHEST), null, charTable); final PsiElement element = SourceTreeToPsiMap.treeElementToPsi(holder.getTreeElement().getFirstChildNode()); if (!(element instanceof PsiAnnotation)) { throw new IncorrectOperationException("Incorrect annotation \"" + text + "\"."); } return (PsiAnnotation) element; } }
@NotNull public static PsiAnnotationMemberValue createMemberValueFromText( final String text, final PsiManager manager, final ClsElementImpl parent) { final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); final PsiJavaFile context = ((PsiJavaParserFacadeImpl) factory).getDummyJavaFile(); // to resolve classes from java.lang final LanguageLevel level = PsiUtil.getLanguageLevel(parent); final DummyHolder holder = DummyHolderFactory.createHolder( manager, new JavaDummyElement(text, ANNOTATION_VALUE, level), context); final PsiElement element = SourceTreeToPsiMap.treeElementToPsi(holder.getTreeElement().getFirstChildNode()); if (!(element instanceof PsiAnnotationMemberValue)) { LOG.error("Could not parse initializer:'" + text + "'"); return null; } return getMemberValue(element, parent); }
@Override public PsiDocTag findTagByName(String name) { if (getFirstChildNode().getElementType() == JavaDocElementType.DOC_COMMENT) { if (getFirstChildNode().getText().indexOf(name) < 0) return null; } for (ASTNode child = getFirstChildNode(); child != null; child = child.getTreeNext()) { if (child.getElementType() == DOC_TAG) { PsiDocTag tag = (PsiDocTag) SourceTreeToPsiMap.treeElementToPsi(child); final CharSequence nameText = ((LeafElement) tag.getNameElement()).getChars(); if (nameText.length() > 0 && nameText.charAt(0) == '@' && CharArrayUtil.regionMatches(nameText, 1, name)) { return tag; } } } return null; }
public boolean isCollapsedByDefault(@NotNull ASTNode node) { CodeFoldingSettings settings = CodeFoldingSettings.getInstance(); final PsiElement element = SourceTreeToPsiMap.treeElementToPsi(node); if (element instanceof PsiComment) { // find out if file header final ASTNode parent = node.getTreeParent(); ASTNode treePrev = node.getTreePrev(); if (parent.getElementType() == CfmlElementTypes.CFML_FILE && treePrev == null) { return CodeFoldingSettings.getInstance().COLLAPSE_FILE_HEADER; } else { return CodeFoldingSettings.getInstance().COLLAPSE_DOC_COMMENTS; } } else if (element instanceof CfmlFunction || node.getElementType() == CfmlElementTypes.FUNCTIONBODY) { return settings.COLLAPSE_METHODS; } /* else if (element instanceof CfmlComponent) { return settings.isCollapseClasses(); }*/ return false; }
public TreeElement process(TreeElement element, boolean addImports, boolean uncompleteCode) { IElementType elementType = element.getElementType(); if (elementType == JavaElementType.JAVA_CODE_REFERENCE || elementType == JavaElementType.REFERENCE_EXPRESSION) { final IElementType parentElementType = element.getTreeParent().getElementType(); if (elementType == JavaElementType.JAVA_CODE_REFERENCE || parentElementType == JavaElementType.REFERENCE_EXPRESSION || parentElementType == JavaElementType.METHOD_REF_EXPRESSION || uncompleteCode) { final PsiJavaCodeReferenceElement ref = (PsiJavaCodeReferenceElement) SourceTreeToPsiMap.treeElementToPsi(element); final PsiReferenceParameterList parameterList = ref.getParameterList(); if (parameterList != null) { final PsiTypeElement[] typeParameters = parameterList.getTypeParameterElements(); for (PsiTypeElement typeParameter : typeParameters) { process( (TreeElement) SourceTreeToPsiMap.psiElementToTree(typeParameter), addImports, uncompleteCode); } } boolean rightKind = true; if (elementType == JavaElementType.JAVA_CODE_REFERENCE) { int kind = ((PsiJavaCodeReferenceElementImpl) element).getKind(); rightKind = kind == PsiJavaCodeReferenceElementImpl.CLASS_NAME_KIND || kind == PsiJavaCodeReferenceElementImpl.CLASS_OR_PACKAGE_NAME_KIND; } if (rightKind) { boolean isInsideDocComment = TreeUtil.findParent(element, JavaDocElementType.DOC_COMMENT) != null; boolean isShort = !((SourceJavaCodeReference) element).isQualified(); if (!makeFQ(isInsideDocComment)) { if (isShort) return element; // short name already, no need to change } PsiElement refElement; if (!uncompleteCode) { refElement = ref.resolve(); } else { PsiResolveHelper helper = JavaPsiFacade.getInstance(element.getManager().getProject()).getResolveHelper(); refElement = helper.resolveReferencedClass( ((SourceJavaCodeReference) element).getClassNameText(), SourceTreeToPsiMap.treeElementToPsi(element)); } if (refElement instanceof PsiClass) { if (makeFQ(isInsideDocComment)) { String qName = ((PsiClass) refElement).getQualifiedName(); if (qName == null) return element; PsiImportHolder file = (PsiImportHolder) SourceTreeToPsiMap.treeElementToPsi(element).getContainingFile(); if (file instanceof PsiJavaFile && ImportHelper.isImplicitlyImported(qName, (PsiJavaFile) file)) { if (isShort) return element; return (TreeElement) makeShortReference( (CompositeElement) element, (PsiClass) refElement, addImports); } if (file instanceof PsiJavaFile) { String thisPackageName = ((PsiJavaFile) file).getPackageName(); if (ImportHelper.hasPackage(qName, thisPackageName)) { if (!isShort) { return (TreeElement) makeShortReference( (CompositeElement) element, (PsiClass) refElement, addImports); } } } return (TreeElement) replaceReferenceWithFQ(element, (PsiClass) refElement); } else { int oldLength = element.getTextLength(); TreeElement treeElement = (TreeElement) makeShortReference( (CompositeElement) element, (PsiClass) refElement, addImports); if (treeElement.getTextLength() == oldLength && ((PsiClass) refElement).getContainingClass() != null) { PsiElement qualifier = ref.getQualifier(); if (qualifier instanceof PsiJavaCodeReferenceElement && ((PsiJavaCodeReferenceElement) qualifier).resolve() instanceof PsiClass) { process((TreeElement) qualifier.getNode(), addImports, uncompleteCode); } } return treeElement; } } } } } for (TreeElement child = element.getFirstChildNode(); child != null; child = child.getTreeNext()) { child = process(child, addImports, uncompleteCode); } return element; }
public void processComment(@Nullable ASTNode element) { if (!getSettings().ENABLE_JAVADOC_FORMATTING) return; PsiElement psiElement = SourceTreeToPsiMap.treeElementToPsi(element); processElementComment(psiElement); }
@Override public PsiElement copy() { ASTNode elementCopy = copyElement(); return SourceTreeToPsiMap.treeElementToPsi(elementCopy); }
public ASTNode processRange(final ASTNode element, final int startOffset, final int endOffset) { final PsiElement psiElement = SourceTreeToPsiMap.treeElementToPsi(element); assert psiElement != null; final PsiFile file = psiElement.getContainingFile(); final Document document = file.getViewProvider().getDocument(); final RangeMarker rangeMarker = document != null && endOffset < document.getTextLength() ? document.createRangeMarker(startOffset, endOffset) : null; PsiElement elementToFormat = document instanceof DocumentWindow ? InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file) : psiElement; final PsiFile fileToFormat = elementToFormat.getContainingFile(); final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(fileToFormat); if (builder != null) { TextRange range = preprocess(element, TextRange.create(startOffset, endOffset)); if (document instanceof DocumentWindow) { DocumentWindow documentWindow = (DocumentWindow) document; range = documentWindow.injectedToHost(range); } // final SmartPsiElementPointer pointer = // SmartPointerManager.getInstance(psiElement.getProject()).createSmartPsiElementPointer(psiElement); final FormattingModel model = CoreFormatterUtil.buildModel( builder, elementToFormat, mySettings, FormattingMode.REFORMAT); if (file.getTextLength() > 0) { try { FormatterEx.getInstanceEx() .format( model, mySettings, mySettings.getIndentOptions(fileToFormat.getFileType()), new FormatTextRanges(range, true)); wrapLongLinesIfNecessary(file, document, startOffset, endOffset); } catch (IncorrectOperationException e) { LOG.error(e); } } if (!psiElement.isValid()) { if (rangeMarker != null) { final PsiElement at = file.findElementAt(rangeMarker.getStartOffset()); final PsiElement result = PsiTreeUtil.getParentOfType(at, psiElement.getClass(), false); assert result != null; rangeMarker.dispose(); return result.getNode(); } else { assert false; } } // return SourceTreeToPsiMap.psiElementToTree(pointer.getElement()); } if (rangeMarker != null) { rangeMarker.dispose(); } return element; }
public String getPackageName() { PsiJavaCodeReferenceElement ref = getPackageReference(); return ref == null ? null : SourceUtil.getTextSkipWhiteSpaceAndComments(SourceTreeToPsiMap.psiElementToTree(ref)); }