Java Code Examples for com.intellij.psi.PsiElement#getParent()

The following examples show how to use com.intellij.psi.PsiElement#getParent() . 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: PhpGoToHandler.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
private void attachThemeJsFieldReferences(final PsiElement psiElement, final List<PsiElement> psiElements) {

        final PsiElement parent = psiElement.getParent();
        if(!(parent instanceof StringLiteralExpression)) {
            return;
        }

        final String contents = ((StringLiteralExpression) parent).getContents();
        if(StringUtils.isBlank(contents)) {
            return;
        }

        ThemeUtil.collectThemeJsFieldReferences((StringLiteralExpression) parent, (virtualFile, path) -> {
            if(path.equals(contents)) {
                PsiFile psiFile = PsiManager.getInstance(psiElement.getProject()).findFile(virtualFile);
                if(psiFile != null) {
                    psiElements.add(psiFile);
                }

                return false;
            }

            return true;
        });

    }
 
Example 2
Source File: BxReferencePatterns.java    From bxfs with MIT License 6 votes vote down vote up
/**
 * Is the element is a parameter of $APPLICATION->IncludeComponent() call
 */
private static boolean isValidComponentCall(Object o, String component) {
	PsiElement parameters = ((PsiElement) o).getParent(); if (parameters instanceof ParameterList) {
		if (component != null) {
			PsiElement[] params = ((ParameterList) parameters).getParameters(); if (params.length == 0 || params[0].getNode().getElementType() != PhpElementTypes.STRING || !((StringLiteralExpression) params[0]).getContents().equals(component))
				return false;
		}
		PsiElement psiMethod = parameters.getParent(); if (psiMethod instanceof MethodReference) {
			MethodReference method = (MethodReference) psiMethod;
			/* CBitrixComponent::includeComponentClass() */
			if (method.getClassReference() instanceof ClassReference && method.isStatic())
				return "CBitrixComponent".equals(method.getClassReference().getName())
					&& "includeComponentClass".equals(method.getName());
			/* $APPLICATION->IncludeComponent() */
			if (method.getClassReference() instanceof Variable && !method.isStatic())
				return "APPLICATION".equals(method.getClassReference().getName())
					&& "IncludeComponent".equals(method.getName());
		}
	}
	return false;
}
 
Example 3
Source File: YamlHelper.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * Returns "@foo" value of ["@foo", "fo<caret>o"]
 */
@Nullable
public static String getPreviousSequenceItemAsText(@NotNull PsiElement psiElement) {
    PsiElement yamlScalar = psiElement.getParent();
    if(!(yamlScalar instanceof YAMLScalar)) {
        return null;
    }

    PsiElement yamlSequence = yamlScalar.getParent();
    if(!(yamlSequence instanceof YAMLSequenceItem)) {
        return null;
    }

    // @TODO: catch new lexer error on empty item [<caret>,@foo] "PsiErrorElement:Sequence item expected"
    YAMLSequenceItem prevSequenceItem = PsiTreeUtil.getPrevSiblingOfType(yamlSequence, YAMLSequenceItem.class);
    if(prevSequenceItem == null) {
        return null;
    }

    YAMLValue value = prevSequenceItem.getValue();
    if(!(value instanceof YAMLScalar)) {
        return null;
    }

    return ((YAMLScalar) value).getTextValue();
}
 
Example 4
Source File: BashSpacingProcessorBasic.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether a node is contained in a parameter expansion.
 *
 * @param node
 * @return True if the on of the nodes is embedded in a string
 */
private static boolean isNodeInParameterExpansion(ASTNode node) {
    if (paramExpansionOperators.contains(node.getElementType())) {
        return true;
    }

    PsiElement psiElement = node.getPsi();
    PsiElement parent = psiElement != null ? psiElement.getParent() : null;

    while (parent != null) {
        if (parent instanceof BashParameterExpansion) {
            return true;
        }

        parent = parent.getParent();
    }

    return false;
}
 
Example 5
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 6
Source File: FusionBreadcrumbsInfoProvider.java    From intellij-neos with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
@Override
public String getElementInfo(@NotNull PsiElement e) {
    String elementInfo = "";
    if (e instanceof FusionBlock) {
        PsiElement currentElement = e;
        do {
            if (currentElement.getPrevSibling() == null) {
                currentElement = currentElement.getParent();
            } else {
                currentElement = currentElement.getPrevSibling();
            }
        } while (currentElement != null && !(currentElement instanceof FusionPath));

        if (currentElement != null) {
            elementInfo = currentElement.getText();

            if (currentElement.getFirstChild() instanceof FusionPrototypeSignature) {
                FusionType type = ((FusionPrototypeSignature) currentElement.getFirstChild()).getType();
                if (type != null) {
                    elementInfo = type.getText();
                }
            }
        }
    }

    if (elementInfo.length() > 30) {
        elementInfo = "..." + elementInfo.substring(elementInfo.length() - 27, elementInfo.length());
    }
    return elementInfo;
}
 
