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.context.generator; 018 019import com.google.common.collect.Lists; 020import com.google.common.collect.Maps; 021import org.jetbrains.annotations.NotNull; 022import org.jetbrains.annotations.Nullable; 023import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; 024 025import java.util.List; 026import java.util.Map; 027 028public class Generator<V> { 029 030 031 @NotNull 032 private final Map<DeclarationDescriptor, V> values = Maps.newHashMap(); 033 @NotNull 034 private final List<Rule<V>> rules = Lists.newArrayList(); 035 036 public void addRule(@NotNull Rule<V> rule) { 037 rules.add(rule); 038 } 039 040 @Nullable 041 public V get(@NotNull DeclarationDescriptor descriptor) { 042 V result = values.get(descriptor); 043 if (result != null) { 044 return result; 045 } 046 result = generate(descriptor); 047 values.put(descriptor, result); 048 return result; 049 } 050 051 @Nullable 052 private V generate(@NotNull DeclarationDescriptor descriptor) { 053 V result = null; 054 for (Rule<V> rule : rules) { 055 result = rule.apply(descriptor); 056 if (result != null) { 057 return result; 058 } 059 } 060 return result; 061 } 062}