public void doTestWithJava(@NotNull String filename) {
   try {
     blackBoxFileWithJavaByFullPath(filename);
   } catch (Exception e) {
     throw UtilsPackage.rethrow(e);
   }
 }
예제 #2
0
  public ReplInterpreter(
      @NotNull Disposable disposable, @NotNull CompilerConfiguration configuration) {
    jetCoreEnvironment = JetCoreEnvironment.createForProduction(disposable, configuration);
    Project project = jetCoreEnvironment.getProject();
    trace = new BindingTraceContext();
    module = AnalyzerFacadeForJVM.createJavaModule("<repl>");
    TopDownAnalysisParameters topDownAnalysisParameters =
        TopDownAnalysisParameters.createForLocalDeclarations(
            new LockBasedStorageManager(),
            new ExceptionTracker(), // dummy
            Predicates.<PsiFile>alwaysTrue());
    injector =
        new InjectorForTopDownAnalyzerForJvm(
            project, topDownAnalysisParameters, trace, module, MemberFilter.ALWAYS_TRUE);
    topDownAnalysisContext = new TopDownAnalysisContext(topDownAnalysisParameters);
    module.addFragmentProvider(SOURCES, injector.getTopDownAnalyzer().getPackageFragmentProvider());
    module.addFragmentProvider(
        BUILT_INS, KotlinBuiltIns.getInstance().getBuiltInsModule().getPackageFragmentProvider());
    module.addFragmentProvider(
        BINARIES, injector.getJavaDescriptorResolver().getPackageFragmentProvider());

    List<URL> classpath = Lists.newArrayList();

    for (File file : configuration.getList(JVMConfigurationKeys.CLASSPATH_KEY)) {
      try {
        classpath.add(file.toURI().toURL());
      } catch (MalformedURLException e) {
        throw UtilsPackage.rethrow(e);
      }
    }

    classLoader = new ReplClassLoader(new URLClassLoader(classpath.toArray(new URL[0])));
  }
  private void blackBox() {
    // If there are many files, the first of them should contain the 'box(): String' function
    JetFile firstFile = myFiles.getPsiFiles().get(0);
    String fqName = getPackageClassFqName(firstFile.getPackageFqName()).asString();

    Class<?> aClass = generateClass(fqName);
    try {
      Method method = aClass.getMethod("box");
      String r = (String) method.invoke(null);
      assertEquals("OK", r);
    } catch (Throwable e) {
      System.out.println(generateToText());
      throw UtilsPackage.rethrow(e);
    }
  }
예제 #4
0
  @NotNull
  public static File compileJava(@NotNull String filename) {
    try {
      File javaClassesTempDirectory = JetTestUtils.tmpDir("java-classes");
      String classPath =
          ForTestCompileRuntime.runtimeJarForTests()
              + File.pathSeparator
              + JetTestUtils.getAnnotationsJar().getPath();
      List<String> options =
          Arrays.asList("-classpath", classPath, "-d", javaClassesTempDirectory.getPath());

      File javaFile = new File("compiler/testData/codegen/" + filename);
      JetTestUtils.compileJavaFiles(Collections.singleton(javaFile), options);

      return javaClassesTempDirectory;
    } catch (IOException e) {
      throw UtilsPackage.rethrow(e);
    }
  }
  @Override
  public void loadClassAnnotations(@NotNull final AnnotationVisitor annotationVisitor) {
    try {
      new ClassReader(file.contentsToByteArray())
          .accept(
              new ClassVisitor(ASM5) {
                @Override
                public org.jetbrains.org.objectweb.asm.AnnotationVisitor visitAnnotation(
                    String desc, boolean visible) {
                  return convertAnnotationVisitor(annotationVisitor, desc);
                }

                @Override
                public void visitEnd() {
                  annotationVisitor.visitEnd();
                }
              },
              SKIP_CODE | SKIP_DEBUG | SKIP_FRAMES);
    } catch (Throwable e) {
      LOG.error(renderFileReadingErrorMessage(file), e);
      throw UtilsPackage.rethrow(e);
    }
  }
  @Override
  public void visitMembers(@NotNull final MemberVisitor memberVisitor) {
    try {
      new ClassReader(file.contentsToByteArray())
          .accept(
              new ClassVisitor(ASM5) {
                @Override
                public FieldVisitor visitField(
                    int access, String name, String desc, String signature, Object value) {
                  final AnnotationVisitor v =
                      memberVisitor.visitField(Name.guess(name), desc, value);
                  if (v == null) return null;

                  return new FieldVisitor(ASM5) {
                    @Override
                    public org.jetbrains.org.objectweb.asm.AnnotationVisitor visitAnnotation(
                        String desc, boolean visible) {
                      return convertAnnotationVisitor(v, desc);
                    }

                    @Override
                    public void visitEnd() {
                      v.visitEnd();
                    }
                  };
                }

                @Override
                public MethodVisitor visitMethod(
                    int access, String name, String desc, String signature, String[] exceptions) {
                  final MethodAnnotationVisitor v =
                      memberVisitor.visitMethod(Name.guess(name), desc);
                  if (v == null) return null;

                  return new MethodVisitor(ASM5) {
                    @Override
                    public org.jetbrains.org.objectweb.asm.AnnotationVisitor visitAnnotation(
                        String desc, boolean visible) {
                      return convertAnnotationVisitor(v, desc);
                    }

                    @Override
                    public org.jetbrains.org.objectweb.asm.AnnotationVisitor
                        visitParameterAnnotation(int parameter, String desc, boolean visible) {
                      AnnotationArgumentVisitor av =
                          v.visitParameterAnnotation(parameter, classNameFromAsmDesc(desc));
                      return av == null ? null : convertAnnotationVisitor(av);
                    }

                    @Override
                    public void visitEnd() {
                      v.visitEnd();
                    }
                  };
                }
              },
              SKIP_CODE | SKIP_DEBUG | SKIP_FRAMES);
    } catch (Throwable e) {
      LOG.error(renderFileReadingErrorMessage(file), e);
      throw UtilsPackage.rethrow(e);
    }
  }
