@NotNull
  private MostlySingularMultiMap<String, AnnotationData> getDataFromFile(
      @NotNull final PsiFile file) {
    Pair<MostlySingularMultiMap<String, AnnotationData>, Long> cached =
        annotationFileToDataAndModStamp.get(file);
    final long fileModificationStamp = file.getModificationStamp();
    if (cached != null && cached.getSecond() == fileModificationStamp) {
      return cached.getFirst();
    }
    DataParsingSaxHandler handler = new DataParsingSaxHandler(file);
    try {
      SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
      saxParser.parse(new InputSource(new StringReader(escapeAttributes(file.getText()))), handler);
    } catch (IOException e) {
      LOG.error(e);
    } catch (ParserConfigurationException e) {
      LOG.error(e);
    } catch (SAXException e) {
      LOG.error(e);
    }

    Pair<MostlySingularMultiMap<String, AnnotationData>, Long> pair =
        Pair.create(handler.getResult(), file.getModificationStamp());
    annotationFileToDataAndModStamp.put(file, pair);

    return pair.first;
  }
  public void readExternal(Element element) throws InvalidDataException {
    super.readExternal(element);
    final String locked = element.getAttributeValue(IS_LOCKED);
    if (locked != null) {
      myLockedProfile = Boolean.parseBoolean(locked);
    }
    myBaseProfile = getDefaultProfile();
    final String version = element.getAttributeValue(VERSION_TAG);
    if (version == null || !version.equals(VALID_VERSION)) {
      try {
        element = InspectionProfileConvertor.convertToNewFormat(element, this);
      } catch (IOException e) {
        LOG.error(e);
      } catch (JDOMException e) {
        LOG.error(e);
      }
    }

    final Element highlightElement = element.getChild(USED_LEVELS);
    if (highlightElement != null) { // from old profiles
      ((SeverityProvider) getProfileManager())
          .getOwnSeverityRegistrar()
          .readExternal(highlightElement);
    }

    for (final Object o : element.getChildren(INSPECTION_TOOL_TAG)) {
      Element toolElement = (Element) o;

      String toolClassName = toolElement.getAttributeValue(CLASS_TAG);

      myDeinstalledInspectionsSettings.put(toolClassName, toolElement);
    }
  }
Пример #3
0
 /**
  * We know that there are problems with incremental soft wraps cache update at the moment. Hence,
  * we may implement full cache reconstruction when the problem is encountered in order to avoid
  * customer annoyance.
  *
  * <p>However, the problems still should be fixed, hence, we report them only if dedicated flag is
  * set.
  *
  * <p>Current method encapsulates the logic mentioned above.
  *
  * @param task command object that which execution may trigger incremental update of update soft
  *     wraps cache
  */
 @SuppressWarnings({"UseOfArchaicSystemPropertyAccessors"})
 private void executeSafely(SoftWrapAwareTask task) {
   try {
     task.run(true);
   } catch (Throwable e) {
     if (Boolean.getBoolean(DEBUG_PROPERTY_NAME)) {
       LOG.error(
           String.format(
               "Unexpected exception occurred during performing '%s'. Current soft wraps cache: %n"
                   + "%s%nFold regions: %s",
               task, myDataMapper, Arrays.toString(myEditor.getFoldingModel().fetchTopLevel())),
           e);
     }
     myEditor.getFoldingModel().rebuild();
     myDataMapper.release();
     myApplianceManager.reset();
     myStorage.removeAll();
     try {
       task.run(true);
     } catch (Throwable e1) {
       LOG.error(
           String.format(
               "Can't perform %s even with complete soft wraps cache re-parsing. Current soft wraps cache: %n"
                   + "%s. Document:%n%s%nFold regions: %s",
               task,
               myDataMapper,
               myEditor.getDocument().getText(),
               Arrays.toString(myEditor.getFoldingModel().fetchTopLevel())),
           e1);
       myEditor.getSettings().setUseSoftWraps(false);
       task.run(false);
     }
   }
 }
 @Override
 @NotNull
 public Project[] getOpenProjects() {
   synchronized (myOpenProjects) {
     if (myOpenProjectsArrayCache.length != myOpenProjects.size()) {
       LOG.error(
           "Open projects: "
               + myOpenProjects
               + "; cache: "
               + Arrays.asList(myOpenProjectsArrayCache));
     }
     if (myOpenProjectsArrayCache.length > 0
         && myOpenProjectsArrayCache[0] != myOpenProjects.get(0)) {
       LOG.error(
           "Open projects cache corrupted. Open projects: "
               + myOpenProjects
               + "; cache: "
               + Arrays.asList(myOpenProjectsArrayCache));
     }
     if (ApplicationManager.getApplication().isUnitTestMode()) {
       Project[] testProjects = myTestProjects.toArray(new Project[myTestProjects.size()]);
       for (Project testProject : testProjects) {
         assert !testProject.isDisposed() : testProject;
       }
       return ArrayUtil.mergeArrays(myOpenProjectsArrayCache, testProjects);
     }
     return myOpenProjectsArrayCache;
   }
 }
