com.intellij.psi.PsiInvalidElementAccessException Java Examples

The following examples show how to use com.intellij.psi.PsiInvalidElementAccessException. 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: WeexFileUtil.java    From weex-language-support with MIT License 6 votes vote down vote up
private static boolean isValid(JSObjectLiteralExpression expression) {
    if (expression == null) {
        return false;
    }
    try {
        PsiFile file = expression.getContainingFile();
        if (file == null) {
            return false;
        }
    } catch (PsiInvalidElementAccessException e) {
        return false;
    }
    JSProperty data = expression.findProperty("data");
    if (data == null || data.getValue() == null) {
        return false;
    }
    return true;
}
 
Example #2
Source File: WeexFileUtil.java    From weex-language-support with MIT License 6 votes vote down vote up
public static int getExportsEndOffset(PsiElement anyElementOnWeexScript, String name) {
    JSObjectLiteralExpression exports = getExportsStatement(anyElementOnWeexScript);
    if (exports != null) {
        try {
            PsiFile file = exports.getContainingFile();
            if (file == null) {
                return -1;
            }
        } catch (PsiInvalidElementAccessException e) {
            return -1;
        }
        JSProperty data = exports.findProperty(name);
        if (data == null || data.getValue() == null) {
            return -1;
        }
        return data.getValue().getTextRange().getEndOffset() - 1;
    }
    return -1;
}
 
Example #3
Source File: SubstrateRef.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
static SubstrateRef createInvalidRef(@Nonnull final StubBasedPsiElementBase<?> psi) {
  return new SubstrateRef() {
    @Nonnull
    @Override
    public ASTNode getNode() {
      throw new PsiInvalidElementAccessException(psi);
    }

    @Override
    public boolean isValid() {
      return false;
    }

    @Nonnull
    @Override
    public PsiFile getContainingFile() {
      throw new PsiInvalidElementAccessException(psi);
    }
  };
}
 
Example #4
Source File: ASTDelegatePsiElement.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public PsiManagerEx getManager() {
  Project project = ProjectCoreUtil.theOnlyOpenProject();
  if (project != null) {
    return PsiManagerEx.getInstanceEx(project);
  }
  PsiElement parent = this;

  while (parent instanceof ASTDelegatePsiElement) {
    parent = parent.getParent();
  }

  if (parent == null) {
    throw new PsiInvalidElementAccessException(this);
  }

  return (PsiManagerEx)parent.getManager();
}
 
