AsyncQueryableGenerator.t4 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <#@ assembly name="System.Core" #>
  2. <#@ assembly name="System.Runtime" #>
  3. <#@ import namespace="System.Linq" #>
  4. <#@ import namespace="System.Reflection" #>
  5. <#@ import namespace="System.Text" #>
  6. <#@ import namespace="System.Threading" #>
  7. <#@ import namespace="System.Threading.Tasks" #>
  8. <#@ import namespace="System.Collections.Generic" #>
  9. <#
  10. var infoFieldNames = new Dictionary<string, int>();
  11. var toQuotedImpl = default(Func<Type, ParameterInfo, int, bool, string>);
  12. toQuotedImpl = (t, paramObjectForAttributes, parameterIndex, notNestedGenericTypeParameter) =>
  13. {
  14. var name = t.Name;
  15. // We always want to look at the whole-type nullability, so we look at that now, and if it's a generic
  16. // type, we'll also go on to inspect per-type-parameter nullability.
  17. var nullableData = paramObjectForAttributes?.GetCustomAttributesData().SingleOrDefault(ad => ad.AttributeType.FullName == "System.Runtime.CompilerServices.NullableAttribute");
  18. bool wholeTypeNullable = false;
  19. if (nullableData is not null)
  20. {
  21. if (nullableData.ConstructorArguments[0].Value is IReadOnlyList<CustomAttributeTypedArgument> nullableFlags)
  22. {
  23. // When we end up in this part, the type argument is, in practice, being used as the type argument to
  24. // the actual type. E.g., ValueTask<TSource?>. So we need to look at the second nullable flag.
  25. wholeTypeNullable = ((byte)nullableFlags[1].Value) == 2;
  26. }
  27. else if (nullableData.ConstructorArguments[0].Value is byte bv)
  28. {
  29. wholeTypeNullable = bv == 2;
  30. }
  31. }
  32. if (t.IsGenericType)
  33. {
  34. var genDef = t.GetGenericTypeDefinition();
  35. name = genDef.Name.Substring(0, genDef.Name.LastIndexOf('`'));
  36. Type[] genericArguments = t.GetGenericArguments();
  37. bool[] typeParamsNullable = new bool[genericArguments.Length];
  38. if (nullableData is not null)
  39. {
  40. if (nullableData.ConstructorArguments[0].Value is IReadOnlyList<CustomAttributeTypedArgument> nullableFlags)
  41. {
  42. // There isn't a 1-1 correspondence between type parameters and nullable flags. Really we should be recursively
  43. // walking the type parameters, but this hack suffices for the types we actually encounter in practice.
  44. int flagIndex = 1;
  45. for (int i = 0; i < typeParamsNullable.Length; ++i)
  46. {
  47. if (!genericArguments[i].IsValueType)
  48. {
  49. if (flagIndex >= nullableFlags.Count) throw new InvalidOperationException($"Type {t} has {typeParamsNullable.Length} type params, but the associated nullable attribute on parameterinto {paramObjectForAttributes} has length {nullableFlags.Count}");
  50. typeParamsNullable[i] = ((byte)nullableFlags[flagIndex].Value) == 2;
  51. flagIndex += 1;
  52. }
  53. }
  54. }
  55. }
  56. var genArgs = "<" + string.Join(", ", genericArguments.Select((a, i) => toQuotedImpl(a, null, parameterIndex, false) + (typeParamsNullable[i] ? "?" : ""))) + ">";
  57. if (notNestedGenericTypeParameter)
  58. {
  59. if (name == "Func" || name == "Action")
  60. {
  61. name = "Expression<" + name + genArgs + ">";
  62. }
  63. else if (name == "IAsyncEnumerable" && parameterIndex == 0)
  64. {
  65. name = "IAsyncQueryable" + genArgs;
  66. }
  67. else if (name == "IOrderedAsyncEnumerable" && parameterIndex == 0)
  68. {
  69. name = "IOrderedAsyncQueryable" + genArgs;
  70. }
  71. else
  72. {
  73. name += genArgs;
  74. }
  75. //if (wholeTypeNullable) { name += "?"; }
  76. }
  77. else
  78. {
  79. if (name == "Nullable")
  80. {
  81. name = genArgs.Substring(1, genArgs.Length - 2) + "?";
  82. }
  83. else
  84. {
  85. name += genArgs;
  86. if (wholeTypeNullable) { name += "?"; }
  87. }
  88. }
  89. }
  90. else if (t.IsArray)
  91. {
  92. var elem = toQuotedImpl(t.GetElementType(), null, parameterIndex, notNestedGenericTypeParameter);
  93. name = elem + "[]";
  94. }
  95. else
  96. {
  97. if (t == typeof(int))
  98. {
  99. name = "int";
  100. }
  101. else if (t == typeof(long))
  102. {
  103. name = "long";
  104. }
  105. else if (t == typeof(float))
  106. {
  107. name = "float";
  108. }
  109. else if (t == typeof(double))
  110. {
  111. name = "double";
  112. }
  113. else if (t == typeof(decimal))
  114. {
  115. name = "decimal";
  116. }
  117. else if (t == typeof(bool))
  118. {
  119. name = "bool";
  120. }
  121. else if (t == typeof(object))
  122. {
  123. name = "object";
  124. }
  125. if (wholeTypeNullable) { name += "?"; }
  126. }
  127. return name;
  128. };
  129. var toQuoted = new Func<Type, ParameterInfo, int, string>((t, paramObjectForAttributes, parameterIndex) => toQuotedImpl(t, paramObjectForAttributes, parameterIndex, true));
  130. #>
  131. #nullable enable
  132. using System.Collections.Generic;
  133. using System.Linq.Expressions;
  134. using System.Reflection;
  135. using System.Threading;
  136. using System.Threading.Tasks;
  137. namespace System.Linq
  138. {
  139. public static partial class <#=className#>
  140. {
  141. <#
  142. // NOTE: Just including extension methods
  143. foreach (var m in asyncEnumerableType.GetMethods()
  144. .Where(m => m.IsStatic)
  145. .Where(m => !exclude.Contains(m.Name))
  146. .Where(m => m.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), true))
  147. .Where(m =>
  148. {
  149. var p0 = m.GetParameters()[0].ParameterType;
  150. if (p0.IsGenericType)
  151. {
  152. var p0d = p0.GetGenericTypeDefinition();
  153. return p0d == typeof(IAsyncEnumerable<>) || p0d == typeof(IOrderedAsyncEnumerable<>);
  154. }
  155. return false;
  156. })
  157. .OrderBy(m => m.Name)
  158. .ThenBy(m => m.IsGenericMethod ? m.GetGenericArguments().Length : 0)
  159. .ThenBy(m => m.GetParameters().Length)
  160. .ThenBy(m => string.Join(", ", m.GetParameters().Select((p, i) => toQuoted(p.ParameterType, p, i) + " " + p.Name))))
  161. {
  162. var genArgs = m.GetGenericArguments();
  163. var ret = toQuoted(m.ReturnType, m.ReturnParameter, 0);
  164. var name = m.Name;
  165. if (genArgs.Length > 0)
  166. {
  167. name += "<" + string.Join(", ", genArgs.Select((a, i) => a.Name)) + ">";
  168. }
  169. var isParams = false;
  170. var lastParameterDefault = false;
  171. var parCount = m.GetParameters().Length;
  172. if (parCount != 0)
  173. {
  174. var lastParam = m.GetParameters().Last();
  175. if (lastParam.IsDefined(typeof(ParamArrayAttribute), true))
  176. {
  177. isParams = true;
  178. }
  179. if (lastParam.ParameterType == typeof(CancellationToken))
  180. {
  181. lastParameterDefault = true;
  182. }
  183. }
  184. var pars = string.Join(", ", m.GetParameters().Select((p, i) => (i == parCount - 1 && isParams ? "params " : "") + toQuoted(p.ParameterType, p, i) + (nullableParameterNames.Contains(p.Name) ? "?" : "") + " " + p.Name + (i == parCount - 1 && lastParameterDefault ? " = default" : "")));
  185. var quotedPars = string.Join(", ", m.GetParameters().Select((p, i) => "default(" + toQuoted(p.ParameterType, p, i) + ")"));
  186. if (m.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), true))
  187. {
  188. pars = "this " + pars;
  189. }
  190. var infoName = m.Name;
  191. var infoTypeArgs = "";
  192. var infoToGeneric = "";
  193. var infoMakeGeneric = "";
  194. var infoGenArgs = "";
  195. if (genArgs.Length > 0)
  196. {
  197. infoName += "__" + string.Join("_", genArgs.Select(a => a.Name));
  198. infoTypeArgs = "(" + string.Join(", ", genArgs.Select(a => "Type " + a.Name)) + ")";
  199. infoToGeneric = "!.GetGenericMethodDefinition()";
  200. infoMakeGeneric = ".MakeGenericMethod(" + string.Join(", ", genArgs.Select(a => a.Name)) + ")";
  201. infoGenArgs = "<" + string.Join(", ", genArgs.Select(_ => "object")) + ">";
  202. }
  203. infoName += "__" + parCount + "__";
  204. int infoNameCount;
  205. if (!infoFieldNames.TryGetValue(infoName, out infoNameCount))
  206. {
  207. infoNameCount = 0;
  208. }
  209. var infoNameId = infoNameCount++;
  210. infoFieldNames[infoName] = infoNameCount;
  211. infoName += infoNameId;
  212. var infoSignature = string.Join(", ", m.GetParameters().Select((p, i) => toQuoted(p.ParameterType, p, i)).Concat(new[] { toQuoted(m.ReturnType, m.ReturnParameter, 0) }));
  213. foreach (var genArg in genArgs)
  214. {
  215. infoSignature = infoSignature.Replace(genArg.Name, "object");
  216. }
  217. var mtd = infoName;
  218. if (m.IsGenericMethod)
  219. {
  220. mtd += "(" + string.Join(", ", genArgs.Select(a => "typeof(" + a.Name + ")")) + ")";
  221. }
  222. var provider = m.GetParameters()[0].Name + ".Provider";
  223. var factory = "";
  224. var rem = "";
  225. var cast = "";
  226. var quotedArgs = new List<string>();
  227. if (m.ReturnType.IsGenericType)
  228. {
  229. var td = m.ReturnType.GetGenericTypeDefinition();
  230. if (td.Name.EndsWith("Task`1")) // NB: Covers Task and ValueTask
  231. {
  232. factory = "ExecuteAsync<" + toQuotedImpl(m.ReturnType.GetGenericArguments()[0], m.ReturnParameter, -1, false) + ">";
  233. var last = m.GetParameters().Last();
  234. if (last.ParameterType == typeof(CancellationToken))
  235. {
  236. rem = ", " + last.Name;
  237. }
  238. else
  239. {
  240. rem = ", CancellationToken.None";
  241. }
  242. }
  243. else if (td == typeof(IAsyncEnumerable<>) || td == typeof(IOrderedAsyncEnumerable<>))
  244. {
  245. factory = "CreateQuery<" + toQuotedImpl(m.ReturnType.GetGenericArguments()[0], null, -1, false) + ">";
  246. if (td == typeof(IOrderedAsyncEnumerable<>))
  247. {
  248. cast = "(" + toQuoted(m.ReturnType, null, 0) + ")";
  249. }
  250. }
  251. }
  252. var n = 0;
  253. foreach (var p in m.GetParameters())
  254. {
  255. var pt = p.ParameterType;
  256. var add = false;
  257. if (pt.IsGenericType)
  258. {
  259. var ptd = pt.GetGenericTypeDefinition();
  260. if (ptd == typeof(IAsyncEnumerable<>) || ptd == typeof(IOrderedAsyncEnumerable<>))
  261. {
  262. if (n == 0)
  263. {
  264. quotedArgs.Add(p.Name + ".Expression");
  265. }
  266. else
  267. {
  268. quotedArgs.Add("GetSourceExpression(" + p.Name + ")");
  269. }
  270. add = true;
  271. }
  272. else if (ptd.Name.StartsWith("Func") || ptd.Name.StartsWith("Action"))
  273. {
  274. quotedArgs.Add(p.Name);
  275. add = true;
  276. }
  277. }
  278. if (!add)
  279. {
  280. quotedArgs.Add("Expression.Constant(" + p.Name + ", typeof(" + toQuoted(pt, null, -1) + "))");
  281. }
  282. n++;
  283. }
  284. var expr = "Expression.Call(" + mtd + ", " + string.Join(", ", quotedArgs) + ")";
  285. var cons = name.StartsWith("ToDictionary") ? " where TKey : notnull" : "";
  286. #>
  287. private static MethodInfo? s_<#=infoName#>;
  288. private static MethodInfo <#=infoName#><#=infoTypeArgs#> =>
  289. (s_<#=infoName#> ??
  290. (s_<#=infoName#> = new Func<<#=infoSignature#>>(<#=m.Name#><#=infoGenArgs#>).GetMethodInfo()<#=infoToGeneric#>))<#=infoMakeGeneric#>;
  291. public static <#=ret#> <#=name#>(<#=pars#>)<#=cons#>
  292. {
  293. <#
  294. var any = false;
  295. foreach (var p in m.GetParameters())
  296. {
  297. if (!p.ParameterType.IsValueType && !p.ParameterType.IsGenericParameter && !nullableParameterNames.Contains(p.Name))
  298. {
  299. any = true;
  300. #>
  301. if (<#=p.Name#> == null)
  302. throw new ArgumentNullException(nameof(<#=p.Name#>));
  303. <#
  304. }
  305. }
  306. #>
  307. <#
  308. if (any)
  309. {
  310. #>
  311. <#
  312. }
  313. #>
  314. return <#=cast#><#=provider#>.<#=factory#>(<#=expr#><#=rem#>);
  315. }
  316. <#
  317. }
  318. #>
  319. }
  320. }