com.intellij.psi.impl.source.tree.TreeElement Java Examples

The following examples show how to use com.intellij.psi.impl.source.tree.TreeElement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LowLevelSearchUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
static boolean processElementsAtOffsets(@Nonnull PsiElement scope,
                                        @Nonnull StringSearcher searcher,
                                        boolean processInjectedPsi,
                                        @Nonnull ProgressIndicator progress,
                                        int[] offsetsInScope,
                                        @Nonnull TextOccurenceProcessor processor) {
  if (offsetsInScope.length == 0) return true;

  Project project = scope.getProject();
  TreeElement lastElement = null;
  for (int offset : offsetsInScope) {
    progress.checkCanceled();
    lastElement = processTreeUp(project, processor, scope, searcher, offset, processInjectedPsi, progress, lastElement);
    if (lastElement == null) return false;
  }
  return true;
}
 
Example #2
Source File: LowLevelSearchUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static TreeElement findNextLeafElementAt(ASTNode scopeNode, TreeElement last, int offset) {
  int offsetR = offset;
  if (last != null) {
    offsetR -= last.getStartOffset() - scopeNode.getStartOffset() + last.getTextLength();
    while (offsetR >= 0) {
      TreeElement next = last.getTreeNext();
      if (next == null) {
        last = last.getTreeParent();
        continue;
      }
      int length = next.getTextLength();
      offsetR -= length;
      last = next;
    }
    scopeNode = last;
    offsetR += scopeNode.getTextLength();
  }
  return (LeafElement)scopeNode.findLeafElementAt(offsetR);
}
 
Example #3
Source File: UnwrapHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void restoreCaretPosition(final PsiFile file) {
  ((TreeElement)file.getNode()).acceptTree(new RecursiveTreeElementWalkingVisitor() {
    @Override
    protected void visitNode(TreeElement element) {
      PsiElement el = element.getPsi();
      Integer offset = el.getCopyableUserData(CARET_POS_KEY);

      // continue;
      if (offset != null) {
        myEditor.getCaretModel().moveToOffset(el.getTextOffset() + offset);
        el.putCopyableUserData(CARET_POS_KEY, null);
        return;
      }
      super.visitNode(element);
    }
  });
}
 
Example #4
Source File: PsiFileFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public PsiElement createElementFromText(@Nullable final String text,
                                        @Nonnull final Language language,
                                        @Nonnull final LanguageVersion languageVersion,
                                        @Nonnull final IElementType type,
                                        @Nullable final PsiElement context) {
  if (text == null) return null;
  final DummyHolder result = DummyHolderFactory.createHolder(myManager, language, context);
  final FileElement holder = result.getTreeElement();

  final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
  if (parserDefinition == null) {
    throw new AssertionError("No parser definition for " + language);
  }
  final Project project = myManager.getProject();
  final Lexer lexer = parserDefinition.createLexer(languageVersion);
  final PsiBuilder builder = PsiBuilderFactory.getInstance().createBuilder(project, holder, lexer, language, languageVersion, text);
  final ASTNode node = parserDefinition.createParser(languageVersion).parse(type, builder, languageVersion);
  holder.rawAddChildren((TreeElement)node);
  markGenerated(result);
  return node.getPsi();
}
 
Example #5
Source File: RequirejsProjectComponent.java    From WebStormRequireJsPlugin with MIT License 6 votes vote down vote up
protected void parseRequireJsPaths(TreeElement node) {
    if (null == node) {
        return ;
    }

    if (node.getElementType() == JSElementTypes.PROPERTY) {
        RequirePathAlias pathAlias = new RequirePathAlias();
        pathAlias.alias = getJSPropertyName(node);
        pathAlias.path = getJSPropertyLiteralValue(node);
        requirePaths.addPath(pathAlias);
    }

    TreeElement next = node.getTreeNext();
    if (null != next) {
        parseRequireJsPaths(next);
    }
}
 
