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

The following examples show how to use com.intellij.psi.impl.source.tree.LeafElement. 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: BuildFileRunLineMarkerContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static FuncallExpression getRuleFuncallExpression(PsiElement element) {
  PsiFile parentFile = element.getContainingFile();
  if (!(parentFile instanceof BuildFile)
      || ((BuildFile) parentFile).getBlazeFileType() != BlazeFileType.BuildPackage) {
    return null;
  }
  if (!(element instanceof LeafElement)
      || element instanceof PsiWhiteSpace
      || element instanceof PsiComment) {
    return null;
  }
  if (!(element.getParent() instanceof ReferenceExpression)) {
    return null;
  }
  PsiElement grandParent = element.getParent().getParent();
  return grandParent instanceof FuncallExpression
          && ((FuncallExpression) grandParent).isTopLevel()
      ? (FuncallExpression) grandParent
      : null;
}
 
Example #2
Source File: DuplocatorUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean isIgnoredNode(PsiElement element) {
  // ex. "var i = 0" in AS: empty JSAttributeList should be skipped
  /*if (element.getText().length() == 0) {
    return true;
  }*/

  if (element instanceof PsiWhiteSpace || element instanceof PsiErrorElement || element instanceof PsiComment) {
    return true;
  }

  if (!(element instanceof LeafElement)) {
    return false;
  }

  if (CharArrayUtil.containsOnlyWhiteSpaces(element.getText())) {
    return true;
  }

  EquivalenceDescriptorProvider descriptorProvider = EquivalenceDescriptorProvider.getInstance(element);
  if (descriptorProvider == null) {
    return false;
  }

  final IElementType elementType = ((LeafElement)element).getElementType();
  return descriptorProvider.getIgnoredTokens().contains(elementType);
}
 
Example #3
Source File: NodeSpecificHasherBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public int getNodeHash(PsiElement node) {
  if (node == null) {
    return 0;
  }
  if (node instanceof PsiWhiteSpace || node instanceof PsiErrorElement) {
    return 0;
  }
  else if (node instanceof LeafElement) {
    if (isToSkipAsLiteral(node)) {
      return 0;
    }
    return node.getText().hashCode();

  }
  return node.getClass().getName().hashCode();
}
 