예제 #7
0
  @NotNull
  public LineResult eval(@NotNull String line) {
    ++lineNumber;

    FqName scriptFqName = new FqName("Line" + lineNumber);
    Type scriptClassType = asmTypeByFqNameWithoutInnerClasses(scriptFqName);

    StringBuilder fullText = new StringBuilder();
    for (String prevLine : previousIncompleteLines) {
      fullText.append(prevLine + "\n");
    }
    fullText.append(line);

    LightVirtualFile virtualFile =
        new LightVirtualFile(
            "line" + lineNumber + JetParserDefinition.STD_SCRIPT_EXT,
            JetLanguage.INSTANCE,
            fullText.toString());
    virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET);
    JetFile psiFile =
        (JetFile)
            ((PsiFileFactoryImpl) PsiFileFactory.getInstance(jetCoreEnvironment.getProject()))
                .trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false);

    MessageCollectorToString errorCollector = new MessageCollectorToString();

    AnalyzerWithCompilerReport.SyntaxErrorReport syntaxErrorReport =
        AnalyzerWithCompilerReport.reportSyntaxErrors(psiFile, errorCollector);

    if (syntaxErrorReport.isOnlyErrorAtEof()) {
      previousIncompleteLines.add(line);
      return LineResult.incomplete();
    }

    previousIncompleteLines.clear();

    if (syntaxErrorReport.isHasErrors()) {
      return LineResult.error(errorCollector.getString());
    }

    prepareForTheNextReplLine(topDownAnalysisContext);
    trace.clearDiagnostics();

    psiFile.getScript().putUserData(ScriptHeaderResolver.PRIORITY_KEY, lineNumber);

    ScriptDescriptor scriptDescriptor = doAnalyze(psiFile, errorCollector);
    if (scriptDescriptor == null) {
      return LineResult.error(errorCollector.getString());
    }

    List<Pair<ScriptDescriptor, Type>> earlierScripts = Lists.newArrayList();

    for (EarlierLine earlierLine : earlierLines) {
      earlierScripts.add(
          Pair.create(earlierLine.getScriptDescriptor(), earlierLine.getClassType()));
    }

    BindingContext bindingContext =
        AnalyzeExhaust.success(trace.getBindingContext(), module).getBindingContext();
    GenerationState generationState =
        new GenerationState(
            psiFile.getProject(),
            ClassBuilderFactories.BINARIES,
            bindingContext,
            Collections.singletonList(psiFile),
            CompilerArgumentsUtil.DEFAULT_INLINE_FLAG);

    compileScript(
        psiFile.getScript(),
        scriptClassType,
        earlierScripts,
        generationState,
        CompilationErrorHandler.THROW_EXCEPTION);

    for (OutputFile outputFile : generationState.getFactory().asList()) {
      classLoader.addClass(
          JvmClassName.byInternalName(outputFile.getRelativePath().replaceFirst("\\.class$", "")),
          outputFile.asByteArray());
    }

    try {
      Class<?> scriptClass = classLoader.loadClass(scriptFqName.asString());

      Class<?>[] constructorParams = new Class<?>[earlierLines.size()];
      Object[] constructorArgs = new Object[earlierLines.size()];

      for (int i = 0; i < earlierLines.size(); ++i) {
        constructorParams[i] = earlierLines.get(i).getScriptClass();
        constructorArgs[i] = earlierLines.get(i).getScriptInstance();
      }

      Constructor<?> scriptInstanceConstructor = scriptClass.getConstructor(constructorParams);
      Object scriptInstance;
      try {
        scriptInstance = scriptInstanceConstructor.newInstance(constructorArgs);
      } catch (Throwable e) {
        return LineResult.error(Throwables.getStackTraceAsString(e));
      }
      Field rvField = scriptClass.getDeclaredField("rv");
      rvField.setAccessible(true);
      Object rv = rvField.get(scriptInstance);

      earlierLines.add(
          new EarlierLine(line, scriptDescriptor, scriptClass, scriptInstance, scriptClassType));

      return LineResult.successful(
          rv,
          KotlinBuiltIns.getInstance()
              .getUnitType()
              .equals(scriptDescriptor.getScriptCodeDescriptor().getReturnType()));
    } catch (Throwable e) {
      PrintWriter writer = new PrintWriter(System.err);
      classLoader.dumpClasses(writer);
      writer.flush();
      throw UtilsPackage.rethrow(e);
    }
  }