Beispiel #1
0
  public static boolean processImplicitImports(
      @NotNull PsiScopeProcessor processor,
      ResolveState state,
      PsiElement lastParent,
      PsiElement place,
      @NotNull GroovyFile file) {
    JavaPsiFacade facade = JavaPsiFacade.getInstance(file.getProject());

    final DelegatingScopeProcessor packageSkipper =
        new DelegatingScopeProcessor(processor) {
          @Override
          public boolean execute(@NotNull PsiElement element, ResolveState state) {
            if (element instanceof PsiPackage) return true;
            return super.execute(element, state);
          }
        };

    for (final String implicitlyImported : getImplicitlyImportedPackages(file)) {
      PsiPackage aPackage = facade.findPackage(implicitlyImported);
      if (aPackage == null) continue;

      if (!aPackage.processDeclarations(packageSkipper, state, lastParent, place)) {
        return false;
      }
    }

    GroovyPsiManager groovyPsiManager = GroovyPsiManager.getInstance(file.getProject());
    for (String implicitlyImportedClass : GroovyFileBase.IMPLICITLY_IMPORTED_CLASSES) {
      PsiClass clazz =
          groovyPsiManager.findClassWithCache(implicitlyImportedClass, file.getResolveScope());
      if (clazz != null && !ResolveUtil.processElement(processor, clazz, state)) return false;
    }
    return true;
  }
 @Override
 public void tuneConfiguration(
     @NotNull GroovyFile file,
     @NotNull GroovyScriptRunConfiguration configuration,
     Location location) {
   List<String> tasks = getTasksTarget(location);
   if (tasks != null) {
     String s = StringUtil.join(tasks, " ");
     configuration.setScriptParameters(s);
     configuration.setName("gradle:" + s);
   }
   RunManagerEx.disableTasks(
       file.getProject(),
       configuration,
       CompileStepBeforeRun.ID,
       CompileStepBeforeRunNoErrorCheck.ID);
 }
  @Override
  public GlobalSearchScope patchResolveScope(
      @NotNull GroovyFile file, @NotNull GlobalSearchScope baseScope) {
    final Module module = ModuleUtilCore.findModuleForPsiElement(file);
    final GradleInstallationManager libraryManager =
        ServiceManager.getService(GradleInstallationManager.class);
    if (module != null) {
      if (libraryManager.getGradleHome(module) != null) {
        return baseScope;
      }
    }

    final Collection<VirtualFile> files = libraryManager.getClassRoots(file.getProject());
    if (files == null || files.isEmpty()) {
      return baseScope;
    }

    GlobalSearchScope result = baseScope;
    for (final VirtualFile root : files) {
      result = result.uniteWith(new NonClasspathDirectoryScope(root));
    }
    return result;
  }
