private void blackBoxFileAgainstJavaByFullPath(@NotNull String ktFileFullPath) {
    String ktFile = relativePath(new File(ktFileFullPath));
    File javaClassesTempDirectory = compileJava(ktFile.replaceFirst("\\.kt$", ".java"));

    myEnvironment =
        JetCoreEnvironment.createForTests(
            getTestRootDisposable(),
            JetTestUtils.compilerConfigurationForTests(
                ConfigurationKind.ALL,
                TestJdkKind.FULL_JDK,
                JetTestUtils.getAnnotationsJar(),
                javaClassesTempDirectory));

    loadFile(ktFile);
    blackBox();
  }
예제 #2
0
  @Override
  protected void analyzeAndCheck(File testDataFile, List<TestFile> testFiles) {
    List<JetFile> jetFiles = getJetFiles(testFiles);

    CliLightClassGenerationSupport support =
        CliLightClassGenerationSupport.getInstanceForCli(getProject());

    BindingContext bindingContext =
        AnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(
                getProject(),
                jetFiles,
                support.getTrace(),
                Predicates.<PsiFile>alwaysTrue(),
                false,
                support.getModule(),
                MemberFilter.ALWAYS_TRUE)
            .getBindingContext();

    boolean ok = true;

    StringBuilder actualText = new StringBuilder();
    for (TestFile testFile : testFiles) {
      ok &= testFile.getActualText(bindingContext, actualText);
    }

    JetTestUtils.assertEqualsToFile(testDataFile, actualText.toString());

    assertTrue("Diagnostics mismatch. See the output above", ok);

    checkAllResolvedCallsAreCompleted(jetFiles, bindingContext);
  }
 public void testAllFilesPresentInType() throws Exception {
   JetTestUtils.assertAllTestsPresentByMetadata(
       this.getClass(),
       "org.jetbrains.jet.generators.tests.GenerateTests",
       new File("idea/testData/hierarchy/class/type"),
       Pattern.compile("^(.+)$"),
       false);
 }
 public void testAllFilesPresentInVisibility() throws Exception {
   JetTestUtils.assertAllTestsPresentByMetadata(
       this.getClass(),
       "org.jetbrains.jet.generators.tests.GenerateTests",
       new File("compiler/testData/loadKotlin/visibility"),
       "kt",
       true);
 }
 public void testAllFilesPresentInGenericWithoutTypeVariables() throws Exception {
   JetTestUtils.assertAllTestsPresentByMetadata(
       this.getClass(),
       "org.jetbrains.jet.generators.tests.GenerateTests",
       new File("compiler/testData/loadKotlin/fun/genericWithoutTypeVariables"),
       "kt",
       true);
 }
 public void testAllFilesPresentInIf() throws Exception {
   JetTestUtils.assertAllTestsPresentByMetadata(
       this.getClass(),
       "org.jetbrains.jet.generators.tests.GenerateTests",
       new File("idea/testData/codeInsight/surroundWith/if"),
       Pattern.compile("^(.+)\\.kt$"),
       true);
 }
예제 #7
0
 public void testAllFilesPresentInRecovery() throws Exception {
   JetTestUtils.assertAllTestsPresentByMetadata(
       this.getClass(),
       "org.jetbrains.jet.generators.tests.GenerateTests",
       new File("compiler/testData/psi/recovery"),
       Pattern.compile("^(.+)\\.kt$"),
       true);
 }
예제 #8
0
  private WritableScope getDeclarationsScope(String path) throws IOException {
    ModuleDescriptor moduleDescriptor =
        LazyResolveTestUtil.resolveEagerly(
            Collections.singletonList(JetTestUtils.loadJetFile(getProject(), new File(path))),
            getEnvironment());

    NamespaceDescriptor testData = moduleDescriptor.getNamespace(new FqName("testData"));
    return addImports(testData.getMemberScope());
  }
예제 #9
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);
    }
  }