Example 7
Source File: ExtractStringAction.java    From idea-android-studio-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Nullable
protected static PsiElement getPsiElement(@Nullable PsiFile file, @Nullable Editor editor) {

    if(file == null || editor == null) {
        return null;
    }

    int offset = editor.getCaretModel().getOffset();
    PsiElement element = file.findElementAt(offset);
    return element != null ? element.getParent() : null;
}
 
Example 8
Source File: DocumentFileLocationMapper.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
@Override
public TextRange getIdentifierRange(int line, int column) {
  if (psiFile == null) {
    return null;
  }

  // Convert to zero based line and column indices.
  line = line - 1;
  column = column - 1;

  if (document == null || line >= document.getLineCount() || document.isLineModified(line)) {
    return null;
  }

  final XSourcePosition pos = debuggerUtil.createPosition(virtualFile, line, column);
  if (pos == null) {
    return null;
  }
  final int offset = pos.getOffset();
  PsiElement element = psiFile.getOriginalFile().findElementAt(offset);
  if (element == null) {
    return null;
  }

  // Handle named constructors gracefully. For example, for the constructor
  // Image.asset(...) we want to return "Image.asset" instead of "asset".
  if (element.getParent() instanceof DartId) {
    element = element.getParent();
  }
  while (element.getParent() instanceof DartReferenceExpression) {
    element = element.getParent();
  }
  return element.getTextRange();
}
 
Example 9
Source File: PsiScopesUtilCore.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean treeWalkUp(@Nonnull final PsiScopeProcessor processor,
                                 @Nonnull final PsiElement entrance,
                                 @Nullable final PsiElement maxScope,
                                 @Nonnull final ResolveState state) {
  if (!entrance.isValid()) {
    LOGGER.error(new PsiInvalidElementAccessException(entrance));
  }
  PsiElement prevParent = entrance;
  PsiElement scope = entrance;

  while (scope != null) {
    ProgressIndicatorProvider.checkCanceled();

    if (!scope.processDeclarations(processor, state, prevParent, entrance)) {
      return false; // resolved
    }


    if (scope == maxScope) break;
    prevParent = scope;
    scope = prevParent.getContext();
    if (scope != null && scope != prevParent.getParent() && !scope.isValid()) {
      break;
    }

  }

  return true;
}
 
Example 10
Source File: PsiElementUtil.java    From Thinkphp5-Plugin with MIT License 5 votes vote down vote up
public static Method getMethod(PsiElement psiElement) {
    if (psiElement == null) return null;
    PsiElement parent = psiElement.getParent();
    if (parent instanceof Method) {
        return (Method) parent;
    } else {
        return getMethod(parent);
    }
}
 
Example 11
Source File: CSharpLocalVariableInlineActionHandler.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canInlineElement(PsiElement element)
{
	if(element instanceof CSharpLocalVariable)
	{
		if(CSharpLocalVariableUtil.isForeachVariable((DotNetVariable) element) || element.getParent() instanceof CSharpForStatementImpl)
		{
			return false;
		}
		return ((CSharpLocalVariable) element).getInitializer() != null;
	}
	return false;
}
 
Example 12
Source File: ThriftKeywordCompletionContributor.java    From intellij-thrift with Apache License 2.0 5 votes vote down vote up
private Collection<String> suggestKeywords(@NotNull PsiElement position) {
  PsiFile psiFile = position.getContainingFile();
  PsiElement topLevelElement = position;
  while (!(topLevelElement.getParent() instanceof PsiFile)) {
    topLevelElement = topLevelElement.getParent();
  }
  PsiFile file = PsiFileFactory.getInstance(psiFile.getProject())
    .createFileFromText("a.thrift", ThriftLanguage.INSTANCE, topLevelElement.getText(), true, false);
  GeneratedParserUtilBase.CompletionState state =
    new GeneratedParserUtilBase.CompletionState(position.getTextOffset() - topLevelElement.getTextOffset());
  file.putUserData(GeneratedParserUtilBase.COMPLETION_STATE_KEY, state);
  TreeUtil.ensureParsed(file.getNode());
  return state.items;
}
 