Пример #5
0
  @NotNull
  public static <T extends PsiJavaCodeReferenceElement> JavaResolveResult[] multiResolveImpl(
      @NotNull T element,
      boolean incompleteCode,
      @NotNull ResolveCache.PolyVariantContextResolver<? super T> resolver) {

    FileASTNode fileElement = SharedImplUtil.findFileElement(element.getNode());
    if (fileElement == null) {
      PsiUtilCore.ensureValid(element);
      LOG.error("fileElement == null!");
      return JavaResolveResult.EMPTY_ARRAY;
    }
    PsiFile psiFile = SharedImplUtil.getContainingFile(fileElement);
    PsiManager manager = psiFile == null ? null : psiFile.getManager();
    if (manager == null) {
      PsiUtilCore.ensureValid(element);
      LOG.error("getManager() == null!");
      return JavaResolveResult.EMPTY_ARRAY;
    }
    boolean valid = psiFile.isValid();
    if (!valid) {
      PsiUtilCore.ensureValid(element);
      LOG.error("psiFile.isValid() == false!");
      return JavaResolveResult.EMPTY_ARRAY;
    }
    if (element instanceof PsiMethodReferenceExpression) {
      // method refs: do not cache results during parent conflict resolving, acceptable checks, etc
      final Map<PsiElement, PsiType> map = LambdaUtil.ourFunctionTypes.get();
      if (map != null && map.containsKey(element)) {
        return (JavaResolveResult[]) resolver.resolve(element, psiFile, incompleteCode);
      }
    }

    return multiResolveImpl(manager.getProject(), psiFile, element, incompleteCode, resolver);
  }
 /**
  * We know that there are problems with incremental soft wraps cache update at the moment. Hence,
  * we may implement full cache reconstruction when the problem is encountered in order to avoid
  * customer annoyance.
  *
  * <p>However, the problems still should be fixed, hence, we report them only if dedicated flag is
  * set.
  *
  * <p>Current method encapsulates the logic mentioned above.
  *
  * @param task command object that which execution may trigger incremental update of update soft
  *     wraps cache
  */
 @SuppressWarnings({"UseOfArchaicSystemPropertyAccessors"})
 private void executeSafely(SoftWrapAwareTask task) {
   try {
     task.run(true);
   } catch (Throwable e) {
     if (Boolean.getBoolean(DEBUG_PROPERTY_NAME)
         || ApplicationManager.getApplication().isUnitTestMode()) {
       String info = myEditor.dumpState();
       LOG.error(
           String.format("Unexpected exception occurred during performing '%s'", task), e, info);
     }
     myEditor.getFoldingModel().rebuild();
     myDataMapper.release();
     myApplianceManager.reset();
     myStorage.removeAll();
     myApplianceManager.recalculateIfNecessary();
     try {
       task.run(true);
     } catch (Throwable e1) {
       String info = myEditor.dumpState();
       LOG.error(
           String.format("Can't perform %s even with complete soft wraps cache re-parsing", task),
           e1,
           info);
       myEditor.getSettings().setUseSoftWraps(false);
       task.run(false);
     }
   }
 }