Example #5
Source File: StubBasedPsiElementBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures this element is AST-based. This is an expensive operation that might take significant time and allocate lots of objects,
 * so it should be to be avoided if possible.
 *
 * @return an AST node corresponding to this element. If the element is currently operating via stubs,
 * this causes AST to be loaded for the whole file and all stub-based PSI elements in this file (including the current one)
 * to be switched from stub to AST. So, after this call {@link #getStub()} will return null.
 */
@Override
@Nonnull
public ASTNode getNode() {
  if (mySubstrateRef instanceof SubstrateRef.StubRef) {
    ApplicationManager.getApplication().assertReadAccessAllowed();
    PsiFileImpl file = (PsiFileImpl)getContainingFile();
    if (!file.isValid()) throw new PsiInvalidElementAccessException(file);

    FileElement treeElement = file.getTreeElement();
    if (treeElement != null && mySubstrateRef instanceof SubstrateRef.StubRef) {
      return notBoundInExistingAst(file, treeElement);
    }

    treeElement = file.calcTreeElement();
    if (mySubstrateRef instanceof SubstrateRef.StubRef) {
      return failedToBindStubToAst(file, treeElement);
    }
  }

  return mySubstrateRef.getNode();
}
 
Example #6
Source File: ExcludedFileFormattingRestriction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isFormatterAllowed(@Nonnull PsiElement context) {
  try {
    PsiFile file = context.getContainingFile();
    CodeStyleSettings settings = CodeStyle.getSettings(file);
    return !settings.getExcludedFiles().contains(file);
  }
  catch (PsiInvalidElementAccessException e) {
    return false;
  }
}
 
Example #7
Source File: ORUtil.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
@NotNull
public static String getQualifiedPath(@NotNull PsiNameIdentifierOwner element) {
    String path = "";

    PsiElement parent = element.getParent();
    while (parent != null) {
        if (parent instanceof PsiQualifiedElement) {
            if (parent instanceof PsiNameIdentifierOwner && ((PsiNameIdentifierOwner) parent).getNameIdentifier() == element) {
                return ((PsiQualifiedElement) parent).getPath();
            }
            return ((PsiQualifiedElement) parent).getQualifiedName() + (path.isEmpty() ? "" : "." + path);
        } else {
            if (parent instanceof PsiNameIdentifierOwner) {
                String parentName = ((PsiNamedElement) parent).getName();
                if (parentName != null && !parentName.isEmpty()) {
                    path = parentName + (path.isEmpty() ? "" : "." + path);
                }
            }
            parent = parent.getParent();
        }
    }

    try {
        PsiFile containingFile = element.getContainingFile(); // Fail in 2019.2... ?
        return ((FileBase) containingFile).getModuleName() + (path.isEmpty() ? "" : "." + path);
    } catch (PsiInvalidElementAccessException e) {
        return path;
    }
}
 
Example #8
Source File: WeexFileUtil.java    From weex-language-support with MIT License 5 votes vote down vote up
public static JSProperty getVarDeclaration(PsiElement anyElementOnWeexScript, String valueName) {
    valueName = CodeUtil.getVarNameFromMustache(valueName);
    JSObjectLiteralExpression exports = getExportsStatement(anyElementOnWeexScript);
    vars.clear();
    JSProperty ret = null;
    if (exports != null) {
        try {
            PsiFile file = exports.getContainingFile();
            if (file == null) {
                return null;
            }
        } catch (PsiInvalidElementAccessException e) {
            return null;
        }
        JSProperty data = exports.findProperty("data");
        if (data == null || data.getValue() == null) {
            return null;
        }
        for (PsiElement pe : data.getValue().getChildren()) {
            if (pe instanceof JSProperty) {
                String varName = ((JSProperty) pe).getName();
                String varValue = getJSPropertyType((JSProperty) pe);
                if (varName != null && varValue != null) {
                    vars.put(varName, varValue);
                }
                if (valueName.equals(varName)) {
                    ret = (JSProperty) pe;
                }
            }

        }
    }
    return ret;
}
 
Example #9
Source File: SubstrateRef.java    From consulo with Apache License 2.0 5 votes vote down vote up
private PsiFile reportError(StubElement stub) {
  ApplicationManager.getApplication().assertReadAccessAllowed();

  String reason = ((PsiFileStubImpl<?>)stub).getInvalidationReason();
  PsiInvalidElementAccessException exception = new PsiInvalidElementAccessException(myStub.getPsi(), "no psi for file stub " + stub + ", invalidation reason=" + reason, null);
  if (PsiFileImpl.STUB_PSI_MISMATCH.equals(reason)) {
    // we're between finding stub-psi mismatch and the next EDT spot where the file is reparsed and stub rebuilt
    //    see com.intellij.psi.impl.source.PsiFileImpl.rebuildStub()
    // most likely it's just another highlighting thread accessing the same PSI concurrently and not yet canceled, so cancel it
    throw new ProcessCanceledException(exception);
  }
  throw exception;
}
 
Example #10
Source File: ExposingClauseReferenceHelper.java    From elm-plugin with MIT License 5 votes vote down vote up
@Nullable
public static PsiElement resolveExposed(PsiElement element, Function<ElmFile, PsiElement> resolveInFile) {
    PsiFile file;
    try {
        file = element.getContainingFile();
    } catch (PsiInvalidElementAccessException ex) {
        return null;
    }
    return resolveExposed(file, resolveInFile);
}
 
Example #11
Source File: FileElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public PsiManagerEx getManager() {
  CompositeElement treeParent = getTreeParent();
  if (treeParent != null) return treeParent.getManager();
  PsiElement psi = getPsi();
  if (psi == null) throw PsiInvalidElementAccessException.createByNode(this, null);
  return (PsiManagerEx)psi.getManager();
}
 
Example #12
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 #13
Source File: StubBasedPsiElementBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public PsiFile getContainingFile() {
  try {
    return mySubstrateRef.getContainingFile();
  }
  catch (PsiInvalidElementAccessException e) {
    if (PsiInvalidElementAccessException.getInvalidationTrace(this) != null) {
      throw new PsiInvalidElementAccessException(this, e);
    }
    else {
      throw e;
    }
  }
}
 
Example #14
Source File: YamlLineMarkerProvider.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void attachEntityClass(@NotNull Collection<LineMarkerInfo> lineMarkerInfos, @NotNull PsiElement psiElement) {
    if(psiElement.getNode().getElementType() != YAMLTokenTypes.SCALAR_KEY) {
        return;
    }

    PsiElement yamlKeyValue = psiElement.getParent();
    if(!(yamlKeyValue instanceof YAMLKeyValue)) {
        return;
    }

    if(yamlKeyValue.getParent() instanceof YAMLMapping && yamlKeyValue.getParent().getParent() instanceof YAMLDocument) {
        PsiFile containingFile;
        try {
            containingFile = yamlKeyValue.getContainingFile();
        } catch (PsiInvalidElementAccessException e) {
            return;
        }

        String fileName = containingFile.getName();
        if(isMetadataFile(fileName)) {
            String keyText = ((YAMLKeyValue) yamlKeyValue).getKeyText();
            if(StringUtils.isNotBlank(keyText)) {
                Collection<PhpClass> phpClasses = PhpElementsUtil.getClassesInterface(psiElement.getProject(), keyText);
                if(phpClasses.size() > 0) {
                    NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.DOCTRINE_LINE_MARKER).
                        setTargets(phpClasses).
                        setTooltipText("Navigate to class");

                    lineMarkerInfos.add(builder.createLineMarkerInfo(psiElement));
                }
            }
        }
    }
}
 