Example 13
Source File: CSharpParameterImpl.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public SearchScope getUseScope()
{
	PsiElement parent = getParent();
	if(parent instanceof DotNetParameterList)
	{
		return new LocalSearchScope(parent.getParent());
	}
	return super.getUseScope();
}
 
Example 14
Source File: CamelBeanReferenceRenameHandler.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAvailableOnDataContext(DataContext dataContext) {
    final PsiElement psiElement = findPsiElementAt(dataContext);
    if (psiElement == null) {
        return false;
    }
    //Make sure the cursor is located in the text where the method name is defined.
    return psiElement.getParent() instanceof PsiLiteralExpression
        && psiElement.getNextSibling() == null
        && getCamelIdeaUtils().getBean(psiElement) != null;
}
 
Example 15
Source File: MainPathResolver.java    From intellij-swagger with MIT License 5 votes vote down vote up
@Override
public boolean childOfRoot(final PsiElement psiElement) {
  return psiElement.getParent() instanceof PsiFile
      || psiElement.getParent().getParent() instanceof PsiFile
      || psiElement.getParent().getParent().getParent() instanceof PsiFile
      || psiElement.getParent().getParent().getParent().getParent() instanceof PsiFile;
}
 
Example 16
Source File: ParenthesesInsertHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void handleInsert(final InsertionContext context, final T item) {
  final Editor editor = context.getEditor();
  final Document document = editor.getDocument();
  context.commitDocument();
  PsiElement lParen = findExistingLeftParenthesis(context);

  final char completionChar = context.getCompletionChar();
  final boolean putCaretInside = completionChar == myLeftParenthesis || placeCaretInsideParentheses(context, item);

  if (completionChar == myLeftParenthesis) {
    context.setAddCompletionChar(false);
  }

  if (lParen != null) {
    int lparenthOffset = lParen.getTextRange().getStartOffset();
    if (mySpaceBeforeParentheses && lparenthOffset == context.getTailOffset()) {
      document.insertString(context.getTailOffset(), " ");
      lparenthOffset++;
    }

    if (completionChar == myLeftParenthesis || completionChar == '\t') {
      editor.getCaretModel().moveToOffset(lparenthOffset + 1);
    }
    else {
      editor.getCaretModel().moveToOffset(context.getTailOffset());
    }

    context.setTailOffset(lparenthOffset + 1);

    PsiElement list = lParen.getParent();
    PsiElement last = list.getLastChild();
    if (isToken(last, String.valueOf(myRightParenthesis))) {
      int rparenthOffset = last.getTextRange().getStartOffset();
      context.setTailOffset(rparenthOffset + 1);
      if (!putCaretInside) {
        for (int i = lparenthOffset + 1; i < rparenthOffset; i++) {
          if (!Character.isWhitespace(document.getCharsSequence().charAt(i))) {
            return;
          }
        }
        editor.getCaretModel().moveToOffset(context.getTailOffset());
      }
      else if (mySpaceBetweenParentheses && document.getCharsSequence().charAt(lparenthOffset) == ' ') {
        editor.getCaretModel().moveToOffset(lparenthOffset + 2);
      }
      else {
        editor.getCaretModel().moveToOffset(lparenthOffset + 1);
      }
      return;
    }
  }
  else {
    document.insertString(context.getTailOffset(), getSpace(mySpaceBeforeParentheses) + myLeftParenthesis + getSpace(mySpaceBetweenParentheses));
    editor.getCaretModel().moveToOffset(context.getTailOffset());
  }

  if (!myMayInsertRightParenthesis) return;

  if (context.getCompletionChar() == myLeftParenthesis) {
    //todo use BraceMatchingUtil.isPairedBracesAllowedBeforeTypeInFileType
    int tail = context.getTailOffset();
    if (tail < document.getTextLength() && StringUtil.isJavaIdentifierPart(document.getCharsSequence().charAt(tail))) {
      return;
    }
  }

  document.insertString(context.getTailOffset(), getSpace(mySpaceBetweenParentheses) + myRightParenthesis);
  if (!putCaretInside) {
    editor.getCaretModel().moveToOffset(context.getTailOffset());
  }
}
 
Example 17
Source File: MisplacedCommentHighlighter.java    From intellij-xquery with Apache License 2.0 4 votes vote down vote up
private boolean isTheStartingElementOfMisplacedComment(PsiElement element, XQueryMisplacedComment misplacedComment) {
    return misplacedComment != null
            && element.getNode().getElementType() == EXPR_COMMENT_START
            && element.getParent() == misplacedComment;
}
 