Пример #7
0
 @Nullable
 public static DomNameStrategy getDomNameStrategy(final Class<?> rawType, boolean isAttribute) {
   Class aClass = null;
   if (isAttribute) {
     NameStrategyForAttributes annotation =
         DomReflectionUtil.findAnnotationDFS(rawType, NameStrategyForAttributes.class);
     if (annotation != null) {
       aClass = annotation.value();
     }
   }
   if (aClass == null) {
     NameStrategy annotation = DomReflectionUtil.findAnnotationDFS(rawType, NameStrategy.class);
     if (annotation != null) {
       aClass = annotation.value();
     }
   }
   if (aClass != null) {
     if (HyphenNameStrategy.class.equals(aClass)) return DomNameStrategy.HYPHEN_STRATEGY;
     if (JavaNameStrategy.class.equals(aClass)) return DomNameStrategy.JAVA_STRATEGY;
     try {
       return (DomNameStrategy) aClass.newInstance();
     } catch (InstantiationException e) {
       LOG.error(e);
     } catch (IllegalAccessException e) {
       LOG.error(e);
     }
   }
   return null;
 }
Пример #8
0
 @Nullable
 public static String getReferencePrefix(@NotNull PsiElement insertedElement, int offsetInFile) {
   final PsiReference ref = insertedElement.getContainingFile().findReferenceAt(offsetInFile);
   if (ref != null) {
     final PsiElement element = ref.getElement();
     final int endIndex = offsetInFile - element.getTextRange().getStartOffset();
     final int beginIndex = ref.getRangeInElement().getStartOffset();
     if (beginIndex > endIndex) {
       LOG.error(
           "Inconsistent reference (found at offset not included in its range): ref="
               + ref
               + " element="
               + element
               + " text="
               + element.getText());
     }
     if (beginIndex < 0) {
       LOG.error(
           "Inconsistent reference (begin < 0): ref="
               + ref
               + " element="
               + element
               + "; begin="
               + beginIndex
               + " text="
               + element.getText());
     }
     LOG.assertTrue(endIndex >= 0);
     return element.getText().substring(beginIndex, endIndex);
   }
   return null;
 }