Example #4
Source File: SampleASTFactory.java    From jetbrains-plugin-sample with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Create a parse tree (AST) leaf node from a token. Doubles as a PSI leaf node.
 *  Does not see whitespace tokens.  Default impl makes {@link LeafPsiElement}
 *  or {@link PsiCoreCommentImpl} depending on {@link ParserDefinition#getCommentTokens()}.
 */
@NotNull
@Override
public LeafElement createLeaf(@NotNull IElementType type, CharSequence text) {
	if ( type instanceof TokenIElementType &&
		 ((TokenIElementType) type).getANTLRTokenType()==SampleLanguageLexer.ID)
	{
		// found an ID node; here we do not distinguish between definitions and references
		// because we have no context information here. All we know is that
		// we have an identifier node that will be connected somewhere in a tree.
		//
		// You can only rename, find usages, etc... on leaves implementing PsiNamedElement
		//
		// TODO: try not to create one for IDs under def subtree roots like vardef, function
		return new IdentifierPSINode(type, text);
	}
	LeafElement leaf = super.createLeaf(type, text);
	return leaf;
   }
 
Example #5
Source File: DefaultASTLeafFactory.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public LeafElement createLeaf(@Nonnull IElementType type, @Nonnull LanguageVersion languageVersion, @Nonnull CharSequence text) {
  final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(type.getLanguage());
  if(parserDefinition != null) {
    if(parserDefinition.getCommentTokens(languageVersion).contains(type)) {
      return new PsiCoreCommentImpl(type, text);
    }
  }

  // this is special case, then type is WHITE_SPACE, but no parser definition
  if(type == TokenType.WHITE_SPACE) {
    return new PsiWhiteSpaceImpl(text);
  }

  if (type instanceof ILeafElementType) {
    return (LeafElement)((ILeafElementType)type).createLeafNode(text);
  }
  return new LeafPsiElement(type, text);
}
 
Example #6
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 #7
Source File: PsiParserFacadeImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public PsiElement createWhiteSpaceFromText(@Nonnull @NonNls String text) throws IncorrectOperationException {
  final FileElement holderElement = DummyHolderFactory.createHolder(myManager, null).getTreeElement();
  final LeafElement newElement = ASTFactory.leaf(TokenType.WHITE_SPACE, holderElement.getCharTable().intern(text));
  holderElement.rawAddChildren(newElement);
  GeneratedMarkerVisitor.markGenerated(newElement.getPsi());
  return newElement.getPsi();
}
 
Example #8
Source File: DuplocatorUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean shouldSkip(PsiElement element, PsiElement elementToMatchWith) {
  if (element == null || elementToMatchWith == null) {
    return false;
  }

  if (element.getClass() == elementToMatchWith.getClass()) {
    return false;
  }

  if (element.getFirstChild() == null && element.getTextLength() == 0 && !(element instanceof LeafElement)) {
    return true;
  }

  return false;
}
 
Example #9
Source File: NodeSpecificHasherBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean isLiteral(PsiElement node) {
  if (node instanceof LeafElement) {
    final IElementType elementType = ((LeafElement)node).getElementType();
    if (myDuplicatesProfile.getLiterals().contains(elementType)) {
      return true;
    }
  }
  return false;
}
 
Example #10
Source File: SimpleTreePatcher.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public LeafElement split(LeafElement leaf, int offset, final CharTable table) {
  final CharSequence chars = leaf.getChars();
  final LeafElement leftPart = ASTFactory.leaf(leaf.getElementType(), table.intern(chars, 0, offset));
  final LeafElement rightPart = ASTFactory.leaf(leaf.getElementType(), table.intern(chars, offset, chars.length()));
  leaf.rawInsertAfterMe(leftPart);
  leftPart.rawInsertAfterMe(rightPart);
  leaf.rawRemove();
  return leftPart;
}
 
Example #11
Source File: CodeEditUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static ASTNode findFirstLeaf(ASTNode first, ASTNode last) {
  do {
    final LeafElement leaf = TreeUtil.findFirstLeaf(first);
    if (leaf != null) return leaf;
    first = first.getTreeNext();
    if (first == null) return null;
  }
  while (first != last);
  return null;
}
 
Example #12
Source File: CodeEditUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void replaceChild(ASTNode parent, @Nonnull ASTNode oldChild, @Nonnull ASTNode newChild) {
  saveWhitespacesInfo(oldChild);
  saveWhitespacesInfo(newChild);
  checkForOuters(oldChild);
  checkForOuters(newChild);

  LeafElement oldFirst = TreeUtil.findFirstLeaf(oldChild);

  parent.replaceChild(oldChild, newChild);
  final LeafElement firstLeaf = TreeUtil.findFirstLeaf(newChild);
  final ASTNode prevToken = TreeUtil.prevLeaf(newChild);
  if (firstLeaf != null) {
    final ASTNode nextLeaf = TreeUtil.nextLeaf(newChild);
    makePlaceHolderBetweenTokens(prevToken, firstLeaf, isFormattingRequired(prevToken, newChild), false);
    if (nextLeaf != null && !CharArrayUtil.containLineBreaks(nextLeaf.getText())) {
      makePlaceHolderBetweenTokens(TreeUtil.prevLeaf(nextLeaf), nextLeaf, false, false);
    }
  }
  else {
    if (oldFirst != null && prevToken == null) {
      ASTNode whitespaceNode = newChild.getTreeNext();
      if (whitespaceNode != null && whitespaceNode.getElementType() == TokenType.WHITE_SPACE) {
        // Replacing non-empty prefix to empty shall remove whitespace
        parent.removeChild(whitespaceNode);
      }
    }

    makePlaceHolderBetweenTokens(prevToken, TreeUtil.nextLeaf(newChild), isFormattingRequired(prevToken, newChild), false);
  }
}
 
Example #13
Source File: TestLineMarkerContributor.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
@Override
public Info getInfo(@NotNull PsiElement element) {
  // We look for leaf nodes of a PSI tree matching the pattern of a Dart unit test, and place
  // the line marker at that leaf node; see #4036 for some background.
  //
  // The pattern we're matching below is:
  // DartCallExpression
  //   DartReferenceExpression
  //     DartId
  //       LeafPsiElement
  if (element instanceof LeafElement && element.getParent() instanceof DartId) {
    final DartId dartId = (DartId)element.getParent();

    if (dartId.getParent() != null && dartId.getParent().getParent() instanceof DartCallExpression) {
      final DartCallExpression dartCallExpression = (DartCallExpression)dartId.getParent().getParent();
      final TestType testCall = testConfigUtils.asTestCall(dartCallExpression);
      if (testCall != null) {
        final Icon icon = getTestStateIcon(element, testCall.getIcon());
        final Function<PsiElement, String> tooltipProvider =
          psiElement -> testCall.getTooltip(psiElement, testConfigUtils);
        return new RunLineMarkerContributor.Info(icon, tooltipProvider, ExecutorAction.getActions());
      }
    }
  }

  return null;
}
 
Example #14
Source File: GraphQLIdentifierManipulator.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Override
public GraphQLIdentifierImpl handleContentChange(@NotNull GraphQLIdentifierImpl element, @NotNull TextRange range, String newContent) throws IncorrectOperationException {
    // replace the NAME leaf element inside the identifier
    final LeafElement renamedLeaf = Factory.createSingleLeafElement(GraphQLElementTypes.NAME, newContent, null, element.getManager());
    final PsiElement renamedPsiElement = SourceTreeToPsiMap.treeElementToPsi(renamedLeaf);
    if (renamedPsiElement != null) {
        element.getFirstChild().replace(renamedPsiElement);
    }
    return element;

}
 
Example #15
Source File: TestLineMarkerContributor.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
@Override
public Info getInfo(@NotNull PsiElement element) {
  // We look for leaf nodes of a PSI tree matching the pattern of a Dart unit test, and place
  // the line marker at that leaf node; see #4036 for some background.
  //
  // The pattern we're matching below is:
  // DartCallExpression
  //   DartReferenceExpression
  //     DartId
  //       LeafPsiElement
  if (element instanceof LeafElement && element.getParent() instanceof DartId) {
    final DartId dartId = (DartId)element.getParent();

    if (dartId.getParent() != null && dartId.getParent().getParent() instanceof DartCallExpression) {
      final DartCallExpression dartCallExpression = (DartCallExpression)dartId.getParent().getParent();
      final TestType testCall = testConfigUtils.asTestCall(dartCallExpression);
      if (testCall != null) {
        final Icon icon = getTestStateIcon(element, testCall.getIcon());
        final Function<PsiElement, String> tooltipProvider =
          psiElement -> testCall.getTooltip(psiElement, testConfigUtils);
        return new RunLineMarkerContributor.Info(icon, tooltipProvider, ExecutorAction.getActions());
      }
    }
  }

  return null;
}
 
Example #16
Source File: ProjectViewParserIntegrationTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
private void nodeToString(PsiElement psi, StringBuilder builder) {
  if (psi.getNode() instanceof LeafElement) {
    return;
  }
  PsiElement[] children =
      Arrays.stream(psi.getChildren())
          .filter(t -> t instanceof ProjectViewPsiElement)
          .toArray(PsiElement[]::new);
  if (psi instanceof ProjectViewPsiElement) {
    builder.append(psi.getNode().getElementType());
    appendChildren(children, builder, true);
  } else {
    appendChildren(children, builder, false);
  }
}
 
Example #17
Source File: BuildParserTest.java    From intellij with Apache License 2.0 5 votes vote down vote up
private void nodeToString(ASTNode node, StringBuilder builder) {
  if (node instanceof LeafElement || node.getPsi() == null) {
    return;
  }
  PsiElement[] childPsis = getChildBuildPsis(node);
  if (node instanceof FileASTNode) {
    appendChildren(childPsis, builder, false);
    return;
  }
  builder.append(node.getElementType());
  appendChildren(childPsis, builder, true);
}
 
Example #18
Source File: GraphQLNamedElementImpl.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Override
public PsiElement setName(@NotNull String newName) throws IncorrectOperationException {
    final GraphQLIdentifier nameIdentifier = getNameIdentifier();
    if (nameIdentifier != null) {
        final LeafElement renamedLeaf = Factory.createSingleLeafElement(GraphQLElementTypes.NAME, newName, null, nameIdentifier.getManager());
        final PsiElement renamedPsiElement = SourceTreeToPsiMap.treeElementToPsi(renamedLeaf);
        if (renamedPsiElement != null) {
            nameIdentifier.getFirstChild().replace(renamedPsiElement);
        }
    }
    return this;
}
 
Example #19
Source File: JSGraphQLEndpointImportFileReferencePsiElement.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@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;
}
 