Example 18
Source File: TestReferenceUtil.java    From camel-idea-plugin with Apache License 2.0 4 votes vote down vote up
public static PsiElement getParentElementAtCaret(JavaCodeInsightTestFixture fixture) {
    PsiElement element = fixture.getFile().findElementAt(fixture.getCaretOffset());
    Assert.assertNotNull(element);
    return element.getParent();
}
 
Example 19
Source File: LtGtInsertHandler.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@Override
public void handleInsert(final InsertionContext context, final T item)
{
	final Editor editor = context.getEditor();
	final Document document = editor.getDocument();
	context.commitDocument();
	PsiElement element = findNextToken(context);

	final char completionChar = context.getCompletionChar();
	final boolean putCaretInside = completionChar == '<' || placeCaretInsideParentheses(context, item);

	if(completionChar == '<')
	{
		context.setAddCompletionChar(false);
	}

	if(isToken(element, "<"))
	{
		int lparenthOffset = element.getTextRange().getStartOffset();
		if(mySpaceBeforeParentheses && lparenthOffset == context.getTailOffset())
		{
			document.insertString(context.getTailOffset(), " ");
			lparenthOffset++;
		}

		if(completionChar == '<' || completionChar == '\t')
		{
			editor.getCaretModel().moveToOffset(lparenthOffset + 1);
		}
		else
		{
			editor.getCaretModel().moveToOffset(context.getTailOffset());
		}

		context.setTailOffset(lparenthOffset + 1);

		PsiElement list = element.getParent();
		PsiElement last = list.getLastChild();
		if(isToken(last, ">"))
		{
			int rparenthOffset = last.getTextRange().getStartOffset();
			context.setTailOffset(rparenthOffset + 1);
			if(!putCaretInside)
			{
				for(int i = lparenthOffset + 1; i < rparenthOffset; i++)
				{
					if(!Character.isWhitespace(document.getCharsSequence().charAt(i)))
					{
						return;
					}
				}
				editor.getCaretModel().moveToOffset(context.getTailOffset());
			}
			else if(mySpaceBetweenParentheses && document.getCharsSequence().charAt(lparenthOffset) == ' ')
			{
				editor.getCaretModel().moveToOffset(lparenthOffset + 2);
			}
			else
			{
				editor.getCaretModel().moveToOffset(lparenthOffset + 1);
			}
			return;
		}
	}
	else
	{
		document.insertString(context.getTailOffset(), getSpace(mySpaceBeforeParentheses) + "<" + getSpace(mySpaceBetweenParentheses));
		editor.getCaretModel().moveToOffset(context.getTailOffset());
	}

	if(!myMayInsertRightParenthesis)
	{
		return;
	}

	if(context.getCompletionChar() == '<')
	{
		//todo use BraceMatchingUtil.isPairedBracesAllowedBeforeTypeInFileType
		int tail = context.getTailOffset();
		if(tail < document.getTextLength() && StringUtil.isJavaIdentifierPart(document.getCharsSequence().charAt(tail)))
		{
			return;
		}
	}

	document.insertString(context.getTailOffset(), getSpace(mySpaceBetweenParentheses) + ">");
	if(!putCaretInside)
	{
		editor.getCaretModel().moveToOffset(context.getTailOffset());
	}
}
 
Example 20
Source File: ContextTypeProviderTest.java    From idea-php-typo3-plugin with MIT License 4 votes vote down vote up
public void testContextTypesCanBeInferred() {
    myFixture.copyFileToProject("classes.php");

    PsiFile psiFile = myFixture.configureByText("foo.php", "<?php\n" +
        "$userAspect = \\TYPO3\\CMS\\Core\\Utility\\GeneralUtility::makeInstance(\\TYPO3\\CMS\\Core\\Context\\Context::class)->getAspect('frontend.user');\n" +
        "$userAspect->getGroup<caret>Ids()");


    PsiElement elementAtCaret = psiFile.findElementAt(myFixture.getCaretOffset());
    assertNotNull(elementAtCaret);

    assertInstanceOf(elementAtCaret.getParent(), MethodReference.class);

    MethodReference methodReference = (MethodReference) elementAtCaret.getParent();
    Method method = (Method) methodReference.resolve();

    assertNotNull(method);
    assertInstanceOf(method, Method.class);

    assertNotNull(method.getContainingClass());
    assertInstanceOf(method.getContainingClass(), PhpClass.class);
}