Пример #9
0
 @Override
 public final void documentChanged(@NotNull DocumentEvent e) {
   int oldStart = intervalStart();
   int oldEnd = intervalEnd();
   int docLength = myDocument.getTextLength();
   if (!isValid()) {
     LOG.error(
         "Invalid range marker "
             + (isGreedyToLeft() ? "[" : "(")
             + oldStart
             + ", "
             + oldEnd
             + (isGreedyToRight() ? "]" : ")")
             + ". Event = "
             + e
             + ". Doc length="
             + docLength
             + "; "
             + getClass());
     return;
   }
   if (intervalStart() > intervalEnd()
       || intervalStart() < 0
       || intervalEnd() > docLength - e.getNewLength() + e.getOldLength()) {
     LOG.error(
         "RangeMarker"
             + (isGreedyToLeft() ? "[" : "(")
             + oldStart
             + ", "
             + oldEnd
             + (isGreedyToRight() ? "]" : ")")
             + " is invalid before update. Event = "
             + e
             + ". Doc length="
             + docLength
             + "; "
             + getClass());
     invalidate(e);
     return;
   }
   changedUpdateImpl(e);
   if (isValid()
       && (intervalStart() > intervalEnd() || intervalStart() < 0 || intervalEnd() > docLength)) {
     LOG.error(
         "Update failed. Event = "
             + e
             + ". "
             + "old doc length="
             + docLength
             + "; real doc length = "
             + myDocument.getTextLength()
             + "; "
             + getClass()
             + "."
             + " After update: '"
             + this
             + "'");
     invalidate(e);
   }
 }
  @SuppressWarnings("OverlyBroadCatchBlock")
  private void multiCast(@NotNull Method method, Object[] args) {
    try {
      method.invoke(myBus.syncPublisher(AppTopics.FILE_DOCUMENT_SYNC), args);
    } catch (ClassCastException e) {
      LOG.error("Arguments: " + Arrays.toString(args), e);
    } catch (Exception e) {
      LOG.error(e);
    }

    // Allows pre-save document modification
    for (FileDocumentManagerListener listener : getListeners()) {
      try {
        method.invoke(listener, args);
      } catch (Exception e) {
        LOG.error(e);
      }
    }

    // stripping trailing spaces
    try {
      method.invoke(myTrailingSpacesStripper, args);
    } catch (Exception e) {
      LOG.error(e);
    }
  }
  @Nullable
  private XmlFile createAnnotationsXml(
      @NotNull VirtualFile root, @NonNls @NotNull String packageName) {
    final String[] dirs = packageName.split("[\\.]");
    for (String dir : dirs) {
      if (dir.isEmpty()) break;
      VirtualFile subdir = root.findChild(dir);
      if (subdir == null) {
        try {
          subdir = root.createChildDirectory(null, dir);
        } catch (IOException e) {
          LOG.error(e);
        }
      }
      root = subdir;
    }
    final PsiDirectory directory = myPsiManager.findDirectory(root);
    if (directory == null) return null;

    final PsiFile psiFile = directory.findFile(ANNOTATIONS_XML);
    if (psiFile instanceof XmlFile) {
      return (XmlFile) psiFile;
    }

    try {
      final PsiFileFactory factory = PsiFileFactory.getInstance(myPsiManager.getProject());
      return (XmlFile)
          directory.add(
              factory.createFileFromText(ANNOTATIONS_XML, XmlFileType.INSTANCE, "<root></root>"));
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
    return null;
  }
Пример #12
0
  @NotNull
  private static FetchParams getFetchParams(@NotNull GitRepository repository) {
    GitLocalBranch currentBranch = repository.getCurrentBranch();
    if (currentBranch == null) {
      // fetching current branch is called from Update Project and Push, where branch tracking is
      // pre-checked
      String message = "Current branch can't be null here. \nRepository: " + repository;
      LOG.error(message);
      return new FetchParams(GitFetchResult.error(new Exception(message)));
    }
    GitBranchTrackInfo trackInfo = GitBranchUtil.getTrackInfoForBranch(repository, currentBranch);
    if (trackInfo == null) {
      String message =
          "Tracked info is null for branch " + currentBranch + "\n Repository: " + repository;
      LOG.error(message);
      return new FetchParams(GitFetchResult.error(new Exception(message)));
    }

    GitRemote remote = trackInfo.getRemote();
    String url = remote.getFirstUrl();
    if (url == null) {
      String message = "URL is null for remote " + remote.getName();
      LOG.error(message);
      return new FetchParams(GitFetchResult.error(new Exception(message)));
    }

    return new FetchParams(remote, trackInfo.getRemoteBranch(), url);
  }
Пример #13
0
    @Override
    public void _setOkBadge(IdeFrame frame, boolean visible) {
      if (!isValid(frame)) {
        return;
      }

      Object icon = null;

      if (visible) {
        synchronized (Win7AppIcon.class) {
          if (myOkIcon == null) {
            try {
              BufferedImage image = ImageIO.read(getClass().getResource("/mac/appIconOk512.png"));
              ByteArrayOutputStream bytes = new ByteArrayOutputStream();
              Sanselan.writeImage(image, bytes, ImageFormat.IMAGE_FORMAT_ICO, new HashMap());
              myOkIcon = Win7TaskBar.createIcon(bytes.toByteArray());
            } catch (Throwable e) {
              LOG.error(e);
              myOkIcon = null;
            }
          }

          icon = myOkIcon;
        }
      }

      try {
        Win7TaskBar.setOverlayIcon(frame, icon, false);
      } catch (Throwable e) {
        LOG.error(e);
      }
    }
 private void copyToolsConfigurations(InspectionProfileImpl profile) {
   try {
     for (ToolsImpl toolList : profile.myTools.values()) {
       final ToolsImpl tools = myTools.get(toolList.getShortName());
       final ScopeToolState defaultState = toolList.getDefaultState();
       tools.setDefaultState(
           copyToolSettings((InspectionTool) defaultState.getTool()),
           defaultState.isEnabled(),
           defaultState.getLevel());
       tools.removeAllScopes();
       tools.setEnabled(toolList.isEnabled());
       final List<ScopeToolState> nonDefaultToolStates = toolList.getNonDefaultTools();
       if (nonDefaultToolStates != null) {
         for (ScopeToolState state : nonDefaultToolStates) {
           final InspectionTool inspectionTool =
               copyToolSettings((InspectionTool) state.getTool());
           if (state.getScope() != null) {
             tools.addTool(state.getScope(), inspectionTool, state.isEnabled(), state.getLevel());
           } else {
             tools.addTool(
                 state.getScopeName(), inspectionTool, state.isEnabled(), state.getLevel());
           }
         }
       }
     }
   } catch (WriteExternalException e) {
     LOG.error(e);
   } catch (InvalidDataException e) {
     LOG.error(e);
   }
 }
 @Nullable
 public Editor getEditor2() {
   if (myDisposed) LOG.error("Disposed");
   Editor editor = myRightSide.getEditor();
   if (editor != null) return editor;
   if (myData.getContent2() == null) LOG.error("No content 2");
   return editor;
 }
Пример #16
0
  public static List<DomElement> getDefinedChildren(
      @NotNull final DomElement parent, final boolean tags, final boolean attributes) {
    if (parent instanceof MergedObject) {
      final SmartList<DomElement> result = new SmartList<>();
      parent.acceptChildren(
          new DomElementVisitor() {
            @Override
            public void visitDomElement(final DomElement element) {
              if (hasXml(element)) {
                result.add(element);
              }
            }
          });
      return result;
    }

    ProgressManager.checkCanceled();

    if (parent instanceof GenericAttributeValue) return Collections.emptyList();

    if (parent instanceof DomFileElement) {
      final DomFileElement element = (DomFileElement) parent;
      return tags ? Arrays.asList(element.getRootElement()) : Collections.<DomElement>emptyList();
    }

    final XmlElement xmlElement = parent.getXmlElement();
    if (xmlElement instanceof XmlTag) {
      XmlTag tag = (XmlTag) xmlElement;
      final DomManager domManager = parent.getManager();
      final SmartList<DomElement> result = new SmartList<>();
      if (attributes) {
        for (final XmlAttribute attribute : tag.getAttributes()) {
          if (!attribute.isValid()) {
            LOG.error("Invalid attr: parent.valid=" + tag.isValid());
            continue;
          }
          GenericAttributeValue element = domManager.getDomElement(attribute);
          if (checkHasXml(attribute, element)) {
            ContainerUtil.addIfNotNull(result, element);
          }
        }
      }
      if (tags) {
        for (final XmlTag subTag : tag.getSubTags()) {
          if (!subTag.isValid()) {
            LOG.error("Invalid subtag: parent.valid=" + tag.isValid());
            continue;
          }
          DomElement element = domManager.getDomElement(subTag);
          if (checkHasXml(subTag, element)) {
            ContainerUtil.addIfNotNull(result, element);
          }
        }
      }
      return result;
    }
    return Collections.emptyList();
  }
Пример #17
0
 /** Log error if not message error */
 public static void logError(@NotNull Logger logger, @NotNull Throwable e) {
   if (e instanceof MessageError) {
     ThreeState log = ((MessageError) e).log;
     if (log == ThreeState.YES
         || (log == ThreeState.UNSURE && ApplicationManager.getApplication().isUnitTestMode())) {
       logger.error(e);
     }
   } else if (!(e instanceof ProcessCanceledException)) {
     logger.error(e);
   }
 }
 protected void prepareSuccessful() {
   if (myPrepareSuccessfulSwingThreadCallback != null) {
     // make sure that dialog is closed in swing thread
     try {
       GuiUtils.runOrInvokeAndWait(myPrepareSuccessfulSwingThreadCallback);
     } catch (InterruptedException e) {
       LOG.error(e);
     } catch (InvocationTargetException e) {
       LOG.error(e);
     }
   }
 }
Пример #19
0
 private void setWindowOpacity(float opacity) {
   try {
     Method setOpacityMethod = myWindow.getClass().getMethod("setOpacity", Float.TYPE);
     setOpacityMethod.invoke(myWindow, opacity);
   } catch (NoSuchMethodException e) {
     LOG.error(e);
   } catch (InvocationTargetException e) {
     LOG.error(e);
   } catch (IllegalAccessException e) {
     LOG.error(e);
   }
 }
  private static void assertAfterCommit(
      Document document,
      final PsiFile file,
      String oldPsiText,
      FileElement myTreeElementBeingReparsedSoItWontBeCollected) {
    if (myTreeElementBeingReparsedSoItWontBeCollected.getTextLength() != document.getTextLength()) {
      final String documentText = document.getText();
      if (ApplicationManagerEx.getApplicationEx().isInternal()) {
        String fileText = file.getText();
        LOG.error(
            "commitDocument left PSI inconsistent; file len="
                + myTreeElementBeingReparsedSoItWontBeCollected.getTextLength()
                + "; doc len="
                + document.getTextLength()
                + "; doc.getText() == file.getText(): "
                + Comparing.equal(fileText, documentText)
                + ";\n file psi text="
                + fileText
                + ";\n doc text="
                + documentText
                + ";\n old psi file text="
                + oldPsiText);
      } else {
        LOG.error("commitDocument left PSI inconsistent: " + file);
      }

      file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE);
      try {
        BlockSupport blockSupport = BlockSupport.getInstance(file.getProject());
        final DiffLog diffLog =
            blockSupport.reparseRange(
                file, 0, documentText.length(), 0, documentText, new ProgressIndicatorBase());
        CodeStyleManager.getInstance(file.getProject())
            .performActionWithFormatterDisabled(
                new Runnable() {
                  @Override
                  public void run() {
                    synchronized (PsiLock.LOCK) {
                      doActualPsiChange(file, diffLog);
                    }
                  }
                });

        if (myTreeElementBeingReparsedSoItWontBeCollected.getTextLength()
            != document.getTextLength()) {
          LOG.error("PSI is broken beyond repair in: " + file);
        }
      } finally {
        file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, null);
      }
    }
  }
