blob: f1fab1e91d98bd5ddaec414255a1dbb9de4f68be [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;
limpbizkit05757142008-06-02 06:58:47 +000023import com.google.inject.internal.Annotations;
24import com.google.inject.internal.ErrorMessages;
25import com.google.inject.internal.ResolveFailedException;
26import com.google.inject.internal.StackTraceElements;
limpbizkit3d58d6b2008-03-08 16:11:47 +000027
28import java.lang.annotation.Annotation;
29import java.lang.reflect.Type;
30import java.util.*;
limpbizkit3d58d6b2008-03-08 16:11:47 +000031
32/**
33 * Handles {@link Binder#bind} and {@link Binder#bindConstant} commands.
34 *
35 * @author crazybob@google.com (Bob Lee)
36 * @author jessewilson@google.com (Jesse Wilson)
37 */
38class BindCommandProcessor extends CommandProcessor {
39
40 private final InjectorImpl injector;
41 private final Map<Class<? extends Annotation>, Scope> scopes;
42 private final List<CreationListener> creationListeners
43 = new ArrayList<CreationListener>();
limpbizkit3d58d6b2008-03-08 16:11:47 +000044 private final Stage stage;
45 private final Map<Key<?>, BindingImpl<?>> bindings;
limpbizkit51515b52008-03-11 03:46:25 +000046 private final Map<Object, Void> outstandingInjections;
limpbizkitf44e9cc2008-03-26 06:33:29 +000047 private final List<Runnable> untargettedBindings = new ArrayList<Runnable>();
limpbizkit3d58d6b2008-03-08 16:11:47 +000048
49 BindCommandProcessor(InjectorImpl injector,
50 Map<Class<? extends Annotation>, Scope> scopes,
51 Stage stage,
limpbizkit51515b52008-03-11 03:46:25 +000052 Map<Key<?>, BindingImpl<?>> bindings,
53 Map<Object, Void> outstandingInjections) {
limpbizkitad94bcb2008-04-28 00:22:43 +000054 super(injector.errorHandler);
limpbizkit3d58d6b2008-03-08 16:11:47 +000055 this.injector = injector;
56 this.scopes = scopes;
57 this.stage = stage;
58 this.bindings = bindings;
limpbizkit51515b52008-03-11 03:46:25 +000059 this.outstandingInjections = outstandingInjections;
limpbizkit3d58d6b2008-03-08 16:11:47 +000060 }
61
62 @Override public <T> Boolean visitBind(BindCommand<T> command) {
63 final Object source = command.getSource();
64
65 final Key<T> key = command.getKey();
66 Class<? super T> rawType = key.getTypeLiteral().getRawType();
67
68 if (rawType == Provider.class) {
69 addError(source, ErrorMessages.BINDING_TO_PROVIDER);
70 return true;
71 }
72
limpbizkit3d58d6b2008-03-08 16:11:47 +000073 validateKey(command.getSource(), command.getKey());
74
limpbizkit05757142008-06-02 06:58:47 +000075 final LoadStrategy loadStrategy = command.getScoping().isEagerSingleton()
76 ? LoadStrategy.EAGER
77 : LoadStrategy.LAZY;
limpbizkit3d58d6b2008-03-08 16:11:47 +000078 final Scope scope = command.getScoping().acceptVisitor(new BindScoping.Visitor<Scope>() {
79 public Scope visitEagerSingleton() {
80 return Scopes.SINGLETON;
81 }
82
83 public Scope visitScope(Scope scope) {
84 return scope;
85 }
86
87 public Scope visitScopeAnnotation(Class<? extends Annotation> scopeAnnotation) {
88 Scope scope = scopes.get(scopeAnnotation);
89 if (scope != null) {
90 return scope;
91 } else {
92 addError(source, ErrorMessages.SCOPE_NOT_FOUND,
93 "@" + scopeAnnotation.getSimpleName());
94 return Scopes.NO_SCOPE;
95 }
96 }
97
98 public Scope visitNoScoping() {
99 return null;
100 }
101 });
102
103 command.getTarget().acceptVisitor(new BindTarget.Visitor<T, Void>() {
104 public Void visitToInstance(T instance) {
limpbizkit51515b52008-03-11 03:46:25 +0000105 ConstantFactory<? extends T> factory = new ConstantFactory<T>(instance);
106 outstandingInjections.put(instance, null);
limpbizkit3d58d6b2008-03-08 16:11:47 +0000107 InternalFactory<? extends T> scopedFactory
108 = Scopes.scope(key, injector, factory, scope);
limpbizkit05757142008-06-02 06:58:47 +0000109 putBinding(new InstanceBindingImpl<T>(
110 injector, key, source, scopedFactory, instance));
limpbizkit3d58d6b2008-03-08 16:11:47 +0000111 return null;
112 }
113
114 public Void visitToProvider(Provider<? extends T> provider) {
limpbizkit51515b52008-03-11 03:46:25 +0000115 InternalFactoryToProviderAdapter<? extends T> factory
limpbizkit3d58d6b2008-03-08 16:11:47 +0000116 = new InternalFactoryToProviderAdapter<T>(provider, source);
limpbizkit51515b52008-03-11 03:46:25 +0000117 outstandingInjections.put(provider, null);
limpbizkit3d58d6b2008-03-08 16:11:47 +0000118 InternalFactory<? extends T> scopedFactory
119 = Scopes.scope(key, injector, factory, scope);
limpbizkit05757142008-06-02 06:58:47 +0000120 putBinding(new ProviderInstanceBindingImpl<T>(
121 injector, key, source, scopedFactory, scope, provider, loadStrategy));
limpbizkit3d58d6b2008-03-08 16:11:47 +0000122 return null;
123 }
124
125 public Void visitToProviderKey(Key<? extends Provider<? extends T>> providerKey) {
126 final BoundProviderFactory<T> boundProviderFactory =
127 new BoundProviderFactory<T>(providerKey, source);
128 creationListeners.add(boundProviderFactory);
129 InternalFactory<? extends T> scopedFactory = Scopes.scope(
130 key, injector, (InternalFactory<? extends T>) boundProviderFactory, scope);
limpbizkit05757142008-06-02 06:58:47 +0000131 putBinding(new LinkedProviderBindingImpl<T>(
132 injector, key, source, scopedFactory, scope, providerKey, loadStrategy));
limpbizkit3d58d6b2008-03-08 16:11:47 +0000133 return null;
134 }
135
136 public Void visitToKey(Key<? extends T> targetKey) {
137 if (key.equals(targetKey)) {
138 addError(source, ErrorMessages.RECURSIVE_BINDING);
139 }
140
141 FactoryProxy<T> factory = new FactoryProxy<T>(key, targetKey, source);
142 creationListeners.add(factory);
143 InternalFactory<? extends T> scopedFactory
144 = Scopes.scope(key, injector, factory, scope);
limpbizkit05757142008-06-02 06:58:47 +0000145 putBinding(new LinkedBindingImpl<T>(
146 injector, key, source, scopedFactory, scope, targetKey, loadStrategy));
limpbizkit3d58d6b2008-03-08 16:11:47 +0000147 return null;
148 }
149
150 public Void visitUntargetted() {
limpbizkitf44e9cc2008-03-26 06:33:29 +0000151 final Type type = key.getTypeLiteral().getType();
limpbizkit3d58d6b2008-03-08 16:11:47 +0000152
153 // Error: Missing implementation.
154 // Example: bind(Date.class).annotatedWith(Red.class);
155 // We can't assume abstract types aren't injectable. They may have an
156 // @ImplementedBy annotation or something.
157 if (key.hasAnnotationType() || !(type instanceof Class<?>)) {
158 addError(source, ErrorMessages.MISSING_IMPLEMENTATION);
limpbizkit05757142008-06-02 06:58:47 +0000159 putBinding(invalidBinding(injector, key, source));
limpbizkit3d58d6b2008-03-08 16:11:47 +0000160 return null;
161 }
162
limpbizkit51411872008-05-13 22:15:29 +0000163 // This cast is safe after the preceeding check.
164 @SuppressWarnings("unchecked")
165 Class<T> clazz = (Class<T>) type;
166 final BindingImpl<T> binding;
167 try {
limpbizkit05757142008-06-02 06:58:47 +0000168 binding = injector.createUnitializedBinding(clazz, scope, source, loadStrategy);
169 putBinding(binding);
limpbizkit51411872008-05-13 22:15:29 +0000170 } catch (ResolveFailedException e) {
171 injector.errorHandler.handle(source, e.getMessage());
limpbizkit05757142008-06-02 06:58:47 +0000172 putBinding(invalidBinding(injector, key, source));
limpbizkit51411872008-05-13 22:15:29 +0000173 return null;
174 }
175
limpbizkitf44e9cc2008-03-26 06:33:29 +0000176 untargettedBindings.add(new Runnable() {
177 public void run() {
limpbizkit3b1cd582008-04-28 00:06:01 +0000178 try {
limpbizkit51411872008-05-13 22:15:29 +0000179 injector.initializeBinding(binding);
limpbizkit3b1cd582008-04-28 00:06:01 +0000180 } catch (ResolveFailedException e) {
181 injector.errorHandler.handle(source, e.getMessage());
limpbizkitf44e9cc2008-03-26 06:33:29 +0000182 }
limpbizkitf44e9cc2008-03-26 06:33:29 +0000183 }
184 });
185
limpbizkit3d58d6b2008-03-08 16:11:47 +0000186 return null;
187 }
188 });
189
190 return true;
191 }
192
193 private <T> void validateKey(Object source, Key<T> key) {
194 if (key.hasAnnotationType()) {
195 Class<? extends Annotation> annotationType = key.getAnnotationType();
196
197 if (!Annotations.isRetainedAtRuntime(annotationType)) {
198 addError(StackTraceElements.forType(annotationType),
199 ErrorMessages.MISSING_RUNTIME_RETENTION, source);
200 }
201
202 if (!Key.isBindingAnnotation(annotationType)) {
203 addError(StackTraceElements.forType(annotationType),
204 ErrorMessages.MISSING_BINDING_ANNOTATION, source);
205 }
206 }
207 }
208
209 <T> InvalidBindingImpl<T> invalidBinding(InjectorImpl injector, Key<T> key, Object source) {
210 return new InvalidBindingImpl<T>(injector, key, source);
211 }
212
limpbizkit3d58d6b2008-03-08 16:11:47 +0000213 @Override public Boolean visitBindConstant(BindConstantCommand command) {
limpbizkitd6967b92008-05-16 15:28:51 +0000214 BindTarget<?> target = command.getTarget();
215 if (target == null) {
limpbizkit3d58d6b2008-03-08 16:11:47 +0000216 addError(command.getSource(), ErrorMessages.MISSING_CONSTANT_VALUE);
limpbizkitd6967b92008-05-16 15:28:51 +0000217 return true;
limpbizkit3d58d6b2008-03-08 16:11:47 +0000218 }
219
limpbizkitd6967b92008-05-16 15:28:51 +0000220 Object value = target.get();
limpbizkit3d58d6b2008-03-08 16:11:47 +0000221 validateKey(command.getSource(), command.getKey());
222 ConstantFactory<Object> factory = new ConstantFactory<Object>(value);
limpbizkitf44e9cc2008-03-26 06:33:29 +0000223 putBinding(new ConstantBindingImpl<Object>(
limpbizkit3d58d6b2008-03-08 16:11:47 +0000224 injector, command.getKey(), command.getSource(), factory, value));
225
226 return true;
227 }
228
limpbizkitf44e9cc2008-03-26 06:33:29 +0000229 public void createUntargettedBindings() {
230 for (Runnable untargettedBinding : untargettedBindings) {
231 untargettedBinding.run();
232 }
233 }
234
limpbizkit05757142008-06-02 06:58:47 +0000235 public void loadEagerSingletons(InjectorImpl injector) {
236 // load eager singletons, or all singletons if we're in Stage.PRODUCTION.
237 for (final BindingImpl<?> binding : bindings.values()) {
238 if (stage == Stage.PRODUCTION || binding.getLoadStrategy() == LoadStrategy.EAGER) {
239 injector.callInContext(new ContextualCallable<Void>() {
240 public Void call(InternalContext context) {
241 InjectionPoint<?> injectionPoint
242 = InjectionPoint.newInstance(binding.key, context.getInjector());
243 context.setInjectionPoint(injectionPoint);
244 try {
245 binding.internalFactory.get(context, injectionPoint);
246 return null;
247 } catch(ProvisionException provisionException) {
248 provisionException.addContext(injectionPoint);
249 throw provisionException;
250 } finally {
251 context.setInjectionPoint(null);
252 }
253 }
254 });
255 }
limpbizkit51515b52008-03-11 03:46:25 +0000256 }
limpbizkit3d58d6b2008-03-08 16:11:47 +0000257 }
258
259 public void runCreationListeners(InjectorImpl injector) {
260 for (CreationListener creationListener : creationListeners) {
261 creationListener.notify(injector);
262 }
263 }
264
limpbizkit3d58d6b2008-03-08 16:11:47 +0000265 private void putBinding(BindingImpl<?> binding) {
266 Key<?> key = binding.getKey();
267 Binding<?> original = bindings.get(key);
268
269 Class<?> rawType = key.getRawType();
270 if (FORBIDDEN_TYPES.contains(rawType)) {
271 addError(binding.getSource(), ErrorMessages.CANNOT_BIND_TO_GUICE_TYPE,
272 rawType.getSimpleName());
273 return;
274 }
275
276 if (bindings.containsKey(key)) {
277 addError(binding.getSource(), ErrorMessages.BINDING_ALREADY_SET, key,
278 original.getSource());
279 } else {
280 bindings.put(key, binding);
281 }
282 }
283
284 private static Set<Class<?>> FORBIDDEN_TYPES = forbiddenTypes();
285
286 @SuppressWarnings("unchecked") // For generic array creation.
287 private static Set<Class<?>> forbiddenTypes() {
288 Set<Class<?>> set = new HashSet<Class<?>>();
289
290 Collections.addAll(set,
291
292 // It's unfortunate that we have to maintain a blacklist of specific
293 // classes, but we can't easily block the whole package because of
294 // all our unit tests.
295
296 AbstractModule.class,
297 Binder.class,
298 Binding.class,
299 Key.class,
300 Module.class,
301 Provider.class,
302 Scope.class,
303 TypeLiteral.class);
304 return Collections.unmodifiableSet(set);
305 }
306
307 interface CreationListener {
308 void notify(InjectorImpl injector);
309 }
310}