コード例 #1
0
 @NotNull
 public static ClassFileFactory generateFiles(
     @NotNull JetCoreEnvironment environment, @NotNull CodegenTestFiles files) {
   AnalyzeExhaust analyzeExhaust =
       AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegrationAndCheckForErrors(
           environment.getProject(),
           files.getPsiFiles(),
           files.getScriptParameterTypes(),
           Predicates.<PsiFile>alwaysTrue());
   analyzeExhaust.throwIfError();
   AnalyzingUtils.throwExceptionOnErrors(analyzeExhaust.getBindingContext());
   CompilerConfiguration configuration = environment.getConfiguration();
   GenerationState state =
       new GenerationState(
           environment.getProject(),
           ClassBuilderFactories.TEST,
           Progress.DEAF,
           analyzeExhaust.getBindingContext(),
           files.getPsiFiles(),
           configuration.get(JVMConfigurationKeys.GENERATE_NOT_NULL_ASSERTIONS, true),
           configuration.get(JVMConfigurationKeys.GENERATE_NOT_NULL_PARAMETER_ASSERTIONS, true),
           /*generateDeclaredClasses = */ true,
           configuration.get(
               JVMConfigurationKeys.ENABLE_INLINE, InlineUtil.DEFAULT_INLINE_FLAG_FOR_TEST));
   KotlinCodegenFacade.compileCorrectFiles(state, CompilationErrorHandler.THROW_EXCEPTION);
   return state.getFactory();
 }
コード例 #2
0
  private void setUpEnvironment(
      boolean generateAssertions, boolean generateParamAssertions, File... extraClassPath) {
    CompilerConfiguration configuration =
        JetTestUtils.compilerConfigurationForTests(
            ConfigurationKind.JDK_ONLY, TestJdkKind.MOCK_JDK, extraClassPath);

    configuration.put(JVMConfigurationKeys.GENERATE_NOT_NULL_ASSERTIONS, generateAssertions);
    configuration.put(
        JVMConfigurationKeys.GENERATE_NOT_NULL_PARAMETER_ASSERTIONS, generateParamAssertions);

    myEnvironment = new JetCoreEnvironment(getTestRootDisposable(), configuration);
  }
コード例 #3
0
  @NotNull
  public static List<Module> loadModuleScript(
      String moduleScriptFile, MessageCollector messageCollector) {
    Disposable disposable =
        new Disposable() {
          @Override
          public void dispose() {}
        };
    CompilerConfiguration configuration = new CompilerConfiguration();
    File defaultRuntimePath = CompilerPathUtil.getRuntimePath();
    if (defaultRuntimePath != null) {
      configuration.add(JVMConfigurationKeys.CLASSPATH_KEY, defaultRuntimePath);
    }
    configuration.add(JVMConfigurationKeys.CLASSPATH_KEY, PathUtil.findRtJar());
    File jdkAnnotationsPath = CompilerPathUtil.getJdkAnnotationsPath();
    if (jdkAnnotationsPath != null) {
      configuration.add(JVMConfigurationKeys.ANNOTATIONS_PATH_KEY, jdkAnnotationsPath);
    }
    configuration.add(CommonConfigurationKeys.SOURCE_ROOTS_KEY, moduleScriptFile);
    JetCoreEnvironment scriptEnvironment =
        JetCoreEnvironment.createCoreEnvironmentForJVM(disposable, configuration);

    GenerationState generationState =
        KotlinToJVMBytecodeCompiler.analyzeAndGenerate(
            new K2JVMCompileEnvironmentConfiguration(
                scriptEnvironment,
                messageCollector,
                false,
                BuiltinsScopeExtensionMode.ALL,
                false,
                BuiltinToJavaTypesMapping.ENABLED),
            false);
    if (generationState == null) {
      throw new CompileEnvironmentException(
          "Module script " + moduleScriptFile + " analyze failed");
    }

    List<Module> modules = runDefineModules(moduleScriptFile, generationState.getFactory());

    Disposer.dispose(disposable);

    if (modules == null) {
      throw new CompileEnvironmentException(
          "Module script " + moduleScriptFile + " compilation failed");
    }

    if (modules.isEmpty()) {
      throw new CompileEnvironmentException("No modules where defined by " + moduleScriptFile);
    }
    return modules;
  }
コード例 #4
0
    public void doTest(String path) throws Exception {
      File dir = new File(path);

      CompilerConfiguration configuration =
          JetTestUtils.compilerConfigurationForTests(
              ConfigurationKind.JDK_ONLY, TestJdkKind.MOCK_JDK, new File(dir, "java"));
      configuration.put(
          CommonConfigurationKeys.SOURCE_ROOTS_KEY,
          Arrays.asList(new File(dir, "kotlin").getAbsolutePath()));
      JetCoreEnvironment environment =
          new JetCoreEnvironment(getTestRootDisposable(), configuration);

      ModuleDescriptor moduleDescriptor = new ModuleDescriptor(Name.special("<test module>"));

      // we need the same binding trace for resolve from Java and Kotlin
      BindingTrace trace =
          CliLightClassGenerationSupport.getInstanceForCli(environment.getProject()).getTrace();

      InjectorForJavaDescriptorResolver injectorForJava =
          new InjectorForJavaDescriptorResolver(environment.getProject(), trace, moduleDescriptor);

      InjectorForTopDownAnalyzerForJvm injectorForAnalyzer =
          new InjectorForTopDownAnalyzerForJvm(
              environment.getProject(),
              new TopDownAnalysisParameters(
                  Predicates.<PsiFile>alwaysFalse(),
                  false,
                  false,
                  Collections.<AnalyzerScriptParameter>emptyList()),
              trace,
              moduleDescriptor);

      injectorForAnalyzer
          .getTopDownAnalyzer()
          .analyzeFiles(
              environment.getSourceFiles(), Collections.<AnalyzerScriptParameter>emptyList());

      JavaDescriptorResolver javaDescriptorResolver = injectorForJava.getJavaDescriptorResolver();
      NamespaceDescriptor namespaceDescriptor =
          javaDescriptorResolver.resolveNamespace(
              LoadDescriptorUtil.TEST_PACKAGE_FQNAME, DescriptorSearchRule.INCLUDE_KOTLIN);
      assert namespaceDescriptor != null;

      compareNamespaceWithFile(
          namespaceDescriptor,
          NamespaceComparator.DONT_INCLUDE_METHODS_OF_OBJECT,
          new File(dir, "expected.txt"));

      ExpectedLoadErrorsUtil.checkForLoadErrors(namespaceDescriptor, trace.getBindingContext());
    }
