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        private AnalyzerFacadeForJS() {
055        }
056    
057        @NotNull
058        public static BindingContext analyzeFilesAndCheckErrors(@NotNull List<JetFile> files,
059                @NotNull Config config) {
060            BindingContext bindingContext = analyzeFiles(files, Predicates.<PsiFile>alwaysTrue(), config).getBindingContext();
061            checkForErrors(Config.withJsLibAdded(files, config), bindingContext);
062            return bindingContext;
063        }
064    
065    
066        //NOTE: web demo related method
067        @SuppressWarnings("UnusedDeclaration")
068        @NotNull
069        public static BindingContext analyzeFiles(@NotNull Collection<JetFile> files, @NotNull Config config) {
070            return analyzeFiles(files, Predicates.<PsiFile>alwaysTrue(), config).getBindingContext();
071        }
072    
073        //TODO: refactor
074        @NotNull
075        public static AnalyzeExhaust analyzeFiles(
076                @NotNull Collection<JetFile> files,
077                @NotNull Predicate<PsiFile> filesToAnalyzeCompletely,
078                @NotNull Config config
079        ) {
080            Project project = config.getProject();
081    
082            ModuleDescriptorImpl owner = createJsModule("<module>");
083    
084            Predicate<PsiFile> completely = Predicates.and(notLibFiles(config.getLibFiles()), filesToAnalyzeCompletely);
085    
086            GlobalContextImpl globalContext = ContextPackage.GlobalContext();
087            TopDownAnalysisParameters topDownAnalysisParameters = TopDownAnalysisParameters.create(
088                    globalContext.getStorageManager(), globalContext.getExceptionTracker(), completely, false, false);
089    
090            ModuleDescriptor libraryModule = config.getLibraryModule();
091            if (libraryModule != null) {
092                owner.addFragmentProvider(DependencyKind.BINARIES, libraryModule.getPackageFragmentProvider()); // "import" analyzed library module
093            }
094    
095            BindingContext libraryContext = config.getLibraryContext();
096            BindingTrace trace = libraryContext == null
097                                 ? new BindingTraceContext()
098                                 : new DelegatingBindingTrace(libraryContext, "trace with preanalyzed library");
099            InjectorForTopDownAnalyzerForJs injector = new InjectorForTopDownAnalyzerForJs(project, topDownAnalysisParameters, trace, owner);
100            try {
101                Collection<JetFile> allFiles = libraryModule != null ?
102                                               files :
103                                               Config.withJsLibAdded(files, config);
104                injector.getTopDownAnalyzer().analyzeFiles(topDownAnalysisParameters, allFiles);
105                return AnalyzeExhaust.success(trace.getBindingContext(), owner);
106            }
107            finally {
108                injector.destroy();
109            }
110        }
111    
112        public static void checkForErrors(@NotNull Collection<JetFile> allFiles, @NotNull BindingContext bindingContext) {
113            AnalyzingUtils.throwExceptionOnErrors(bindingContext);
114            for (JetFile file : allFiles) {
115                AnalyzingUtils.checkForSyntacticErrors(file);
116            }
117        }
118    
119        @NotNull
120        private static Predicate<PsiFile> notLibFiles(@NotNull final List<JetFile> jsLibFiles) {
121            return new Predicate<PsiFile>() {
122                @Override
123                public boolean apply(@Nullable PsiFile file) {
124                    assert file instanceof JetFile;
125                    @SuppressWarnings("UnnecessaryLocalVariable") boolean notLibFile = !jsLibFiles.contains(file);
126                    return notLibFile;
127                }
128            };
129        }
130    
131        @NotNull
132        public static ResolveSession getLazyResolveSession(Collection<JetFile> files, Config config) {
133            GlobalContextImpl globalContext = ContextPackage.GlobalContext();
134            DeclarationProviderFactory declarationProviderFactory =
135                    createDeclarationProviderFactory(config.getProject(), globalContext.getStorageManager(),
136                                                     Config.withJsLibAdded(files, config));
137            ModuleDescriptorImpl module = createJsModule("<lazy module>");
138            module.addFragmentProvider(DependencyKind.BUILT_INS, KotlinBuiltIns.getInstance().getBuiltInsModule().getPackageFragmentProvider());
139    
140            return new InjectorForLazyResolve(
141                    config.getProject(),
142                    globalContext,
143                    module,
144                    declarationProviderFactory,
145                    new BindingTraceContext()).getResolveSession();
146        }
147    
148        @NotNull
149        private static ModuleDescriptorImpl createJsModule(@NotNull String name) {
150            return new ModuleDescriptorImpl(Name.special(name), DEFAULT_IMPORTS, PlatformToKotlinClassMap.EMPTY);
151        }
152    
153    }