Java 类com.intellij.psi.impl.source.tree.Factory 实例源码

项目:intellij-ce-playground    文件:DeclarationMover.java   
@Override
public void beforeMove(@NotNull final Editor editor, @NotNull final MoveInfo info, final boolean down) {
  super.beforeMove(editor, info, down);

  if (myEnumToInsertSemicolonAfter != null) {
    TreeElement semicolon = Factory.createSingleLeafElement(JavaTokenType.SEMICOLON, ";", 0, 1, null, myEnumToInsertSemicolonAfter.getManager());

    try {
      PsiElement inserted = myEnumToInsertSemicolonAfter.getParent().addAfter(semicolon.getPsi(), myEnumToInsertSemicolonAfter);
      inserted = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(inserted);
      final LogicalPosition position = editor.offsetToLogicalPosition(inserted.getTextRange().getEndOffset());

      info.toMove2 = new LineRange(position.line + 1, position.line + 1);
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
    finally {
      myEnumToInsertSemicolonAfter = null;
    }
  }
}
项目:intellij-ce-playground    文件:PsiBuilderImpl.java   
@Override
public ASTNode convert(final Node n) {
  if (n instanceof Token) {
    final Token token = (Token)n;
    return token.myBuilder.createLeaf(token.getTokenType(), token.myTokenStart, token.myTokenEnd);
  }
  else if (n instanceof ErrorItem) {
    return Factory.createErrorElement(((ErrorItem)n).myMessage);
  }
  else {
    final StartMarker startMarker = (StartMarker)n;
    final CompositeElement composite = n == myRoot ? (CompositeElement)myRoot.myBuilder.createRootAST(myRoot)
                                                     : createComposite(startMarker);
    startMarker.myBuilder.bind(startMarker, composite);
    return composite;
  }
}
项目:tools-idea    文件:DeclarationMover.java   
@Override
public void beforeMove(@NotNull final Editor editor, @NotNull final MoveInfo info, final boolean down) {
  super.beforeMove(editor, info, down);

  if (myEnumToInsertSemicolonAfter != null) {
    TreeElement semicolon = Factory.createSingleLeafElement(JavaTokenType.SEMICOLON, ";", 0, 1, null, myEnumToInsertSemicolonAfter.getManager());

    try {
      PsiElement inserted = myEnumToInsertSemicolonAfter.getParent().addAfter(semicolon.getPsi(), myEnumToInsertSemicolonAfter);
      inserted = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(inserted);
      final LogicalPosition position = editor.offsetToLogicalPosition(inserted.getTextRange().getEndOffset());

      info.toMove2 = new LineRange(position.line + 1, position.line + 1);
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
    finally {
      myEnumToInsertSemicolonAfter = null;
    }
  }
}
项目:consulo    文件:PsiBuilderImpl.java   
@Override
public ASTNode convert(final Node n) {
  if (n instanceof Token) {
    final Token token = (Token)n;
    return token.myBuilder.createLeaf(token.getTokenType(), token.myTokenStart, token.myTokenEnd);
  }
  else if (n instanceof ErrorItem) {
    return Factory.createErrorElement(((ErrorItem)n).myMessage);
  }
  else {
    final StartMarker startMarker = (StartMarker)n;
    final CompositeElement composite = n == myRoot ? (CompositeElement)myRoot.myBuilder.createRootAST(myRoot) : createComposite(startMarker);
    startMarker.myBuilder.bind(startMarker, composite);
    return composite;
  }
}
项目:consulo-java    文件:PsiImportStaticReferenceElementImpl.java   
@Override
public PsiImportStaticStatement bindToTargetClass(final PsiClass aClass) throws IncorrectOperationException {
  final String qualifiedName = aClass.getQualifiedName();
  if (qualifiedName == null) throw new IncorrectOperationException();
  final PsiJavaParserFacade parserFacade = JavaPsiFacade.getInstance(getProject()).getParserFacade();
  final CompositeElement newRef = (CompositeElement)parserFacade.createReferenceFromText(qualifiedName, null).getNode();
  if (getQualifier() != null) {
    replaceChildInternal(findChildByRole(ChildRole.QUALIFIER), newRef);
    return (PsiImportStaticStatement)getParent();
  }
  else {
    final LeafElement dot = Factory.createSingleLeafElement(JavaTokenType.DOT, ".", 0, 1, SharedImplUtil.findCharTableByTree(newRef), getManager());
    newRef.rawInsertAfterMe(dot);
    final CompositeElement errorElement = Factory.createErrorElement(JavaErrorMessages.message("import.statement.identifier.or.asterisk.expected."));
    dot.rawInsertAfterMe(errorElement);
    final CompositeElement parentComposite = (CompositeElement)SourceTreeToPsiMap.psiElementToTree(getParent());
    parentComposite.addInternal(newRef, errorElement, this, Boolean.TRUE);
    parentComposite.deleteChildInternal(this);
    return (PsiImportStaticStatement)SourceTreeToPsiMap.treeElementToPsi(parentComposite);
  }
}
项目:consulo-java    文件:DeclarationMover.java   
@Override
public void beforeMove(@NotNull final Editor editor, @NotNull final MoveInfo info, final boolean down) {
  super.beforeMove(editor, info, down);

  if (myEnumToInsertSemicolonAfter != null) {
    TreeElement semicolon = Factory.createSingleLeafElement(JavaTokenType.SEMICOLON, ";", 0, 1, null, myEnumToInsertSemicolonAfter.getManager());

    try {
      PsiElement inserted = myEnumToInsertSemicolonAfter.getParent().addAfter(semicolon.getPsi(), myEnumToInsertSemicolonAfter);
      inserted = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(inserted);
      final LogicalPosition position = editor.offsetToLogicalPosition(inserted.getTextRange().getEndOffset());

      info.toMove2 = new LineRange(position.line + 1, position.line + 1);
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
    finally {
      myEnumToInsertSemicolonAfter = null;
    }
  }
}
项目:intellij-ce-playground    文件:LanguageTokenSeparatorGenerators.java   
private LanguageTokenSeparatorGenerators() {
  super("com.intellij.lang.tokenSeparatorGenerator", new TokenSeparatorGenerator() {
    @Override
    public ASTNode generateWhitespaceBetweenTokens(ASTNode left, ASTNode right) {
      Language l = PsiUtilCore.getNotAnyLanguage(left);
      Language rightLang = PsiUtilCore.getNotAnyLanguage(right);
      if (rightLang.isKindOf(l)) {
        l = rightLang; // get more precise lexer
      }
      final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(l);
      if (parserDefinition != null) {
        PsiManager manager = right.getTreeParent().getPsi().getManager();
        ASTNode generatedWhitespace;
        //noinspection EnumSwitchStatementWhichMissesCases
        switch(parserDefinition.spaceExistanceTypeBetweenTokens(left, right)){
          case MUST:
            generatedWhitespace = Factory.createSingleLeafElement(TokenType.WHITE_SPACE, " ", 0, 1, null, manager);
            break;
          case MUST_LINE_BREAK:
            generatedWhitespace = Factory.createSingleLeafElement(TokenType.WHITE_SPACE, "\n", 0, 1, null, manager);
            break;
          default:
            generatedWhitespace = null;
        }
        return generatedWhitespace;
      }
      return null;
    }
  });
}
项目:intellij-ce-playground    文件:PsiBuilderImpl.java   
private void bind(@NotNull StartMarker rootMarker, @NotNull CompositeElement rootNode) {
  StartMarker curMarker = rootMarker;
  CompositeElement curNode = rootNode;

  int lexIndex = rootMarker.myLexemeIndex;
  ProductionMarker item = rootMarker.myFirstChild != null ? rootMarker.myFirstChild : rootMarker.myDoneMarker;
  while (true) {
    lexIndex = insertLeaves(lexIndex, item.myLexemeIndex, curNode);

    if (item == rootMarker.myDoneMarker) break;

    if (item instanceof StartMarker) {
      final StartMarker marker = (StartMarker)item;
      if (!marker.myDoneMarker.myCollapse) {
        curMarker = marker;

        final CompositeElement childNode = createComposite(marker);
        curNode.rawAddChildrenWithoutNotifications(childNode);
        curNode = childNode;

        item = marker.myFirstChild != null ? marker.myFirstChild : marker.myDoneMarker;
        continue;
      }
      else {
        lexIndex = collapseLeaves(curNode, marker);
      }
    }
    else if (item instanceof ErrorItem) {
      final CompositeElement errorElement = Factory.createErrorElement(((ErrorItem)item).myMessage);
      curNode.rawAddChildrenWithoutNotifications(errorElement);
    }
    else if (item instanceof DoneMarker) {
      curMarker = (StartMarker)((DoneMarker)item).myStart.myParent;
      curNode = curNode.getTreeParent();
      item = ((DoneMarker)item).myStart;
    }

    item = item.myNext != null ? item.myNext : curMarker.myDoneMarker;
  }
}
项目:intellij-ce-playground    文件:PsiBuilderImpl.java   
@NotNull
private static CompositeElement createComposite(@NotNull StartMarker marker) {
  final IElementType type = marker.myType;
  if (type == TokenType.ERROR_ELEMENT) {
    String message = marker.myDoneMarker instanceof DoneWithErrorMarker ? ((DoneWithErrorMarker)marker.myDoneMarker).myMessage : null;
    return Factory.createErrorElement(message);
  }

  if (type == null) {
    throw new RuntimeException(UNBALANCED_MESSAGE);
  }

  return ASTFactory.composite(type);
}
项目:intellij-ce-playground    文件:XmlAttributeValueManipulator.java   
public static <T extends PsiElement> T handleContentChange(T element,
                                                           TextRange range,
                                                           String newContent,
                                                           final IElementType tokenType) {
  CheckUtil.checkWritable(element);
  final CompositeElement attrNode = (CompositeElement)element.getNode();
  final ASTNode valueNode = attrNode.findLeafElementAt(range.getStartOffset());
  LOG.assertTrue(valueNode != null, "Leaf not found in " + attrNode + " at offset " + range.getStartOffset() + " in element " + element);
  final PsiElement elementToReplace = valueNode.getPsi();

  String text;
  try {
    text = elementToReplace.getText();
    final int offsetInParent = elementToReplace.getStartOffsetInParent();
    String textBeforeRange = text.substring(0, range.getStartOffset() - offsetInParent);
    String textAfterRange = text.substring(range.getEndOffset()- offsetInParent, text.length());
    newContent = element.getText().startsWith("'") || element.getText().endsWith("'") ?
                 newContent.replace("'", "&apos;") : newContent.replace("\"", "&quot;");
    text = textBeforeRange + newContent + textAfterRange;
  } catch(StringIndexOutOfBoundsException e) {
    LOG.error("Range: " + range + " in text: '" + element.getText() + "'", e);
    throw e;
  }
  final CharTable charTableByTree = SharedImplUtil.findCharTableByTree(attrNode);
  final LeafElement newValueElement = Factory.createSingleLeafElement(tokenType, text, charTableByTree, element.getManager());

  attrNode.replaceChildInternal(valueNode, newValueElement);
  return element;
}
项目:intellij-ce-playground    文件:XmlTagImpl.java   
@Override
public void collapseIfEmpty() {
  final XmlTag[] tags = getSubTags();
  if (tags.length > 0) {
    return;
  }
  final ASTNode closingName = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(this);
  final ASTNode startTagEnd = XmlChildRole.START_TAG_END_FINDER.findChild(this);
  if (closingName == null || startTagEnd == null) {
    return;
  }

  final PomModel pomModel = PomManager.getModel(getProject());
  final PomTransactionBase transaction = new PomTransactionBase(this, pomModel.getModelAspect(XmlAspect.class)) {

    @Override
    @Nullable
    public PomModelEvent runInner() {
      final ASTNode closingBracket = closingName.getTreeNext();
      removeRange(startTagEnd, closingBracket);
      final LeafElement emptyTagEnd = Factory.createSingleLeafElement(XmlTokenType.XML_EMPTY_ELEMENT_END, "/>", 0, 2, null, getManager());
      replaceChild(closingBracket, emptyTagEnd);
      return null;
    }
  };
  try {
    pomModel.runTransaction(transaction);
  }
  catch (IncorrectOperationException e) {
    LOG.error(e);
  }
}
项目:intellij-ce-playground    文件:XmlElementChangeUtil.java   
static void doNameReplacement(final PsiNamedElement xmlElementDecl, XmlElement nameElement, final String name) throws
                                                                                                               IncorrectOperationException {
  if (xmlElementDecl.isWritable() && isInProjectContent(xmlElementDecl.getProject(), xmlElementDecl.getContainingFile().getVirtualFile())) {

    if (nameElement!=null) {
      nameElement.replace(
        SourceTreeToPsiMap.treeElementToPsi(Factory.createSingleLeafElement(XmlTokenType.XML_NAME, name, null, xmlElementDecl.getManager()))
      );
    }
  }
}
项目:intellij-ce-playground    文件:PsiImplUtil.java   
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 == GroovyTokenTypes.mSEMI || type == TokenType.WHITE_SPACE && !next.getText().contains("\n")) {
      final PsiElement nnext = next.getNextSibling();
      container.deleteChildRange(next, next);
      next = nnext;
    }
    else if (type == GroovyTokenTypes.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, Factory.createSingleLeafElement(type, substring, 0, substring.length(), null, container.getManager()));
      return;
    }
    else {
      break;
    }
  }
}
项目:js-graphql-intellij-plugin    文件:JSGraphQLEndpointImportFileReferencePsiElement.java   
@Override
public PsiElement setName(@NonNls @NotNull String name) throws IncorrectOperationException {
    final PsiElement nameIdentifier = getNameIdentifier();
    if(nameIdentifier != null) {
        final LeafElement renamedLeaf = Factory.createSingleLeafElement(JSGraphQLEndpointTokenTypes.STRING_BODY, name, null, getManager());
        final PsiElement renamedPsiElement = SourceTreeToPsiMap.treeElementToPsi(renamedLeaf);
        if (renamedPsiElement != null) {
            nameIdentifier.replace(renamedPsiElement);
        }
    }
    return this;
}
项目:js-graphql-intellij-plugin    文件:JSGraphQLEndpointPsiUtil.java   
/**
 * Renames an identifier, e.g. during a refactoring
 */
