Search in sources :

Example 6 with AnalysisResult

use of org.jetbrains.kotlin.analyzer.AnalysisResult in project kotlin by JetBrains.

the class AbstractDiagnosticMessageTest method doTest.

public void doTest(String filePath) throws Exception {
    File file = new File(filePath);
    String fileName = file.getName();
    String fileData = KotlinTestUtils.doLoadFile(file);
    Map<String, String> directives = KotlinTestUtils.parseDirectives(fileData);
    int diagnosticNumber = getDiagnosticNumber(directives);
    final Set<DiagnosticFactory<?>> diagnosticFactories = getDiagnosticFactories(directives);
    MessageType messageType = getMessageTypeDirective(directives);
    String explicitLanguageVersion = InTextDirectivesUtils.findStringWithPrefixes(fileData, "// LANGUAGE_VERSION:");
    LanguageVersion version = explicitLanguageVersion == null ? null : LanguageVersion.fromVersionString(explicitLanguageVersion);
    KtFile psiFile = KotlinTestUtils.createFile(fileName, KotlinTestUtils.doLoadFile(getTestDataPath(), fileName), getProject());
    AnalysisResult analysisResult = analyze(psiFile, version);
    BindingContext bindingContext = analysisResult.getBindingContext();
    List<Diagnostic> diagnostics = ContainerUtil.filter(bindingContext.getDiagnostics().all(), new Condition<Diagnostic>() {

        @Override
        public boolean value(Diagnostic diagnostic) {
            return diagnosticFactories.contains(diagnostic.getFactory());
        }
    });
    assertEquals("Expected diagnostics number mismatch:", diagnosticNumber, diagnostics.size());
    int index = 1;
    String name = FileUtil.getNameWithoutExtension(fileName);
    for (Diagnostic diagnostic : diagnostics) {
        String readableDiagnosticText;
        String extension;
        if (messageType != MessageType.TEXT && IdeErrorMessages.hasIdeSpecificMessage(diagnostic)) {
            readableDiagnosticText = FormatHtmlUtilKt.formatHtml(IdeErrorMessages.render(diagnostic));
            extension = MessageType.HTML.extension;
        } else {
            readableDiagnosticText = DefaultErrorMessages.render(diagnostic);
            extension = MessageType.TEXT.extension;
        }
        String errorMessageFileName = name + index;
        String path = getTestDataPath() + "/" + errorMessageFileName + "." + extension;
        String actualText = "<!-- " + errorMessageFileName + " -->\n" + readableDiagnosticText;
        assertSameLinesWithFile(path, actualText);
        index++;
    }
}
Also used : Diagnostic(org.jetbrains.kotlin.diagnostics.Diagnostic) BindingContext(org.jetbrains.kotlin.resolve.BindingContext) AnalysisResult(org.jetbrains.kotlin.analyzer.AnalysisResult) DiagnosticFactory(org.jetbrains.kotlin.diagnostics.DiagnosticFactory) LanguageVersion(org.jetbrains.kotlin.config.LanguageVersion) KtFile(org.jetbrains.kotlin.psi.KtFile) KtFile(org.jetbrains.kotlin.psi.KtFile) File(java.io.File)

Example 7 with AnalysisResult

use of org.jetbrains.kotlin.analyzer.AnalysisResult in project kotlin by JetBrains.

the class KotlinTypeCheckerTest method getDeclarationsScope.

@NotNull
private LexicalScope getDeclarationsScope(String path) throws IOException {
    KtFile ktFile = KotlinTestUtils.loadJetFile(getProject(), new File(path));
    AnalysisResult result = JvmResolveUtil.analyze(ktFile, getEnvironment());
    //noinspection ConstantConditions
    return result.getBindingContext().get(BindingContext.LEXICAL_SCOPE, ktFile);
}
Also used : KtFile(org.jetbrains.kotlin.psi.KtFile) KtFile(org.jetbrains.kotlin.psi.KtFile) File(java.io.File) AnalysisResult(org.jetbrains.kotlin.analyzer.AnalysisResult) NotNull(org.jetbrains.annotations.NotNull)

Example 8 with AnalysisResult

use of org.jetbrains.kotlin.analyzer.AnalysisResult in project kotlin by JetBrains.

the class TypeSubstitutorTest method getContextScope.

