@Override
 public void visitReferenceExpression(GrReferenceExpression expression) {
   super.visitReferenceExpression(expression);
   if (org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isSuperReference(expression)) {
     final GrExpression qualifier = expression.getQualifier();
     if (qualifier instanceof GrReferenceExpression
         && ((GrReferenceExpression) qualifier).isReferenceTo(mySourceClass)) {
       try {
         expression.putCopyableUserData(SUPER_REF, Boolean.TRUE);
       } catch (IncorrectOperationException e) {
         LOG.error(e);
       }
     }
   } else if (org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isThisReference(expression)) {
     final GrExpression qualifier = expression.getQualifier();
     if (qualifier instanceof GrReferenceExpression
         && ((GrReferenceExpression) qualifier).isReferenceTo(mySourceClass)) {
       try {
         expression.putCopyableUserData(THIS_REF, Boolean.TRUE);
       } catch (IncorrectOperationException e) {
         LOG.error(e);
       }
     }
   }
 }
  @Override
  protected void collectAdditionalElementsToRename(List<Pair<PsiElement, TextRange>> stringUsages) {
    if (isReplaceAllOccurrences()) {
      for (E expression : getOccurrences()) {
        LOG.assertTrue(expression.isValid(), expression.getText());
        stringUsages.add(
            Pair.<PsiElement, TextRange>create(
                expression, new TextRange(0, expression.getTextLength())));
      }
    } else if (getExpr() != null) {
      correctExpression();
      final E expr = getExpr();
      LOG.assertTrue(expr.isValid(), expr.getText());
      stringUsages.add(
          Pair.<PsiElement, TextRange>create(expr, new TextRange(0, expr.getTextLength())));
    }

    final V localVariable = getLocalVariable();
    if (localVariable != null) {
      final PsiElement nameIdentifier = localVariable.getNameIdentifier();
      if (nameIdentifier != null) {
        int length = nameIdentifier.getTextLength();
        stringUsages.add(
            Pair.<PsiElement, TextRange>create(nameIdentifier, new TextRange(0, length)));
      }
    }
  }
 @Override
 public void visitReferenceExpression(GrReferenceExpression expression) {
   super.visitReferenceExpression(expression);
   if (expression.getCopyableUserData(SUPER_REF) != null) {
     expression.putCopyableUserData(SUPER_REF, null);
     final GrExpression qualifier = expression.getQualifier();
     if (qualifier instanceof GrReferenceExpression
         && ((GrReferenceExpression) qualifier).isReferenceTo(mySourceClass)) {
       try {
         GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(myProject);
         GrExpression newExpr =
             factory.createExpressionFromText(myTargetSuperClass.getName() + ".this", null);
         expression.replace(newExpr);
       } catch (IncorrectOperationException e) {
         LOG.error(e);
       }
     }
   } else if (expression.getCopyableUserData(THIS_REF) != null) {
     expression.putCopyableUserData(THIS_REF, null);
     final GrExpression qualifier = expression.getQualifier();
     if (qualifier instanceof GrReferenceExpression
         && ((GrReferenceExpression) qualifier).isReferenceTo(mySourceClass)) {
       try {
         ((GrReferenceExpression) qualifier).bindToElement(myTargetSuperClass);
         GroovyChangeContextUtil.clearContextInfo(qualifier);
       } catch (IncorrectOperationException e) {
         LOG.error(e);
       }
     }
   }
 }
 @Override
 @NotNull
 public Collection<RefMethod> getSuperMethods() {
   if (mySuperMethods == null) return EMPTY_METHOD_LIST;
   if (mySuperMethods.size() > 10) {
     LOG.info("method: " + getName() + " owner:" + getOwnerClass().getQualifiedName());
   }
   if (getRefManager().isOfflineView()) {
     LOG.debug("Should not traverse graph offline");
   }
   return mySuperMethods;
 }
    private PsiWildcardType rebound(PsiWildcardType type, PsiType newBound) {
      LOG.assertTrue(type.getBound() != null);
      LOG.assertTrue(newBound.isValid());

      if (type.isExtends()) {
        if (newBound.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) {
          return PsiWildcardType.createUnbounded(type.getManager());
        } else {
          return PsiWildcardType.createExtends(type.getManager(), newBound);
        }
      } else {
        return PsiWildcardType.createSuper(type.getManager(), newBound);
      }
    }
  public void testRemoveSourceRoot() {
    final VirtualFile root = ModuleRootManager.getInstance(myModule).getContentRoots()[0];

    PsiTodoSearchHelper.SERVICE
        .getInstance(myProject)
        .findFilesWithTodoItems(); // to initialize caches

    new WriteCommandAction.Simple(getProject()) {
      @Override
      protected void run() throws Throwable {
        VirtualFile newFile = createChildData(root, "New.java");
        setFileText(newFile, "class A{ Exception e;} //todo");
      }
    }.execute().throwException();

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to update caches

    VirtualFile[] sourceRoots = ModuleRootManager.getInstance(myModule).getSourceRoots();
    LOG.assertTrue(sourceRoots.length == 1);
    PsiTestUtil.removeSourceRoot(myModule, sourceRoots[0]);

    PsiClass exceptionClass =
        myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject()));
    assertNotNull(exceptionClass);
    // currently it actually finds usages by FQN due to Java PSI enabled for out-of-source java
    // files
    // so the following check is disabled
    // checkUsages(exceptionClass, new String[]{});
    checkTodos(new String[] {"2.java", "New.java"});
  }
    public void merge(final Binding b, final boolean removeObject) {
      for (final PsiTypeVariable var : b.getBoundVariables()) {
        final int index = var.getIndex();

        if (myBindings.get(index) != null) {
          LOG.error("Oops... Binding conflict...");
        } else {
          final PsiType type = b.apply(var);
          final PsiClassType javaLangObject =
              PsiType.getJavaLangObject(
                  PsiManager.getInstance(myProject), GlobalSearchScope.allScope(myProject));

          if (removeObject && javaLangObject.equals(type)) {
            final HashSet<PsiTypeVariable> cluster = myFactory.getClusterOf(var.getIndex());

            if (cluster != null) {
              for (final PsiTypeVariable war : cluster) {
                final PsiType wtype = b.apply(war);

                if (!javaLangObject.equals(wtype)) {
                  myBindings.put(index, type);
                  break;
                }
              }
            }
          } else {
            myBindings.put(index, type);
          }
        }
      }
    }