Example #15
Source File: CSharpResolveUtil.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
public static boolean treeWalkUp(@Nonnull final PsiScopeProcessor processor,
		@Nonnull final PsiElement entrance,
		@Nonnull final PsiElement sender,
		@Nullable PsiElement maxScope,
		@Nonnull final ResolveState state)
{
	if(!entrance.isValid())
	{
		CSharpResolveUtil.LOG.error(new PsiInvalidElementAccessException(entrance));
	}

	PsiElement prevParent = entrance;
	PsiElement scope = entrance;

	if(maxScope == null)
	{
		maxScope = sender.getContainingFile();
	}

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

		if(entrance != sender && scope instanceof PsiFile)
		{
			break;
		}

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

		if(entrance != sender)
		{
			break;
		}

		if(scope == maxScope)
		{
			break;
		}

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

	return true;
}
 
Example #16
Source File: CSharpResolveUtil.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
public static boolean walkUsing(@Nonnull final PsiScopeProcessor processor, @Nonnull final PsiElement entrance, @Nullable PsiElement maxScope, @Nonnull final ResolveState state)
{
	if(!entrance.isValid())
	{
		LOG.error(new PsiInvalidElementAccessException(entrance));
	}

	DotNetNamespaceAsElement root = DotNetPsiSearcher.getInstance(entrance.getProject()).findNamespace("", entrance.getResolveScope());

	// skip null - indexing
	if(root == null)
	{
		return true;
	}

	if(!processor.execute(root, state))
	{
		return false;
	}

	// we cant go to use list
	if(PsiTreeUtil.getParentOfType(entrance, CSharpUsingListChild.class) != null)
	{
		return true;
	}

	CSharpResolveSelector selector = state.get(SELECTOR);
	if(selector instanceof MemberByNameSelector)
	{
		((MemberByNameSelector) selector).putUserData(BaseDotNetNamespaceAsElement.FILTER, DotNetNamespaceAsElement.ChildrenFilter.ONLY_ELEMENTS);
	}

	PsiElement prevParent = entrance;
	PsiElement scope = entrance;

	maxScope = validateMaxScope(entrance, maxScope);

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

		if(scope instanceof CSharpUsingListOwner)
		{
			CSharpUsingListChild[] usingStatements = ((CSharpUsingListOwner) scope).getUsingStatements();
			for(CSharpUsingListChild usingStatement : usingStatements)
			{
				ProgressManager.checkCanceled();

				if(!processor.execute(usingStatement, state))
				{
					return false;
				}
			}
		}

		if(scope == maxScope)
		{
			break;
		}

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

	return true;
}
 
Example #17
Source File: LSPPSiElement.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
@NotNull
@Override
public Project getProject() throws PsiInvalidElementAccessException {
    return project;
}
 
