blob: d03bacf11cacf116c415478857cf26645907a623 [file] [log] [blame]
limpbizkit3d58d6b2008-03-08 16:11:47 +00001/**
2 * Copyright (C) 2008 Google Inc.
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
17package com.google.inject;
18
19import com.google.inject.commands.BindCommand;
20import com.google.inject.commands.BindConstantCommand;
21import com.google.inject.commands.BindScoping;
22import com.google.inject.commands.BindTarget;
limpbizkit3b1cd582008-04-28 00:06:01 +000023import com.google.inject.internal.*;
limpbizkit3d58d6b2008-03-08 16:11:47 +000024
25import java.lang.annotation.Annotation;
26import java.lang.reflect.Type;
27import java.util.*;
limpbizkit3d58d6b2008-03-08 16:11:47 +000028
29/**
30 * Handles {@link Binder#bind} and {@link Binder#bindConstant} commands.
31 *
32 * @author crazybob@google.com (Bob Lee)
33 * @author jessewilson@google.com (Jesse Wilson)
34 */
35class BindCommandProcessor extends CommandProcessor {
36
37 private final InjectorImpl injector;
38 private final Map<Class<? extends Annotation>, Scope> scopes;
39 private final List<CreationListener> creationListeners
40 = new ArrayList<CreationListener>();
limpbizkit51515b52008-03-11 03:46:25 +000041 private final List<ContextualCallable<Void>> eagerSingletonCreators
limpbizkit3d58d6b2008-03-08 16:11:47 +000042 = new ArrayList<ContextualCallable<Void>>();
43 private final Stage stage;
44 private final Map<Key<?>, BindingImpl<?>> bindings;
limpbizkit51515b52008-03-11 03:46:25 +000045 private final Map<Object, Void> outstandingInjections;
limpbizkitf44e9cc2008-03-26 06:33:29 +000046 private final List<Runnable> untargettedBindings = new ArrayList<Runnable>();
limpbizkit3d58d6b2008-03-08 16:11:47 +000047
48 BindCommandProcessor(InjectorImpl injector,
49 Map<Class<? extends Annotation>, Scope> scopes,
50 Stage stage,
limpbizkit51515b52008-03-11 03:46:25 +000051 Map<Key<?>, BindingImpl<?>> bindings,
52 Map<Object, Void> outstandingInjections) {
limpbizkit3d58d6b2008-03-08 16:11:47 +000053 this.injector = injector;
54 this.scopes = scopes;
55 this.stage = stage;
56 this.bindings = bindings;
limpbizkit51515b52008-03-11 03:46:25 +000057 this.outstandingInjections = outstandingInjections;
limpbizkit3d58d6b2008-03-08 16:11:47 +000058 }
59
60 @Override public <T> Boolean visitBind(BindCommand<T> command) {
61 final Object source = command.getSource();
62
63 final Key<T> key = command.getKey();
64 Class<? super T> rawType = key.getTypeLiteral().getRawType();
65
66 if (rawType == Provider.class) {
67 addError(source, ErrorMessages.BINDING_TO_PROVIDER);
68 return true;
69 }
70
limpbizkit3d58d6b2008-03-08 16:11:47 +000071 validateKey(command.getSource(), command.getKey());
72
73 // TODO(jessewilson): Scope annotation on type, like @Singleton
74 final boolean shouldPreload = command.getScoping().isEagerSingleton();
75 final Scope scope = command.getScoping().acceptVisitor(new BindScoping.Visitor<Scope>() {
76 public Scope visitEagerSingleton() {
77 return Scopes.SINGLETON;
78 }
79
80 public Scope visitScope(Scope scope) {
81 return scope;
82 }
83
84 public Scope visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
85 Scope scope = scopes.get(scopeAnnotation);
86 if (scope != null) {
87 return scope;
88 } else {
89 addError(source, ErrorMessages.SCOPE_NOT_FOUND,
90 "@" + scopeAnnotation.getSimpleName());
91 return Scopes.NO_SCOPE;
92 }
93 }
94
95 public Scope visitNoScoping() {
96 return null;
97 }
98 });
99
100 command.getTarget().acceptVisitor(new BindTarget.Visitor<T, Void>() {
101 public Void visitToInstance(T instance) {
limpbizkit51515b52008-03-11 03:46:25 +0000102 ConstantFactory<? extends T> factory = new ConstantFactory<T>(instance);
103 outstandingInjections.put(instance, null);
limpbizkit3d58d6b2008-03-08 16:11:47 +0000104 InternalFactory<? extends T> scopedFactory
105 = Scopes.scope(key, injector, factory, scope);
106 createBinding(source, shouldPreload, new InstanceBindingImpl<T>(
107 injector, key, source, scopedFactory, instance));
108 return null;
109 }
110
111 public Void visitToProvider(Provider<? extends T> provider) {
limpbizkit51515b52008-03-11 03:46:25 +0000112 InternalFactoryToProviderAdapter<? extends T> factory
limpbizkit3d58d6b2008-03-08 16:11:47 +0000113 = new InternalFactoryToProviderAdapter<T>(provider, source);
limpbizkit51515b52008-03-11 03:46:25 +0000114 outstandingInjections.put(provider, null);
limpbizkit3d58d6b2008-03-08 16:11:47 +0000115 InternalFactory<? extends T> scopedFactory
116 = Scopes.scope(key, injector, factory, scope);
117 createBinding(source, shouldPreload, new ProviderInstanceBindingImpl<T>(
118 injector, key, source, scopedFactory, scope, provider));
119 return null;
120 }
121
122 public Void visitToProviderKey(Key<? extends Provider<? extends T>> providerKey) {
123 final BoundProviderFactory<T> boundProviderFactory =
124 new BoundProviderFactory<T>(providerKey, source);
125 creationListeners.add(boundProviderFactory);
126 InternalFactory<? extends T> scopedFactory = Scopes.scope(
127 key, injector, (InternalFactory<? extends T>) boundProviderFactory, scope);
128 createBinding(source, shouldPreload, new LinkedProviderBindingImpl<T>(
129 injector, key, source, scopedFactory, scope, providerKey));
130 return null;
131 }
132
133 public Void visitToKey(Key<? extends T> targetKey) {
134 if (key.equals(targetKey)) {
135 addError(source, ErrorMessages.RECURSIVE_BINDING);
136 }
137
138 FactoryProxy<T> factory = new FactoryProxy<T>(key, targetKey, source);
139 creationListeners.add(factory);
140 InternalFactory<? extends T> scopedFactory
141 = Scopes.scope(key, injector, factory, scope);
142 createBinding(source, shouldPreload, new LinkedBindingImpl<T>(
143 injector, key, source, scopedFactory, scope, targetKey));
144 return null;
145 }
146
147 public Void visitUntargetted() {
limpbizkitf44e9cc2008-03-26 06:33:29 +0000148 final Type type = key.getTypeLiteral().getType();
limpbizkit3d58d6b2008-03-08 16:11:47 +0000149
150 // Error: Missing implementation.
151 // Example: bind(Date.class).annotatedWith(Red.class);
152 // We can't assume abstract types aren't injectable. They may have an
153 // @ImplementedBy annotation or something.
154 if (key.hasAnnotationType() || !(type instanceof Class<?>)) {
155 addError(source, ErrorMessages.MISSING_IMPLEMENTATION);
156 createBinding(source, shouldPreload, invalidBinding(injector, key, source));
157 return null;
158 }
159
limpbizkitf44e9cc2008-03-26 06:33:29 +0000160 untargettedBindings.add(new Runnable() {
161 public void run() {
162 // This cast is safe after the preceeding check.
163 @SuppressWarnings("unchecked")
164 Class<T> clazz = (Class<T>) type;
limpbizkit3d58d6b2008-03-08 16:11:47 +0000165
limpbizkit3b1cd582008-04-28 00:06:01 +0000166 try {
167 BindingImpl<T> binding = injector.createBindingFromType(clazz, scope, source);
168 createBinding(source, shouldPreload, binding);
169 } catch (ResolveFailedException e) {
170 injector.errorHandler.handle(source, e.getMessage());
limpbizkitf44e9cc2008-03-26 06:33:29 +0000171 createBinding(source, shouldPreload, invalidBinding(injector, key, source));
limpbizkitf44e9cc2008-03-26 06:33:29 +0000172 }
limpbizkitf44e9cc2008-03-26 06:33:29 +0000173 }
174 });
175
limpbizkit3d58d6b2008-03-08 16:11:47 +0000176 return null;
177 }
178 });
179
180 return true;
181 }
182
183 private <T> void validateKey(Object source, Key<T> key) {
184 if (key.hasAnnotationType()) {
185 Class<? extends Annotation> annotationType = key.getAnnotationType();
186
187 if (!Annotations.isRetainedAtRuntime(annotationType)) {
188 addError(StackTraceElements.forType(annotationType),
189 ErrorMessages.MISSING_RUNTIME_RETENTION, source);
190 }
191
192 if (!Key.isBindingAnnotation(annotationType)) {
193 addError(StackTraceElements.forType(annotationType),
194 ErrorMessages.MISSING_BINDING_ANNOTATION, source);
195 }
196 }
197 }
198
199 <T> InvalidBindingImpl<T> invalidBinding(InjectorImpl injector, Key<T> key, Object source) {
200 return new InvalidBindingImpl<T>(injector, key, source);
201 }
202
limpbizkit3d58d6b2008-03-08 16:11:47 +0000203 @Override public Boolean visitBindConstant(BindConstantCommand command) {
204 Object value = command.getTarget().get();
205 if (value == null) {
206 addError(command.getSource(), ErrorMessages.MISSING_CONSTANT_VALUE);
207 }
208
209 validateKey(command.getSource(), command.getKey());
210 ConstantFactory<Object> factory = new ConstantFactory<Object>(value);
limpbizkitf44e9cc2008-03-26 06:33:29 +0000211 putBinding(new ConstantBindingImpl<Object>(
limpbizkit3d58d6b2008-03-08 16:11:47 +0000212 injector, command.getKey(), command.getSource(), factory, value));
213
214 return true;
215 }
216
217 private <T> void createBinding(Object source, boolean shouldPreload,
218 BindingImpl<T> binding) {
219 putBinding(binding);
220
221 // Register to preload if necessary.
222 if (binding.getScope() == Scopes.SINGLETON) {
223 if (stage == Stage.PRODUCTION || shouldPreload) {
limpbizkit51515b52008-03-11 03:46:25 +0000224 eagerSingletonCreators.add(new EagerSingletonCreator(binding.key, binding.internalFactory));
limpbizkit3d58d6b2008-03-08 16:11:47 +0000225 }
226 } else {
227 if (shouldPreload) {
228 addError(source, ErrorMessages.PRELOAD_NOT_ALLOWED);
229 }
230 }
231 }
232
limpbizkitf44e9cc2008-03-26 06:33:29 +0000233 public void createUntargettedBindings() {
234 for (Runnable untargettedBinding : untargettedBindings) {
235 untargettedBinding.run();
236 }
237 }
238
limpbizkit51515b52008-03-11 03:46:25 +0000239 public void createEagerSingletons(InjectorImpl injector) {
240 for (ContextualCallable<Void> preloader : eagerSingletonCreators) {
241 injector.callInContext(preloader);
242 }
limpbizkit3d58d6b2008-03-08 16:11:47 +0000243 }
244
245 public void runCreationListeners(InjectorImpl injector) {
246 for (CreationListener creationListener : creationListeners) {
247 creationListener.notify(injector);
248 }
249 }
250
limpbizkit51515b52008-03-11 03:46:25 +0000251 private static class EagerSingletonCreator implements ContextualCallable<Void> {
limpbizkit3d58d6b2008-03-08 16:11:47 +0000252 private final Key<?> key;
253 private final InternalFactory<?> factory;
254
limpbizkit51515b52008-03-11 03:46:25 +0000255 public EagerSingletonCreator(Key<?> key, InternalFactory<?> factory) {
limpbizkit3d58d6b2008-03-08 16:11:47 +0000256 this.key = key;
257 this.factory = Objects.nonNull(factory, "factory");
258 }
259
260 public Void call(InternalContext context) {
261 InjectionPoint<?> injectionPoint
limpbizkit8b237452008-04-22 06:47:36 +0000262 = InjectionPoint.newInstance(key, context.getInjector());
limpbizkit3d58d6b2008-03-08 16:11:47 +0000263 context.setInjectionPoint(injectionPoint);
264 try {
265 factory.get(context, injectionPoint);
266 return null;
267 } catch(ProvisionException provisionException) {
268 provisionException.addContext(injectionPoint);
269 throw provisionException;
270 } finally {
271 context.setInjectionPoint(null);
272 }
273 }
274 }
275
276 private void putBinding(BindingImpl<?> binding) {
277 Key<?> key = binding.getKey();
278 Binding<?> original = bindings.get(key);
279
280 Class<?> rawType = key.getRawType();
281 if (FORBIDDEN_TYPES.contains(rawType)) {
282 addError(binding.getSource(), ErrorMessages.CANNOT_BIND_TO_GUICE_TYPE,
283 rawType.getSimpleName());
284 return;
285 }
286
287 if (bindings.containsKey(key)) {
288 addError(binding.getSource(), ErrorMessages.BINDING_ALREADY_SET, key,
289 original.getSource());
290 } else {
291 bindings.put(key, binding);
292 }
293 }
294
295 private static Set<Class<?>> FORBIDDEN_TYPES = forbiddenTypes();
296
297 @SuppressWarnings("unchecked") // For generic array creation.
298 private static Set<Class<?>> forbiddenTypes() {
299 Set<Class<?>> set = new HashSet<Class<?>>();
300
301 Collections.addAll(set,
302
303 // It's unfortunate that we have to maintain a blacklist of specific
304 // classes, but we can't easily block the whole package because of
305 // all our unit tests.
306
307 AbstractModule.class,
308 Binder.class,
309 Binding.class,
310 Key.class,
311 Module.class,
312 Provider.class,
313 Scope.class,
314 TypeLiteral.class);
315 return Collections.unmodifiableSet(set);
316 }
317
318 interface CreationListener {
319 void notify(InjectorImpl injector);
320 }
321}