Example #6
Source File: CodeEditUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void markToReformatBeforeOrInsertWhitespace(final ASTNode left, @Nonnull final ASTNode right) {
  final Language leftLang = left != null ? PsiUtilCore.getNotAnyLanguage(left) : null;
  final Language rightLang = PsiUtilCore.getNotAnyLanguage(right);

  ASTNode generatedWhitespace = null;
  if (leftLang != null && leftLang.isKindOf(rightLang)) {
    generatedWhitespace = LanguageTokenSeparatorGenerators.INSTANCE.forLanguage(leftLang).generateWhitespaceBetweenTokens(left, right);
  }
  else if (rightLang.isKindOf(leftLang)) {
    generatedWhitespace = LanguageTokenSeparatorGenerators.INSTANCE.forLanguage(rightLang).generateWhitespaceBetweenTokens(left, right);
  }

  if (generatedWhitespace != null) {
    final TreeUtil.CommonParentState parentState = new TreeUtil.CommonParentState();
    TreeUtil.prevLeaf((TreeElement)right, parentState);
    parentState.nextLeafBranchStart.getTreeParent().addChild(generatedWhitespace, parentState.nextLeafBranchStart);
  }
  else {
    markToReformatBefore(right, true);
  }
}
 
Example #7
Source File: PomModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static PsiFile getContainingFileByTree(@Nonnull final PsiElement changeScope) {
  // there could be pseudo physical trees (JSPX/JSP/etc.) which must not translate
  // any changes to document and not to fire any PSI events
  final PsiFile psiFile;
  final ASTNode node = changeScope.getNode();
  if (node == null) {
    psiFile = changeScope.getContainingFile();
  }
  else {
    final FileElement fileElement = TreeUtil.getFileElement((TreeElement)node);
    // assert fileElement != null : "Can't find file element for node: " + node;
    // Hack. the containing tree can be invalidated if updating supplementary trees like HTML in JSP.
    if (fileElement == null) return null;

    psiFile = (PsiFile)fileElement.getPsi();
  }
  return psiFile.getNode() != null ? psiFile : null;
}
 
Example #8
Source File: DummyHolder.java    From consulo with Apache License 2.0 6 votes vote down vote up
public DummyHolder(@Nonnull PsiManager manager, @Nullable TreeElement contentElement, @Nullable PsiElement context, @Nullable CharTable table, @Nullable Boolean validity, Language language) {
  super(TokenType.DUMMY_HOLDER, TokenType.DUMMY_HOLDER, new DummyHolderViewProvider(manager));
  myLanguage = language;
  ((DummyHolderViewProvider)getViewProvider()).setDummyHolder(this);
  myContext = context;
  myTable = table != null ? table : IdentityCharTable.INSTANCE;
  if (contentElement instanceof FileElement) {
    ((FileElement)contentElement).setPsi(this);
    ((FileElement)contentElement).setCharTable(myTable);
    setTreeElementPointer((FileElement)contentElement);
  }
  else if (contentElement != null) {
    getTreeElement().rawAddChildren(contentElement);
    clearCaches();
  }
  myExplicitlyValid = validity;
}
 
Example #9
Source File: RequirejsProjectComponent.java    From WebStormRequireJsPlugin with MIT License 6 votes vote down vote up
private void parsePackage(TreeElement node) {
    if (null == node) {
        return;
    }
    if (node.getElementType() == JSElementTypes.OBJECT_LITERAL_EXPRESSION
        || node.getElementType() == JSElementTypes.LITERAL_EXPRESSION
    ) {
        // TODO: Not adding not resolve package
        Package p = new Package();
        packageConfig.packages.add(p);
        if (node.getElementType() == JSElementTypes.OBJECT_LITERAL_EXPRESSION) {
            TreeElement prop = (TreeElement) node.findChildByType(JSElementTypes.PROPERTY);
            parsePackageObject(prop, p);
        } else {
            p.name = dequote(node.getText());
        }
        normalizeParsedPackage(p);
        validatePackage(p);
    }
    TreeElement next = node.getTreeNext();
    parsePackage(next);
}
 