Example #18
Source File: PhpToolboxGotoDeclarationHandler.java    From idea-php-toolbox with MIT License 4 votes vote down vote up
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(@Nullable PsiElement psiElement, int i, Editor editor) {
    if(psiElement == null) {
        return new PsiElement[0];
    }

    PsiFile containingFile;
    try {
        containingFile = psiElement.getContainingFile();
    } catch (PsiInvalidElementAccessException e) {
        return new PsiElement[0];
    }

    FileType fileType = containingFile.getFileType();
    if(!(fileType instanceof PhpFileType) && !(fileType instanceof TwigFileType)) {
        return new PsiElement[0];
    }

    String selectedItem = null;
    if(psiElement.getNode().getElementType() == TwigTokenTypes.STRING_TEXT) {
        // twig language
        selectedItem = psiElement.getText();
    } else {
        // php language

        PsiElement stringLiteral = psiElement.getParent();
        if(stringLiteral instanceof StringLiteralExpression) {
            selectedItem = ((StringLiteralExpression) stringLiteral).getContents();
        }
    }

    if(StringUtils.isBlank(selectedItem)) {
        return new PsiElement[0];
    }

    Map<PhpToolboxProviderInterface, Set<JsonRegistrar>> providers = RegistrarMatchUtil.getProviders(psiElement);
    if(providers.size() == 0) {
        return new PsiElement[0];
    }

    PhpToolboxDeclarationHandlerParameter parameter = new PhpToolboxDeclarationHandlerParameter(psiElement, selectedItem, fileType);

    Collection<PsiElement> targets = new HashSet<>();
    for (Map.Entry<PhpToolboxProviderInterface, Set<JsonRegistrar>> provider : providers.entrySet()) {
        targets.addAll(provider.getKey().getPsiTargets(parameter));
    }

    return targets.toArray(new PsiElement[targets.size()]);
}
 
Example #19
Source File: PhpToolboxGotoDeclarationHandler.java    From idea-php-toolbox with MIT License 4 votes vote down vote up
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(@Nullable PsiElement psiElement, int i, Editor editor) {
    if(psiElement == null) {
        return new PsiElement[0];
    }

    PsiFile containingFile;
    try {
        containingFile = psiElement.getContainingFile();
    } catch (PsiInvalidElementAccessException e) {
        return new PsiElement[0];
    }

    FileType fileType = containingFile.getFileType();
    if(!(fileType instanceof PhpFileType) && !(fileType instanceof TwigFileType)) {
        return new PsiElement[0];
    }

    String selectedItem = null;
    if(psiElement.getNode().getElementType() == TwigTokenTypes.STRING_TEXT) {
        // twig language
        selectedItem = psiElement.getText();
    } else {
        // php language

        PsiElement stringLiteral = psiElement.getParent();
        if(stringLiteral instanceof StringLiteralExpression) {
            selectedItem = ((StringLiteralExpression) stringLiteral).getContents();
        }
    }

    if(StringUtils.isBlank(selectedItem)) {
        return new PsiElement[0];
    }

    Map<PhpToolboxProviderInterface, Set<JsonRegistrar>> providers = RegistrarMatchUtil.getProviders(psiElement);
    if(providers.size() == 0) {
        return new PsiElement[0];
    }

    PhpToolboxDeclarationHandlerParameter parameter = new PhpToolboxDeclarationHandlerParameter(psiElement, selectedItem, fileType);

    Collection<PsiElement> targets = new HashSet<>();
    for (Map.Entry<PhpToolboxProviderInterface, Set<JsonRegistrar>> provider : providers.entrySet()) {
        targets.addAll(provider.getKey().getPsiTargets(parameter));
    }

    return targets.toArray(new PsiElement[targets.size()]);
}
 