public static PsiElement renameIdentifier(PsiNameIdentifierOwner owner, String name) throws IncorrectOperationException {
    final PsiElement identifier = owner.getNameIdentifier();
    if (identifier == null) {
        throw new IncorrectOperationException();
    }
    final LeafElement renamedLeaf = Factory.createSingleLeafElement(JSGraphQLEndpointTokenTypes.IDENTIFIER, name, null, identifier.getManager());
    final PsiElement renamedPsiElement = SourceTreeToPsiMap.treeElementToPsi(renamedLeaf);
    if (renamedPsiElement != null) {
        identifier.replace(renamedPsiElement);
    }
    return owner;
}
项目:tools-idea    文件:LanguageTokenSeparatorGenerators.java   
private LanguageTokenSeparatorGenerators() {
  super("com.intellij.lang.tokenSeparatorGenerator", new TokenSeparatorGenerator() {
    @Override
    public ASTNode generateWhitespaceBetweenTokens(ASTNode left, ASTNode right) {
      Language l = PsiUtilCore.getNotAnyLanguage(left);
      Language rightLang = PsiUtilCore.getNotAnyLanguage(right);
      if (rightLang.isKindOf(l)) {
        l = rightLang; // get more precise lexer
      }
      final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(l);
      if (parserDefinition != null) {
        PsiManager manager = right.getTreeParent().getPsi().getManager();
        ASTNode generatedWhitespace;
        //noinspection EnumSwitchStatementWhichMissesCases
        switch(parserDefinition.spaceExistanceTypeBetweenTokens(left, right)){
          case MUST:
            generatedWhitespace = Factory.createSingleLeafElement(TokenType.WHITE_SPACE, " ", 0, 1, null, manager);
            break;
          case MUST_LINE_BREAK:
            generatedWhitespace = Factory.createSingleLeafElement(TokenType.WHITE_SPACE, "\n", 0, 1, null, manager);
            break;
          default:
            generatedWhitespace = null;
        }
        return generatedWhitespace;
      }
      return null;
    }
  });
}
项目:tools-idea    文件:XmlTagImpl.java   
@Override
public void collapseIfEmpty() {
  final XmlTag[] tags = getSubTags();
  if (tags.length > 0) {
    return;
  }
  final ASTNode closingName = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(this);
  final ASTNode startTagEnd = XmlChildRole.START_TAG_END_FINDER.findChild(this);
  if (closingName == null || startTagEnd == null) {
    return;
  }

  final PomModel pomModel = PomManager.getModel(getProject());
  final PomTransactionBase transaction = new PomTransactionBase(this, pomModel.getModelAspect(XmlAspect.class)) {

    @Override
    @Nullable
    public PomModelEvent runInner() {
      final ASTNode closingBracket = closingName.getTreeNext();
      removeRange(startTagEnd, closingBracket);
      final LeafElement emptyTagEnd = Factory.createSingleLeafElement(XmlTokenType.XML_EMPTY_ELEMENT_END, "/>", 0, 2, null, getManager());
      replaceChild(closingBracket, emptyTagEnd);
      return null;
    }
  };
  try {
    pomModel.runTransaction(transaction);
  }
  catch (IncorrectOperationException e) {
    LOG.error(e);
  }
}
项目:tools-idea    文件:XmlElementChangeUtil.java   
static void doNameReplacement(final PsiNamedElement xmlElementDecl, XmlElement nameElement, final String name) throws
                                                                                                               IncorrectOperationException {
  if (xmlElementDecl.isWritable() && isInProjectContent(xmlElementDecl.getProject(), xmlElementDecl.getContainingFile().getVirtualFile())) {

    if (nameElement!=null) {
      nameElement.replace(
        SourceTreeToPsiMap.treeElementToPsi(Factory.createSingleLeafElement(XmlTokenType.XML_NAME, name, null, xmlElementDecl.getManager()))
      );
    }
  }
}
项目:tools-idea    文件:XmlAttributeValueManipulator.java   
public static <T extends PsiElement> T handleContentChange(T element,
                                                           TextRange range,
                                                           String newContent,
                                                           final IElementType tokenType) {
  CheckUtil.checkWritable(element);
  final CompositeElement attrNode = (CompositeElement)element.getNode();
  final ASTNode valueNode = attrNode.findLeafElementAt(range.getStartOffset());
  LOG.assertTrue(valueNode != null, "Leaf not found in " + attrNode + " at offset " + range.getStartOffset() + " in element " + element);
  final PsiElement elementToReplace = valueNode.getPsi();

  String text;
  try {
    text = elementToReplace.getText();
    final int offsetInParent = elementToReplace.getStartOffsetInParent();
    String textBeforeRange = text.substring(0, range.getStartOffset() - offsetInParent);
    String textAfterRange = text.substring(range.getEndOffset()- offsetInParent, text.length());
    text = textBeforeRange + newContent + textAfterRange;
  } catch(StringIndexOutOfBoundsException e) {
    LOG.error("Range: " + range + " in text: '" + element.getText() + "'", e);
    throw e;
  }
  final CharTable charTableByTree = SharedImplUtil.findCharTableByTree(attrNode);
  final LeafElement newValueElement = Factory.createSingleLeafElement(tokenType, text, charTableByTree, element.getManager());

  attrNode.replaceChildInternal(valueNode, newValueElement);
  return element;
}
项目:tools-idea    文件:GrBlockImpl.java   
@NotNull
public GrStatement addStatementBefore(@NotNull GrStatement element, @Nullable GrStatement anchor) throws IncorrectOperationException {
  if (anchor == null && getRBrace() == null) {
    throw new IncorrectOperationException();
  }

  if (anchor != null && !this.equals(anchor.getParent())) {
    throw new IncorrectOperationException();
  }

  final LeafElement nls = Factory.createSingleLeafElement(GroovyTokenTypes.mNLS, "\n", 0, 1, null, getManager());

  PsiElement actualAnchor = anchor == null ? getRBrace() : anchor;
  if (mayUseNewLinesAsSeparators()) {
    PsiElement prev = actualAnchor.getPrevSibling();
    if (prev instanceof GrParameterList && prev.getTextLength() == 0 && prev.getPrevSibling() != null) {
      prev = prev.getPrevSibling();
    }
    if (!PsiUtil.isLineFeed(prev)) {
      addBefore(nls.getPsi(), actualAnchor);
    }
  }
  element = (GrStatement)addBefore(element, actualAnchor);
  if (mayUseNewLinesAsSeparators()) {
    addBefore(nls.getPsi(), actualAnchor);
  }
  else {
    addBefore(Factory.createSingleLeafElement(GroovyTokenTypes.mNLS, "\n", 0, 1, null, getManager()).getPsi(), actualAnchor);
  }
  return element;
}
项目:consulo-csharp    文件:CSharpDeclarationMover.java   
@RequiredReadAction
@Override
public void beforeMove(@NotNull final Editor editor, @NotNull final MoveInfo info, final boolean down)
{
    super.beforeMove(editor, info, down);

    if(myEnumToInsertSemicolonAfter != null)
    {
        TreeElement semicolon = Factory.createSingleLeafElement(CSharpTokens.SEMICOLON, ";", 0, 1, null, myEnumToInsertSemicolonAfter.getManager());

        try
        {
            PsiElement inserted = myEnumToInsertSemicolonAfter.getParent().addAfter(semicolon.getPsi(), myEnumToInsertSemicolonAfter);
            inserted = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(inserted);
            final LogicalPosition position = editor.offsetToLogicalPosition(inserted.getTextRange().getEndOffset());

            info.toMove2 = new LineRange(position.line + 1, position.line + 1);
        }
        catch(IncorrectOperationException e)
        {
            LOG.error(e);
        }
        finally
        {
            myEnumToInsertSemicolonAfter = null;
        }
    }
}
项目:consulo    文件:LanguageTokenSeparatorGenerators.java   
private LanguageTokenSeparatorGenerators() {
  super("com.intellij.lang.tokenSeparatorGenerator", new TokenSeparatorGenerator() {
    @Override
    public ASTNode generateWhitespaceBetweenTokens(ASTNode left, ASTNode right) {
      Language l = PsiUtilCore.getNotAnyLanguage(left);
      Language rightLang = PsiUtilCore.getNotAnyLanguage(right);
      if (rightLang.isKindOf(l)) {
        l = rightLang; // get more precise lexer
      }
      final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(l);
      if (parserDefinition != null) {
        PsiManager manager = right.getTreeParent().getPsi().getManager();
        ASTNode generatedWhitespace;
        //noinspection EnumSwitchStatementWhichMissesCases
        switch(parserDefinition.spaceExistanceTypeBetweenTokens(left, right)){
          case MUST:
            generatedWhitespace = Factory.createSingleLeafElement(TokenType.WHITE_SPACE, " ", 0, 1, null, manager);
            break;
          case MUST_LINE_BREAK:
            generatedWhitespace = Factory.createSingleLeafElement(TokenType.WHITE_SPACE, "\n", 0, 1, null, manager);
            break;
          default:
            generatedWhitespace = null;
        }
        return generatedWhitespace;
      }
      return null;
    }
  });
}
项目:consulo    文件:PsiBuilderImpl.java   
private void bind(@Nonnull StartMarker rootMarker, @Nonnull CompositeElement rootNode) {
  StartMarker curMarker = rootMarker;
  CompositeElement curNode = rootNode;

  int lexIndex = rootMarker.myLexemeIndex;
  ProductionMarker item = rootMarker.myFirstChild != null ? rootMarker.myFirstChild : rootMarker.myDoneMarker;
  while (true) {
    lexIndex = insertLeaves(lexIndex, item.myLexemeIndex, curNode);

    if (item == rootMarker.myDoneMarker) break;

    if (item instanceof StartMarker) {
      final StartMarker marker = (StartMarker)item;
      if (!marker.myDoneMarker.myCollapse) {
        curMarker = marker;

        final CompositeElement childNode = createComposite(marker);
        curNode.rawAddChildrenWithoutNotifications(childNode);
        curNode = childNode;

        item = marker.myFirstChild != null ? marker.myFirstChild : marker.myDoneMarker;
        continue;
      }
      else {
        lexIndex = collapseLeaves(curNode, marker);
      }
    }
    else if (item instanceof ErrorItem) {
      final CompositeElement errorElement = Factory.createErrorElement(((ErrorItem)item).myMessage);
      curNode.rawAddChildrenWithoutNotifications(errorElement);
    }
    else if (item instanceof DoneMarker) {
      curMarker = (StartMarker)((DoneMarker)item).myStart.myParent;
      curNode = curNode.getTreeParent();
      item = ((DoneMarker)item).myStart;
    }

    item = item.myNext != null ? item.myNext : curMarker.myDoneMarker;
  }
}
项目:consulo    文件:PsiBuilderImpl.java   
@Nonnull
private static CompositeElement createComposite(@Nonnull StartMarker marker) {
  final IElementType type = marker.myType;
  if (type == TokenType.ERROR_ELEMENT) {
    String message = marker.myDoneMarker instanceof DoneWithErrorMarker ? ((DoneWithErrorMarker)marker.myDoneMarker).myMessage : null;
    return Factory.createErrorElement(message);
  }

  if (type == null) {
    throw new RuntimeException(UNBALANCED_MESSAGE);
  }

  return ASTFactory.composite(type);
}
项目:consulo-xml    文件:XmlTagImpl.java   
@Override
public void collapseIfEmpty()
{
    final XmlTag[] tags = getSubTags();
    if(tags.length > 0)
    {
        return;
    }
    final ASTNode closingName = XmlChildRole.CLOSING_TAG_NAME_FINDER.findChild(this);
    final ASTNode startTagEnd = XmlChildRole.START_TAG_END_FINDER.findChild(this);
    if(closingName == null || startTagEnd == null)
    {
        return;
    }

    final PomModel pomModel = PomManager.getModel(getProject());
    final PomTransactionBase transaction = new PomTransactionBase(this, pomModel.getModelAspect(XmlAspect.class))
    {

        @Override
        @Nullable
        public PomModelEvent runInner()
        {
            final ASTNode closingBracket = closingName.getTreeNext();
            removeRange(startTagEnd, closingBracket);
            final LeafElement emptyTagEnd = Factory.createSingleLeafElement(XmlTokenType.XML_EMPTY_ELEMENT_END, "/>", 0, 2, null, getManager());
            replaceChild(closingBracket, emptyTagEnd);
            return null;
        }
    };
    try
    {
        pomModel.runTransaction(transaction);
    }
    catch(IncorrectOperationException e)
    {
        LOG.error(e);
    }
}
项目:consulo-xml    文件:XmlElementChangeUtil.java   
static void doNameReplacement(final PsiNamedElement xmlElementDecl, XmlElement nameElement, final String name) throws
                                                                                                               IncorrectOperationException {
  if (xmlElementDecl.isWritable() && isInProjectContent(xmlElementDecl.getProject(), xmlElementDecl.getContainingFile().getVirtualFile())) {

    if (nameElement!=null) {
      nameElement.replace(
        SourceTreeToPsiMap.treeElementToPsi(Factory.createSingleLeafElement(XmlTokenType.XML_NAME, name, null, xmlElementDecl.getManager()))
      );
    }
  }
}
项目:consulo-xml    文件:XmlAttributeValueManipulator.java   
public static <T extends PsiElement> T handleContentChange(T element,
                                                           TextRange range,
                                                           String newContent,
                                                           final IElementType tokenType) {
  CheckUtil.checkWritable(element);
  final CompositeElement attrNode = (CompositeElement)element.getNode();
  final ASTNode valueNode = attrNode.findLeafElementAt(range.getStartOffset());
  LOG.assertTrue(valueNode != null, "Leaf not found in " + attrNode + " at offset " + range.getStartOffset() + " in element " + element);
  final PsiElement elementToReplace = valueNode.getPsi();

  String text;
  try {
    text = elementToReplace.getText();
    final int offsetInParent = elementToReplace.getStartOffsetInParent();
    String textBeforeRange = text.substring(0, range.getStartOffset() - offsetInParent);
    String textAfterRange = text.substring(range.getEndOffset()- offsetInParent, text.length());
    text = textBeforeRange + newContent + textAfterRange;
  } catch(StringIndexOutOfBoundsException e) {
    LOG.error("Range: " + range + " in text: '" + element.getText() + "'", e);
    throw e;
  }
  final CharTable charTableByTree = SharedImplUtil.findCharTableByTree(attrNode);
  final LeafElement newValueElement = Factory.createSingleLeafElement(tokenType, text, charTableByTree, element.getManager());

  attrNode.replaceChildInternal(valueNode, newValueElement);
  return element;
}
项目:consulo-java    文件:PsiReferenceExpressionImpl.java   
@Override
public void setQualifierExpression(@Nullable PsiExpression newQualifier) throws IncorrectOperationException
{
    final PsiExpression oldQualifier = getQualifierExpression();
    if(newQualifier == null)
    {
        if(oldQualifier != null)
        {
            deleteChildInternal(oldQualifier.getNode());
        }
    }
    else
    {
        if(oldQualifier != null)
        {
            oldQualifier.replace(newQualifier);
        }
        else
        {
            final CharTable treeCharTab = SharedImplUtil.findCharTableByTree(this);
            TreeElement dot = (TreeElement) findChildByRole(ChildRole.DOT);
            if(dot == null)
            {
                dot = Factory.createSingleLeafElement(JavaTokenType.DOT, ".", 0, 1, treeCharTab, getManager());
                dot = addInternal(dot, dot, getFirstChildNode(), Boolean.TRUE);
            }
            addBefore(newQualifier, dot.getPsi());
        }
    }
}
项目:consulo-java    文件:PsiFieldImpl.java   
@Override
public void normalizeDeclaration() throws IncorrectOperationException
{
    CheckUtil.checkWritable(this);

    final PsiTypeElement type = getTypeElement();
    PsiElement modifierList = getModifierList();
    ASTNode field = SourceTreeToPsiMap.psiElementToTree(type.getParent());
    while(true)
    {
        ASTNode comma = PsiImplUtil.skipWhitespaceAndComments(field.getTreeNext());
        if(comma == null || comma.getElementType() != JavaTokenType.COMMA)
        {
            break;
        }
        ASTNode nextField = PsiImplUtil.skipWhitespaceAndComments(comma.getTreeNext());
        if(nextField == null || nextField.getElementType() != JavaElementType.FIELD)
        {
            break;
        }

        TreeElement semicolon = Factory.createSingleLeafElement(JavaTokenType.SEMICOLON, ";", 0, 1, null, getManager());
        CodeEditUtil.addChild(field, semicolon, null);

        CodeEditUtil.removeChild(comma.getTreeParent(), comma);

        PsiElement typeClone = type.copy();
        CodeEditUtil.addChild(nextField, SourceTreeToPsiMap.psiElementToTree(typeClone), nextField.getFirstChildNode());

        PsiElement modifierListClone = modifierList.copy();
        CodeEditUtil.addChild(nextField, SourceTreeToPsiMap.psiElementToTree(modifierListClone), nextField.getFirstChildNode());

        field = nextField;
    }

    JavaSharedImplUtil.normalizeBrackets(this);
}
项目:intellij-ce-playground    文件:PsiModifierListImpl.java   
@Override
public void setModifierProperty(@NotNull String name, boolean value) throws IncorrectOperationException{
  checkSetModifierProperty(name, value);

  PsiElement parent = getParent();
  PsiElement grandParent = parent != null ? parent.getParent() : null;
  IElementType type = NAME_TO_KEYWORD_TYPE_MAP.get(name);
  CompositeElement treeElement = (CompositeElement)getNode();

  // There is a possible case that parameters list occupies more than one line and its elements are aligned. Modifiers list change
  // changes horizontal position of parameters list start, hence, we need to reformat them in order to preserve alignment.
  if (parent instanceof PsiMethod) {
    PsiMethod method = (PsiMethod)parent;
    CodeEditUtil.markToReformat(method.getParameterList().getNode(), true);
  }

  if (value) {
    if (type == JavaTokenType.PUBLIC_KEYWORD ||
        type == JavaTokenType.PRIVATE_KEYWORD ||
        type == JavaTokenType.PROTECTED_KEYWORD ||
        type == null /* package local */) {
      if (type != JavaTokenType.PUBLIC_KEYWORD) {
        setModifierProperty(PsiModifier.PUBLIC, false);
      }
      if (type != JavaTokenType.PRIVATE_KEYWORD) {
        setModifierProperty(PsiModifier.PRIVATE, false);
      }
      if (type != JavaTokenType.PROTECTED_KEYWORD) {
        setModifierProperty(PsiModifier.PROTECTED, false);
      }
      if (type == null) return;
    }

    if (parent instanceof PsiField && grandParent instanceof PsiClass && ((PsiClass)grandParent).isInterface()) {
      if (type == JavaTokenType.PUBLIC_KEYWORD || type == JavaTokenType.STATIC_KEYWORD || type == JavaTokenType.FINAL_KEYWORD) return;
    }
    else if (parent instanceof PsiMethod && grandParent instanceof PsiClass && ((PsiClass)grandParent).isInterface()) {
      if (type == JavaTokenType.PUBLIC_KEYWORD || type == JavaTokenType.ABSTRACT_KEYWORD) return;
    }
    else if (parent instanceof PsiClass && grandParent instanceof PsiClass && ((PsiClass)grandParent).isInterface()) {
      if (type == JavaTokenType.PUBLIC_KEYWORD) return;
    }
    else if (parent instanceof PsiAnnotationMethod && grandParent instanceof PsiClass && ((PsiClass)grandParent).isAnnotationType()) {
      if (type == JavaTokenType.PUBLIC_KEYWORD || type == JavaTokenType.ABSTRACT_KEYWORD) return;
    }

    if (treeElement.findChildByType(type) == null) {
      TreeElement keyword = Factory.createSingleLeafElement(type, name, null, getManager());
      treeElement.addInternal(keyword, keyword, null, null);
    }
  }
  else {
    if (type == null /* package local */) {
      throw new IncorrectOperationException("Cannot reset package local modifier."); //?
    }

    ASTNode child = treeElement.findChildByType(type);
    if (child != null) {
      SourceTreeToPsiMap.treeToPsiNotNull(child).delete();
    }
  }
}
项目:intellij-ce-playground    文件:CodeEditUtil.java   
@Nullable
public static PsiElement createLineFeed(final PsiManager manager) {
  return Factory.createSingleLeafElement(TokenType.WHITE_SPACE, "\n", 0, 1, null, manager).getPsi();
}
项目:intellij-ce-playground    文件:PyTokenSeparatorGenerator.java   
private static ASTNode createWhitespace(PsiManager manager, final String text) {
  return Factory.createSingleLeafElement(TokenType.WHITE_SPACE, text, 0, text.length(), null, manager);
}
项目:js-graphql-intellij-plugin    文件:JSGraphQLNamedPsiElement.java   
@Override
public PsiReference getReference() {

    if(reference == null) {

        final PsiElement self = this;
        reference = new PsiReferenceBase<JSGraphQLPsiElement>(this, TextRange.from(0, self.getTextLength())) {

            private JSGraphQLSchemaLanguageProjectService service;
            private PsiElement cachedResolvedReference;
            private int cachedSchemaVersion = -1;

            @Nullable
            @Override
            public PsiElement resolve() {
                if(!self.isValid()) {
                    return null;
                }
                if(service == null) {
                    service = JSGraphQLSchemaLanguageProjectService.getService(self.getProject());
                }
                if(service.hasEndpointEntryFile()) {
                    // with the endpoint language in use we can't cache the reference here
                    // since endpoint language files are editable
                    return service.getReference(self);
                }
                final int currentSchemaVersion = service.getSchemaVersion();
                if(currentSchemaVersion != cachedSchemaVersion) {
                    cachedSchemaVersion = currentSchemaVersion;
                    cachedResolvedReference = service.getReference(self);
                }
                return cachedResolvedReference;
            }

            @NotNull
            @Override
            public Object[] getVariants() {
                // variants appears to filter the shown completions -- but should be okay for now inside a single property/type name
                return NO_VARIANTS;
            }

            @Override
            public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
                PsiElement nameIdentifier = getNameIdentifier();
                if(nameIdentifier != null) {
                    final PsiElement psiLeaf = nameIdentifier.getFirstChild() != null ? nameIdentifier.getFirstChild() : nameIdentifier;
                    final LeafElement renamedLeaf = Factory.createSingleLeafElement(psiLeaf.getNode().getElementType(), newElementName, null, nameIdentifier.getManager());
                    final PsiElement renamedPsiElement = SourceTreeToPsiMap.treeElementToPsi(renamedLeaf);
                    if (renamedPsiElement != null) {
                        psiLeaf.replace(renamedPsiElement);
                    }
                    return self;
                } else {
                    throw new IncorrectOperationException();
                }
            }
        };
    }
    return reference;
}
项目:tools-idea    文件:PsiModifierListImpl.java   
@Override
public void setModifierProperty(@NotNull String name, boolean value) throws IncorrectOperationException{
  checkSetModifierProperty(name, value);

  PsiElement parent = getParent();
  PsiElement grandParent = parent != null ? parent.getParent() : null;
  IElementType type = NAME_TO_KEYWORD_TYPE_MAP.get(name);
  CompositeElement treeElement = (CompositeElement)getNode();

  // There is a possible case that parameters list occupies more than one line and its elements are aligned. Modifiers list change
  // changes horizontal position of parameters list start, hence, we need to reformat them in order to preserve alignment.
  if (parent instanceof PsiMethod) {
    PsiMethod method = (PsiMethod)parent;
    CodeEditUtil.markToReformat(method.getParameterList().getNode(), true);
  }

  if (value) {
    if (type == JavaTokenType.PUBLIC_KEYWORD ||
        type == JavaTokenType.PRIVATE_KEYWORD ||
        type == JavaTokenType.PROTECTED_KEYWORD ||
        type == null /* package local */) {
      if (type != JavaTokenType.PUBLIC_KEYWORD) {
        setModifierProperty(PsiModifier.PUBLIC, false);
      }
      if (type != JavaTokenType.PRIVATE_KEYWORD) {
        setModifierProperty(PsiModifier.PRIVATE, false);
      }
      if (type != JavaTokenType.PROTECTED_KEYWORD) {
        setModifierProperty(PsiModifier.PROTECTED, false);
      }
      if (type == null) return;
    }

    if (parent instanceof PsiField && grandParent instanceof PsiClass && ((PsiClass)grandParent).isInterface()) {
      if (type == JavaTokenType.PUBLIC_KEYWORD || type == JavaTokenType.STATIC_KEYWORD || type == JavaTokenType.FINAL_KEYWORD) return;
    }
    else if (parent instanceof PsiMethod && grandParent instanceof PsiClass && ((PsiClass)grandParent).isInterface()) {
      if (type == JavaTokenType.PUBLIC_KEYWORD || type == JavaTokenType.ABSTRACT_KEYWORD) return;
    }
    else if (parent instanceof PsiClass && grandParent instanceof PsiClass && ((PsiClass)grandParent).isInterface()) {
      if (type == JavaTokenType.PUBLIC_KEYWORD) return;
    }
    else if (parent instanceof PsiAnnotationMethod && grandParent instanceof PsiClass && ((PsiClass)grandParent).isAnnotationType()) {
      if (type == JavaTokenType.PUBLIC_KEYWORD || type == JavaTokenType.ABSTRACT_KEYWORD) return;
    }

    if (treeElement.findChildByType(type) == null) {
      TreeElement keyword = Factory.createSingleLeafElement(type, name, null, getManager());
      treeElement.addInternal(keyword, keyword, null, null);
    }
  }
  else {
    if (type == null /* package local */) {
      throw new IncorrectOperationException("Cannot reset package local modifier."); //?
    }

    ASTNode child = treeElement.findChildByType(type);
    if (child != null) {
      SourceTreeToPsiMap.treeToPsiNotNull(child).delete();
    }
  }
}
项目:tools-idea    文件:CodeEditUtil.java   
@Nullable
public static PsiElement createLineFeed(final PsiManager manager) {
  return Factory.createSingleLeafElement(TokenType.WHITE_SPACE, "\n", 0, 1, null, manager).getPsi();
}
项目:consulo    文件:CodeEditUtil.java   
@Nullable
public static PsiElement createLineFeed(final PsiManager manager) {
  return Factory.createSingleLeafElement(TokenType.WHITE_SPACE, "\n", 0, 1, null, manager).getPsi();
}