1 /* 2 * Copyright 2016 Google Inc. All Rights Reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.turbine.binder.lookup; 18 19 import static com.google.common.base.Preconditions.checkNotNull; 20 21 import javax.annotation.Nullable; 22 23 /** A {@link Scope} that chains other scopes together. */ 24 public class CompoundScope implements Scope { 25 26 private final Scope scope; 27 @Nullable private final Scope base; 28 CompoundScope(Scope scope, Scope base)29 private CompoundScope(Scope scope, Scope base) { 30 this.scope = checkNotNull(scope); 31 this.base = base; 32 } 33 34 @Override lookup(LookupKey key)35 public LookupResult lookup(LookupKey key) { 36 LookupResult result = scope.lookup(key); 37 if (result != null) { 38 return result; 39 } 40 if (base != null) { 41 return base.lookup(key); 42 } 43 return null; 44 } 45 46 /** Adds a scope to the chain. */ append(Scope scope)47 public CompoundScope append(Scope scope) { 48 return new CompoundScope(scope, this); 49 } 50 51 /** A chainable compound scope with a single entry. */ base(Scope scope)52 public static CompoundScope base(Scope scope) { 53 return new CompoundScope(scope, null); 54 } 55 } 56