Example #20
Source File: TestLineMarkerContributor.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@NotNull
private static Icon getTestStateIcon(@NotNull PsiElement element, @NotNull Icon defaultIcon) {
  // SMTTestProxy maps test run data to a URI derived from a location hint produced by `package:test`.
  // If we can find corresponding data, we can provide state-aware icons. If not, we default to
  // a standard Run state.

  PsiFile containingFile;
  try {
    containingFile = element.getContainingFile();
  }
  catch (PsiInvalidElementAccessException e) {
    containingFile = null;
  }

  final Project project = element.getProject();
  final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);

  final Document document = containingFile == null ? null : psiDocumentManager.getDocument(containingFile);
  if (document != null) {
    final int textOffset = element.getTextOffset();
    final int lineNumber = document.getLineNumber(textOffset);

    // e.g., dart_location:///Users/pq/IdeaProjects/untitled1298891289891/test/unit_test.dart,3,2,["my first unit test"]
    final String path = FileUtil.toSystemIndependentName(containingFile.getVirtualFile().getPath());
    final String testLocationPrefix = "dart_location://" + path + "," + lineNumber;

    final TestStateStorage storage = TestStateStorage.getInstance(project);
    if (storage != null) {
      final Map<String, TestStateStorage.Record> tests = storage.getRecentTests(SCANNED_TEST_RESULT_LIMIT, getSinceDate());
      if (tests != null) {
        // TODO(pq): investigate performance implications.
        for (Map.Entry<String, TestStateStorage.Record> entry : tests.entrySet()) {
          if (entry.getKey().startsWith(testLocationPrefix)) {
            final TestStateStorage.Record state = entry.getValue();
            final TestStateInfo.Magnitude magnitude = TestIconMapper.getMagnitude(state.magnitude);
            if (magnitude != null) {
              switch (magnitude) {
                case IGNORED_INDEX:
                  return AllIcons.RunConfigurations.TestState.Yellow2;
                case ERROR_INDEX:
                case FAILED_INDEX:
                  return AllIcons.RunConfigurations.TestState.Red2;
                case PASSED_INDEX:
                case COMPLETE_INDEX:
                  return AllIcons.RunConfigurations.TestState.Green2;
                default:
              }
            }
          }
        }
      }
    }
  }

  return defaultIcon;
}
 
Example #21
Source File: TestLineMarkerContributor.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@NotNull
private static Icon getTestStateIcon(@NotNull PsiElement element, @NotNull Icon defaultIcon) {
  // SMTTestProxy maps test run data to a URI derived from a location hint produced by `package:test`.
  // If we can find corresponding data, we can provide state-aware icons. If not, we default to
  // a standard Run state.

  PsiFile containingFile;
  try {
    containingFile = element.getContainingFile();
  }
  catch (PsiInvalidElementAccessException e) {
    containingFile = null;
  }

  final Project project = element.getProject();
  final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);

  final Document document = containingFile == null ? null : psiDocumentManager.getDocument(containingFile);
  if (document != null) {
    final int textOffset = element.getTextOffset();
    final int lineNumber = document.getLineNumber(textOffset);

    // e.g., dart_location:///Users/pq/IdeaProjects/untitled1298891289891/test/unit_test.dart,3,2,["my first unit test"]
    final String path = FileUtil.toSystemIndependentName(containingFile.getVirtualFile().getPath());
    final String testLocationPrefix = "dart_location://" + path + "," + lineNumber;

    final TestStateStorage storage = TestStateStorage.getInstance(project);
    if (storage != null) {
      final Map<String, TestStateStorage.Record> tests = storage.getRecentTests(SCANNED_TEST_RESULT_LIMIT, getSinceDate());
      if (tests != null) {
        // TODO(pq): investigate performance implications.
        for (Map.Entry<String, TestStateStorage.Record> entry : tests.entrySet()) {
          if (entry.getKey().startsWith(testLocationPrefix)) {
            final TestStateStorage.Record state = entry.getValue();
            final TestStateInfo.Magnitude magnitude = TestIconMapper.getMagnitude(state.magnitude);
            if (magnitude != null) {
              switch (magnitude) {
                case IGNORED_INDEX:
                  return AllIcons.RunConfigurations.TestState.Yellow2;
                case ERROR_INDEX:
                case FAILED_INDEX:
                  return AllIcons.RunConfigurations.TestState.Red2;
                case PASSED_INDEX:
                case COMPLETE_INDEX:
                  return AllIcons.RunConfigurations.TestState.Green2;
                default:
              }
            }
          }
        }
      }
    }
  }

  return defaultIcon;
}
 
Example #22
Source File: LSPPSiElement.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public PsiFile getContainingFile() throws PsiInvalidElementAccessException {
    return file;
}