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.declaration;
018    
019    import com.google.dart.compiler.backend.js.ast.*;
020    import com.intellij.util.SmartList;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.jet.lang.descriptors.ClassDescriptor;
023    import org.jetbrains.jet.lang.descriptors.ClassKind;
024    import org.jetbrains.jet.lang.descriptors.PropertyDescriptor;
025    import org.jetbrains.jet.lang.descriptors.ReceiverParameterDescriptor;
026    import org.jetbrains.jet.lang.psi.JetClassOrObject;
027    import org.jetbrains.jet.lang.psi.JetObjectDeclaration;
028    import org.jetbrains.jet.lang.psi.JetParameter;
029    import org.jetbrains.jet.lang.types.JetType;
030    import org.jetbrains.jet.lang.types.TypeConstructor;
031    import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
032    import org.jetbrains.k2js.translate.context.DefinitionPlace;
033    import org.jetbrains.k2js.translate.context.Namer;
034    import org.jetbrains.k2js.translate.context.TranslationContext;
035    import org.jetbrains.k2js.translate.declaration.propertyTranslator.PropertyTranslatorPackage;
036    import org.jetbrains.k2js.translate.expression.ExpressionPackage;
037    import org.jetbrains.k2js.translate.general.AbstractTranslator;
038    import org.jetbrains.k2js.translate.initializer.ClassInitializerTranslator;
039    import org.jetbrains.k2js.translate.utils.JsAstUtils;
040    
041    import java.util.*;
042    
043    import static org.jetbrains.jet.lang.resolve.DescriptorUtils.*;
044    import static org.jetbrains.jet.lang.types.TypeUtils.topologicallySortSuperclassesAndRecordAllInstances;
045    import static org.jetbrains.k2js.translate.reference.ReferenceTranslator.translateAsFQReference;
046    import static org.jetbrains.k2js.translate.utils.BindingUtils.getClassDescriptor;
047    import static org.jetbrains.k2js.translate.utils.BindingUtils.getPropertyDescriptorForConstructorParameter;
048    import static org.jetbrains.k2js.translate.utils.JsDescriptorUtils.*;
049    import static org.jetbrains.k2js.translate.utils.PsiUtils.getPrimaryConstructorParameters;
050    import static org.jetbrains.k2js.translate.utils.TranslationUtils.simpleReturnFunction;
051    
052    /**
053     * Generates a definition of a single class.
054     */
055    public final class ClassTranslator extends AbstractTranslator {
056        @NotNull
057        private final JetClassOrObject classDeclaration;
058    
059        @NotNull
060        private final ClassDescriptor descriptor;
061    
062        @NotNull
063        public static JsInvocation generateClassCreation(@NotNull JetClassOrObject classDeclaration, @NotNull TranslationContext context) {
064            return new ClassTranslator(classDeclaration, context).translate();
065        }
066    
067        @NotNull
068        public static JsExpression generateObjectLiteral(@NotNull JetObjectDeclaration objectDeclaration, @NotNull TranslationContext context) {
069            return new ClassTranslator(objectDeclaration, context).translateObjectLiteralExpression();
070        }
071    
072        private ClassTranslator(@NotNull JetClassOrObject classDeclaration, @NotNull TranslationContext context) {
073            super(context);
074            this.classDeclaration = classDeclaration;
075            this.descriptor = getClassDescriptor(context.bindingContext(), classDeclaration);
076        }
077    
078        @NotNull
079        private JsExpression translateObjectLiteralExpression() {
080            ClassDescriptor containingClass = getContainingClass(descriptor);
081            if (containingClass == null) {
082                return translate(context());
083            }
084    
085            return translateObjectInsideClass(context());
086        }
087    
088        @NotNull
089        public JsInvocation translate() {
090            return translate(context());
091        }
092    
093        @NotNull
094        public JsInvocation translate(@NotNull TranslationContext declarationContext) {
095            return new JsInvocation(context().namer().classCreateInvocation(descriptor), getClassCreateInvocationArguments(declarationContext));
096        }
097    
098        private boolean isTrait() {
099            return descriptor.getKind().equals(ClassKind.TRAIT);
100        }
101    
102        @NotNull
103        private List<JsExpression> getClassCreateInvocationArguments(@NotNull TranslationContext declarationContext) {
104            List<JsExpression> invocationArguments = new ArrayList<JsExpression>();
105    
106            List<JsPropertyInitializer> properties = new SmartList<JsPropertyInitializer>();
107            List<JsPropertyInitializer> staticProperties = new SmartList<JsPropertyInitializer>();
108    
109            boolean isTopLevelDeclaration = context() == declarationContext;
110    
111            JsNameRef qualifiedReference = null;
112            if (isTopLevelDeclaration) {
113                DefinitionPlace definitionPlace = null;
114    
115                if (!descriptor.getKind().isSingleton() && !isAnonymousObject(descriptor)) {
116                    qualifiedReference = declarationContext.getQualifiedReference(descriptor);
117                    JsScope scope = context().getScopeForDescriptor(descriptor);
118                    definitionPlace = new DefinitionPlace((JsObjectScope) scope, qualifiedReference, staticProperties);
119                }
120    
121                declarationContext = declarationContext.newDeclaration(descriptor, definitionPlace);
122            }
123    
124            declarationContext = fixContextForClassObjectAccessing(declarationContext);
125    
126            invocationArguments.add(getSuperclassReferences(declarationContext));
127            DelegationTranslator delegationTranslator = new DelegationTranslator(classDeclaration, context());
128            if (!isTrait()) {
129                JsFunction initializer = new ClassInitializerTranslator(classDeclaration, declarationContext).generateInitializeMethod(delegationTranslator);
130                invocationArguments.add(initializer.getBody().getStatements().isEmpty() ? JsLiteral.NULL : initializer);
131            }
132    
133            translatePropertiesAsConstructorParameters(declarationContext, properties);
134            DeclarationBodyVisitor bodyVisitor = new DeclarationBodyVisitor(properties, staticProperties);
135            bodyVisitor.traverseContainer(classDeclaration, declarationContext);
136            delegationTranslator.generateDelegated(properties);
137    
138            if (KotlinBuiltIns.getInstance().isData(descriptor)) {
139                new JsDataClassGenerator(classDeclaration, declarationContext, properties).generate();
140            }
141    
142            if (isEnumClass(descriptor)) {
143                JsObjectLiteral enumEntries = new JsObjectLiteral(bodyVisitor.getEnumEntryList(), true);
144                JsFunction function = simpleReturnFunction(declarationContext.getScopeForDescriptor(descriptor), enumEntries);
145                invocationArguments.add(function);
146            }
147    
148            boolean hasStaticProperties = !staticProperties.isEmpty();
149            if (!properties.isEmpty() || hasStaticProperties) {
150                if (properties.isEmpty()) {
151                    invocationArguments.add(JsLiteral.NULL);
152                }
153                else {
154                    if (qualifiedReference != null) {
155                        // about "prototype" - see http://code.google.com/p/jsdoc-toolkit/wiki/TagLends
156                        invocationArguments.add(new JsDocComment(JsAstUtils.LENDS_JS_DOC_TAG, new JsNameRef("prototype", qualifiedReference)));
157                    }
158                    invocationArguments.add(new JsObjectLiteral(properties, true));
159                }
160            }
161            if (hasStaticProperties) {
162                invocationArguments.add(new JsDocComment(JsAstUtils.LENDS_JS_DOC_TAG, qualifiedReference));
163                invocationArguments.add(new JsObjectLiteral(staticProperties, true));
164            }
165    
166            return invocationArguments;
167        }
168    
169        private TranslationContext fixContextForClassObjectAccessing(TranslationContext declarationContext) {
170            // In Kotlin we can access to class object members without qualifier just by name, but we should translate it to access with FQ name.
171            // So create alias for class object receiver parameter.
172            ClassDescriptor classObjectDescriptor = descriptor.getClassObjectDescriptor();
173            if (classObjectDescriptor != null) {
174                JsExpression referenceToClass = translateAsFQReference(classObjectDescriptor.getContainingDeclaration(), declarationContext);
175                JsExpression classObjectAccessor = Namer.getClassObjectAccessor(referenceToClass);
176                ReceiverParameterDescriptor classObjectReceiver = getReceiverParameterForDeclaration(classObjectDescriptor);
177                declarationContext.aliasingContext().registerAlias(classObjectReceiver, classObjectAccessor);
178            }
179    
180            // Overlap alias of class object receiver for accessing from containing class(see previous if block),
181            // because inside class object we should use simple name for access.
182            if (descriptor.getKind() == ClassKind.CLASS_OBJECT) {
183                declarationContext = declarationContext.innerContextWithAliased(descriptor.getThisAsReceiverParameter(), JsLiteral.THIS);
184            }
185    
186            return declarationContext;
187        }
188    
189        private JsExpression getSuperclassReferences(@NotNull TranslationContext declarationContext) {
190            List<JsExpression> superClassReferences = getSupertypesNameReferences();
191            if (superClassReferences.isEmpty()) {
192                return JsLiteral.NULL;
193            } else {
194                return simpleReturnFunction(declarationContext.scope(), new JsArrayLiteral(superClassReferences));
195            }
196        }
197    
198        @NotNull
199        private List<JsExpression> getSupertypesNameReferences() {
200            List<JetType> supertypes = getSupertypesWithoutFakes(descriptor);
201            if (supertypes.isEmpty()) {
202                return Collections.emptyList();
203            }
204            if (supertypes.size() == 1) {
205                JetType type = supertypes.get(0);
206                ClassDescriptor supertypeDescriptor = getClassDescriptorForType(type);
207                return Collections.<JsExpression>singletonList(getClassReference(supertypeDescriptor));
208            }
209    
210            Set<TypeConstructor> supertypeConstructors = new HashSet<TypeConstructor>();
211            for (JetType type : supertypes) {
212                supertypeConstructors.add(type.getConstructor());
213            }
214            List<TypeConstructor> sortedAllSuperTypes = topologicallySortSuperclassesAndRecordAllInstances(descriptor.getDefaultType(),
215                                                                                                           new HashMap<TypeConstructor, Set<JetType>>(),
216                                                                                                           new HashSet<TypeConstructor>());
217            List<JsExpression> supertypesRefs = new ArrayList<JsExpression>();
218            for (TypeConstructor typeConstructor : sortedAllSuperTypes) {
219                if (supertypeConstructors.contains(typeConstructor)) {
220                    ClassDescriptor supertypeDescriptor = getClassDescriptorForTypeConstructor(typeConstructor);
221                    supertypesRefs.add(getClassReference(supertypeDescriptor));
222                }
223            }
224            return supertypesRefs;
225        }
226    
227        @NotNull
228        private JsNameRef getClassReference(@NotNull ClassDescriptor superClassDescriptor) {
229            return context().getQualifiedReference(superClassDescriptor);
230        }
231    
232        private void translatePropertiesAsConstructorParameters(@NotNull TranslationContext classDeclarationContext,
233                @NotNull List<JsPropertyInitializer> result) {
234            for (JetParameter parameter : getPrimaryConstructorParameters(classDeclaration)) {
235                PropertyDescriptor descriptor = getPropertyDescriptorForConstructorParameter(bindingContext(), parameter);
236                if (descriptor != null) {
237                    PropertyTranslatorPackage.translateAccessors(descriptor, result, classDeclarationContext);
238                }
239            }
240        }
241    
242        @NotNull
243        private JsExpression translateObjectInsideClass(@NotNull TranslationContext outerClassContext) {
244            JsFunction fun = new JsFunction(outerClassContext.scope(), new JsBlock(), "initializer for " + descriptor.getName().asString());
245            TranslationContext funContext = outerClassContext.newFunctionBodyWithUsageTracker(fun, descriptor);
246    
247            fun.getBody().getStatements().add(new JsReturn(translate(funContext)));
248    
249            return ExpressionPackage.withCapturedParameters(fun, funContext, outerClassContext, descriptor);
250        }
251    }