Пример #21
0
 private void assertSyncRequestAllowed() {
   if (ApplicationManager.getApplication().isDispatchThread()) {
     LOG.error("EDT should not be blocked by waiting for for the answer from the Dart debugger");
   }
   if (ApplicationManager.getApplication().isReadAccessAllowed()) {
     LOG.error(
         "Waiting for for the answer from the Dart debugger under read action may lead to EDT freeze");
   }
   if (myVmServiceReceiverThreadId == Thread.currentThread().getId()) {
     LOG.error(
         "Synchronous requests must not be made in Web Socket listening thread: answer will never be received");
   }
 }
  @NotNull
  @Override
  public EditorHighlighter createEditorHighlighter(
      @NotNull VirtualFile vFile, @NotNull EditorColorsScheme settings, @Nullable Project project) {
    FileType fileType = vFile.getFileType();
    if (fileType instanceof LanguageFileType) {
      LanguageFileType substFileType =
          substituteFileType(((LanguageFileType) fileType).getLanguage(), vFile, project);
      if (substFileType != null) {
        EditorHighlighterProvider provider =
            FileTypeEditorHighlighterProviders.INSTANCE.forFileType(substFileType);
        EditorHighlighter editorHighlighter =
            provider.getEditorHighlighter(project, fileType, vFile, settings);
        boolean isPlain =
            editorHighlighter.getClass() == LexerEditorHighlighter.class
                && ((LexerEditorHighlighter) editorHighlighter).isPlain();
        if (!isPlain) {
          return editorHighlighter;
        }
      }
      try {
        return FileTypeEditorHighlighterProviders.INSTANCE
            .forFileType(fileType)
            .getEditorHighlighter(project, fileType, vFile, settings);
      } catch (ProcessCanceledException e) {
        throw e;
      } catch (Exception e) {
        LOG.error(e);
      }
    }

    SyntaxHighlighter highlighter = null;
    for (ContentBasedFileSubstitutor processor :
        Extensions.getExtensions(ContentBasedFileSubstitutor.EP_NAME)) {
      boolean applicable;
      try {
        applicable = processor.isApplicable(project, vFile);
      } catch (Exception e) {
        LOG.error(e);
        continue;
      }
      if (applicable && processor instanceof ContentBasedClassFileProcessor) {
        highlighter =
            ((ContentBasedClassFileProcessor) processor).createHighlighter(project, vFile);
      }
    }
    if (highlighter == null) {
      highlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, project, vFile);
    }
    return createEditorHighlighter(highlighter, settings);
  }
 public static FormattingDocumentModelImpl createOn(PsiFile file) {
   Document document = getDocumentToBeUsedFor(file);
   if (document != null) {
     if (PsiDocumentManager.getInstance(file.getProject()).isUncommited(document)) {
       LOG.error("Document is uncommitted");
     }
     if (!file.textMatches(document.getImmutableCharSequence())) {
       LOG.error("Document and psi file texts should be equal: file " + file);
     }
     return new FormattingDocumentModelImpl(document, file);
   } else {
     return new FormattingDocumentModelImpl(new DocumentImpl(file.getText()), file);
   }
 }