private LexicalScope getContextScope() throws IOException {
    // todo comments
    String text = FileUtil.loadFile(new File("compiler/testData/type-substitutor.kt"), true);
    KtFile ktFile = KtPsiFactoryKt.KtPsiFactory(getProject()).createFile(text);
    AnalysisResult analysisResult = JvmResolveUtil.analyze(ktFile, getEnvironment());
    ModuleDescriptor module = analysisResult.getModuleDescriptor();
    LexicalScope topLevelScope = analysisResult.getBindingContext().get(BindingContext.LEXICAL_SCOPE, ktFile);
    final ClassifierDescriptor contextClass = ScopeUtilsKt.findClassifier(topLevelScope, Name.identifier("___Context"), NoLookupLocation.FROM_TEST);
    assert contextClass instanceof ClassDescriptor;
    LocalRedeclarationChecker redeclarationChecker = new ThrowingLocalRedeclarationChecker(new OverloadChecker(TypeSpecificityComparator.NONE.INSTANCE));
    LexicalScope typeParameters = new LexicalScopeImpl(topLevelScope, module, false, null, LexicalScopeKind.SYNTHETIC, redeclarationChecker, new Function1<LexicalScopeImpl.InitializeHandler, Unit>() {

        @Override
        public Unit invoke(LexicalScopeImpl.InitializeHandler handler) {
            for (TypeParameterDescriptor parameterDescriptor : contextClass.getTypeConstructor().getParameters()) {
                handler.addClassifierDescriptor(parameterDescriptor);
            }
            return Unit.INSTANCE;
        }
    });
    return new LexicalChainedScope(typeParameters, module, false, null, LexicalScopeKind.SYNTHETIC, Arrays.asList(contextClass.getDefaultType().getMemberScope(), module.getBuiltIns().getBuiltInsPackageScope()));
}
Also used : TypeParameterDescriptor(org.jetbrains.kotlin.descriptors.TypeParameterDescriptor) ClassDescriptor(org.jetbrains.kotlin.descriptors.ClassDescriptor) ClassifierDescriptor(org.jetbrains.kotlin.descriptors.ClassifierDescriptor) Unit(kotlin.Unit) AnalysisResult(org.jetbrains.kotlin.analyzer.AnalysisResult) ModuleDescriptor(org.jetbrains.kotlin.descriptors.ModuleDescriptor) KtFile(org.jetbrains.kotlin.psi.KtFile) KtFile(org.jetbrains.kotlin.psi.KtFile) File(java.io.File)

Example 9 with AnalysisResult

use of org.jetbrains.kotlin.analyzer.AnalysisResult in project kotlin by JetBrains.

the class AbstractCompileJavaAgainstKotlinTest method doTest.

protected void doTest(String ktFilePath) throws IOException {
    Assert.assertTrue(ktFilePath.endsWith(".kt"));
    File ktFile = new File(ktFilePath);
    File javaFile = new File(ktFilePath.replaceFirst("\\.kt$", ".java"));
    File expectedFile = new File(ktFilePath.replaceFirst("\\.kt$", ".txt"));
    File javaErrorFile = new File(ktFilePath.replaceFirst("\\.kt$", ".javaerr.txt"));
    File out = new File(tmpdir, "out");
    compileKotlinWithJava(Collections.singletonList(javaFile), Collections.singletonList(ktFile), out, getTestRootDisposable(), javaErrorFile);
    KotlinCoreEnvironment environment = KotlinCoreEnvironment.createForTests(getTestRootDisposable(), newConfiguration(ConfigurationKind.ALL, TestJdkKind.MOCK_JDK, getAnnotationsJar(), out), EnvironmentConfigFiles.JVM_CONFIG_FILES);
    AnalysisResult analysisResult = JvmResolveUtil.analyze(environment);
    PackageViewDescriptor packageView = analysisResult.getModuleDescriptor().getPackage(LoadDescriptorUtil.TEST_PACKAGE_FQNAME);
    assertFalse("Nothing found in package " + LoadDescriptorUtil.TEST_PACKAGE_FQNAME, packageView.isEmpty());
    validateAndCompareDescriptorWithFile(packageView, CONFIGURATION, expectedFile);
}
Also used : KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) RecursiveDescriptorComparator.validateAndCompareDescriptorWithFile(org.jetbrains.kotlin.test.util.RecursiveDescriptorComparator.validateAndCompareDescriptorWithFile) File(java.io.File) AnalysisResult(org.jetbrains.kotlin.analyzer.AnalysisResult) PackageViewDescriptor(org.jetbrains.kotlin.descriptors.PackageViewDescriptor)