예제 #10
0
  @NotNull
  public static NamespaceDescriptor compileJava(
      @NotNull Collection<File> javaFiles, File tmpdir, Disposable disposable) throws IOException {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();

    StandardJavaFileManager fileManager =
        javaCompiler.getStandardFileManager(null, Locale.ENGLISH, Charset.forName("utf-8"));
    try {
      Iterable<? extends JavaFileObject> javaFileObjectsFromFiles =
          fileManager.getJavaFileObjectsFromFiles(javaFiles);
      List<String> options =
          Arrays.asList(
              "-classpath",
              "out/production/runtime"
                  + File.pathSeparator
                  + JetTestUtils.getAnnotationsJar().getPath(),
              "-d",
              tmpdir.getPath());
      JavaCompiler.CompilationTask task =
          javaCompiler.getTask(null, fileManager, null, options, null, javaFileObjectsFromFiles);

      Assert.assertTrue(task.call());
    } finally {
      fileManager.close();
    }

    JetCoreEnvironment jetCoreEnvironment =
        new JetCoreEnvironment(
            disposable,
            CompileCompilerDependenciesTest.compilerConfigurationForTests(
                ConfigurationKind.JDK_ONLY,
                TestJdkKind.MOCK_JDK,
                JetTestUtils.getAnnotationsJar(),
                tmpdir,
                new File("out/production/runtime")));

    InjectorForJavaSemanticServices injector =
        new InjectorForJavaSemanticServices(
            BuiltinsScopeExtensionMode.ALL, jetCoreEnvironment.getProject());
    JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver();
    return javaDescriptorResolver.resolveNamespace(
        FqName.topLevel(Name.identifier("test")), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN);
  }
  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();
  }
  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);
  }
예제 #13
0
  @Override
  public void setUp() throws Exception {
    super.setUp();

    builtIns = KotlinBuiltIns.getInstance();

    InjectorForTests injector =
        new InjectorForTests(getProject(), JetTestUtils.createEmptyModule());
    typeResolver = injector.getTypeResolver();
    expressionTypingServices = injector.getExpressionTypingServices();

    scopeWithImports = getDeclarationsScope("compiler/testData/type-checker-test.kt");
  }
예제 #14
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());
    }
예제 #15
0
  private void doTest(@NotNull String expectedFileName, @NotNull String... javaFileNames)
      throws Exception {
    List<File> files =
        ContainerUtil.map(
            Arrays.asList(javaFileNames),
            new Function<String, File>() {
              @Override
              public File fun(String s) {
                return new File(s);
              }
            });
    File expectedFile = new File(expectedFileName);
    File tmpDir = JetTestUtils.tmpDir(expectedFile.getName());

    Pair<NamespaceDescriptor, BindingContext> javaNamespaceAndBindingContext =
        compileJavaAndLoadTestNamespaceAndBindingContextFromBinary(
            files, tmpDir, getTestRootDisposable(), ConfigurationKind.JDK_ONLY);

    AbstractLoadJavaTest.checkJavaNamespace(expectedFile, javaNamespaceAndBindingContext);
  }
  public void testNoAssertionsForKotlinFromBinary() throws Exception {
    CompilerConfiguration configuration =
        JetTestUtils.compilerConfigurationForTests(
            ConfigurationKind.JDK_ONLY, TestJdkKind.MOCK_JDK);
    JetCoreEnvironment tmpEnvironment =
        new JetCoreEnvironment(getTestRootDisposable(), configuration);
    GenerationState state =
        generateCommon(
            ClassBuilderFactories.TEST,
            tmpEnvironment,
            CodegenTestFiles.create(
                tmpEnvironment.getProject(),
                new String[] {"notNullAssertions/noAssertionsForKotlin.kt"}));
    File compiledDirectory = new File(FileUtil.getTempDirectory(), "kotlin-classes");
    CompileEnvironmentUtil.writeToOutputDirectory(state.getFactory(), compiledDirectory);

    setUpEnvironment(true, false, compiledDirectory);

    loadFile("notNullAssertions/noAssertionsForKotlinMain.kt");

    assertNoIntrinsicsMethodIsCalled(PackageClassUtils.getPackageClassName(FqName.ROOT));
  }
예제 #17
0
 private void doTest() {
   myFixture.configureByFile(getTestName(false) + ".kt");
   JetFile file = (JetFile) myFixture.getFile();
   final String expectedResultText = JetTestUtils.getLastCommentInFile(file);
   try {
     JetRefactoringUtil.selectExpression(
         myFixture.getEditor(),
         file,
         new JetRefactoringUtil.SelectExpressionCallback() {
           @Override
           public void run(@Nullable JetExpression expression) {
             String[] names =
                 JetNameSuggester.suggestNames(
                     expression, JetNameValidator.getEmptyValidator(getProject()), "value");
             Arrays.sort(names);
             String result = StringUtil.join(names, "\n").trim();
             assertEquals(expectedResultText, result);
           }
         });
   } catch (JetRefactoringUtil.IntroduceRefactoringException e) {
     throw new AssertionError("Failed to find expression: " + e.getMessage());
   }
 }
 public void doTestWithStdlib(@NotNull String filename) {
   myEnvironment = JetTestUtils.createEnvironmentWithFullJdk(getTestRootDisposable());
   blackBoxFileByFullPath(filename);
 }