Пример #24
0
 public void validate() {
   this.myValid = false;
   if (!new File(myProject.getBaseDir().getPath()).exists()) {
     LOG.error("Work dir not found " + myProject.getBaseDir().getPath());
     return;
   }
   try {
     myCommandLine = buildCommandLine(collectClassPath());
   } catch (Exception e) {
     LOG.error(e);
     return;
   }
   this.myValid = true;
 }
Пример #25
0
  private void ensureParsed() {
    if (!ourParsingAllowed) {
      LOG.error("Parsing not allowed!!!");
    }
    CharSequence text = myText();
    if (text == null) return;

    if (TreeUtil.getFileElement(this) == null) {
      LOG.error("Chameleons must not be parsed till they're in file tree: " + this);
    }

    ApplicationManager.getApplication().assertReadAccessAllowed();

    DebugUtil.startPsiModification("lazy-parsing");
    try {
      ILazyParseableElementType type = (ILazyParseableElementType) getElementType();
      ASTNode parsedNode = type.parseContents(this);

      if (parsedNode == null && text.length() > 0) {
        CharSequence diagText = ApplicationManager.getApplication().isInternal() ? text : "";
        LOG.error(
            "No parse for a non-empty string: "
                + diagText
                + "; type="
                + LogUtil.objectAndClass(type));
      }

      synchronized (lock) {
        if (myText == null) return;
        if (rawFirstChild() != null) {
          LOG.error("Reentrant parsing?");
        }

        myText = null;

        if (parsedNode == null) return;
        super.rawAddChildrenWithoutNotifications((TreeElement) parsedNode);
      }
    } finally {
      DebugUtil.finishPsiModification();
    }

    if (!Boolean.TRUE.equals(ourSuppressEagerPsiCreation.get())) {
      // create PSI all at once, to reduce contention of PsiLock in CompositeElement.getPsi()
      // create PSI outside the 'lock' since this method grabs PSI_LOCK and deadlock is possible
      // when someone else locks in the other order.
      createAllChildrenPsiIfNecessary();
    }
  }
  @Nullable
  public static PsiElement[] findTargetElementsNoVS(
      Project project, Editor editor, int offset, boolean lookupAccepted) {
    Document document = editor.getDocument();
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (file == null) return null;

    PsiElement elementAt =
        file.findElementAt(TargetElementUtil.adjustOffset(file, document, offset));
    for (GotoDeclarationHandler handler :
        Extensions.getExtensions(GotoDeclarationHandler.EP_NAME)) {
      try {
        PsiElement[] result = handler.getGotoDeclarationTargets(elementAt, offset, editor);
        if (result != null && result.length > 0) {
          for (PsiElement element : result) {
            if (element == null) {
              LOG.error("Null target element is returned by " + handler.getClass().getName());
              return null;
            }
          }
          return result;
        }
      } catch (AbstractMethodError e) {
        LOG.error(new ExtensionException(handler.getClass()));
      }
    }

    int flags =
        TargetElementUtil.getInstance().getAllAccepted() & ~TargetElementUtil.ELEMENT_NAME_ACCEPTED;
    if (!lookupAccepted) {
      flags &= ~TargetElementUtil.LOOKUP_ITEM_ACCEPTED;
    }
    PsiElement element = TargetElementUtil.getInstance().findTargetElement(editor, flags, offset);
    if (element != null) {
      return new PsiElement[] {element};
    }

    // if no references found in injected fragment, try outer document
    if (editor instanceof EditorWindow) {
      EditorWindow window = (EditorWindow) editor;
      return findTargetElementsNoVS(
          project,
          window.getDelegate(),
          window.getDocument().injectedToHost(offset),
          lookupAccepted);
    }

    return null;
  }