Example #20
Source File: JSGraphQLEndpointPsiUtil.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example #21
Source File: HaxeAstFactory.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public LeafElement createLeaf(IElementType type, CharSequence text) {
  if (HaxeTokenTypeSets.COMMENTS.contains(type)) {
    return new PsiCommentImpl(type, text);
  }

  return new HaxePsiTokenImpl(type, text);
}
 
Example #22
Source File: WhiteSpaceFormattingStrategyAdapter.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean addWhitespace(@Nonnull ASTNode treePrev, @Nonnull LeafElement whiteSpaceElement) {
  return false;
}
 
Example #23
Source File: HaxePreprocessorInspection.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
  if (!(file instanceof HaxeFile)) return null;
  final List<ProblemDescriptor> result = new ArrayList<ProblemDescriptor>();
  final ProblemReporter reporter = new ProblemReporter() {
    @Override
    public void reportProblem(ASTNode node, String message) {
      result.add( manager.createProblemDescriptor( node.getPsi(),
                                                   message,
                                                   (LocalQuickFix)null,
                                                   ProblemHighlightType.ERROR,
                                                   isOnTheFly));
    }
  };

  FileASTNode node1 = file.getNode();
  LeafElement firstLeaf = TreeUtil.findFirstLeaf(node1);

  Stack<List<ASTNode>> levels = new Stack<List<ASTNode>>();
  List<ASTNode> nodes = new ArrayList<ASTNode>();
  // Push the root node, just in case there is no #if to start it off.
  levels.push(nodes);

  ASTNode leaf = firstLeaf;
  while (leaf != null) {
    IElementType leafElementType = leaf.getElementType();

    if (leafElementType.equals(HaxeTokenTypes.PPIF)) {
      nodes = new ArrayList<ASTNode>();
      levels.push(nodes);
      nodes.add(leaf);
    }
    else if (leafElementType.equals(HaxeTokenTypes.PPEND)) {
      nodes.add(leaf);
      // Leave the base level in place, even if there are extra ends.
      if (levels.size() > 1) {
        validateLevel(nodes, reporter);
        levels.pop();
        nodes = levels.peek();
      }
    }
    else if (leafElementType.equals(HaxeTokenTypes.PPELSEIF)) {
      nodes.add(leaf);
    }
    else if (leafElementType.equals(HaxeTokenTypes.PPELSE)) {
      nodes.add(leaf);
    }
    leaf = TreeUtil.nextLeaf(leaf);
  }

  // Any levels that are still left need to be validated.
  for (List<ASTNode> level : levels) {
    validateLevel(level, reporter);
  }

  return ArrayUtil.toObjectArray(result, ProblemDescriptor.class);
}
 