Example 10 with AnalysisResult

use of org.jetbrains.kotlin.analyzer.AnalysisResult in project kotlin by JetBrains.

the class K2JSCompiler method doExecute.

@NotNull
@Override
protected ExitCode doExecute(@NotNull K2JSCompilerArguments arguments, @NotNull CompilerConfiguration configuration, @NotNull Disposable rootDisposable) {
    final MessageCollector messageCollector = configuration.getNotNull(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY);
    if (arguments.freeArgs.isEmpty()) {
        if (arguments.version) {
            return OK;
        }
        messageCollector.report(CompilerMessageSeverity.ERROR, "Specify at least one source file or directory", NO_LOCATION);
        return COMPILATION_ERROR;
    }
    ContentRootsKt.addKotlinSourceRoots(configuration, arguments.freeArgs);
    KotlinCoreEnvironment environmentForJS = KotlinCoreEnvironment.createForProduction(rootDisposable, configuration, EnvironmentConfigFiles.JS_CONFIG_FILES);
    Project project = environmentForJS.getProject();
    List<KtFile> sourcesFiles = environmentForJS.getSourceFiles();
    environmentForJS.getConfiguration().put(CLIConfigurationKeys.ALLOW_KOTLIN_PACKAGE, arguments.allowKotlinPackage);
    if (!checkKotlinPackageUsage(environmentForJS, sourcesFiles))
        return ExitCode.COMPILATION_ERROR;
    if (arguments.outputFile == null) {
        messageCollector.report(CompilerMessageSeverity.ERROR, "Specify output file via -output", CompilerMessageLocation.NO_LOCATION);
        return ExitCode.COMPILATION_ERROR;
    }
    if (messageCollector.hasErrors()) {
        return ExitCode.COMPILATION_ERROR;
    }
    if (sourcesFiles.isEmpty()) {
        messageCollector.report(CompilerMessageSeverity.ERROR, "No source files", CompilerMessageLocation.NO_LOCATION);
        return COMPILATION_ERROR;
    }
    if (arguments.verbose) {
        reportCompiledSourcesList(messageCollector, sourcesFiles);
    }
    File outputFile = new File(arguments.outputFile);
    configuration.put(CommonConfigurationKeys.MODULE_NAME, FileUtil.getNameWithoutExtension(outputFile));
    JsConfig config = new LibrarySourcesConfig(project, configuration);
    if (config.checkLibFilesAndReportErrors(new JsConfig.Reporter() {

        @Override
        public void error(@NotNull String message) {
            messageCollector.report(CompilerMessageSeverity.ERROR, message, CompilerMessageLocation.NO_LOCATION);
        }

        @Override
        public void warning(@NotNull String message) {
            messageCollector.report(CompilerMessageSeverity.STRONG_WARNING, message, CompilerMessageLocation.NO_LOCATION);
        }
    })) {
        return COMPILATION_ERROR;
    }
    AnalyzerWithCompilerReport analyzerWithCompilerReport = analyzeAndReportErrors(messageCollector, sourcesFiles, config);
    if (analyzerWithCompilerReport.hasErrors()) {
        return COMPILATION_ERROR;
    }
    ProgressIndicatorAndCompilationCanceledStatus.checkCanceled();
    AnalysisResult analysisResult = analyzerWithCompilerReport.getAnalysisResult();
    assert analysisResult instanceof JsAnalysisResult : "analysisResult should be instance of JsAnalysisResult, but " + analysisResult;
    JsAnalysisResult jsAnalysisResult = (JsAnalysisResult) analysisResult;
    File outputPrefixFile = null;
    if (arguments.outputPrefix != null) {
        outputPrefixFile = new File(arguments.outputPrefix);
        if (!outputPrefixFile.exists()) {
            messageCollector.report(CompilerMessageSeverity.ERROR, "Output prefix file '" + arguments.outputPrefix + "' not found", CompilerMessageLocation.NO_LOCATION);
            return ExitCode.COMPILATION_ERROR;
        }
    }
    File outputPostfixFile = null;
    if (arguments.outputPostfix != null) {
        outputPostfixFile = new File(arguments.outputPostfix);
        if (!outputPostfixFile.exists()) {
            messageCollector.report(CompilerMessageSeverity.ERROR, "Output postfix file '" + arguments.outputPostfix + "' not found", CompilerMessageLocation.NO_LOCATION);
            return ExitCode.COMPILATION_ERROR;
        }
    }
    MainCallParameters mainCallParameters = createMainCallParameters(arguments.main);
    TranslationResult translationResult;
    K2JSTranslator translator = new K2JSTranslator(config);
    try {
        //noinspection unchecked
        translationResult = translator.translate(sourcesFiles, mainCallParameters, jsAnalysisResult);
    } catch (Exception e) {
        throw ExceptionUtilsKt.rethrow(e);
    }
    ProgressIndicatorAndCompilationCanceledStatus.checkCanceled();
    AnalyzerWithCompilerReport.Companion.reportDiagnostics(translationResult.getDiagnostics(), messageCollector);
    if (!(translationResult instanceof TranslationResult.Success))
        return ExitCode.COMPILATION_ERROR;
    TranslationResult.Success successResult = (TranslationResult.Success) translationResult;
    OutputFileCollection outputFiles = successResult.getOutputFiles(outputFile, outputPrefixFile, outputPostfixFile);
    if (outputFile.isDirectory()) {
        messageCollector.report(CompilerMessageSeverity.ERROR, "Cannot open output file '" + outputFile.getPath() + "': is a directory", CompilerMessageLocation.NO_LOCATION);
        return ExitCode.COMPILATION_ERROR;
    }
    File outputDir = outputFile.getParentFile();
    if (outputDir == null) {
        outputDir = outputFile.getAbsoluteFile().getParentFile();
    }
    ProgressIndicatorAndCompilationCanceledStatus.checkCanceled();
    OutputUtilsKt.writeAll(outputFiles, outputDir, messageCollector);
    return OK;
}
Also used : MainCallParameters(org.jetbrains.kotlin.js.facade.MainCallParameters) JsConfig(org.jetbrains.kotlin.js.config.JsConfig) AnalyzerWithCompilerReport(org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport) K2JSTranslator(org.jetbrains.kotlin.js.facade.K2JSTranslator) LibrarySourcesConfig(org.jetbrains.kotlin.js.config.LibrarySourcesConfig) JsAnalysisResult(org.jetbrains.kotlin.js.analyzer.JsAnalysisResult) AnalysisResult(org.jetbrains.kotlin.analyzer.AnalysisResult) Project(com.intellij.openapi.project.Project) JsAnalysisResult(org.jetbrains.kotlin.js.analyzer.JsAnalysisResult) OutputFileCollection(org.jetbrains.kotlin.backend.common.output.OutputFileCollection) KotlinCoreEnvironment(org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment) MessageCollector(org.jetbrains.kotlin.cli.common.messages.MessageCollector) KtFile(org.jetbrains.kotlin.psi.KtFile) TranslationResult(org.jetbrains.kotlin.js.facade.TranslationResult) VirtualFile(com.intellij.openapi.vfs.VirtualFile) KtFile(org.jetbrains.kotlin.psi.KtFile) File(java.io.File) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

AnalysisResult (org.jetbrains.kotlin.analyzer.AnalysisResult)14 File (java.io.File)9 KtFile (org.jetbrains.kotlin.psi.KtFile)8 NotNull (org.jetbrains.annotations.NotNull)7 KotlinCoreEnvironment (org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment)6 CompilerConfiguration (org.jetbrains.kotlin.config.CompilerConfiguration)3 PackageViewDescriptor (org.jetbrains.kotlin.descriptors.PackageViewDescriptor)3 BindingContext (org.jetbrains.kotlin.resolve.BindingContext)3 AnalyzerWithCompilerReport (org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport)2 JsAnalysisResult (org.jetbrains.kotlin.js.analyzer.JsAnalysisResult)2 Project (com.intellij.openapi.project.Project)1 VirtualFile (com.intellij.openapi.vfs.VirtualFile)1 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)1 FileFilter (java.io.FileFilter)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 Unit (kotlin.Unit)1 OutputFileCollection (org.jetbrains.kotlin.backend.common.output.OutputFileCollection)1 Pseudocode (org.jetbrains.kotlin.cfg.pseudocode.Pseudocode)1 MessageCollector (org.jetbrains.kotlin.cli.common.messages.MessageCollector)1