Example #10
Source File: RequirejsProjectComponent.java    From WebStormRequireJsPlugin with MIT License 6 votes vote down vote up
protected void parseMapConfigElement(TreeElement mapConfigElement) {
    if (null == mapConfigElement) {
        return;
    }

    if (mapConfigElement.getElementType() == JSElementTypes.PROPERTY) {
        String module = getJSPropertyName(mapConfigElement);

        TreeElement mapAliasesObject = (TreeElement) mapConfigElement
                .findChildByType(JSElementTypes.OBJECT_LITERAL_EXPRESSION);

        if (null != mapAliasesObject) {
            RequireMapModule requireMapModule = new RequireMapModule();

            requireMapModule.module = module;
            TreeElement mapAliasProperty = (TreeElement) mapAliasesObject.findChildByType(JSElementTypes.PROPERTY);
            parseMapAliasProperty(requireMapModule, mapAliasProperty);

            requireMap.addModule(requireMapModule);
        }
    }

    parseMapConfigElement(mapConfigElement.getTreeNext());
}
 
Example #11
Source File: RequirejsProjectComponent.java    From WebStormRequireJsPlugin with MIT License 6 votes vote down vote up
protected void parseMapAliasProperty(RequireMapModule requireMapModule, TreeElement mapAliasProperty) {
    if (null == mapAliasProperty) {
        return;
    }

    if (mapAliasProperty.getElementType() == JSElementTypes.PROPERTY) {
        RequirePathAlias alias = new RequirePathAlias();
        alias.alias = getJSPropertyName(mapAliasProperty);
        alias.path = getJSPropertyLiteralValue(mapAliasProperty);

        if (null != alias.alias && alias.path != null) {
            requireMapModule.addAlias(alias);
        } else {
            LOG.debug("Error parse require js path", alias);
        }
    }

    parseMapAliasProperty(requireMapModule, mapAliasProperty.getTreeNext());
}
 
Example #12
Source File: TreeChangeEventImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void mergeChange(TreeChangeImpl nextChange) {
  CompositeElement newParent = nextChange.getChangedParent();

  for (TreeChangeImpl descendant : new ArrayList<>(myChangesByAllParents.get(newParent))) {
    TreeElement ancestorChild = findAncestorChild(newParent, descendant);
    if (ancestorChild != null) {
      nextChange.markChildChanged(ancestorChild, descendant.getLengthDelta());
    }

    unregisterChange(descendant);
  }

  registerChange(nextChange);
}
 
Example #13
Source File: ChangeInfoImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void childReplaced(PsiTreeChangeEventImpl e, TreeElement oldChild, TreeElement newChild, CompositeElement parent) {
  e.setParent(parent.getPsi());
  e.setOldChild(oldChild.getPsi());
  e.setChild(newChild.getPsi());
  e.setNewChild(newChild.getPsi());
  e.setOldLength(myOldLength);
  getPsiManagerImpl(e).childReplaced(e);
}
 
Example #14
Source File: ChangeInfoImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
ChangeInfoImpl(@Nullable TreeElement oldChild, @Nullable TreeElement newChild, int offset, int oldLength) {
  myOldChild = oldChild;
  myNewChild = newChild;
  myOffset = offset;
  myOldLength = oldLength;
  myNewLength = newChild != null ? newChild.getTextLength() : 0;
}
 
Example #15
Source File: TreeChangeEventImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @return a direct child of {@code ancestor} which contains {@code change}
 */
@Nullable
private static TreeElement findAncestorChild(@Nonnull CompositeElement ancestor, @Nonnull TreeChangeImpl change) {
  List<CompositeElement> superParents = change.getSuperParents();
  int index = superParents.indexOf(ancestor);
  return index < 0 ? null : index == 0 ? change.getChangedParent() : superParents.get(index - 1);
}
 
Example #16
Source File: DiffLog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
void doActualPsiChange(@Nonnull PsiFile file, @Nonnull TreeChangeEventImpl changeEvent) {
  TreeElement anchor = null;
  TreeElement firstChildNode = myOldParent.getFirstChildNode();
  for (int i = 0; i < myPos; i++) {
    anchor = anchor == null ? firstChildNode : anchor.getTreeNext();
  }

  PsiElement psiParent = myOldParent.getPsi();
  PsiElement psiChild = getPsi(myNewNode, file);
  if (psiParent != null && psiChild != null) {
    PsiTreeChangeEventImpl event = new PsiTreeChangeEventImpl(file.getManager());
    event.setParent(psiParent);
    event.setChild(psiChild);
    event.setFile(file);
    ((PsiManagerEx)file.getManager()).beforeChildAddition(event);
  }

  changeEvent.addElementaryChange(myOldParent);

  myNewNode.rawRemove();
  if (anchor != null) {
    anchor.rawInsertAfterMe(myNewNode);
  }
  else {
    if (firstChildNode != null) {
      firstChildNode.rawInsertBeforeMe(myNewNode);
    }
    else {
      myOldParent.rawAddChildren(myNewNode);
    }
  }

  myNewNode.clearCaches();
  myOldParent.subtreeChanged();

  DebugUtil.checkTreeStructure(myOldParent);
}
 
