private static Document createDocument(
     final String text,
     Project project,
     boolean isClassesAccepted,
     final JavaCodeFragment.VisibilityChecker visibilityChecker) {
   PsiPackage defaultPackage = JavaPsiFacade.getInstance(project).findPackage("");
   final JavaCodeFragment fragment =
       JavaCodeFragmentFactory.getInstance(project)
           .createReferenceCodeFragment(text, defaultPackage, true, isClassesAccepted);
   fragment.setVisibilityChecker(visibilityChecker);
   return PsiDocumentManager.getInstance(project).getDocument(fragment);
 }
  @Nullable
  private ExpressionEvaluator getExpressionEvaluator(DebuggerContextImpl debuggerContext)
      throws EvaluateException {
    if (myCurrentExpression instanceof PsiExpression) {
      return EvaluatorBuilderImpl.getInstance()
          .build(myCurrentExpression, debuggerContext.getSourcePosition());
    }

    CodeFragmentFactory factory =
        DebuggerUtilsEx.getEffectiveCodeFragmentFactory(myCurrentExpression);
    TextWithImportsImpl textWithImports =
        new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, myCurrentExpression.getText());
    if (factory == null) return null;
    JavaCodeFragment codeFragment =
        factory.createCodeFragment(textWithImports, myCurrentExpression.getContext(), getProject());
    codeFragment.forceResolveScope(GlobalSearchScope.allScope(getProject()));
    return factory.getEvaluatorBuilder().build(codeFragment, debuggerContext.getSourcePosition());
  }
  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;
  }