001    /*
002     * Copyright 2010-2015 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.kotlin.js.translate.utils;
018    
019    import com.intellij.openapi.util.text.StringUtil;
020    import com.intellij.util.Function;
021    import com.intellij.util.containers.ContainerUtil;
022    import kotlin.KotlinPackage;
023    import kotlin.jvm.functions.Function1;
024    import org.jetbrains.annotations.NotNull;
025    import org.jetbrains.kotlin.backend.common.CodegenUtil;
026    import org.jetbrains.kotlin.descriptors.*;
027    import org.jetbrains.kotlin.descriptors.annotations.Annotations;
028    import org.jetbrains.kotlin.descriptors.impl.ConstructorDescriptorImpl;
029    import org.jetbrains.kotlin.name.FqNameUnsafe;
030    import org.jetbrains.kotlin.name.Name;
031    import org.jetbrains.kotlin.resolve.DescriptorUtils;
032    import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter;
033    import org.jetbrains.kotlin.resolve.scopes.JetScope;
034    
035    import java.util.*;
036    
037    import static org.jetbrains.kotlin.js.descriptorUtils.DescriptorUtilsPackage.getJetTypeFqName;
038    import static org.jetbrains.kotlin.js.descriptorUtils.DescriptorUtilsPackage.hasPrimaryConstructor;
039    import static org.jetbrains.kotlin.resolve.DescriptorUtils.getFqName;
040    
041    public class ManglingUtils {
042        private ManglingUtils() {}
043    
044        public static final Comparator<CallableDescriptor> CALLABLE_COMPARATOR = new CallableComparator();
045    
046        @NotNull
047        public static String getMangledName(@NotNull PropertyDescriptor descriptor, @NotNull String suggestedName) {
048            return getStableMangledName(suggestedName, getFqName(descriptor).asString());
049        }
050    
051        @NotNull
052        public static String getSuggestedName(@NotNull DeclarationDescriptor descriptor) {
053            String suggestedName = descriptor.getName().asString();
054    
055            if (descriptor instanceof FunctionDescriptor ||
056                descriptor instanceof PropertyDescriptor && DescriptorUtils.isExtension((PropertyDescriptor) descriptor)
057            ) {
058                suggestedName = getMangledName((CallableMemberDescriptor) descriptor);
059            }
060    
061            return suggestedName;
062        }
063    
064        @NotNull
065        private static String getMangledName(@NotNull CallableMemberDescriptor descriptor) {
066            if (needsStableMangling(descriptor)) {
067                return getStableMangledName(descriptor);
068            }
069    
070            return getSimpleMangledName(descriptor);
071        }
072    
073        //TODO extend logic for nested/inner declarations
074        private static boolean needsStableMangling(CallableMemberDescriptor descriptor) {
075            // Use stable mangling for overrides because we use stable mangling when any function inside a overridable declaration
076            // for avoid clashing names when inheritance.
077            if (DescriptorUtils.isOverride(descriptor)) {
078                return true;
079            }
080    
081            DeclarationDescriptor containingDeclaration = descriptor.getContainingDeclaration();
082    
083            if (containingDeclaration instanceof PackageFragmentDescriptor) {
084                return descriptor.getVisibility().isPublicAPI();
085            }
086            else if (containingDeclaration instanceof ClassDescriptor) {
087                ClassDescriptor classDescriptor = (ClassDescriptor) containingDeclaration;
088    
089                // Use stable mangling when it's inside an overridable declaration to avoid clashing names on inheritance.
090                if (classDescriptor.getModality().isOverridable()) {
091                    return true;
092                }
093    
094                // valueOf() is created in the library with a mangled name for every enum class
095                if (descriptor instanceof FunctionDescriptor && CodegenUtil.isEnumValueOfMethod((FunctionDescriptor) descriptor)) {
096                    return true;
097                }
098    
099                // Don't use stable mangling when it inside a non-public API declaration.
100                if (!classDescriptor.getVisibility().isPublicAPI()) {
101                    return false;
102                }
103    
104                // Ignore the `protected` visibility because it can be use outside a containing declaration
105                // only when the containing declaration is overridable.
106                if (descriptor.getVisibility() == Visibilities.PUBLIC) {
107                    return true;
108                }
109    
110                return false;
111            }
112    
113            assert containingDeclaration instanceof CallableMemberDescriptor :
114                    "containingDeclaration for descriptor have unsupported type for mangling, " +
115                    "descriptor: " + descriptor + ", containingDeclaration: " + containingDeclaration;
116    
117            return false;
118        }
119    
120        @NotNull
121        public static String getMangledMemberNameForExplicitDelegation(
122                @NotNull String suggestedName,
123                @NotNull FqNameUnsafe classFqName,
124                @NotNull FqNameUnsafe typeFqName
125        ) {
126            String forCalculateId = classFqName.asString() + ":" + typeFqName.asString();
127            return getStableMangledName(suggestedName, forCalculateId);
128        }
129    
130        @NotNull
131        private static String getStableMangledName(@NotNull String suggestedName, String forCalculateId) {
132            int absHashCode = Math.abs(forCalculateId.hashCode());
133            String suffix = absHashCode == 0 ? "" : ("_" + Integer.toString(absHashCode, Character.MAX_RADIX) + "$");
134            return suggestedName + suffix;
135        }
136    
137        @NotNull
138        private static String getStableMangledName(@NotNull CallableDescriptor descriptor) {
139            String suggestedName = getSuggestedName(descriptor);
140            return getStableMangledName(suggestedName, getArgumentTypesAsString(descriptor));
141        }
142    
143        @NotNull
144        private static String getSuggestedName(@NotNull CallableDescriptor descriptor) {
145            if (descriptor instanceof ConstructorDescriptor && !((ConstructorDescriptor) descriptor).isPrimary()) {
146                DeclarationDescriptor classDescriptor = descriptor.getContainingDeclaration();
147                assert classDescriptor != null;
148                return classDescriptor.getName().asString();
149            }
150            else {
151                return descriptor.getName().asString();
152            }
153        }
154    
155        @NotNull
156        private static String getSimpleMangledName(@NotNull CallableMemberDescriptor descriptor) {
157            DeclarationDescriptor containingDeclaration = descriptor.getContainingDeclaration();
158    
159            JetScope jetScope = null;
160    
161            String nameToCompare = descriptor.getName().asString();
162    
163            if (containingDeclaration != null && descriptor instanceof ConstructorDescriptor) {
164                nameToCompare = containingDeclaration.getName().asString();
165                containingDeclaration = containingDeclaration.getContainingDeclaration();
166            }
167    
168            if (containingDeclaration instanceof PackageFragmentDescriptor) {
169                jetScope = ((PackageFragmentDescriptor) containingDeclaration).getMemberScope();
170            }
171            else if (containingDeclaration instanceof ClassDescriptor) {
172                jetScope = ((ClassDescriptor) containingDeclaration).getDefaultType().getMemberScope();
173            }
174    
175            int counter = 0;
176    
177            if (jetScope != null) {
178                final String finalNameToCompare = nameToCompare;
179    
180                Collection<DeclarationDescriptor> declarations = jetScope.getDescriptors(DescriptorKindFilter.CALLABLES, JetScope.ALL_NAME_FILTER);
181                List<CallableDescriptor> overloadedFunctions =
182                        KotlinPackage.flatMap(declarations, new Function1<DeclarationDescriptor, Iterable<? extends CallableDescriptor>>() {
183                    @Override
184                    public Iterable<? extends CallableDescriptor> invoke(DeclarationDescriptor declarationDescriptor) {
185                        if (declarationDescriptor instanceof ClassDescriptor && finalNameToCompare.equals(declarationDescriptor.getName().asString())) {
186                            ClassDescriptor classDescriptor = (ClassDescriptor) declarationDescriptor;
187                            Collection<ConstructorDescriptor> constructors = classDescriptor.getConstructors();
188    
189                            if (!hasPrimaryConstructor(classDescriptor)) {
190                                ConstructorDescriptorImpl fakePrimaryConstructor =
191                                        ConstructorDescriptorImpl.create(classDescriptor, Annotations.EMPTY, true, SourceElement.NO_SOURCE);
192                                return KotlinPackage.plus(constructors, fakePrimaryConstructor);
193                            }
194    
195                            return constructors;
196                        }
197    
198                        if (!(declarationDescriptor instanceof CallableMemberDescriptor)) return Collections.emptyList();
199    
200                        CallableMemberDescriptor callableMemberDescriptor = (CallableMemberDescriptor) declarationDescriptor;
201    
202                        String name = AnnotationsUtils.getNameForAnnotatedObjectWithOverrides(callableMemberDescriptor);
203    
204                        // when name == null it's mean that it's not native.
205                        if (name == null) {
206                            // skip functions without arguments, because we don't use mangling for them
207                            if (needsStableMangling(callableMemberDescriptor) && !callableMemberDescriptor.getValueParameters().isEmpty()) return Collections.emptyList();
208    
209                            // TODO add prefix for property: get_$name and set_$name
210                            name = callableMemberDescriptor.getName().asString();
211                        }
212    
213                        if (finalNameToCompare.equals(name)) return Collections.singletonList(callableMemberDescriptor);
214    
215                        return Collections.emptyList();
216                    }
217                });
218    
219                if (overloadedFunctions.size() > 1) {
220                    Collections.sort(overloadedFunctions, CALLABLE_COMPARATOR);
221                    counter = ContainerUtil.indexOfIdentity(overloadedFunctions, descriptor);
222                    assert counter >= 0;
223                }
224            }
225    
226            String name = getSuggestedName(descriptor);
227            return counter == 0 ? name : name + '_' + counter;
228        }
229    
230        private static String getArgumentTypesAsString(CallableDescriptor descriptor) {
231            StringBuilder argTypes = new StringBuilder();
232    
233            ReceiverParameterDescriptor receiverParameter = descriptor.getExtensionReceiverParameter();
234            if (receiverParameter != null) {
235                argTypes.append(getJetTypeFqName(receiverParameter.getType(), true)).append(".");
236            }
237    
238            argTypes.append(StringUtil.join(descriptor.getValueParameters(), new Function<ValueParameterDescriptor, String>() {
239                @Override
240                public String fun(ValueParameterDescriptor descriptor) {
241                    return getJetTypeFqName(descriptor.getType(), true);
242                }
243            }, ","));
244    
245            return argTypes.toString();
246        }
247    
248        @NotNull
249        public static String getStableMangledNameForDescriptor(@NotNull ClassDescriptor descriptor, @NotNull String functionName) {
250            Collection<FunctionDescriptor> functions = descriptor.getDefaultType().getMemberScope().getFunctions(Name.identifier(functionName));
251            assert functions.size() == 1 : "Can't select a single function: " + functionName + " in " + descriptor;
252            return getSuggestedName((DeclarationDescriptor) functions.iterator().next());
253        }
254    
255        private static class CallableComparator implements Comparator<CallableDescriptor> {
256            @Override
257            public int compare(@NotNull CallableDescriptor a, @NotNull CallableDescriptor b) {
258                // primary constructors
259                if (a instanceof ConstructorDescriptor && ((ConstructorDescriptor) a).isPrimary()) {
260                    if (!(b instanceof ConstructorDescriptor) || !((ConstructorDescriptor) b).isPrimary()) return -1;
261                }
262                else if (b instanceof ConstructorDescriptor && ((ConstructorDescriptor) b).isPrimary()) {
263                    return 1;
264                }
265    
266                // native functions
267                if (isNativeOrOverrideNative(a)) {
268                    if (!isNativeOrOverrideNative(b)) return -1;
269                }
270                else if (isNativeOrOverrideNative(b)) {
271                    return 1;
272                }
273    
274                // be visibility
275                // Actually "internal" > "private", but we want to have less number for "internal", so compare b with a instead of a with b.
276                Integer result = Visibilities.compare(b.getVisibility(), a.getVisibility());
277                if (result != null && result != 0) return result;
278    
279                // by arity
280                int aArity = arity(a);
281                int bArity = arity(b);
282                if (aArity != bArity) return aArity - bArity;
283    
284                // by stringify argument types
285                String aArguments = getArgumentTypesAsString(a);
286                String bArguments = getArgumentTypesAsString(b);
287                assert aArguments != bArguments;
288    
289                return aArguments.compareTo(bArguments);
290            }
291    
292            private static int arity(CallableDescriptor descriptor) {
293                return descriptor.getValueParameters().size() + (descriptor.getExtensionReceiverParameter() == null ? 0 : 1);
294            }
295    
296            private static boolean isNativeOrOverrideNative(CallableDescriptor descriptor) {
297                if (!(descriptor instanceof CallableMemberDescriptor)) return false;
298    
299                if (AnnotationsUtils.isNativeObject(descriptor)) return true;
300    
301                Set<CallableMemberDescriptor> declarations = DescriptorUtils.getAllOverriddenDeclarations((CallableMemberDescriptor) descriptor);
302                for (CallableMemberDescriptor memberDescriptor : declarations) {
303                    if (AnnotationsUtils.isNativeObject(memberDescriptor)) return true;
304                }
305                return false;
306            }
307        }
308    }