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.intrinsic.functions.factories;
018
019 import com.google.common.base.Predicate;
020 import com.google.common.collect.Lists;
021 import com.google.dart.compiler.backend.js.ast.JsExpression;
022 import com.google.dart.compiler.backend.js.ast.JsNameRef;
023 import com.intellij.openapi.util.Pair;
024 import org.jetbrains.annotations.NotNull;
025 import org.jetbrains.annotations.Nullable;
026 import org.jetbrains.jet.lang.descriptors.FunctionDescriptor;
027 import org.jetbrains.k2js.translate.context.TranslationContext;
028 import org.jetbrains.k2js.translate.intrinsic.functions.basic.BuiltInPropertyIntrinsic;
029 import org.jetbrains.k2js.translate.intrinsic.functions.basic.FunctionIntrinsic;
030 import org.jetbrains.k2js.translate.utils.JsAstUtils;
031
032 import java.util.List;
033
034 public abstract class CompositeFIF implements FunctionIntrinsicFactory {
035 @NotNull
036 public static final FunctionIntrinsic LENGTH_PROPERTY_INTRINSIC = new BuiltInPropertyIntrinsic("length");
037 public static final FunctionIntrinsic IS_EMPTY_INTRINSIC = new FunctionIntrinsic() {
038 @NotNull
039 @Override
040 public JsExpression apply(
041 @Nullable JsExpression receiver, @NotNull List<JsExpression> arguments, @NotNull TranslationContext context
042 ) {
043 assert receiver != null;
044 return JsAstUtils.equality(new JsNameRef("length", receiver), context.program().getNumberLiteral(0));
045 }
046 };
047
048 @NotNull
049 private final List<Pair<Predicate<FunctionDescriptor>, FunctionIntrinsic>> patternsAndIntrinsics = Lists.newArrayList();
050
051 protected CompositeFIF() {
052 }
053
054 @Nullable
055 @Override
056 public FunctionIntrinsic getIntrinsic(@NotNull FunctionDescriptor descriptor) {
057 for (Pair<Predicate<FunctionDescriptor>, FunctionIntrinsic> entry : patternsAndIntrinsics) {
058 if (entry.first.apply(descriptor)) {
059 return entry.second;
060 }
061 }
062 return null;
063 }
064
065 protected void add(@NotNull Predicate<FunctionDescriptor> pattern, @NotNull FunctionIntrinsic intrinsic) {
066 patternsAndIntrinsics.add(Pair.create(pattern, intrinsic));
067 }
068 }