Пример #27
0
  private Set<File> collectClassPath() throws Exception {
    File mpsPluginHome = null;
    String mpsCoreRes = getResource(MPSMakeLauncher.class);
    if (mpsCoreRes.endsWith(".jar")) {
      mpsPluginHome =
          new File(mpsCoreRes)
              .getParentFile()
              .getParentFile(); // MPS_PLUGIN_HOME/lib/mps-plugin.jar
    } else if (mpsCoreRes.endsWith("classes")) {
      mpsPluginHome = new File(mpsCoreRes).getParentFile(); // MPS_PLUGIN_HOME/classes
    }

    if (mpsPluginHome == null || !mpsPluginHome.exists()) {
      LOG.error("MPS plugin home not found: " + mpsPluginHome);
      throw new Exception();
    }

    String ideaJar = getResource(Project.class);
    File ideaHome = new File(ideaJar).getParentFile().getParentFile();

    if (ideaHome == null || !ideaHome.exists()) {
      LOG.error("IDEA home not found: " + ideaHome);
      throw new Exception();
    }

    File[] pathsToLook = new File[] {new File(mpsPluginHome, "lib"), new File(ideaHome, "lib")};

    Set<File> classPaths = new LinkedHashSet<File>();
    for (File path : pathsToLook) {
      if (!(path.exists())
          || (!(path.isDirectory()) && !(path.getAbsolutePath().endsWith(".jar")))) {
        throw new Exception(
            mpsPluginHome
                + " is invalid MPS home path: path "
                + path
                + " does not exist or is not a directory or a jar file.");
      } else if (!(path.isDirectory())) {
        classPaths.add(path.getAbsoluteFile());
      } else {
        gatherAllClassesAndJarsUnder(path, classPaths);
      }
    }
    // support running from sources
    File classes = new File(mpsPluginHome, "classes");
    if (classes.exists()) {
      classPaths.add(classes);
    }
    return classPaths;
  }
 @NotNull
 public static <T> T createInstance(final Constructor<T> constructor, final Object... args) {
   try {
     return constructor.newInstance(args);
   } catch (InstantiationException e) {
     LOG.error(e);
     return null;
   } catch (IllegalAccessException e) {
     LOG.error(e);
     return null;
   } catch (InvocationTargetException e) {
     LOG.error(e);
     return null;
   }
 }
  protected OuterLanguageElementImpl createOuterLanguageElement(
      final Lexer lexer, final CharTable table, final IElementType outerElementType) {
    final CharSequence buffer = lexer.getBufferSequence();
    final int tokenStart = lexer.getTokenStart();
    if (tokenStart < 0 || tokenStart > buffer.length()) {
      LOG.error("Invalid start: " + tokenStart + "; " + lexer);
    }
    final int tokenEnd = lexer.getTokenEnd();
    if (tokenEnd < 0 || tokenEnd > buffer.length()) {
      LOG.error("Invalid end: " + tokenEnd + "; " + lexer);
    }

    return new OuterLanguageElementImpl(
        outerElementType, table.intern(buffer, tokenStart, tokenEnd));
  }
Пример #30
0
 protected boolean calcValue() {
   if (!myVersionHigher_15) {
     return false;
   }
   try {
     final Method method = VirtualMachine.class.getMethod("canGetInstanceInfo");
     return (Boolean) method.invoke(myVirtualMachine);
   } catch (NoSuchMethodException ignored) {
   } catch (IllegalAccessException e) {
     LOG.error(e);
   } catch (InvocationTargetException e) {
     LOG.error(e);
   }
   return false;
 }