下面列出了怎么用com.intellij.psi.PsiElement的API类实例代码及写法,或者点击链接到github查看源代码。
@Nullable
public static CSharpCallArgumentListOwner findCallArgumentListOwner(ResolveToKind kind, CSharpReferenceExpression referenceExpression)
{
PsiElement parent = referenceExpression.getParent();
CSharpCallArgumentListOwner p = null;
if(CSharpReferenceExpressionImplUtil.isConstructorKind(kind) || kind == ResolveToKind.PARAMETER)
{
p = PsiTreeUtil.getParentOfType(referenceExpression, CSharpCallArgumentListOwner.class);
}
else if(parent instanceof CSharpCallArgumentListOwner)
{
p = (CSharpCallArgumentListOwner) parent;
}
return p;
}
@Nonnull
public static Collection<PsiElement> filterOverrideElements(@Nonnull PsiScopeProcessor processor,
@Nonnull PsiElement scopeElement,
@Nonnull Collection<PsiElement> psiElements,
@Nonnull OverrideProcessor overrideProcessor)
{
if(psiElements.size() == 0)
{
return psiElements;
}
if(!ExecuteTargetUtil.canProcess(processor, ExecuteTarget.ELEMENT_GROUP, ExecuteTarget.EVENT, ExecuteTarget.PROPERTY))
{
return CSharpResolveUtil.mergeGroupsToIterable(psiElements);
}
List<PsiElement> elements = CSharpResolveUtil.mergeGroupsToIterable(psiElements);
return filterOverrideElements(scopeElement, elements, overrideProcessor);
}
@Override
public void addOccurrenceHighlights(@Nonnull Editor editor,
@Nonnull PsiElement[] elements,
@Nonnull TextAttributes attributes,
boolean hideByTextChange,
Collection<RangeHighlighter> outHighlighters) {
if (elements.length == 0) return;
int flags = HIDE_BY_ESCAPE;
if (hideByTextChange) {
flags |= HIDE_BY_TEXT_CHANGE;
}
Color scrollmarkColor = getScrollMarkColor(attributes);
if (editor instanceof EditorWindow) {
editor = ((EditorWindow)editor).getDelegate();
}
for (PsiElement element : elements) {
TextRange range = element.getTextRange();
range = InjectedLanguageManager.getInstance(myProject).injectedToHost(element, range);
addOccurrenceHighlight(editor, range.getStartOffset(), range.getEndOffset(), attributes, flags, outHighlighters, scrollmarkColor);
}
}
private static boolean filterElements(@Nonnull ChooseByNameViewModel base,
@Nonnull ProgressIndicator indicator,
@Nullable PsiElement context,
@Nullable Supplier<String[]> allNamesProducer,
@Nonnull Processor<FoundItemDescriptor<?>> consumer,
@Nonnull FindSymbolParameters parameters) {
boolean everywhere = parameters.isSearchInLibraries();
String pattern = parameters.getCompletePattern();
if (base.getProject() != null) {
base.getProject().putUserData(ChooseByNamePopup.CURRENT_SEARCH_PATTERN, pattern);
}
String namePattern = getNamePattern(base, pattern);
boolean preferStartMatches = !pattern.startsWith("*");
List<MatchResult> namesList = getSortedNamesForAllWildcards(base, parameters, indicator, allNamesProducer, namePattern, preferStartMatches);
indicator.checkCanceled();
return processByNames(base, everywhere, indicator, context, consumer, preferStartMatches, namesList, parameters);
}
private void findTestAndDo(AnActionEvent anActionEvent, BiConsumer<PsiClass, PsiMethod> action) {
PsiElement psiElement = anActionEvent.getData(CommonDataKeys.PSI_ELEMENT);
PsiFile psiFile = anActionEvent.getData(LangDataKeys.PSI_FILE);
if (psiElement == null) {
Editor editor = anActionEvent.getData(CommonDataKeys.EDITOR);
if (editor != null && psiFile != null) {
psiElement = psiFile.findElementAt(editor.getCaretModel().getOffset());
}
}
if (psiFile == null && psiElement != null) {
psiFile = psiElement.getContainingFile();
}
if (psiElement != null) {
PsiElement testElement = findNearestTestElement(psiFile, psiElement);
if (testElement instanceof PsiClass) {
PsiClass psiClass = (PsiClass) testElement;
action.accept(psiClass, null);
return;
} else if (testElement instanceof PsiMethod) {
PsiMethod psiMethod = (PsiMethod) testElement;
action.accept(psiMethod.getContainingClass(), psiMethod);
return;
}
}
action.accept(null, null);
}
@Nullable
public static <E extends PsiElement> E findArgumentList(PsiFile file, int offset, int lbraceOffset) {
if (file == null) return null;
ParameterInfoHandler[] handlers = ShowParameterInfoHandler.getHandlers(file.getProject(), PsiUtilCore.getLanguageAtOffset(file, offset), file.getViewProvider().getBaseLanguage());
if (handlers != null) {
for (ParameterInfoHandler handler : handlers) {
if (handler instanceof ParameterInfoHandlerWithTabActionSupport) {
final ParameterInfoHandlerWithTabActionSupport parameterInfoHandler2 = (ParameterInfoHandlerWithTabActionSupport)handler;
// please don't remove typecast in the following line; it's required to compile the code under old JDK 6 versions
final E e = ParameterInfoUtils.findArgumentList(file, offset, lbraceOffset, parameterInfoHandler2);
if (e != null) return e;
}
}
}
return null;
}
/** Find smallest subtree of t enclosing range startCharIndex..stopCharIndex
* inclusively using postorder traversal. Recursive depth-first-search.
*/
public static PsiElement getRootOfSubtreeEnclosingRegion(PsiElement t,
int startCharIndex, // inclusive
int stopCharIndex) // inclusive
{
for (PsiElement c : t.getChildren()) {
PsiElement sub = getRootOfSubtreeEnclosingRegion(c, startCharIndex, stopCharIndex);
if ( sub!=null ) return sub;
}
IElementType elementType = t.getNode().getElementType();
if ( elementType instanceof RuleIElementType ) {
TextRange r = t.getNode().getTextRange();
// is range fully contained in t? Note: jetbrains uses exclusive right end (use < not <=)
if ( startCharIndex>=r.getStartOffset() && stopCharIndex<r.getEndOffset() ) {
return t;
}
}
return null;
}
@Nullable
public static String extractArrayIndexFromValue(PsiElement element) {
PsiElement arrayElement;
if (element.getParent() instanceof StringLiteralExpression) {
arrayElement = element.getParent().getParent().getParent();
} else {
arrayElement = element.getParent().getParent();
}
if (arrayElement instanceof ArrayHashElement) {
ArrayHashElement arrayHashElement = (ArrayHashElement) arrayElement;
return extractIndexFromArrayHash(arrayHashElement);
}
return null;
}
public static ElementPattern<PsiElement> getSetVariablePattern() {
// {% set count1 = "var" %}
//noinspection unchecked
return PlatformPatterns
.psiElement(TwigTokenTypes.IDENTIFIER)
.afterLeafSkipping(
PlatformPatterns.or(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement(TwigTokenTypes.WHITE_SPACE)
),
PlatformPatterns.psiElement(TwigTokenTypes.EQ)
)
.withParent(
PlatformPatterns.psiElement(TwigElementTypes.SET_TAG)
)
.withLanguage(TwigLanguage.INSTANCE);
}
static private void checkMethod(PsiElement element, HaxeExpressionEvaluatorContext context) {
if (!(element instanceof HaxeMethod)) return;
final HaxeTypeTag typeTag = UsefulPsiTreeUtil.getChild(element, HaxeTypeTag.class);
ResultHolder expectedType = SpecificTypeReference.getDynamic(element).createHolder();
if (typeTag == null) {
final List<ReturnInfo> infos = context.getReturnInfos();
if (!infos.isEmpty()) {
expectedType = infos.get(0).type;
}
} else {
expectedType = getTypeFromTypeTag(typeTag, element);
}
if (expectedType == null) return;
for (ReturnInfo retinfo : context.getReturnInfos()) {
if (expectedType.canAssign(retinfo.type)) continue;
context.addError(
retinfo.element,
"Can't return " + retinfo.type + ", expected " + expectedType.toStringWithoutConstant()
);
}
}
/**
* [$this, '']
* array($this, '')
*/
@NotNull
@Override
public PsiElementPattern.Capture<PsiElement> getPattern() {
return PlatformPatterns.psiElement().withParent(
PlatformPatterns.psiElement(StringLiteralExpression.class).withParent(
PlatformPatterns.psiElement().withElementType(PhpElementTypes.ARRAY_VALUE).afterLeafSkipping(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement().withText(",")
).afterSiblingSkipping(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement().withElementType(PhpElementTypes.ARRAY_VALUE).withFirstNonWhitespaceChild(
PlatformPatterns.psiElement(Variable.class)
).afterLeafSkipping(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement().withText(PlatformPatterns.string().oneOf("[", "("))
)
)
)
);
}
public void testReferenceCanResolveDefinition() {
PsiFile file = myFixture.configureByText(PhpFileType.INSTANCE, "<?php \n" +
"\"LLL:EXT:foo/sample.xlf:sys_<caret>language.language_isocode.ab\";");
PsiElement elementAtCaret = file.findElementAt(myFixture.getCaretOffset()).getParent();
PsiReference[] references = elementAtCaret.getReferences();
for (PsiReference reference : references) {
if (reference instanceof TranslationReference) {
ResolveResult[] resolveResults = ((TranslationReference) reference).multiResolve(false);
for (ResolveResult resolveResult : resolveResults) {
assertInstanceOf(resolveResult.getElement(), XmlAttributeValue.class);
return;
}
}
}
fail("TranslationReference could not be resolved");
}
@Override
public void navigate(MouseEvent mouseEvent, PsiElement psiElement) {
if (canNavigate(psiElement)) {
final Project project = psiElement.getProject();
final List<PsiElement> psiElements = findReferences(psiElement);
if (psiElements.size() == 1) {
FileEditorManager.getInstance(project).openFile(PsiUtil.getVirtualFile(psiElements.get(0)), true);
} else if (psiElements.size() > 1) {
NavigationUtil.getPsiElementPopup(psiElements.toArray(new PsiElement[0]), title).show(new RelativePoint(mouseEvent));
} else {
if (Objects.isNull(psiElements) || psiElements.size() <= 0) {
Messages.showErrorDialog("没有找到这个调用的方法,请检查!", "错误提示");
}
}
}
}
public void testRml_FileInclude() {
configureCode("A.re", "module Make = (M:I) => { let a = 3; }; include Make({})");
configureCode("B.re", "let b = A.a<caret>;");
PsiElement e = myFixture.getElementAtCaret();
assertEquals("A.Make.a", ((PsiQualifiedElement) e.getParent()).getQualifiedName());
}
public void annotate(@Nonnull PsiElement element, @Nonnull AnnotationHolder holder) {
if (!(element instanceof MMPsiElement)) {
return;
}
final ASTNode keyNode = element.getNode();
highlightTokens(keyNode, holder, new MMHighlighter());
}
private void annotateVarDef(BashVarDef bashVarDef, AnnotationHolder annotationHolder) {
final PsiElement identifier = bashVarDef.findAssignmentWord();
if (identifier != null) {
final Annotation annotation = annotationHolder.createInfoAnnotation(identifier, null);
annotation.setTextAttributes(BashSyntaxHighlighter.VAR_DEF);
}
}
@Override
public PsiElement getContext() {
T stub = getStub();
if (stub != null) {
if (!(stub instanceof PsiFileStub)) {
return stub.getParentStub().getPsi();
}
}
return super.getContext();
}
@RequiredReadAction
@Nullable
@Override
public PsiElement getVarElement()
{
return findChildByType(CSharpPreprocesorTokens.IDENTIFIER);
}
@Override
@Nonnull
public ProblemDescriptor createProblemDescriptor(@Nonnull PsiElement psiElement,
@Nonnull String descriptionTemplate,
LocalQuickFix[] fixes,
@Nonnull ProblemHighlightType highlightType,
boolean onTheFly,
boolean isAfterEndOfLine) {
return new ProblemDescriptorBase(psiElement, psiElement, descriptionTemplate, fixes, highlightType, isAfterEndOfLine, null, true, onTheFly);
}
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
if (element instanceof LeafPsiElement) {
IElementType tokenType = ((LeafPsiElement)element).getElementType();
if (tokenType == ThriftTokenTypes.IDENTIFIER && ThriftUtils.getKeywords().contains(element.getText())) {
annotateKeyword(element, holder);
}
}
}
private void addCompletionsAfterWhiteSpace(PsiElement element, CompletionResultSet resultSet) {
if (isJustAfterModule(element)) {
this.currentModuleProvider.addCompletions((ElmFile) element.getContainingFile(), resultSet);
return;
}
char firstChar = element.getText().charAt(0);
ElmFile file = (ElmFile) element.getContainingFile();
if (Character.isLowerCase(firstChar)) {
this.valueProvider.addCompletions(file, resultSet);
this.keywordsProvider.addCompletions(resultSet);
} else if (Character.isUpperCase(firstChar)) {
this.typeProvider.addCompletions(file, resultSet);
this.moduleProvider.addCompletions(file, resultSet);
}
}
/**
* Invokes {@link #parseAndGetConfigHeaderFiles(Module)} by first getting a {@link Module} instance for the given PsiElement.
*
* @return the root config file, or an empty list if couldn't locate a {@link Module} or couldn't be parsed
*/
@NotNull
public List<HeaderFile> parseAndGetConfigHeaderFiles(@NotNull PsiElement elementFromModule) {
ArmaPluginModuleData moduleData = getModuleData(elementFromModule);
if (moduleData == null) {
return Collections.emptyList();
}
return doParseAndGetConfigHeaderFiles(moduleData);
}
/**
* Test if the given element is contained in a module with a pub root that declares a flutter dependency.
*/
public static boolean isInFlutterProject(@NotNull Project project, @NotNull PsiElement element) {
final PsiFile file = element.getContainingFile();
if (file == null) {
return false;
}
final PubRoot pubRoot = PubRootCache.getInstance(project).getRoot(file);
if (pubRoot == null) {
return false;
}
return pubRoot.declaresFlutter();
}
public static boolean shouldHighlight(@Nonnull PsiElement psiRoot) {
final HighlightingSettingsPerFile component = HighlightingSettingsPerFile.getInstance(psiRoot.getProject());
if (component == null) return true;
final FileHighlightingSetting settingForRoot = component.getHighlightingSettingForRoot(psiRoot);
return settingForRoot != FileHighlightingSetting.SKIP_HIGHLIGHTING;
}
/**
* Returns {@code true} if {@code child} is a descendant of the {@code parent}, {@code false} otherwise.
*/
private static boolean isChildOfParent(@NotNull PsiElement child, @NotNull PsiElement parent) {
List<PsiElement> childElements = Lists.newArrayList(parent);
while (!childElements.isEmpty()) {
PsiElement element = childElements.remove(0);
if (element.equals(child)) {
return true;
}
childElements.addAll(Arrays.asList(element.getChildren()));
}
return false;
}
public PsiElement[] getParameterLists() {
if(parameterLists != null) {
return parameterLists;
}
return parameterLists = PsiTreeUtil.collectElements(method, psiElement ->
psiElement.getParent() instanceof ParameterList
);
}
private static PsiNameValuePair findContainingNameValuePair(PsiElement highlightedElement) {
PsiElement nameValuePair = highlightedElement;
while (!(nameValuePair == null || nameValuePair instanceof PsiNameValuePair)) {
nameValuePair = nameValuePair.getContext();
}
return (PsiNameValuePair) nameValuePair;
}
public CSharpExtractMethodDialog(Project project, CSharpMethodDescriptor method, boolean allowDelegation, PsiElement defaultValueContext,
@Nonnull Processor<DotNetLikeMethodDeclaration> processor)
{
super(project, method, allowDelegation, defaultValueContext);
myProcessor = processor;
setOKButtonText(CommonBundle.getOkButtonText());
setTitle("Extract Method");
getRefactorAction().putValue(Action.NAME, CommonBundle.getOkButtonText());
}
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(PsiElement psiElement, int offset, Editor editor) {
if(!Symfony2ProjectComponent.isEnabled(psiElement) || !PhpElementsUtil.getClassNamePattern().accepts(psiElement)) {
return new PsiElement[0];
}
return ServiceIndexUtil.findServiceDefinitions((PhpClass) psiElement.getContext());
}
@RequiredReadAction
@Nullable
@Override
public String getPresentableParentQName()
{
PsiElement parent = getParent();
if(parent instanceof DotNetQualifiedElement)
{
return ((DotNetQualifiedElement) parent).getPresentableQName();
}
return myParentQName;
}