Beispiel #4
0
 public void doCollectInformation(ProgressIndicator progress) {
   if (!(myFile instanceof GroovyFile)) return;
   GroovyFile groovyFile = (GroovyFile) myFile;
   GroovyImportsTracker importsTracker = GroovyImportsTracker.getInstance(groovyFile.getProject());
   myUnusedImports = importsTracker.getUnusedImportStatements(groovyFile);
 }
 protected GrKeywordAndDeclarationHighlighter(GroovyFile file, Document document) {
   super(file.getProject(), document);
   myFile = file;
 }
  public JavaCodeFragment createCodeFragment(
      TextWithImports textWithImports, PsiElement context, Project project) {
    String text = textWithImports.getText();
    String imports = textWithImports.getImports();
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
    final GroovyFile toEval = factory.createGroovyFile(text, false, context);
    final Set<String> namesList = new HashSet<String>();
    final GrClosableBlock closure = PsiTreeUtil.getParentOfType(context, GrClosableBlock.class);

    final Set<String> valList = new HashSet<String>();
    toEval.accept(
        new GroovyRecursiveElementVisitor() {
          public void visitReferenceExpression(GrReferenceExpression referenceExpression) {
            super.visitReferenceExpression(referenceExpression);
            PsiElement resolved = referenceExpression.resolve();

            if (resolved instanceof PsiMethod
                && "getDelegate".equals(((PsiMethod) resolved).getName())
                && closure != null) {
              replaceWithReference(referenceExpression, "owner");
              return;
            }

            if (resolved instanceof GrField && !referenceExpression.isQualified()) {
              replaceWithReference(
                  referenceExpression,
                  (closure == null ? "delegate" : "owner")
                      + "."
                      + referenceExpression.getReferenceName());
              return;
            }

            if (resolved instanceof GrVariableBase
                && !(resolved instanceof GrField)
                && !PsiTreeUtil.isAncestor(toEval, resolved, false)) {
              final String name = ((GrVariableBase) resolved).getName();
              if (resolved instanceof ClosureSyntheticParameter
                  && PsiTreeUtil.isAncestor(
                      toEval, ((ClosureSyntheticParameter) resolved).getClosure(), false)) {
                return;
              }
              namesList.add(name);
              if (closure != null
                  && PsiTreeUtil.findCommonParent(resolved, closure) != closure
                  && !(resolved instanceof ClosureSyntheticParameter)) {
                // Evaluating inside closure for outer variable definitions
                // All non-local variables are accessed by references
                valList.add("this." + name);
              } else {
                valList.add(name);
              }
            }
          }

          @Override
          public void visitThisExpression(final GrThisReferenceExpression thisExpression) {
            super.visitThisExpression(thisExpression);
            replaceWithReference(thisExpression, closure == null ? "delegate" : "owner");
          }

          @Override
          public void visitSuperExpression(final GrSuperReferenceExpression superExpression) {
            super.visitSuperExpression(superExpression);
            replaceWithReference(superExpression, closure == null ? "delegate" : "owner");
          }

          private void replaceWithReference(GrExpression expr, final String exprText) {
            final GroovyPsiElementFactory factory =
                GroovyPsiElementFactory.getInstance(expr.getProject());
            visitReferenceExpression(
                (GrReferenceExpression)
                    expr.replaceWithExpression(factory.createExpressionFromText(exprText), false));
          }

          public void visitCodeReferenceElement(GrCodeReferenceElement refElement) {
            if (refElement.getQualifier() != null) {
              super.visitCodeReferenceElement(refElement);
            } else {
              PsiElement resolved = refElement.resolve();
              if (resolved instanceof PsiClass) {
                String qName = ((PsiClass) resolved).getQualifiedName();
                if (qName != null) {
                  int dotIndex = qName.lastIndexOf(".");
                  if (dotIndex < 0) return;
                  String packageName = qName.substring(0, dotIndex);
                  refElement.setQualifier(factory.createReferenceElementFromText(packageName));
                }
              }
            }
          }
        });

    text = toEval.getText();

    String[] names = namesList.toArray(new String[namesList.size()]);
    String[] vals = valList.toArray(new String[valList.size()]);

    PsiClass contextClass = PsiUtil.getContextClass(context);
    boolean isStatic = isStaticContext(context);
    StringBuffer javaText = new StringBuffer();

    javaText.append("groovy.lang.MetaClass mc;\n");
    javaText.append("java.lang.Class clazz;\n");
    if (!isStatic) {
      javaText.append("clazz = ((java.lang.Object)this).getClass();\n");
      javaText.append("mc = ((groovy.lang.GroovyObject)this).getMetaClass();\n");
    } else {
      javaText
          .append("clazz = java.lang.Class.forName(\"")
          .append(contextClass.getQualifiedName())
          .append("\");\n");
      javaText.append(
          "mc = groovy.lang.GroovySystem.getMetaClassRegistry().getMetaClass(clazz);\n");
    }

    javaText.append(createProperty(stripImports(text, toEval), imports, names));

    javaText.append(
        "groovy.lang.ExpandoMetaClass emc = new groovy.lang.ExpandoMetaClass(clazz);\n");
    if (!isStatic) {
      javaText.append("emc.setProperty(\"").append(EVAL_NAME).append("\", closure);\n");
      javaText.append("((groovy.lang.GroovyObject)this).setMetaClass(emc);\n");
    } else {
      javaText
          .append("((groovy.lang.GroovyObject)emc.getProperty(\"static\")).setProperty(\"")
          .append(EVAL_NAME)
          .append("\", closure);\n");
      javaText.append(
          "groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(clazz, emc);\n");
    }
    javaText.append("emc.initialize();\n");
    javaText.append(unwrapVals(vals));
    if (!isStatic) {
      javaText
          .append("java.lang.Object res = ((groovy.lang.MetaClassImpl)emc).invokeMethod(this, \"")
          .append(EVAL_NAME)
          .append("\", ")
          .append("resVals")
          .append(");\n");
      javaText.append(
          "((groovy.lang.GroovyObject)this).setMetaClass(mc);"); // try/finally is not supported
    } else {
      javaText
          .append(
              "java.lang.Object res = ((groovy.lang.MetaClassImpl)emc).invokeStaticMethod(clazz, \"")
          .append(EVAL_NAME)
          .append("\", ")
          .append("resVals")
          .append(");\n");
      javaText.append("groovy.lang.GroovySystem.getMetaClassRegistry().setMetaClass(clazz, mc);\n");
    }
    javaText.append("res");

    PsiElementFactory elementFactory =
        JavaPsiFacade.getInstance(toEval.getProject()).getElementFactory();
    JavaCodeFragment result =
        elementFactory.createCodeBlockCodeFragment(javaText.toString(), null, true);
    if (contextClass != null) {
      result.setThisType(elementFactory.createType(contextClass));
    }
    return result;
  }