下面列出了怎么用com.intellij.psi.impl.source.tree.LeafPsiElement的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @param psiElement checking element
* @return true if this is process.env.*** variable
*/
static boolean checkPsiElement(@NotNull PsiElement psiElement) {
if(!(psiElement instanceof LeafPsiElement)) {
return false;
}
IElementType elementType = ((LeafPsiElement) psiElement).getElementType();
if(!elementType.toString().equals("JS:IDENTIFIER")) {
return false;
}
PsiElement parent = psiElement.getParent();
if(!(parent instanceof JSReferenceExpression)) {
return false;
}
return ((JSReferenceExpression) parent).getCanonicalText().startsWith("process.env");
}
/**
* Returns the contents of a Dart string literal, provided that it doesn't do any interpolation.
* <p>
* Returns null if there is any string interpolation.
*/
@Nullable
public static String unquote(@NotNull DartStringLiteralExpression lit) {
if (!lit.getShortTemplateEntryList().isEmpty() || !lit.getLongTemplateEntryList().isEmpty()) {
return null; // is a template
}
// We expect a quote, string part, quote.
if (lit.getFirstChild() == null) return null;
final PsiElement second = lit.getFirstChild().getNextSibling();
if (second.getNextSibling() != lit.getLastChild()) return null; // not three items
if (!(second instanceof LeafPsiElement)) return null;
final LeafPsiElement leaf = (LeafPsiElement)second;
if (leaf.getElementType() != DartTokenTypes.REGULAR_STRING_PART) return null;
return leaf.getText();
}
/**
* Returns the contents of a Dart string literal, provided that it doesn't do any interpolation.
* <p>
* Returns null if there is any string interpolation.
*/
@Nullable
public static String unquote(@NotNull DartStringLiteralExpression lit) {
if (!lit.getShortTemplateEntryList().isEmpty() || !lit.getLongTemplateEntryList().isEmpty()) {
return null; // is a template
}
// We expect a quote, string part, quote.
if (lit.getFirstChild() == null) return null;
final PsiElement second = lit.getFirstChild().getNextSibling();
if (second.getNextSibling() != lit.getLastChild()) return null; // not three items
if (!(second instanceof LeafPsiElement)) return null;
final LeafPsiElement leaf = (LeafPsiElement)second;
if (leaf.getElementType() != DartTokenTypes.REGULAR_STRING_PART) return null;
return leaf.getText();
}
@Override
public boolean isAlwaysLeaf(StructureViewTreeElement element) {
if (element instanceof GraphQLStructureViewTreeElement) {
GraphQLStructureViewTreeElement treeElement = (GraphQLStructureViewTreeElement) element;
if (treeElement.childrenBase instanceof LeafPsiElement) {
return true;
}
if (treeElement.childrenBase instanceof GraphQLField) {
final PsiElement[] children = treeElement.childrenBase.getChildren();
if (children.length == 0) {
// field with no sub selections, but we have to check if there's attributes
final PsiElement nextVisible = PsiTreeUtil.nextVisibleLeaf(treeElement.childrenBase);
if (nextVisible != null && nextVisible.getNode().getElementType() == GraphQLElementTypes.PAREN_L) {
return false;
}
return true;
}
if (children.length == 1 && children[0] instanceof LeafPsiElement) {
return true;
}
}
}
return false;
}
/**
* Support: @push('foobar')
*/
@NotNull
private Collection<LineMarkerInfo> collectPushOverwrites(@NotNull LeafPsiElement psiElement, @NotNull String sectionName) {
final List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>();
BladeTemplateUtil.visitUpPath(psiElement.getContainingFile(), 10, parameter -> {
if(sectionName.equalsIgnoreCase(parameter.getContent())) {
gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(parameter.getPsiElement()).withIcon(LaravelIcons.LARAVEL, LaravelIcons.LARAVEL));
}
}, BladeTokenTypes.STACK_DIRECTIVE);
if(gotoRelatedItems.size() == 0) {
return Collections.emptyList();
}
return Collections.singletonList(
getRelatedPopover("Stack Section", "Stack Overwrites", psiElement, gotoRelatedItems, PhpIcons.OVERRIDES)
);
}
private boolean propertiesHandling(Editor editor, DataContext dataContext, SelectionModel selectionModel,
PsiFile psiFile) {
PsiElement elementAtCaret = PsiUtilBase.getElementAtCaret(editor);
if (elementAtCaret instanceof PsiWhiteSpace) {
return false;
} else if (elementAtCaret instanceof LeafPsiElement) {
IElementType elementType = ((LeafPsiElement) elementAtCaret).getElementType();
if (elementType.toString().equals("Properties:VALUE_CHARACTERS")
|| elementType.toString().equals("Properties:KEY_CHARACTERS")) {
TextRange textRange = elementAtCaret.getTextRange();
if (textRange.getLength() == 0) {
return super.selectSomethingUnderCaret(editor, dataContext, selectionModel);
}
selectionModel.setSelection(textRange.getStartOffset(), textRange.getEndOffset());
return true;
}
}
return false;
}
@Nullable
private IElementType getIElementType(int newChildIndex) {
Block block = getSubBlocks().get(newChildIndex - 1);
while (block instanceof XQueryFormattingBlock && ! block.getSubBlocks().isEmpty()) {
List<Block> subBlocks = block.getSubBlocks();
Block childBlock = subBlocks.get(subBlocks.size() - 1);
if (! (childBlock instanceof XQueryFormattingBlock)) break;
else {
ASTNode node = ((XQueryFormattingBlock) childBlock).getNode();
PsiElement psi = node.getPsi();
IElementType elementType = node.getElementType();
if (elementType instanceof XQueryTokenType) break;
if (psi instanceof LeafPsiElement || psi instanceof XQueryFunctionName || psi instanceof
XQueryVarName || psi instanceof XQueryNamespacePrefix)
break;
}
block = childBlock;
}
return block instanceof XQueryFormattingBlock ? ((XQueryFormattingBlock) block).getNode().getElementType() :
null;
}
private PsiElement findElementBeforeNameFragment(InsertionContext context) {
final PsiFile file = context.getFile();
PsiElement element = file.findElementAt(context.getStartOffset() - 1);
element = getElementInFrontOfWhitespace(file, element);
if (element instanceof LeafPsiElement
&& ((LeafPsiElement) element).getElementType() == XQueryTypes.COLON) {
PsiElement elementBeforeColon = file.findElementAt(context.getStartOffset() - 2);
if (elementBeforeColon != null) {
element = elementBeforeColon;
PsiElement beforeElementBeforeColon = file.findElementAt(elementBeforeColon.getTextRange().getStartOffset() - 1);
if (beforeElementBeforeColon != null) {
element = getElementInFrontOfWhitespace(file, beforeElementBeforeColon);
}
}
}
return element;
}
/**
* key: !my_tag <caret>
*/
public static boolean isElementAfterYamlTag(PsiElement psiElement) {
if (!(psiElement instanceof LeafPsiElement)) {
return false;
}
// key: !my_tag <caret>\n
if (((LeafPsiElement) psiElement).getElementType() == YAMLTokenTypes.EOL) {
PsiElement prevElement = PsiTreeUtil.getDeepestVisibleLast(psiElement);
if (prevElement instanceof LeafPsiElement) {
if (((LeafPsiElement) prevElement).getElementType() == YAMLTokenTypes.TAG) {
return ((LeafPsiElement) prevElement).getText().startsWith("!");
}
}
}
return PsiTreeUtil.findSiblingBackward(psiElement, YAMLTokenTypes.TAG, null) != null;
}
@Override
public boolean isSuppressedFor(@NotNull PsiElement element) {
Project project = element.getProject();
DojoSettings settings = ServiceManager.getService(project, DojoSettings.class);
if(!settings.isNeedsMoreDojoEnabled())
{
return super.isSuppressedFor(element);
}
if(element instanceof LeafPsiElement)
{
LeafPsiElement leafPsiElement = (LeafPsiElement) element;
if(leafPsiElement.getElementType() == JSTokenTypes.IDENTIFIER &&
leafPsiElement.getParent() != null &&
leafPsiElement.getParent().getFirstChild() instanceof JSThisExpression)
{
return AttachPointResolver.getGotoDeclarationTargets(element, 0, null).length > 0 || super.isSuppressedFor(element);
}
}
return super.isSuppressedFor(element);
}
@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);
}
@Override
public void annotate(@NotNull final PsiElement element, @NotNull final AnnotationHolder holder) {
if (element instanceof LeafPsiElement) {
final TextAttributesKey kind = getKeywordKind(element);
if (kind == null) {
return;
}
final TextRange textRange = element.getTextRange();
final TextRange range = new TextRange(textRange.getStartOffset(), textRange.getEndOffset());
final Annotation annotation = holder.createAnnotation(HighlightSeverity.INFORMATION, range, null);
annotation.setTextAttributes(kind);
}
}
@Override
protected void addCompletions(final CompletionParameters completionParameters,
final ProcessingContext processingContext, final CompletionResultSet resultSet) {
final PsiElement element = completionParameters.getPosition();
if (!LeafPsiElement.class.isInstance(element)) {
return; // ignore comment
}
final Project project = element.getProject();
final Module module = findModule(element);
final SuggestionService service = ServiceManager.getService(project, SuggestionService.class);
if ((module == null || !service.isSupported(completionParameters))) { // limit suggestion to Messages
return;
}
if (PropertyValueImpl.class.isInstance(element)) {
ofNullable(PropertyValueImpl.class.cast(element).getPrevSibling())
.map(PsiElement::getPrevSibling)
.map(PsiElement::getText)
.ifPresent(text -> resultSet.addAllElements(service.computeValueSuggestions(text)));
} else if (PropertyKeyImpl.class.isInstance(element)) {
final List<String> containerElements = PropertiesFileImpl.class
.cast(element.getContainingFile())
.getProperties()
.stream()
.filter(p -> !Objects.equals(p.getKey(), element.getText()))
.map(IProperty::getKey)
.collect(toList());
resultSet
.addAllElements(service
.computeKeySuggestions(project, module, getPropertiesPackage(module, completionParameters),
containerElements, truncateIdeaDummyIdentifier(element)));
}
}
@Test
public void isMainFunctionDeclaration() throws Exception {
run(() -> {
final PsiElement mainIdentifier = setUpDartElement("main() { test('my first test', () {} ); }", "main", LeafPsiElement.class);
final PsiElement main =
PsiTreeUtil.findFirstParent(mainIdentifier, element -> element instanceof DartFunctionDeclarationWithBodyOrNative);
assertTrue(DartSyntax.isMainFunctionDeclaration(main));
});
}
@Test
public void shouldFindEnclosingFunctionCall() throws Exception {
run(() -> {
final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);
final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, "test");
assertNotNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
});
}
@Test
public void shouldFindEnclosingFunctionCallPattern() throws Exception {
run(() -> {
final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);
final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, Pattern.compile("t.*t"));
assertNotNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
});
}
@Test
public void shouldNotFindEnclosingFunctionCallPattern() throws Exception {
run(() -> {
final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);
final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, Pattern.compile("t.*a"));
assertNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
});
}
@Test
public void shouldGetFirstArgumentFromFunctionCall() throws Exception {
run(() -> {
final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);
final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, "test");
assertNotNull(call);
final DartStringLiteralExpression lit = DartSyntax.getArgument(call, 0, DartStringLiteralExpression.class);
assertNotNull("getSyntax() didn't return first argument", lit);
});
}
private ConfigurationContext getMainContext() {
// Set up fake source code.
final PsiElement mainIdentifier = setUpDartElement(
"workspace/foo/bar.dart", fileContents, "main", LeafPsiElement.class);
final PsiElement main = PsiTreeUtil.findFirstParent(
mainIdentifier, element -> element instanceof DartFunctionDeclarationWithBodyOrNative);
assertThat(main, not(equalTo(null)));
return new ConfigurationContext(main);
}
private ConfigurationContext getTest1Context() {
// Set up fake source code.
final PsiElement testIdentifier = setUpDartElement(
TEST_FILE_PATH, fileContents, "test 1", LeafPsiElement.class);
final PsiElement test =
PsiTreeUtil.findFirstParent(testIdentifier, element -> element instanceof DartStringLiteralExpression);
assertThat(test, not(equalTo(null)));
return new ConfigurationContext(test);
}
/**
* Gets a specific test or test group call.
*
* @param functionName The name of the function being called, eg test() or testWidgets()
* @param testName The name of the test desired, such as 'test 0' or 'test widgets 0'
* @param filePath The file containing the desired test.
*/
@NotNull
private DartCallExpression getTestCallWithName(String functionName, String testName, String filePath) {
final PsiElement testIdentifier = setUpDartElement(filePath,
fileContents.get(filePath), testName, LeafPsiElement.class);
assertThat(testIdentifier, not(equalTo(null)));
final DartCallExpression result = DartSyntax.findClosestEnclosingFunctionCall(testIdentifier);
assertThat(result, not(equalTo(null)));
return result;
}
@Test
public void isMainFunctionDeclaration() throws Exception {
run(() -> {
final PsiElement mainIdentifier = setUpDartElement("main() { test('my first test', () {} ); }", "main", LeafPsiElement.class);
final PsiElement main =
PsiTreeUtil.findFirstParent(mainIdentifier, element -> element instanceof DartFunctionDeclarationWithBodyOrNative);
assertTrue(DartSyntax.isMainFunctionDeclaration(main));
});
}
@Test
public void shouldFindEnclosingFunctionCall() throws Exception {
run(() -> {
final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);
final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, "test");
assertNotNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
});
}
@Test
public void shouldFindEnclosingFunctionCallPattern() throws Exception {
run(() -> {
final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);
final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, Pattern.compile("t.*t"));
assertNotNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
});
}
@Test
public void shouldNotFindEnclosingFunctionCallPattern() throws Exception {
run(() -> {
final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);
final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, Pattern.compile("t.*a"));
assertNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
});
}
@Test
public void shouldGetFirstArgumentFromFunctionCall() throws Exception {
run(() -> {
final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);
final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, "test");
assertNotNull(call);
final DartStringLiteralExpression lit = DartSyntax.getArgument(call, 0, DartStringLiteralExpression.class);
assertNotNull("getSyntax() didn't return first argument", lit);
});
}
private ConfigurationContext getMainContext() {
// Set up fake source code.
final PsiElement mainIdentifier = setUpDartElement(
"workspace/foo/bar.dart", fileContents, "main", LeafPsiElement.class);
final PsiElement main = PsiTreeUtil.findFirstParent(
mainIdentifier, element -> element instanceof DartFunctionDeclarationWithBodyOrNative);
assertThat(main, not(equalTo(null)));
return new ConfigurationContext(main);
}
private ConfigurationContext getTest1Context() {
// Set up fake source code.
final PsiElement testIdentifier = setUpDartElement(
TEST_FILE_PATH, fileContents, "test 1", LeafPsiElement.class);
final PsiElement test =
PsiTreeUtil.findFirstParent(testIdentifier, element -> element instanceof DartStringLiteralExpression);
assertThat(test, not(equalTo(null)));
return new ConfigurationContext(test);
}
/**
* Gets a specific test or test group call.
*
* @param functionName The name of the function being called, eg test() or testWidgets()
* @param testName The name of the test desired, such as 'test 0' or 'test widgets 0'
* @param filePath The file containing the desired test.
*/
@NotNull
private DartCallExpression getTestCallWithName(String functionName, String testName, String filePath) {
final PsiElement testIdentifier = setUpDartElement(filePath,
fileContents.get(filePath), testName, LeafPsiElement.class);
assertThat(testIdentifier, not(equalTo(null)));
final DartCallExpression result = DartSyntax.findClosestEnclosingFunctionCall(testIdentifier);
assertThat(result, not(equalTo(null)));
return result;
}
@Override
public Optional<String> extractTextFromElement(PsiElement element, boolean concatString, boolean stripWhitespace) {
// maybe its yaml
if (element instanceof LeafPsiElement) {
IElementType type = ((LeafPsiElement) element).getElementType();
if (type.getLanguage().isKindOf("yaml")) {
return Optional.ofNullable(element.getText());
}
}
return Optional.empty();
}