コード例 #5
0
ファイル: ReplInterpreter.java プロジェクト: kuity/kotlin
  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])));
  }
コード例 #6
0
  private void blackBoxFileWithJavaByFullPath(@NotNull String directory) throws Exception {
    File dirFile = new File(directory);

    final List<String> javaFilePaths = new ArrayList<String>();
    final List<String> ktFilePaths = new ArrayList<String>();
    FileUtil.processFilesRecursively(
        dirFile,
        new Processor<File>() {
          @Override
          public boolean process(File file) {
            String path = relativePath(file);
            if (path.endsWith(".kt")) {
              ktFilePaths.add(path);
            } else if (path.endsWith(".java")) {
              javaFilePaths.add(path);
            }
            return true;
          }
        });

    CompilerConfiguration configuration =
        JetTestUtils.compilerConfigurationForTests(
            ConfigurationKind.ALL, TestJdkKind.FULL_JDK, JetTestUtils.getAnnotationsJar());
    configuration.add(JVMConfigurationKeys.CLASSPATH_KEY, dirFile);
    myEnvironment = JetCoreEnvironment.createForTests(getTestRootDisposable(), configuration);
    loadFiles(ArrayUtil.toStringArray(ktFilePaths));
    classFileFactory =
        GenerationUtils.compileManyFilesGetGenerationStateForTest(
                myEnvironment.getProject(), myFiles.getPsiFiles())
            .getFactory();
    File kotlinOut = JetTestUtils.tmpDir(toString());
    OutputUtilsPackage.writeAllTo(classFileFactory, kotlinOut);

    // TODO: support several Java sources
    File javaOut = compileJava(KotlinPackage.single(javaFilePaths), kotlinOut.getPath());
    // Add javac output to classpath so that the created class loader can find generated Java
    // classes
    configuration.add(JVMConfigurationKeys.CLASSPATH_KEY, javaOut);

    blackBox();
  }
コード例 #7
0
ファイル: BytecodeCompiler.java プロジェクト: kazhida/kotlin
  private CompilerConfiguration createConfiguration(
      @Nullable String stdlib,
      @Nullable String[] classpath,
      @Nullable String[] externalAnnotationsPath,
      @NotNull String[] sourceRoots,
      boolean enableInline,
      boolean enableOptimization) {
    KotlinPaths paths = getKotlinPathsForAntTask();
    CompilerConfiguration configuration = new CompilerConfiguration();
    configuration.addAll(CLASSPATH_KEY, PathUtil.getJdkClassesRoots());
    if ((stdlib != null) && (stdlib.trim().length() > 0)) {
      configuration.add(CLASSPATH_KEY, new File(stdlib));
    } else {
      File path = paths.getRuntimePath();
      if (path.exists()) {
        configuration.add(CLASSPATH_KEY, path);
      }
    }
    if ((classpath != null) && (classpath.length > 0)) {
      for (String path : classpath) {
        configuration.add(CLASSPATH_KEY, new File(path));
      }
    }
    if ((externalAnnotationsPath != null) && (externalAnnotationsPath.length > 0)) {
      for (String path : externalAnnotationsPath) {
        configuration.add(ANNOTATIONS_PATH_KEY, new File(path));
      }
    }
    File jdkAnnotationsPath = paths.getJdkAnnotationsPath();
    if (jdkAnnotationsPath.exists()) {
      configuration.add(ANNOTATIONS_PATH_KEY, jdkAnnotationsPath);
    }

    configuration.addAll(CommonConfigurationKeys.SOURCE_ROOTS_KEY, Arrays.asList(sourceRoots));
    for (String sourceRoot : sourceRoots) {
      File file = new File(sourceRoot);
      if (!file.isFile() || !"kt".equals(FileUtilRt.getExtension(file.getName()))) {
        configuration.add(JVMConfigurationKeys.CLASSPATH_KEY, file);
      }
    }
    configuration.put(
        CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY,
        MessageCollectorPlainTextToStream.PLAIN_TEXT_TO_SYSTEM_ERR);

    configuration.put(ENABLE_INLINE, enableInline);
    configuration.put(ENABLE_OPTIMIZATION, enableOptimization);

    // lets register any compiler plugins
    configuration.addAll(CLIConfigurationKeys.COMPILER_PLUGINS, getCompilerPlugins());
    return configuration;
  }