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.utils;
018    
019    import com.google.dart.compiler.backend.js.ast.*;
020    import org.jetbrains.annotations.NotNull;
021    import org.jetbrains.jet.lang.descriptors.FunctionDescriptor;
022    import org.jetbrains.jet.lang.descriptors.ValueParameterDescriptor;
023    import org.jetbrains.jet.lang.psi.JetDeclarationWithBody;
024    import org.jetbrains.jet.lang.psi.JetExpression;
025    import org.jetbrains.jet.lang.types.JetType;
026    import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
027    import org.jetbrains.k2js.translate.context.TranslationContext;
028    import org.jetbrains.k2js.translate.general.AbstractTranslator;
029    import org.jetbrains.k2js.translate.general.Translation;
030    import org.jetbrains.k2js.translate.utils.mutator.Mutator;
031    
032    import java.util.ArrayList;
033    import java.util.List;
034    
035    import static org.jetbrains.k2js.translate.utils.BindingUtils.getDefaultArgument;
036    import static org.jetbrains.k2js.translate.utils.JsAstUtils.assignment;
037    import static org.jetbrains.k2js.translate.utils.JsAstUtils.convertToBlock;
038    import static org.jetbrains.k2js.translate.utils.JsAstUtils.equality;
039    import static org.jetbrains.k2js.translate.utils.mutator.LastExpressionMutator.mutateLastExpression;
040    
041    public final class FunctionBodyTranslator extends AbstractTranslator {
042    
043        @NotNull
044        public static JsBlock translateFunctionBody(@NotNull FunctionDescriptor descriptor,
045                                                    @NotNull JetDeclarationWithBody declarationWithBody,
046                                                    @NotNull TranslationContext functionBodyContext) {
047            return (new FunctionBodyTranslator(descriptor, declarationWithBody, functionBodyContext)).translate();
048        }
049    
050        @NotNull
051        public static List<JsStatement> setDefaultValueForArguments(@NotNull FunctionDescriptor descriptor,
052                @NotNull TranslationContext functionBodyContext) {
053            List<JsStatement> result = new ArrayList<JsStatement>();
054            for (ValueParameterDescriptor valueParameter : descriptor.getValueParameters()) {
055                if (valueParameter.hasDefaultValue()) {
056                    JsNameRef jsNameRef = functionBodyContext.getNameForDescriptor(valueParameter).makeRef();
057                    JetExpression defaultArgument = getDefaultArgument(valueParameter);
058                    JsBlock defaultArgBlock = new JsBlock();
059                    JsExpression defaultValue = Translation.translateAsExpression(defaultArgument, functionBodyContext, defaultArgBlock);
060                    JsStatement assignStatement = assignment(jsNameRef, defaultValue).makeStmt();
061                    JsStatement thenStatement = JsAstUtils.mergeStatementInBlockIfNeeded(assignStatement, defaultArgBlock);
062                    JsBinaryOperation checkArgIsUndefined = equality(jsNameRef, functionBodyContext.namer().getUndefinedExpression());
063                    JsIf jsIf = JsAstUtils.newJsIf(checkArgIsUndefined, thenStatement);
064                    result.add(jsIf);
065                }
066            }
067            return result;
068        }
069    
070        @NotNull
071        private final FunctionDescriptor descriptor;
072        @NotNull
073        private final JetDeclarationWithBody declaration;
074    
075        private FunctionBodyTranslator(@NotNull FunctionDescriptor descriptor,
076                                       @NotNull JetDeclarationWithBody declaration,
077                                       @NotNull TranslationContext context) {
078            super(context);
079            this.descriptor = descriptor;
080            this.declaration = declaration;
081        }
082    
083        @NotNull
084        private JsBlock translate() {
085            JetExpression jetBodyExpression = declaration.getBodyExpression();
086            assert jetBodyExpression != null : "Cannot translate a body of an abstract function.";
087            JsBlock jsBlock = new JsBlock(setDefaultValueForArguments(descriptor, context()));
088            jsBlock.getStatements().addAll(mayBeWrapWithReturn(Translation.translateExpression(jetBodyExpression, context(), jsBlock)).getStatements());
089            return jsBlock;
090        }
091    
092        @NotNull
093        private JsBlock mayBeWrapWithReturn(@NotNull JsNode body) {
094            if (!mustAddReturnToGeneratedFunctionBody()) {
095                return convertToBlock(body);
096            }
097            return convertToBlock(lastExpressionReturned(body));
098        }
099    
100        private boolean mustAddReturnToGeneratedFunctionBody() {
101            JetType functionReturnType = descriptor.getReturnType();
102            assert functionReturnType != null : "Function return typed type must be resolved.";
103            return (!declaration.hasBlockBody()) && (!KotlinBuiltIns.isUnit(functionReturnType));
104        }
105    
106        @NotNull
107        private static JsNode lastExpressionReturned(@NotNull JsNode body) {
108            return mutateLastExpression(body, new Mutator() {
109                @Override
110                @NotNull
111                public JsNode mutate(@NotNull JsNode node) {
112                    if (!(node instanceof JsExpression)) {
113                        return node;
114                    }
115                    return new JsReturn((JsExpression)node);
116                }
117            });
118        }
119    }