Example #24
Source File: ASTFactory.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static LeafElement leaf(@Nonnull final IElementType type, final CharSequence text) {
  return leaf(type, LanguageVersionUtil.findDefaultVersion(type.getLanguage()), text);
}
 
Example #25
Source File: TreeHashingUtils.java    From consulo with Apache License 2.0 4 votes vote down vote up
static TreeHashResult computeElementHashForIndexing(AbstractTreeHasher base,
                                                    FragmentsCollector callBack,
                                                    PsiElement root,
                                                    PsiFragment upper,
                                                    NodeSpecificHasher hasher
) {
  final List<PsiElement> children = hasher.getNodeChildren(root);
  final PsiFragment fragment = base.buildFragment(hasher, root, base.getCost(root));

  if (upper != null) {
    fragment.setParent(upper);
  }

  final int size = children.size();
  if (size == 0 && !(root instanceof LeafElement)) {
    // contains only whitespaces and other unmeaning children
    return new TreeHashResult(0, hasher.getNodeCost(root), fragment);
  }

  final int discardCost = base.getDiscardCost(root);
  int c = hasher.getNodeCost(root);
  int h = hasher.getNodeHash(root);

  for (int i = 0; i < size; i++) {
    PsiElement child = children.get(i);
    final TreeHashResult res = base.hash(child, fragment, hasher);
    int childCost = res.getCost();
    c += childCost;
    if (childCost > discardCost || !base.ignoreChildHash(child)) {
      h += res.getHash();
    }
  }

  if (base.shouldAnonymize(root, hasher)) {
    h = 0;
  }

  if (callBack != null) {
    callBack.add(h, c, fragment);
  }

  return new TreeHashResult(h, c, fragment);
}
 