Example #17
Source File: TreeChangeEventImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean integrateIntoExistingChanges(CompositeElement nextParent) {
  for (CompositeElement eachParent : JBIterable.generate(nextParent, TreeElement::getTreeParent)) {
    CompositeElement superParent = eachParent.getTreeParent();
    TreeChangeImpl superChange = myChangedElements.get(superParent);
    if (superChange != null) {
      superChange.markChildChanged(eachParent, 0);
      return true;
    }
  }
  return false;
}
 
Example #18
Source File: TreeChangeImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void markChildChanged(@Nonnull TreeElement child, int lengthDelta) {
  myContentChangeChildren.add(child);
  if (lengthDelta != 0) {
    myInitialLengths.computeIfPresent(child, (c, oldLength) -> oldLength - lengthDelta);
  }
  clearCache();
}
 
Example #19
Source File: RequirejsProjectComponent.java    From WebStormRequireJsPlugin with MIT License 5 votes vote down vote up
private void parsePackages(TreeElement node) {
    TokenSet tokenSet = TokenSet.create(
            JSElementTypes.OBJECT_LITERAL_EXPRESSION,
            JSElementTypes.LITERAL_EXPRESSION);
    TreeElement packageNode = (TreeElement) node.findChildByType(tokenSet);
    parsePackage(packageNode);
}
 
Example #20
Source File: RequirejsProjectComponent.java    From WebStormRequireJsPlugin with MIT License 5 votes vote down vote up
protected String getJSPropertyName(TreeElement jsProperty) {
    TreeElement identifier = (TreeElement) jsProperty.findChildByType(
            TokenSet.create(JSTokenTypes.IDENTIFIER, JSTokenTypes.STRING_LITERAL, JSTokenTypes.PUBLIC_KEYWORD)
    );
    String identifierName = null;
    if (null != identifier) {
        identifierName = dequote(identifier.getText());
    }

    return identifierName;
}
 
Example #21
Source File: LombokLightMethodTreeGenerator.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
public TreeElement generateTreeFor(PsiElement original, CharTable table, PsiManager manager) {
  TreeElement result = null;
  if (original instanceof LombokLightMethodBuilder) {
    result = ChangeUtil.copyElement((TreeElement) SourceTreeToPsiMap.psiElementToTree(original), table);
  }
  return result;
}
 
Example #22
Source File: SqliteMagicLightMethodGenerator.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public TreeElement generateTreeFor(PsiElement original, CharTable table, PsiManager manager) {
  TreeElement result = null;
  if (original instanceof SqliteMagicLightMethodBuilder) {
    result = ChangeUtil.copyElement((TreeElement) SourceTreeToPsiMap.psiElementToTree(original), table);
  }
  return result;
}
 
Example #23
Source File: DiffLog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
void doActualPsiChange(@Nonnull PsiFile file, @Nonnull TreeChangeEventImpl event) {
  PsiFileImpl fileImpl = (PsiFileImpl)file;
  final int oldLength = myOldNode.getTextLength();
  PsiManagerImpl manager = (PsiManagerImpl)fileImpl.getManager();
  BlockSupportImpl.sendBeforeChildrenChangeEvent(manager, fileImpl, false);
  if (myOldNode.getFirstChildNode() != null) myOldNode.rawRemoveAllChildren();
  final TreeElement firstChildNode = myNewNode.getFirstChildNode();
  if (firstChildNode != null) myOldNode.rawAddChildren(firstChildNode);
  fileImpl.calcTreeElement().setCharTable(myNewNode.getCharTable());
  myOldNode.subtreeChanged();
  BlockSupportImpl.sendAfterChildrenChangedEvent(manager, fileImpl, oldLength, false);
}
 
