001    /*
002     * Copyright 2010-2014 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.k2js.analyze;
018    
019    import com.google.common.base.Predicate;
020    import com.google.common.base.Predicates;
021    import com.google.common.collect.ImmutableList;
022    import com.intellij.openapi.project.Project;
023    import com.intellij.psi.PsiFile;
024    import org.jetbrains.annotations.NotNull;
025    import org.jetbrains.annotations.Nullable;
026    import org.jetbrains.jet.analyzer.AnalyzeExhaust;
027    import org.jetbrains.jet.context.ContextPackage;
028    import org.jetbrains.jet.context.GlobalContextImpl;
029    import org.jetbrains.jet.di.InjectorForLazyResolve;
030    import org.jetbrains.jet.di.InjectorForTopDownAnalyzerForJs;
031    import org.jetbrains.jet.lang.PlatformToKotlinClassMap;
032    import org.jetbrains.jet.lang.descriptors.DependencyKind;
033    import org.jetbrains.jet.lang.descriptors.ModuleDescriptor;
034    import org.jetbrains.jet.lang.descriptors.ModuleDescriptorImpl;
035    import org.jetbrains.jet.lang.psi.JetFile;
036    import org.jetbrains.jet.lang.resolve.*;
037    import org.jetbrains.jet.lang.resolve.lazy.ResolveSession;
038    import org.jetbrains.jet.lang.resolve.lazy.declarations.DeclarationProviderFactory;
039    import org.jetbrains.jet.lang.resolve.name.Name;
040    import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
041    import org.jetbrains.k2js.config.Config;
042    
043    import java.util.Collection;
044    import java.util.List;
045    
046    import static org.jetbrains.jet.lang.resolve.lazy.declarations.DeclarationProviderFactoryService.createDeclarationProviderFactory;
047    
048    public final class AnalyzerFacadeForJS {
049        public static final List<ImportPath> DEFAULT_IMPORTS = ImmutableList.of(
050                new ImportPath("js.*"),
051                new ImportPath("java.lang.*"),
052                new ImportPath("kotlin.*")
053        );
054    
055        private AnalyzerFacadeForJS() {
056        }
057    
058        @NotNull
059        public static BindingContext analyzeFilesAndCheckErrors(@NotNull List<JetFile> files,
060                @NotNull Config config) {
061            BindingContext bindingContext = analyzeFiles(files, Predicates.<PsiFile>alwaysTrue(), config).getBindingContext();
062            checkForErrors(Config.withJsLibAdded(files, config), bindingContext);
063            return bindingContext;
064        }
065    
066    
067        //NOTE: web demo related method
068        @SuppressWarnings("UnusedDeclaration")
069        @NotNull
070        public static BindingContext analyzeFiles(@NotNull Collection<JetFile> files, @NotNull Config config) {
071            return analyzeFiles(files, Predicates.<PsiFile>alwaysTrue(), config).getBindingContext();
072        }
073    
074        //TODO: refactor
075        @NotNull
076        public static AnalyzeExhaust analyzeFiles(
077                @NotNull Collection<JetFile> files,
078                @NotNull Predicate<PsiFile> filesToAnalyzeCompletely,
079                @NotNull Config config
080        ) {
081            Project project = config.getProject();
082    
083            ModuleDescriptorImpl owner = createJsModule("<module>");
084    
085            Predicate<PsiFile> completely = Predicates.and(notLibFiles(config.getLibFiles()), filesToAnalyzeCompletely);
086    
087            GlobalContextImpl globalContext = ContextPackage.GlobalContext();
088            TopDownAnalysisParameters topDownAnalysisParameters = TopDownAnalysisParameters.create(
089                    globalContext.getStorageManager(), globalContext.getExceptionTracker(), completely, false, false);
090    
091            ModuleDescriptor libraryModule = config.getLibraryModule();
092            if (libraryModule != null) {
093                owner.addFragmentProvider(DependencyKind.BINARIES, libraryModule.getPackageFragmentProvider()); // "import" analyzed library module
094            }
095    
096            BindingContext libraryContext = config.getLibraryContext();
097            BindingTrace trace = libraryContext == null
098                                 ? new BindingTraceContext()
099                                 : new DelegatingBindingTrace(libraryContext, "trace with preanalyzed library");
100            InjectorForTopDownAnalyzerForJs injector = new InjectorForTopDownAnalyzerForJs(project, topDownAnalysisParameters, trace, owner);
101            try {
102                Collection<JetFile> allFiles = libraryModule != null ?
103                                               files :
104                                               Config.withJsLibAdded(files, config);
105                injector.getTopDownAnalyzer().analyzeFiles(topDownAnalysisParameters, allFiles);
106                return AnalyzeExhaust.success(trace.getBindingContext(), owner);
107            }
108            finally {
109                injector.destroy();
110            }
111        }
112    
113        public static void checkForErrors(@NotNull Collection<JetFile> allFiles, @NotNull BindingContext bindingContext) {
114            AnalyzingUtils.throwExceptionOnErrors(bindingContext);
115            for (JetFile file : allFiles) {
116                AnalyzingUtils.checkForSyntacticErrors(file);
117            }
118        }
119    
120        @NotNull
121        private static Predicate<PsiFile> notLibFiles(@NotNull final List<JetFile> jsLibFiles) {
122            return new Predicate<PsiFile>() {
123                @Override
124                public boolean apply(@Nullable PsiFile file) {
125                    assert file instanceof JetFile;
126                    @SuppressWarnings("UnnecessaryLocalVariable") boolean notLibFile = !jsLibFiles.contains(file);
127                    return notLibFile;
128                }
129            };
130        }
131    
132        @NotNull
133        public static ResolveSession getLazyResolveSession(Collection<JetFile> files, Config config) {
134            GlobalContextImpl globalContext = ContextPackage.GlobalContext();
135            DeclarationProviderFactory declarationProviderFactory =
136                    createDeclarationProviderFactory(config.getProject(), globalContext.getStorageManager(),
137                                                     Config.withJsLibAdded(files, config));
138            ModuleDescriptorImpl module = createJsModule("<lazy module>");
139            module.addFragmentProvider(DependencyKind.BUILT_INS, KotlinBuiltIns.getInstance().getBuiltInsModule().getPackageFragmentProvider());
140    
141            return new InjectorForLazyResolve(
142                    config.getProject(),
143                    globalContext,
144                    module,
145                    declarationProviderFactory,
146                    new BindingTraceContext()).getResolveSession();
147        }
148    
149        @NotNull
150        private static ModuleDescriptorImpl createJsModule(@NotNull String name) {
151            return new ModuleDescriptorImpl(Name.special(name), DEFAULT_IMPORTS, PlatformToKotlinClassMap.EMPTY);
152        }
153    
154    }