Example #26
Source File: DuplicatesMatchingVisitor.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean match(PsiElement element1, PsiElement element2) {
  if (element1 == null || element2 == null) {
    return element1 == element2;
  }

  if (myDiscardCost > 0) {
    final int cost1 = myTreeHasher.hash(element1, null, myNodeSpecificHasher).getCost();
    final int cost2 = myTreeHasher.hash(element2, null, myNodeSpecificHasher).getCost();

    if (cost1 < myDiscardCost || cost2 < myDiscardCost) {
      return true;
    }
  }

  final DuplicatesProfileBase duplicatesProfile = myNodeSpecificHasher.getDuplicatesProfile();

  final PsiElementRole role1 = duplicatesProfile.getRole(element1);
  final PsiElementRole role2 = duplicatesProfile.getRole(element2);

  final Set<PsiElementRole> skippedRoles = EnumSet.noneOf(PsiElementRole.class);
  final ExternalizableDuplocatorState duplocatorState =
    duplicatesProfile.getDuplocatorState(duplicatesProfile.getLanguage(element1));

  for (PsiElementRole role : PsiElementRole.values()) {
    if (!duplocatorState.distinguishRole(role)) {
      skippedRoles.add(role);
    }
  }

  if (role1 == role2 && skippedRoles.contains(role1)) {
    return true;
  }

  final EquivalenceDescriptorProvider descriptorProvider = EquivalenceDescriptorProvider.getInstance(element1);
  EquivalenceDescriptor descriptor1 = descriptorProvider != null ? descriptorProvider.buildDescriptor(element1) : null;
  EquivalenceDescriptor descriptor2 = descriptorProvider != null ? descriptorProvider.buildDescriptor(element2) : null;

  PsiElement newElement1 = DuplocatorUtil.skipNodeIfNeccessary(element1, descriptor1, myNodeFilter);
  PsiElement newElement2 = DuplocatorUtil.skipNodeIfNeccessary(element2, descriptor2, myNodeFilter);

  if (newElement1 != element1 || newElement2 != element2) {
    return match(newElement1, newElement2);
  }

  if (!element1.getClass().equals(element2.getClass())) {
    return false;
  }

  if (descriptor1 != null && descriptor2 != null) {
    return DuplocatorUtil.match(descriptor1, descriptor2, this, skippedRoles, duplicatesProfile);
  }

  if (element1 instanceof LeafElement) {
    IElementType elementType1 = ((LeafElement)element1).getElementType();
    IElementType elementType2 = ((LeafElement)element2).getElementType();

    if (!duplocatorState.distinguishLiterals() &&
        duplicatesProfile.getLiterals().contains(elementType1) &&
        duplicatesProfile.getLiterals().contains(elementType2)) {
      return true;
    }
    return element1.getText().equals(element2.getText());
  }

  if (element1.getFirstChild() == null && element1.getTextLength() == 0) {
    return element2.getFirstChild() == null && element2.getTextLength() == 0;
  }

  return matchSequentially(new FilteringNodeIterator(new SiblingNodeIterator(element1.getFirstChild()), getNodeFilter()),
                           new FilteringNodeIterator(new SiblingNodeIterator(element2.getFirstChild()), getNodeFilter()));
}
 
