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 017package org.jetbrains.k2js.translate.intrinsic.functions.factories; 018 019import com.google.common.base.Predicate; 020import com.google.common.base.Predicates; 021import com.google.common.collect.Maps; 022import org.jetbrains.annotations.NotNull; 023import org.jetbrains.annotations.Nullable; 024import org.jetbrains.jet.lang.descriptors.FunctionDescriptor; 025import org.jetbrains.k2js.translate.intrinsic.functions.basic.FunctionIntrinsic; 026import org.jetbrains.k2js.translate.intrinsic.functions.patterns.DescriptorPredicate; 027 028import java.util.Collection; 029import java.util.Map; 030 031public abstract class CompositeFIF implements FunctionIntrinsicFactory { 032 033 @NotNull final Map<DescriptorPredicate, FunctionIntrinsic> patternToIntrinsic = Maps.newHashMap(); 034 035 protected CompositeFIF() { 036 } 037 038 @NotNull 039 @Override 040 public Predicate<FunctionDescriptor> getPredicate() { 041 Collection<DescriptorPredicate> patterns = patternToIntrinsic.keySet(); 042 final DescriptorPredicate[] patterns1 = patterns.toArray(new DescriptorPredicate[patterns.size()]); 043 return new DescriptorPredicate() { 044 @Override 045 public boolean apply(@Nullable FunctionDescriptor descriptor) { 046 return Predicates.or(patterns1).apply(descriptor); 047 } 048 }; 049 } 050 051 @NotNull 052 @Override 053 public FunctionIntrinsic getIntrinsic(@NotNull FunctionDescriptor descriptor) { 054 for (DescriptorPredicate pattern : patternToIntrinsic.keySet()) { 055 if (pattern.apply(descriptor)) { 056 return patternToIntrinsic.get(pattern); 057 } 058 } 059 throw new IllegalStateException("Must have intrinsic for pattern."); 060 } 061 062 protected void add(@NotNull DescriptorPredicate pattern, @NotNull FunctionIntrinsic intrinsic) { 063 patternToIntrinsic.put(pattern, intrinsic); 064 } 065}