Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Providers/Reactive/ObservableQuery.cs

raw
1 // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
2
3 using System.Collections.Generic;
4 using System.Globalization;
5 using System.Linq;
6 using System.Linq.Expressions;
7 using System.Reactive.Joins;
8 using System.Reactive.Linq;
9 using System.Reflection;
10
11 namespace System.Reactive
12 {
13 internal class ObservableQueryProvider : IQbservableProvider, IQueryProvider
14 {
15 public IQbservable<TResult> CreateQuery<TResult>(Expression expression)
16 {
17 if (expression == null)
18 throw new ArgumentNullException("expression");
19 if (!typeof(IObservable<TResult>).IsAssignableFrom(expression.Type))
20 throw new ArgumentException(Strings_Providers.INVALID_TREE_TYPE, "expression");
21
22 return new ObservableQuery<TResult>(expression);
23 }
24
25 IQueryable<TElement> IQueryProvider.CreateQuery<TElement>(Expression expression)
26 {
27 //
28 // Here we're on the edge between IQbservable and IQueryable for the local
29 // execution case. E.g.:
30 //
31 // observable.AsQbservable().<operators>.ToQueryable()
32 //
33 // This should be turned into a local execution, with the push-to-pull
34 // adapter in the middle, so we rewrite to:
35 //
36 // observable.AsQbservable().<operators>.ToEnumerable().AsQueryable()
37 //
38 var call = expression as MethodCallExpression;
39 if (call == null || call.Method.DeclaringType != typeof(Qbservable) || call.Method.Name != "ToQueryable")
40 throw new ArgumentException(Strings_Providers.EXPECTED_TOQUERYABLE_METHODCALL, "expression");
41
42 //
43 // This is the IQbservable<T> object corresponding to the lhs. Now wrap
44 // it in two calls to get the local queryable.
45 //
46 var arg0 = call.Arguments[0];
47 var res =
48 Expression.Call(
49 AsQueryable.MakeGenericMethod(typeof(TElement)),
50 Expression.Call(
51 typeof(Observable).GetMethod("ToEnumerable").MakeGenericMethod(typeof(TElement)),
52 arg0
53 )
54 );
55
56 //
57 // Queryable operator calls should be taken care of by the provider for
58 // LINQ to Objects. So we compile and get the resulting IQueryable<T>
59 // back to hand it out.
60 //
61 return Expression.Lambda<Func<IQueryable<TElement>>>(res).Compile()();
62 }
63
64 private static MethodInfo s_AsQueryable;
65
66 private static MethodInfo AsQueryable
67 {
68 get
69 {
70 if (s_AsQueryable == null)
71 s_AsQueryable = Qbservable.InfoOf<object>(() => Queryable.AsQueryable<object>(null)).GetGenericMethodDefinition();
72
73 return s_AsQueryable;
74 }
75 }
76
77 IQueryable IQueryProvider.CreateQuery(Expression expression)
78 {
79 throw new NotImplementedException();
80 }
81
82 TResult IQueryProvider.Execute<TResult>(Expression expression)
83 {
84 throw new NotImplementedException();
85 }
86
87 object IQueryProvider.Execute(Expression expression)
88 {
89 throw new NotImplementedException();
90 }
91 }
92
93 internal class ObservableQuery
94 {
95 protected object _source;
96 protected Expression _expression;
97
98 public object Source
99 {
100 get { return _source; }
101 }
102
103 public Expression Expression
104 {
105 get { return _expression; }
106 }
107 }
108
109 internal class ObservableQuery<TSource> : ObservableQuery, IQbservable<TSource>
110 {
111 internal ObservableQuery(IObservable<TSource> source)
112 {
113 _source = source;
114 _expression = Expression.Constant(this);
115 }
116
117 internal ObservableQuery(Expression expression)
118 {
119 _expression = expression;
120 }
121
122 public Type ElementType
123 {
124 get { return typeof(TSource); }
125 }
126
127 public IQbservableProvider Provider
128 {
129 get { return Qbservable.Provider; }
130 }
131
132 public IDisposable Subscribe(IObserver<TSource> observer)
133 {
134 if (_source == null)
135 {
136 var rewriter = new ObservableRewriter();
137 var body = rewriter.Visit(_expression);
138 var f = Expression.Lambda<Func<IObservable<TSource>>>(body);
139 _source = f.Compile()();
140 }
141
142 //
143 // [OK] Use of unsafe Subscribe: non-pretentious mapping to IObservable<T> behavior equivalent to the expression tree.
144 //
145 return ((IObservable<TSource>)_source).Subscribe/*Unsafe*/(observer);
146 }
147
148 public override string ToString()
149 {
150 var c = _expression as ConstantExpression;
151 if (c != null && c.Value == this)
152 {
153 if (_source != null)
154 return _source.ToString();
155
156 return "null";
157 }
158
159 return _expression.ToString();
160 }
161
162 class ObservableRewriter : ExpressionVisitor
163 {
164 protected override Expression VisitConstant(ConstantExpression/*!*/ node)
165 {
166 var query = node.Value as ObservableQuery;
167 if (query != null)
168 {
169 var source = query.Source;
170 if (source != null)
171 {
172 return Expression.Constant(source);
173 }
174 else
175 {
176 return Visit(query.Expression);
177 }
178 }
179
180 return node;
181 }
182
183 protected override Expression VisitMethodCall(MethodCallExpression/*!*/ node)
184 {
185 var method = node.Method;
186 var declaringType = method.DeclaringType;
187 #if (CRIPPLED_REFLECTION && HAS_WINRT)
188 var baseType = declaringType.GetTypeInfo().BaseType;
189 #else
190 var baseType = declaringType.BaseType;
191 #endif
192 if (baseType == typeof(QueryablePattern))
193 {
194 if (method.Name == "Then")
195 {
196 //
197 // Retarget Then to the corresponding pattern. Recursive visit of the lhs will rewrite
198 // the chain of And operators.
199 //
200 var pattern = Visit(node.Object);
201 var arguments = node.Arguments.Select(arg => Unquote(Visit(arg))).ToArray();
202 var then = Expression.Call(pattern, "Then", method.GetGenericArguments(), arguments);
203 return then;
204 }
205 else if (method.Name == "And")
206 {
207 //
208 // Retarget And to the corresponding pattern.
209 //
210 var lhs = Visit(node.Object);
211 var arguments = node.Arguments.Select(arg => Visit(arg)).ToArray();
212 var and = Expression.Call(lhs, "And", method.GetGenericArguments(), arguments);
213 return and;
214 }
215 }
216 else
217 {
218 var arguments = node.Arguments.AsEnumerable();
219
220 //
221 // Checking for an IQbservable operator, being either:
222 // - an extension method on IQbservableProvider
223 // - an extension method on IQbservable<T>
224 //
225 var isOperator = false;
226
227 var firstParameter = method.GetParameters().FirstOrDefault();
228 if (firstParameter != null)
229 {
230 var firstParameterType = firstParameter.ParameterType;
231
232 //
233 // Operators like Qbservable.Amb have an n-ary form that take in an IQbservableProvider
234 // as the first argument. In such a case we need to make sure that the given provider is
235 // the one targeting regular Observable. If not, we keep the subtree as-is and let that
236 // provider handle the execution.
237 //
238 if (firstParameterType == typeof(IQbservableProvider))
239 {
240 isOperator = true;
241
242 //
243 // Since we could be inside a lambda expression where one tries to obtain a query
244 // provider, or that provider could be stored in an outer variable, we need to
245 // evaluate the expression to obtain an IQbservableProvider object.
246 //
247 var provider = Expression.Lambda<Func<IQbservableProvider>>(Visit(node.Arguments[0])).Compile()();
248
249 //
250 // Let's see whether the ObservableQuery provider is targeted. This one always goes
251 // to local execution. E.g.:
252 //
253 // var xs = Observable.Return(1).AsQbservable();
254 // var ys = Observable.Return(2).AsQbservable();
255 // var zs = Observable.Return(3).AsQbservable();
256 //
257 // var res = Qbservable.Provider.Amb(xs, ys, zs);
258 // ^^^^^^^^^^^^^^^^^^^
259 //
260 if (provider is ObservableQueryProvider)
261 {
262 //
263 // For further rewrite, simply ignore the query provider argument now to match
264 // up with the Observable signature. E.g.:
265 //
266 // var res = Qbservable.Provider.Amb(xs, ys, zs);
267 // = Qbservable.Amb(Qbservable.Provider, xs, ys, zs)'
268 // ^^^^^^^^^^^^^^^^^^^
269 // ->
270 // var res = Observable.Amb(xs, ys, zs);
271 //
272 arguments = arguments.Skip(1);
273 }
274 else
275 {
276 //
277 // We've hit an unknown provider and will defer further execution to it. Upon
278 // calling Subscribe to the node's output, that provider will take care of it.
279 //
280 return node;
281 }
282 }
283 else if (typeof(IQbservable).IsAssignableFrom(firstParameterType))
284 {
285 isOperator = true;
286 }
287 }
288
289 if (isOperator)
290 {
291 var args = VisitQbservableOperatorArguments(method, arguments);
292 return FindObservableMethod(method, args);
293 }
294 }
295
296 return base.VisitMethodCall(node);
297 }
298
299 private IList<Expression> VisitQbservableOperatorArguments(MethodInfo method, IEnumerable<Expression> arguments)
300 {
301 //
302 // Recognize the Qbservable.When<TResult>(IQbservableProvider, QueryablePlan<TResult>[])
303 // overload in order to substitute the array with a Plan<TResult>[].
304 //
305 if (method.Name == "When")
306 {
307 var lastArgument = arguments.Last();
308 if (lastArgument.NodeType == ExpressionType.NewArrayInit)
309 {
310 var paramsArray = (NewArrayExpression)lastArgument;
311 return new List<Expression>
312 {
313 Expression.NewArrayInit(
314 typeof(Plan<>).MakeGenericType(method.GetGenericArguments()[0]),
315 paramsArray.Expressions.Select(param => Visit(param))
316 )
317 };
318 }
319 }
320
321 return arguments.Select(arg => Visit(arg)).ToList();
322 }
323
324 class Lazy<T>
325 {
326 private readonly Func<T> _factory;
327 private T _value;
328 private bool _initialized;
329
330 public Lazy(Func<T> factory)
331 {
332 _factory = factory;
333 }
334
335 public T Value
336 {
337 get
338 {
339 lock (_factory)
340 {
341 if (!_initialized)
342 {
343 _value = _factory();
344 _initialized = true;
345 }
346 }
347
348 return _value;
349 }
350 }
351 }
352
353 private static Lazy<ILookup<string, MethodInfo>> _observableMethods = new Lazy<ILookup<string, MethodInfo>>(() => GetMethods(typeof(Observable)));
354
355 private static MethodCallExpression FindObservableMethod(MethodInfo method, IList<Expression> arguments)
356 {
357 //
358 // Where to look for the matching operator?
359 //
360 var targetType = default(Type);
361 var methods = default(ILookup<string, MethodInfo>);
362 if (method.DeclaringType == typeof(Qbservable))
363 {
364 targetType = typeof(Observable);
365 methods = _observableMethods.Value;
366 }
367 else
368 {
369 targetType = method.DeclaringType;
370
371 #if (CRIPPLED_REFLECTION && HAS_WINRT)
372 var typeInfo = targetType.GetTypeInfo();
373 if (typeInfo.IsDefined(typeof(LocalQueryMethodImplementationTypeAttribute), false))
374 {
375 var mapping = (LocalQueryMethodImplementationTypeAttribute)typeInfo.GetCustomAttributes(typeof(LocalQueryMethodImplementationTypeAttribute), false).Single();
376 targetType = mapping.TargetType;
377 }
378 #else
379 if (targetType.IsDefined(typeof(LocalQueryMethodImplementationTypeAttribute), false))
380 {
381 var mapping = (LocalQueryMethodImplementationTypeAttribute)targetType.GetCustomAttributes(typeof(LocalQueryMethodImplementationTypeAttribute), false)[0];
382 targetType = mapping.TargetType;
383 }
384 #endif
385
386 methods = GetMethods(targetType);
387 }
388
389 //
390 // From all the operators with the method's name, find the one that matches all arguments.
391 //
392 var typeArgs = method.IsGenericMethod ? method.GetGenericArguments() : null;
393 var targetMethod = methods[method.Name].FirstOrDefault(candidateMethod => ArgsMatch(candidateMethod, arguments, typeArgs));
394 if (targetMethod == null)
395 throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Providers.NO_MATCHING_METHOD_FOUND, method.Name, targetType.Name));
396
397 //
398 // Restore generic arguments.
399 //
400 if (typeArgs != null)
401 targetMethod = targetMethod.MakeGenericMethod(typeArgs);
402
403 //
404 // Finally, we need to deal with mismatches on Expression<Func<...>> versus Func<...>.
405 //
406 var parameters = targetMethod.GetParameters();
407 for (int i = 0, n = parameters.Length; i < n; i++)
408 {
409 arguments[i] = Unquote(arguments[i]);
410 }
411
412 //
413 // Emit a new call to the discovered target method.
414 //
415 return Expression.Call(null, targetMethod, arguments);
416 }
417
418 private static ILookup<string, MethodInfo> GetMethods(Type type)
419 {
420 #if !(CRIPPLED_REFLECTION && HAS_WINRT)
421 return type.GetMethods(BindingFlags.Static | BindingFlags.Public).ToLookup(m => m.Name);
422 #else
423 return type.GetTypeInfo().DeclaredMethods.Where(m => m.IsStatic && m.IsPublic).ToLookup(m => m.Name);
424 #endif
425 }
426
427 private static bool ArgsMatch(MethodInfo method, IList<Expression> arguments, Type[] typeArgs)
428 {
429 //
430 // Number of parameters should match. Notice we've sanitized IQbservableProvider "this"
431 // parameters first (see VisitMethodCall).
432 //
433 var parameters = method.GetParameters();
434 if (parameters.Length != arguments.Count)
435 return false;
436
437 //
438 // Genericity should match too.
439 //
440 if (!method.IsGenericMethod && typeArgs != null && typeArgs.Length > 0)
441 return false;
442
443 //
444 // Reconstruct the generic method if needed.
445 //
446 if (method.IsGenericMethodDefinition)
447 {
448 if (typeArgs == null)
449 return false;
450
451 if (method.GetGenericArguments().Length != typeArgs.Length)
452 return false;
453
454 var result = method.MakeGenericMethod(typeArgs);
455 parameters = result.GetParameters();
456 }
457
458 //
459 // Check compatibility for the parameter types.
460 //
461 for (int i = 0, n = arguments.Count; i < n; i++)
462 {
463 var parameterType = parameters[i].ParameterType;
464 var argument = arguments[i];
465
466 //
467 // For operators that take a function (like Where, Select), we'll be faced
468 // with a quoted argument and a discrepancy between Expression<Func<...>>
469 // and the underlying Func<...>.
470 //
471 if (!parameterType.IsAssignableFrom(argument.Type))
472 {
473 argument = Unquote(argument);
474 if (!parameterType.IsAssignableFrom(argument.Type))
475 return false;
476 }
477 }
478
479 return true;
480 }
481
482 private static Expression Unquote(Expression expression)
483 {
484 //
485 // Get rid of all outer quotes around an expression.
486 //
487 while (expression.NodeType == ExpressionType.Quote)
488 expression = ((UnaryExpression)expression).Operand;
489
490 return expression;
491 }
492 }
493 }
494
495 #if (CRIPPLED_REFLECTION && HAS_WINRT)
496 static class Helpers
497 {
498 public static MethodInfo GetMethod(this Type type, string name)
499 {
500 return type.GetTypeInfo().GetDeclaredMethod(name);
501 }
502
503 public static bool IsAssignableFrom(this Type type1, Type type2)
504 {
505 return type1.GetTypeInfo().IsAssignableFrom(type2.GetTypeInfo());
506 }
507 }
508 #endif
509 }