Example #27
Source File: AbstractTreeHasher.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Computes element hash using children hashes.
 * Creates only single PsiFragment.
 */
protected TreeHashResult computeElementHash(@Nonnull final PsiElement root, final PsiFragment upper, final NodeSpecificHasher hasher) {
  if (myForIndexing) {
    return TreeHashingUtils.computeElementHashForIndexing(this, myCallBack, root, upper, hasher);
  }
  ProgressManager.checkCanceled();
  final List<PsiElement> children = hasher.getNodeChildren(root);
  final int size = children.size();
  final int[] childHashes = new int[size];
  final int[] childCosts = new int[size];

  final PsiFragment fragment = buildFragment(hasher, root, getCost(root));

  if (upper != null) {
    fragment.setParent(upper);
  }

  if (size == 0 && !(root instanceof LeafElement)) {
    return new TreeHashResult(hasher.getNodeHash(root), hasher.getNodeCost(root), fragment);
  }

  for (int i = 0; i < size; i++) {
    final TreeHashResult res = hash(children.get(i), fragment, hasher);
    childHashes[i] = res.getHash();
    childCosts[i] = res.getCost();
  }

  final int c = hasher.getNodeCost(root) + vector(childCosts);
  final int h1 = hasher.getNodeHash(root);

  final int discardCost = getDiscardCost(root);

  for (int i = 0; i < size; i++) {
    if (childCosts[i] <= discardCost && ignoreChildHash(children.get(i))) {
      childHashes[i] = 0;
    }
  }
  final int h = h1 + vector(childHashes);

  if (myCallBack != null) {
    myCallBack.add(h, c, fragment);
  }

  return new TreeHashResult(h, c, fragment);
}
 
Example #28
Source File: ASTFactory.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static LeafElement leaf(@Nonnull final IElementType type, @Nonnull LanguageVersion languageVersion, final CharSequence text) {
  return ASTLeafFactory.EP.getValue(type).createLeaf(type, languageVersion, text);
}
 
Example #29
Source File: ASTFactory.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static LeafElement whitespace(final CharSequence text) {
  final PsiWhiteSpaceImpl w = new PsiWhiteSpaceImpl(WHITESPACES.intern(text));
  CodeEditUtil.setNodeGenerated(w, true);
  return w;
}
 
Example #30
Source File: TreeHasherBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected TreeHashResult computeElementHash(@Nonnull PsiElement root, PsiFragment upper, NodeSpecificHasher hasher) {
  if (myForIndexing) {
    return TreeHashingUtils.computeElementHashForIndexing(this, myCallBack, root, upper, hasher);
  }

  final List<PsiElement> children = hasher.getNodeChildren(root);
  final int size = children.size();
  final int[] childHashes = new int[size];
  final int[] childCosts = new int[size];

  final PsiFragment fragment = buildFragment(hasher, root, getCost(root));

  if (upper != null) {
    fragment.setParent(upper);
  }

  if (size == 0 && !(root instanceof LeafElement)) {
    // contains only whitespaces and other unmeaning children
    return new TreeHashResult(0, hasher.getNodeCost(root), fragment);
  }

  for (int i = 0; i < size; i++) {
    final TreeHashResult res = this.hash(children.get(i), fragment, hasher);
    childHashes[i] = res.getHash();
    childCosts[i] = res.getCost();
  }

  final int c = hasher.getNodeCost(root) + AbstractTreeHasher.vector(childCosts);
  final int h1 = hasher.getNodeHash(root);

  final int discardCost = getDiscardCost(root);

  for (int i = 0; i < size; i++) {
    if (childCosts[i] <= discardCost && ignoreChildHash(children.get(i))) {
      childHashes[i] = 0;
    }
  }

  int h = h1 + AbstractTreeHasher.vector(childHashes);

  if (shouldBeAnonymized(root, (NodeSpecificHasherBase)hasher)) {
    h = 0;
  }

  if (myCallBack != null) {
    myCallBack.add(h, c, fragment);
  }

  return new TreeHashResult(h, c, fragment);
}