Exemple #8
0
    @Override
    public void consume(Object o) {
      if (!(o instanceof GroovyResolveResult)) {
        LOG.error(o);
        return;
      }

      GroovyResolveResult result = (GroovyResolveResult) o;
      if (!result.isStaticsOK()) {
        if (myInapplicable == null) myInapplicable = ContainerUtil.newArrayList();
        myInapplicable.add(result);
        return;
      }
      if (!result.isAccessible() && myParameters.getInvocationCount() < 2) return;

      if (mySkipPackages && result.getElement() instanceof PsiPackage) return;

      PsiElement element = result.getElement();
      if (element instanceof PsiVariable
          && !myMatcher.prefixMatches(((PsiVariable) element).getName())) {
        return;
      }

      if (element instanceof GrReflectedMethod) {
        element = ((GrReflectedMethod) element).getBaseMethod();
        if (!myProcessedMethodWithOptionalParams.add((GrMethod) element)) return;

        result =
            new GroovyResolveResultImpl(
                element,
                result.getCurrentFileResolveContext(),
                result.getSpreadState(),
                result.getSubstitutor(),
                result.isAccessible(),
                result.isStaticsOK(),
                result.isInvokedOnProperty(),
                result.isValidResult());
      }

      if (myFieldPointerOperator && !(element instanceof PsiVariable)) {
        return;
      }
      if (myMethodPointerOperator && !(element instanceof PsiMethod)) {
        return;
      }
      addCandidate(result);

      if (!myFieldPointerOperator && !myMethodPointerOperator) {
        if (element instanceof PsiMethod) {
          processProperty((PsiMethod) element, result);
        } else if (element instanceof GrField) {
          if (((GrField) element).isProperty()) {
            processPropertyFromField((GrField) element, result);
          }
        }
      }
      if (element instanceof GrVariable && !(element instanceof GrField)) {
        myLocalVars.add(((GrVariable) element).getName());
      }
    }
 @Override
 protected void hyperlinkActivated(HyperlinkEvent e) {
   final Module moduleByName =
       ModuleManager.getInstance(myProject).findModuleByName(e.getDescription());
   if (moduleByName != null) {
     myConfiguration.getConfigurationModule().setModule(moduleByName);
     try {
       final Executor executor =
           myConsoleProperties.isDebug()
               ? DefaultDebugExecutor.getDebugExecutorInstance()
               : DefaultRunExecutor.getRunExecutorInstance();
       final ProgramRunner runner =
           RunnerRegistry.getInstance().getRunner(executor.getId(), myConfiguration);
       assert runner != null;
       runner.execute(
           executor,
           new ExecutionEnvironment(
               myConfiguration,
               myProject,
               getRunnerSettings(),
               getConfigurationSettings(),
               null));
       final Balloon balloon = myToolWindowManager.getToolWindowBalloon(myTestRunDebugId);
       if (balloon != null) {
         balloon.hide();
       }
     } catch (ExecutionException e1) {
       LOG.error(e1);
     }
   }
 }
  @Override
  protected void setUpProject() throws Exception {
    myProjectManager = ProjectManagerEx.getInstanceEx();
    LOG.assertTrue(myProjectManager != null, "Cannot instantiate ProjectManager component");

    File projectFile = getIprFile();
    loadAndSetupProject(projectFile.getPath());
  }
 public void run(@NotNull ProgressIndicator indicator) {
   try {
     mySocket = myServerSocket.accept();
     DumbService.getInstance(myProject)
         .repeatUntilPassesInSmartMode(
             new Runnable() {
               @Override
               public void run() {
                 myClasses.clear();
                 myJunit4[0] = ConfigurationUtil.findAllTestClasses(myClassFilter, myClasses);
               }
             });
     myFoundTests = !myClasses.isEmpty();
   } catch (IOException e) {
     LOG.info(e);
   } catch (Throwable e) {
     LOG.error(e);
   }
 }
  @Override
  protected void initialize() {
    final PsiMethod method = (PsiMethod) getElement();
    LOG.assertTrue(method != null);
    setConstructor(method.isConstructor());
    final PsiType returnType = method.getReturnType();
    setFlag(
        returnType == null
            || PsiType.VOID.equals(returnType)
            || returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID),
        IS_RETURN_VALUE_USED_MASK);

    if (!isReturnValueUsed()) {
      myReturnValueTemplate = RETURN_VALUE_UNDEFINED;
    }

    if (isConstructor()) {
      addReference(getOwnerClass(), getOwnerClass().getElement(), method, false, true, null);
    }

    if (getOwnerClass().isInterface()) {
      setAbstract(false);
    } else {
      setAbstract(method.hasModifierProperty(PsiModifier.ABSTRACT));
    }

    setAppMain(isAppMain(method, this));
    setLibraryOverride(method.hasModifierProperty(PsiModifier.NATIVE));

    initializeSuperMethods(method);
    if (isExternalOverride()) {
      ((RefClassImpl) getOwnerClass()).addLibraryOverrideMethod(this);
    }

    @NonNls final String name = method.getName();
    if (getOwnerClass().isTestCase() && name.startsWith("test")) {
      setTestMethod(true);
    }

    PsiParameter[] paramList = method.getParameterList().getParameters();
    if (paramList.length > 0) {
      myParameters = new RefParameterImpl[paramList.length];
      for (int i = 0; i < paramList.length; i++) {
        PsiParameter parameter = paramList[i];
        myParameters[i] = getRefJavaManager().getParameterReference(parameter, i);
      }
    }

    if (method.hasModifierProperty(PsiModifier.NATIVE)) {
      updateReturnValueTemplate(null);
      updateThrowsList(null);
    }
    collectUncaughtExceptions(method);
  }
 @Override
 public void visitThisExpression(PsiThisExpression expression) {
   super.visitThisExpression(expression);
   final PsiJavaCodeReferenceElement qualifier = expression.getQualifier();
   if (qualifier != null && qualifier.isReferenceTo(mySourceClass)) {
     try {
       qualifier.bindToElement(myTargetSuperClass);
     } catch (IncorrectOperationException e) {
       LOG.error(e);
     }
   }
 }
  protected void initialize() throws ExecutionException {
    super.initialize();
    final JUnitConfiguration.Data data = myConfiguration.getPersistentData();
    getClassFilter(data); // check if junit found
    configureClasspath();

    try {
      myTempFile = FileUtil.createTempFile("idea_junit", ".tmp");
      myTempFile.deleteOnExit();
      myJavaParameters.getProgramParametersList().add("@" + myTempFile.getAbsolutePath());
    } catch (IOException e) {
      LOG.error(e);
    }

    try {
      myServerSocket = new ServerSocket(0, 0, InetAddress.getByName("127.0.0.1"));
      myJavaParameters.getProgramParametersList().add("-socket" + myServerSocket.getLocalPort());
    } catch (IOException e) {
      LOG.error(e);
    }
  }
 @Override
 public void visitSuperExpression(PsiSuperExpression expression) {
   super.visitSuperExpression(expression);
   final PsiJavaCodeReferenceElement qualifier = expression.getQualifier();
   if (qualifier != null && qualifier.isReferenceTo(mySourceClass)) {
     try {
       expression.replace(
           JavaPsiFacade.getElementFactory(myProject)
               .createExpressionFromText(myTargetSuperClass.getName() + ".this", null));
     } catch (IncorrectOperationException e) {
       LOG.error(e);
     }
   }
 }
    protected void finish() {
      DataOutputStream os = null;
      try {
        if (mySocket == null || mySocket.isClosed()) return;
        os = new DataOutputStream(mySocket.getOutputStream());
        os.writeBoolean(true);
      } catch (Throwable e) {
        LOG.info(e);
      } finally {
        try {
          if (os != null) os.close();
        } catch (Throwable e) {
          LOG.info(e);
        }

        try {
          if (!myServerSocket.isClosed()) {
            myServerSocket.close();
          }
        } catch (Throwable e) {
          LOG.info(e);
        }
      }
    }
 protected static LocalInspectionTool[] createLocalInspectionTools(
     final InspectionToolProvider... provider) {
   final ArrayList<LocalInspectionTool> result = new ArrayList<LocalInspectionTool>();
   for (InspectionToolProvider toolProvider : provider) {
     for (Class aClass : toolProvider.getInspectionClasses()) {
       try {
         final Object tool = aClass.newInstance();
         assertTrue(tool instanceof LocalInspectionTool);
         result.add((LocalInspectionTool) tool);
       } catch (Exception e) {
         LOG.error(e);
       }
     }
   }
   return result.toArray(new LocalInspectionTool[result.size()]);
 }
 @Override
 @Nullable
 public PsiClass[] getUnThrownExceptions() {
   if (getRefManager().isOfflineView()) {
     LOG.debug("Should not traverse graph offline");
   }
   if (myUnThrownExceptions == null) return null;
   JavaPsiFacade facade = JavaPsiFacade.getInstance(myManager.getProject());
   List<PsiClass> result = new ArrayList<PsiClass>(myUnThrownExceptions.size());
   for (String exception : myUnThrownExceptions) {
     PsiClass element =
         facade.findClass(exception, GlobalSearchScope.allScope(myManager.getProject()));
     if (element != null) result.add(element);
   }
   return result.toArray(new PsiClass[result.size()]);
 }
  @Override
  protected void addHighlights(
      @NotNull Map<TextRange, TextAttributes> ranges,
      @NotNull Editor editor,
      @NotNull Collection<RangeHighlighter> highlighters,
      @NotNull HighlightManager highlightManager) {
    final TextAttributes attributes =
        EditorColorsManager.getInstance()
            .getGlobalScheme()
            .getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    final V variable = getVariable();
    if (variable != null) {
      final String name = variable.getName();
      LOG.assertTrue(name != null, variable);
      final int variableNameLength = name.length();
      if (isReplaceAllOccurrences()) {
        for (RangeMarker marker : getOccurrenceMarkers()) {
          final int startOffset = marker.getStartOffset();
          highlightManager.addOccurrenceHighlight(
              editor,
              startOffset,
              startOffset + variableNameLength,
              attributes,
              0,
              highlighters,
              null);
        }
      } else if (getExpr() != null) {
        final int startOffset = getExprMarker().getStartOffset();
        highlightManager.addOccurrenceHighlight(
            editor,
            startOffset,
            startOffset + variableNameLength,
            attributes,
            0,
            highlighters,
            null);
      }
    }

    for (RangeHighlighter highlighter : highlighters) {
      highlighter.setGreedyToLeft(true);
      highlighter.setGreedyToRight(true);
    }
  }
  public void testExternalDirCreation() throws Exception {
    VirtualFile root = ProjectRootManager.getInstance(myProject).getContentRoots()[0];

    String newFilePath =
        root.getPresentableUrl() + File.separatorChar + "dir" + File.separatorChar + "New.java";
    LOG.assertTrue(new File(newFilePath).getParentFile().mkdir());
    FileUtil.writeToFile(
        new File(newFilePath), "class A{ Object o;}".getBytes(CharsetToolkit.UTF8_CHARSET));
    VirtualFile file =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(newFilePath.replace(File.separatorChar, '/'));
    assertNotNull(file);
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiClass objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {"New.java"});
  }
