@Override
 public void doCollectInformation(@NotNull ProgressIndicator progress) {
   final List<HighlightInfo> result = new ArrayList<HighlightInfo>();
   myFile.accept(
       new PsiRecursiveElementVisitor() {
         @Override
         public void visitElement(PsiElement element) {
           IElementType tokenType = element.getNode().getElementType();
           if (TokenSets.KEYWORDS.contains(tokenType)) {
             if (highlightKeyword(element, tokenType)) {
               result.add(
                   HighlightInfo.createHighlightInfo(
                       HighlightInfoType.INFORMATION, element, null, DefaultHighlighter.KEYWORD));
             }
           } else if (!(element instanceof GroovyPsiElement)) {
             final TextAttributesKey attribute = getDeclarationAttribute(element);
             if (attribute != null) {
               result.add(
                   HighlightInfo.createHighlightInfo(
                       HighlightInfoType.INFORMATION, element, null, attribute));
             }
           } else {
             super.visitElement(element);
           }
         }
       });
   toHighlight = result;
 }
  public boolean hasWriteAccess() {
    if (myHasWriteAccess != null) return myHasWriteAccess.booleanValue();

    myFile.accept(
        new GroovyRecursiveElementVisitor() {
          @Override
          public void visitAssignmentExpression(GrAssignmentExpression expression) {
            if (isRefToMe(expression.getLValue())) {
              myHasWriteAccess = true;
            }
            super.visitAssignmentExpression(expression);
          }

          @Override
          public void visitTypeDefinition(GrTypeDefinition typeDefinition) {
            // don't go inside type definitions
          }

          @Override
          public void visitElement(GroovyPsiElement element) {
            if (myHasWriteAccess == null) {
              super.visitElement(element);
            }
          }
        });

    if (myHasWriteAccess == null) myHasWriteAccess = false;
    return myHasWriteAccess.booleanValue();
  }
  @Nullable
  private static GrVariableDeclaration findDeclaration(GroovyFile file) {
    final Ref<GrVariableDeclaration> ref = Ref.create();
    file.accept(
        new GroovyRecursiveElementVisitor() {
          @Override
          public void visitVariableDeclaration(@NotNull GrVariableDeclaration variableDeclaration) {
            super.visitVariableDeclaration(variableDeclaration);
            if (variableDeclaration
                    .getModifierList()
                    .findAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_BASE_SCRIPT)
                != null) {
              ref.set(variableDeclaration);
            }
          }

          @Override
          public void visitElement(@NotNull GroovyPsiElement element) {
            if (ref.isNull()) {
              super.visitElement(element);
            }
          }
        });

    return ref.get();
  }
예제 #4
0
  private void getBindings() {
    final PsiClass containingClass = PsiTreeUtil.getParentOfType(myRefExpr, PsiClass.class);
    if (containingClass != null) return;

    final PsiFile file = FileContextUtil.getContextFile(myRefExpr);
    if (file instanceof GroovyFile) {
      ((GroovyFile) file)
          .accept(
              new GroovyRecursiveElementVisitor() {
                @Override
                public void visitAssignmentExpression(GrAssignmentExpression expression) {
                  super.visitAssignmentExpression(expression);

                  final GrExpression value = expression.getLValue();
                  if (value instanceof GrReferenceExpression
                      && !((GrReferenceExpression) value).isQualified()) {
                    final PsiElement resolved = ((GrReferenceExpression) value).resolve();
                    if (resolved instanceof GrBindingVariable) {
                      myProcessor.execute(resolved, ResolveState.initial());
                    } else if (resolved == null) {
                      myProcessor.execute(
                          new GrBindingVariable(
                              (GroovyFile) file,
                              ((GrReferenceExpression) value).getReferenceName(),
                              true),
                          ResolveState.initial());
                    }
                  }
                }

                @Override
                public void visitTypeDefinition(GrTypeDefinition typeDefinition) {
                  // don't go into classes
                }
              });
    }
  }
예제 #5
0
  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;
  }