001    /*
002     * Copyright 2010-2013 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.translate.general;
018    
019    import com.google.dart.compiler.backend.js.ast.*;
020    import org.jetbrains.annotations.NotNull;
021    import org.jetbrains.annotations.Nullable;
022    import org.jetbrains.jet.lang.descriptors.FunctionDescriptor;
023    import org.jetbrains.jet.lang.psi.JetDeclarationWithBody;
024    import org.jetbrains.jet.lang.psi.JetExpression;
025    import org.jetbrains.jet.lang.psi.JetFile;
026    import org.jetbrains.jet.lang.psi.JetNamedFunction;
027    import org.jetbrains.jet.lang.resolve.BindingContext;
028    import org.jetbrains.jet.plugin.MainFunctionDetector;
029    import org.jetbrains.k2js.config.Config;
030    import org.jetbrains.k2js.facade.MainCallParameters;
031    import org.jetbrains.k2js.facade.exceptions.MainFunctionNotFoundException;
032    import org.jetbrains.k2js.facade.exceptions.TranslationException;
033    import org.jetbrains.k2js.facade.exceptions.TranslationInternalException;
034    import org.jetbrains.k2js.facade.exceptions.UnsupportedFeatureException;
035    import org.jetbrains.k2js.translate.callTranslator.CallTranslator;
036    import org.jetbrains.k2js.translate.context.Namer;
037    import org.jetbrains.k2js.translate.context.StaticContext;
038    import org.jetbrains.k2js.translate.context.TranslationContext;
039    import org.jetbrains.k2js.translate.declaration.PackageDeclarationTranslator;
040    import org.jetbrains.k2js.translate.expression.ExpressionVisitor;
041    import org.jetbrains.k2js.translate.expression.FunctionTranslator;
042    import org.jetbrains.k2js.translate.expression.PatternTranslator;
043    import org.jetbrains.k2js.translate.test.JSTestGenerator;
044    import org.jetbrains.k2js.translate.test.JSTester;
045    import org.jetbrains.k2js.translate.utils.JsAstUtils;
046    import org.jetbrains.k2js.translate.utils.dangerous.DangerousData;
047    import org.jetbrains.k2js.translate.utils.dangerous.DangerousTranslator;
048    
049    import java.util.Collection;
050    import java.util.Collections;
051    import java.util.List;
052    
053    import static org.jetbrains.k2js.translate.utils.BindingUtils.getFunctionDescriptor;
054    import static org.jetbrains.k2js.translate.utils.JsAstUtils.*;
055    import static org.jetbrains.k2js.translate.utils.dangerous.DangerousData.collect;
056    
057    /**
058     * This class provides a interface which all translators use to interact with each other.
059     * Goal is to simplify interaction between translators.
060     */
061    public final class Translation {
062    
063        private Translation() {
064        }
065    
066        @NotNull
067        public static FunctionTranslator functionTranslator(@NotNull JetDeclarationWithBody function,
068                @NotNull TranslationContext context) {
069            return FunctionTranslator.newInstance(function, context);
070        }
071    
072        @NotNull
073        public static PatternTranslator patternTranslator(@NotNull TranslationContext context) {
074            return PatternTranslator.newInstance(context);
075        }
076    
077        @NotNull
078        public static JsNode translateExpression(@NotNull JetExpression expression, @NotNull TranslationContext context) {
079            JsExpression aliasForExpression = context.aliasingContext().getAliasForExpression(expression);
080            if (aliasForExpression != null) {
081                return aliasForExpression;
082            }
083            DangerousData data = collect(expression, context);
084            if (data.shouldBeTranslated()) {
085                return DangerousTranslator.translate(data, context);
086            }
087            return doTranslateExpression(expression, context);
088        }
089    
090        //NOTE: use with care
091        @NotNull
092        public static JsNode doTranslateExpression(JetExpression expression, TranslationContext context) {
093            return expression.accept(new ExpressionVisitor(), context);
094        }
095    
096        @NotNull
097        public static JsExpression translateAsExpression(@NotNull JetExpression expression,
098                @NotNull TranslationContext context) {
099            return convertToExpression(translateExpression(expression, context));
100        }
101    
102        @NotNull
103        public static JsStatement translateAsStatement(@NotNull JetExpression expression,
104                @NotNull TranslationContext context) {
105            return convertToStatement(translateExpression(expression, context));
106        }
107    
108        @NotNull
109        public static JsProgram generateAst(@NotNull BindingContext bindingContext,
110                @NotNull Collection<JetFile> files, @NotNull MainCallParameters mainCallParameters,
111                @NotNull Config config)
112                throws TranslationException {
113            try {
114                return doGenerateAst(bindingContext, files, mainCallParameters, config);
115            }
116            catch (UnsupportedOperationException e) {
117                throw new UnsupportedFeatureException("Unsupported feature used.", e);
118            }
119            catch (Throwable e) {
120                throw new TranslationInternalException(e);
121            }
122        }
123    
124        @NotNull
125        private static JsProgram doGenerateAst(@NotNull BindingContext bindingContext, @NotNull Collection<JetFile> files,
126                @NotNull MainCallParameters mainCallParameters,
127                @NotNull Config config) throws MainFunctionNotFoundException {
128            StaticContext staticContext = StaticContext.generateStaticContext(bindingContext, config.getTarget());
129            JsProgram program = staticContext.getProgram();
130            JsBlock block = program.getGlobalBlock();
131    
132            JsFunction rootFunction = JsAstUtils.createPackage(block.getStatements(), program.getScope());
133            JsBlock rootBlock = rootFunction.getBody();
134            List<JsStatement> statements = rootBlock.getStatements();
135            statements.add(program.getStringLiteral("use strict").makeStmt());
136    
137            TranslationContext context = TranslationContext.rootContext(staticContext, rootFunction);
138            statements.addAll(PackageDeclarationTranslator.translateFiles(files, context));
139            defineModule(context, statements, config.getModuleId());
140    
141            if (mainCallParameters.shouldBeGenerated()) {
142                JsStatement statement = generateCallToMain(context, files, mainCallParameters.arguments());
143                if (statement != null) {
144                    statements.add(statement);
145                }
146            }
147            mayBeGenerateTests(files, config, rootBlock, context);
148            return context.program();
149        }
150    
151        private static void defineModule(@NotNull TranslationContext context, @NotNull List<JsStatement> statements, @NotNull String moduleId) {
152            JsName rootPackageName = context.scope().findName(Namer.getRootPackageName());
153            if (rootPackageName != null) {
154                statements.add(new JsInvocation(context.namer().kotlin("defineModule"), context.program().getStringLiteral(moduleId),
155                                                rootPackageName.makeRef()).makeStmt());
156            }
157        }
158    
159        private static void mayBeGenerateTests(@NotNull Collection<JetFile> files, @NotNull Config config,
160                @NotNull JsBlock rootBlock, @NotNull TranslationContext context) {
161            JSTester tester = config.getTester();
162            if (tester != null) {
163                tester.initialize(context, rootBlock);
164                JSTestGenerator.generateTestCalls(context, files, tester);
165                tester.deinitialize();
166            }
167        }
168    
169        //TODO: determine whether should throw exception
170        @Nullable
171        private static JsStatement generateCallToMain(@NotNull TranslationContext context, @NotNull Collection<JetFile> files,
172                @NotNull List<String> arguments) throws MainFunctionNotFoundException {
173            MainFunctionDetector mainFunctionDetector = new MainFunctionDetector(context.bindingContext());
174            JetNamedFunction mainFunction = mainFunctionDetector.getMainFunction(files);
175            if (mainFunction == null) {
176                return null;
177            }
178            FunctionDescriptor functionDescriptor = getFunctionDescriptor(context.bindingContext(), mainFunction);
179            JsArrayLiteral argument = new JsArrayLiteral(toStringLiteralList(arguments, context.program()));
180            return CallTranslator.instance$.buildCall(context, functionDescriptor, Collections.singletonList(argument), null).makeStmt();
181        }
182    }