Example #24
Source File: DebugUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String treeToStringWithUserData(TreeElement root, boolean skipWhitespaces) {
  final LengthBuilder ruler = new LengthBuilder();
  treeToBufferWithUserData(ruler, root, 0, skipWhitespaces);
  final StringBuilder buffer = new StringBuilder(ruler.getLength());
  treeToBufferWithUserData(buffer, root, 0, skipWhitespaces);
  return buffer.toString();
}
 
Example #25
Source File: DebugUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void treeToBufferWithUserData(Appendable buffer, TreeElement root, int indent, boolean skipWhiteSpaces) {
  if (skipWhiteSpaces && root.getElementType() == TokenType.WHITE_SPACE) return;

  StringUtil.repeatSymbol(buffer, ' ', indent);
  try {
    final PsiElement psi = SourceTreeToPsiMap.treeElementToPsi(root);
    assert psi != null : root;
    if (root instanceof CompositeElement) {
      buffer.append(psi.toString());
    }
    else {
      final String text = fixWhiteSpaces(root.getText());
      buffer.append(root.toString()).append("('").append(text).append("')");
    }
    buffer.append(root.getUserDataString());
    buffer.append("\n");
    if (root instanceof CompositeElement) {
      PsiElement[] children = psi.getChildren();

      for (PsiElement child : children) {
        treeToBufferWithUserData(buffer, (TreeElement)SourceTreeToPsiMap.psiElementToTree(child), indent + 2, skipWhiteSpaces);
      }

      if (children.length == 0) {
        StringUtil.repeatSymbol(buffer, ' ', indent + 2);
        buffer.append("<empty list>\n");
      }
    }
  }
  catch (IOException e) {
    LOG.error(e);
  }
}
 
Example #26
Source File: PsiParserFacadeImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private PsiComment findPsiCommentChild(PsiFile aFile) {
  PsiElement[] children = aFile.getChildren();
  for (PsiElement aChildren : children) {
    if (aChildren instanceof PsiComment) {
      PsiComment comment = (PsiComment)aChildren;
      DummyHolderFactory.createHolder(myManager, (TreeElement)SourceTreeToPsiMap.psiElementToTree(comment), null);
      return comment;
    }
  }
  throw new IncorrectOperationException("Incorrect comment \"" + aFile.getText() + "\".");
}
 
Example #27
Source File: CodeEditUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void saveWhitespacesInfo(ASTNode first) {
  if (first == null || isNodeGenerated(first) || getOldIndentation(first) >= 0) {
    return;
  }

  PsiElement psiElement = first.getPsi();
  if (psiElement == null) {
    return;
  }

  PsiFile file = psiElement.getContainingFile();
  setOldIndentation((TreeElement)first, IndentHelper.getInstance().getIndent(file.getProject(), file.getFileType(), first));
}
 
Example #28
Source File: PsiDirectoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void updateAddedFile(PsiFile copyPsi) throws IncorrectOperationException {
  final UpdateAddedFileProcessor processor = UpdateAddedFileProcessor.forElement(copyPsi);
  if (processor != null) {
    final TreeElement tree = (TreeElement)SourceTreeToPsiMap.psiElementToTree(copyPsi);
    if (tree != null) {
      ChangeUtil.encodeInformation(tree);
    }
    processor.update(copyPsi, null);
    if (tree != null) {
      ChangeUtil.decodeInformation(tree);
    }
  }
}
 
Example #29
Source File: SimpleTreePatcher.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void insert(CompositeElement parent, TreeElement anchorBefore, OuterLanguageElement toInsert) {
  if(anchorBefore != null) {
    anchorBefore.rawInsertBeforeMe((TreeElement)toInsert);
  }
  else parent.rawAddChildren((TreeElement)toInsert);
}
 
Example #30
Source File: ParseUtilBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static TreeElement createTokenElement(Lexer lexer, CharTable table) {
  IElementType tokenType = lexer.getTokenType();
  if (tokenType == null) {
    return null;
  }
  else if (tokenType instanceof ILazyParseableElementType) {
    return ASTFactory.lazy((ILazyParseableElementType)tokenType, LexerUtil.internToken(lexer, table));
  }
  else {
    return ASTFactory.leaf(tokenType, LexerUtil.internToken(lexer, table));
  }
}