Exemple #21
0
  protected void initialize() {
    myDefaultConstructor = null;

    final PsiClass psiClass = getElement();

    LOG.assertTrue(psiClass != null);

    PsiElement psiParent = psiClass.getParent();
    if (psiParent instanceof PsiFile) {
      if (isSyntheticJSP()) {
        final RefFileImpl refFile =
            (RefFileImpl) getRefManager().getReference(JspPsiUtil.getJspFile(psiClass));
        LOG.assertTrue(refFile != null);
        refFile.add(this);
      } else if (psiParent instanceof PsiJavaFile) {
        PsiJavaFile psiFile = (PsiJavaFile) psiParent;
        String packageName = psiFile.getPackageName();
        if (!"".equals(packageName)) {
          ((RefPackageImpl) getRefJavaManager().getPackage(packageName)).add(this);
        } else {
          ((RefPackageImpl) getRefJavaManager().getDefaultPackage()).add(this);
        }
      }
      final Module module = ModuleUtil.findModuleForPsiElement(psiClass);
      LOG.assertTrue(module != null);
      final RefModuleImpl refModule = ((RefModuleImpl) getRefManager().getRefModule(module));
      LOG.assertTrue(refModule != null);
      refModule.add(this);
    } else {
      while (!(psiParent instanceof PsiClass
          || psiParent instanceof PsiMethod
          || psiParent instanceof PsiField)) {
        psiParent = psiParent.getParent();
      }
      RefElement refParent = getRefManager().getReference(psiParent);
      LOG.assertTrue(refParent != null);
      ((RefElementImpl) refParent).add(this);
    }

    setAbstract(psiClass.hasModifierProperty(PsiModifier.ABSTRACT));

    setAnonymous(psiClass instanceof PsiAnonymousClass);
    setIsLocal(!(isAnonymous() || psiParent instanceof PsiClass || psiParent instanceof PsiFile));
    setInterface(psiClass.isInterface());

    initializeSuperReferences(psiClass);

    PsiMethod[] psiMethods = psiClass.getMethods();
    PsiField[] psiFields = psiClass.getFields();

    setUtilityClass(psiMethods.length > 0 || psiFields.length > 0);

    for (PsiField psiField : psiFields) {
      getRefManager().getReference(psiField);
    }

    if (!isApplet()) {
      final PsiClass servlet = getRefJavaManager().getServlet();
      setServlet(servlet != null && psiClass.isInheritor(servlet, true));
    }
    if (!isApplet() && !isServlet()) {
      setTestCase(TestUtil.isTestClass(psiClass));
      for (RefClass refBase : getBaseClasses()) {
        ((RefClassImpl) refBase).setTestCase(true);
      }
    }

    for (PsiMethod psiMethod : psiMethods) {
      RefMethod refMethod = (RefMethod) getRefManager().getReference(psiMethod);

      if (refMethod != null) {
        if (psiMethod.isConstructor()) {
          if (psiMethod.getParameterList().getParametersCount() > 0
              || !psiMethod.hasModifierProperty(PsiModifier.PRIVATE)) {
            setUtilityClass(false);
          }

          addConstructor(refMethod);
          if (psiMethod.getParameterList().getParametersCount() == 0) {
            setDefaultConstructor((RefMethodImpl) refMethod);
          }
        } else {
          if (!psiMethod.hasModifierProperty(PsiModifier.STATIC)) {
            setUtilityClass(false);
          }
        }
      }
    }

    if (getConstructors().size() == 0 && !isInterface() && !isAnonymous()) {
      RefImplicitConstructorImpl refImplicitConstructor = new RefImplicitConstructorImpl(this);
      setDefaultConstructor(refImplicitConstructor);
      addConstructor(refImplicitConstructor);
    }

    if (isInterface()) {
      for (int i = 0; i < psiFields.length && isUtilityClass(); i++) {
        PsiField psiField = psiFields[i];
        if (!psiField.hasModifierProperty(PsiModifier.STATIC)) {
          setUtilityClass(false);
        }
      }
    }

    final PsiClass applet = getRefJavaManager().getApplet();
    setApplet(applet != null && psiClass.isInheritor(applet, true));
    getRefManager().fireNodeInitialized(this);
  }
    public Binding compose(final Binding b) {
      LOG.assertTrue(b instanceof BindingImpl);

      final BindingImpl b1 = this;
      final BindingImpl b2 = (BindingImpl) b;

      final BindingImpl b3 = new BindingImpl();

      for (PsiTypeVariable boundVariable : myBoundVariables) {
        final int i = boundVariable.getIndex();

        final PsiType b1i = b1.myBindings.get(i);
        final PsiType b2i = b2.myBindings.get(i);

        final int flag = (b1i == null ? 0 : 1) + (b2i == null ? 0 : 2);

        switch (flag) {
          case 0:
            break;

          case 1: /* b1(i)\b2(i) */
            {
              final PsiType type = b2.apply(b1i);

              if (type == null) {
                return null;
              }

              b3.myBindings.put(i, type);
              b3.myCyclic = type instanceof PsiTypeVariable;
            }
            break;

          case 2: /* b2(i)\b1(i) */
            {
              final PsiType type = b1.apply(b2i);

              if (type == null) {
                return null;
              }

              b3.myBindings.put(i, type);
              b3.myCyclic = type instanceof PsiTypeVariable;
            }
            break;

          case 3: /* b2(i) \cap b1(i) */
            {
              final Binding common = rise(b1i, b2i, null);

              if (common == null) {
                return null;
              }

              final PsiType type = common.apply(b1i);
              if (type == null) {
                return null;
              }

              if (type == null) {
                return null;
              }

              b3.myBindings.put(i, type);
              b3.myCyclic = type instanceof PsiTypeVariable;
            }
        }
      }

      return b3;
    }