DynamicLibrary.cs 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293
  1. //Copyright (C) Microsoft Corporation. All rights reserved.
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Linq;
  6. using System.Linq.Expressions;
  7. using System.Reflection;
  8. using System.Reflection.Emit;
  9. using System.Threading;
  10. namespace System.Linq.Dynamic
  11. {
  12. public static class DynamicQueryable
  13. {
  14. public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values)
  15. {
  16. return (IQueryable<T>)Where((IQueryable)source, predicate, values);
  17. }
  18. public static IQueryable Where(this IQueryable source, string predicate, params object[] values)
  19. {
  20. if (source == null) throw new ArgumentNullException("source");
  21. if (predicate == null) throw new ArgumentNullException("predicate");
  22. LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
  23. return source.Provider.CreateQuery(
  24. Expression.Call(
  25. typeof(Queryable), "Where",
  26. new Type[] { source.ElementType },
  27. source.Expression, Expression.Quote(lambda)));
  28. }
  29. public static IQueryable Select(this IQueryable source, string selector, params object[] values)
  30. {
  31. if (source == null) throw new ArgumentNullException("source");
  32. if (selector == null) throw new ArgumentNullException("selector");
  33. LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, null, selector, values);
  34. return source.Provider.CreateQuery(
  35. Expression.Call(
  36. typeof(Queryable), "Select",
  37. new Type[] { source.ElementType, lambda.Body.Type },
  38. source.Expression, Expression.Quote(lambda)));
  39. }
  40. public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values)
  41. {
  42. return (IQueryable<T>)OrderBy((IQueryable)source, ordering, values);
  43. }
  44. public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values)
  45. {
  46. if (source == null) throw new ArgumentNullException("source");
  47. if (ordering == null) throw new ArgumentNullException("ordering");
  48. ParameterExpression[] parameters = new ParameterExpression[] {
  49. Expression.Parameter(source.ElementType, "") };
  50. ExpressionParser parser = new ExpressionParser(parameters, ordering, values);
  51. IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
  52. Expression queryExpr = source.Expression;
  53. string methodAsc = "OrderBy";
  54. string methodDesc = "OrderByDescending";
  55. foreach (DynamicOrdering o in orderings)
  56. {
  57. queryExpr = Expression.Call(
  58. typeof(Queryable), o.Ascending ? methodAsc : methodDesc,
  59. new Type[] { source.ElementType, o.Selector.Type },
  60. queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters)));
  61. methodAsc = "ThenBy";
  62. methodDesc = "ThenByDescending";
  63. }
  64. return source.Provider.CreateQuery(queryExpr);
  65. }
  66. public static IQueryable Take(this IQueryable source, int count)
  67. {
  68. if (source == null) throw new ArgumentNullException("source");
  69. return source.Provider.CreateQuery(
  70. Expression.Call(
  71. typeof(Queryable), "Take",
  72. new Type[] { source.ElementType },
  73. source.Expression, Expression.Constant(count)));
  74. }
  75. public static IQueryable Skip(this IQueryable source, int count)
  76. {
  77. if (source == null) throw new ArgumentNullException("source");
  78. return source.Provider.CreateQuery(
  79. Expression.Call(
  80. typeof(Queryable), "Skip",
  81. new Type[] { source.ElementType },
  82. source.Expression, Expression.Constant(count)));
  83. }
  84. public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values)
  85. {
  86. if (source == null) throw new ArgumentNullException("source");
  87. if (keySelector == null) throw new ArgumentNullException("keySelector");
  88. if (elementSelector == null) throw new ArgumentNullException("elementSelector");
  89. LambdaExpression keyLambda = DynamicExpression.ParseLambda(source.ElementType, null, keySelector, values);
  90. LambdaExpression elementLambda = DynamicExpression.ParseLambda(source.ElementType, null, elementSelector, values);
  91. return source.Provider.CreateQuery(
  92. Expression.Call(
  93. typeof(Queryable), "GroupBy",
  94. new Type[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type },
  95. source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda)));
  96. }
  97. public static bool Any(this IQueryable source)
  98. {
  99. if (source == null) throw new ArgumentNullException("source");
  100. return (bool)source.Provider.Execute(
  101. Expression.Call(
  102. typeof(Queryable), "Any",
  103. new Type[] { source.ElementType }, source.Expression));
  104. }
  105. public static int Count(this IQueryable source)
  106. {
  107. if (source == null) throw new ArgumentNullException("source");
  108. return (int)source.Provider.Execute(
  109. Expression.Call(
  110. typeof(Queryable), "Count",
  111. new Type[] { source.ElementType }, source.Expression));
  112. }
  113. }
  114. public abstract class DynamicClass
  115. {
  116. public override string ToString()
  117. {
  118. PropertyInfo[] props = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
  119. StringBuilder sb = new StringBuilder();
  120. sb.Append("{");
  121. for (int i = 0; i < props.Length; i++)
  122. {
  123. if (i > 0) sb.Append(", ");
  124. sb.Append(props[i].Name);
  125. sb.Append("=");
  126. sb.Append(props[i].GetValue(this, null));
  127. }
  128. sb.Append("}");
  129. return sb.ToString();
  130. }
  131. }
  132. public class DynamicProperty
  133. {
  134. string name;
  135. Type type;
  136. public DynamicProperty(string name, Type type)
  137. {
  138. if (name == null) throw new ArgumentNullException("name");
  139. if (type == null) throw new ArgumentNullException("type");
  140. this.name = name;
  141. this.type = type;
  142. }
  143. public string Name
  144. {
  145. get { return name; }
  146. }
  147. public Type Type
  148. {
  149. get { return type; }
  150. }
  151. }
  152. public static class DynamicExpression
  153. {
  154. public static Expression Parse(Type resultType, string expression, params object[] values)
  155. {
  156. ExpressionParser parser = new ExpressionParser(null, expression, values);
  157. return parser.Parse(resultType);
  158. }
  159. public static LambdaExpression ParseLambda(Type itType, Type resultType, string expression, params object[] values)
  160. {
  161. return ParseLambda(new ParameterExpression[] { Expression.Parameter(itType, "") }, resultType, expression, values);
  162. }
  163. public static LambdaExpression ParseLambda(ParameterExpression[] parameters, Type resultType, string expression, params object[] values)
  164. {
  165. ExpressionParser parser = new ExpressionParser(parameters, expression, values);
  166. return Expression.Lambda(parser.Parse(resultType), parameters);
  167. }
  168. public static Expression<Func<T, S>> ParseLambda<T, S>(string expression, params object[] values)
  169. {
  170. return (Expression<Func<T, S>>)ParseLambda(typeof(T), typeof(S), expression, values);
  171. }
  172. public static Type CreateClass(params DynamicProperty[] properties)
  173. {
  174. return ClassFactory.Instance.GetDynamicClass(properties);
  175. }
  176. public static Type CreateClass(IEnumerable<DynamicProperty> properties)
  177. {
  178. return ClassFactory.Instance.GetDynamicClass(properties);
  179. }
  180. }
  181. internal class DynamicOrdering
  182. {
  183. public Expression Selector;
  184. public bool Ascending;
  185. }
  186. internal class Signature : IEquatable<Signature>
  187. {
  188. public DynamicProperty[] properties;
  189. public int hashCode;
  190. public Signature(IEnumerable<DynamicProperty> properties)
  191. {
  192. this.properties = properties.ToArray();
  193. hashCode = 0;
  194. foreach (DynamicProperty p in properties)
  195. {
  196. hashCode ^= p.Name.GetHashCode() ^ p.Type.GetHashCode();
  197. }
  198. }
  199. public override int GetHashCode()
  200. {
  201. return hashCode;
  202. }
  203. public override bool Equals(object obj)
  204. {
  205. return obj is Signature ? Equals((Signature)obj) : false;
  206. }
  207. public bool Equals(Signature other)
  208. {
  209. if (properties.Length != other.properties.Length) return false;
  210. for (int i = 0; i < properties.Length; i++)
  211. {
  212. if (properties[i].Name != other.properties[i].Name ||
  213. properties[i].Type != other.properties[i].Type) return false;
  214. }
  215. return true;
  216. }
  217. }
  218. internal class ClassFactory
  219. {
  220. public static readonly ClassFactory Instance = new ClassFactory();
  221. static ClassFactory() { } // Trigger lazy initialization of static fields
  222. ModuleBuilder module;
  223. Dictionary<Signature, Type> classes;
  224. int classCount;
  225. ReaderWriterLock rwLock;
  226. private ClassFactory()
  227. {
  228. AssemblyName name = new AssemblyName("DynamicClasses");
  229. AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
  230. #if ENABLE_LINQ_PARTIAL_TRUST
  231. new ReflectionPermission(PermissionState.Unrestricted).Assert();
  232. #endif
  233. try
  234. {
  235. module = assembly.DefineDynamicModule("Module");
  236. }
  237. finally
  238. {
  239. #if ENABLE_LINQ_PARTIAL_TRUST
  240. PermissionSet.RevertAssert();
  241. #endif
  242. }
  243. classes = new Dictionary<Signature, Type>();
  244. rwLock = new ReaderWriterLock();
  245. }
  246. public Type GetDynamicClass(IEnumerable<DynamicProperty> properties)
  247. {
  248. rwLock.AcquireReaderLock(Timeout.Infinite);
  249. try
  250. {
  251. Signature signature = new Signature(properties);
  252. Type type;
  253. if (!classes.TryGetValue(signature, out type))
  254. {
  255. type = CreateDynamicClass(signature.properties);
  256. classes.Add(signature, type);
  257. }
  258. return type;
  259. }
  260. finally
  261. {
  262. rwLock.ReleaseReaderLock();
  263. }
  264. }
  265. Type CreateDynamicClass(DynamicProperty[] properties)
  266. {
  267. LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite);
  268. try
  269. {
  270. string typeName = "DynamicClass" + (classCount + 1);
  271. #if ENABLE_LINQ_PARTIAL_TRUST
  272. new ReflectionPermission(PermissionState.Unrestricted).Assert();
  273. #endif
  274. try
  275. {
  276. TypeBuilder tb = this.module.DefineType(typeName, TypeAttributes.Class |
  277. TypeAttributes.Public, typeof(DynamicClass));
  278. FieldInfo[] fields = GenerateProperties(tb, properties);
  279. GenerateEquals(tb, fields);
  280. GenerateGetHashCode(tb, fields);
  281. Type result = tb.CreateType();
  282. classCount++;
  283. return result;
  284. }
  285. finally
  286. {
  287. #if ENABLE_LINQ_PARTIAL_TRUST
  288. PermissionSet.RevertAssert();
  289. #endif
  290. }
  291. }
  292. finally
  293. {
  294. rwLock.DowngradeFromWriterLock(ref cookie);
  295. }
  296. }
  297. FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties)
  298. {
  299. FieldInfo[] fields = new FieldBuilder[properties.Length];
  300. for (int i = 0; i < properties.Length; i++)
  301. {
  302. DynamicProperty dp = properties[i];
  303. FieldBuilder fb = tb.DefineField("_" + dp.Name, dp.Type, FieldAttributes.Private);
  304. PropertyBuilder pb = tb.DefineProperty(dp.Name, PropertyAttributes.HasDefault, dp.Type, null);
  305. MethodBuilder mbGet = tb.DefineMethod("get_" + dp.Name,
  306. MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
  307. dp.Type, Type.EmptyTypes);
  308. ILGenerator genGet = mbGet.GetILGenerator();
  309. genGet.Emit(OpCodes.Ldarg_0);
  310. genGet.Emit(OpCodes.Ldfld, fb);
  311. genGet.Emit(OpCodes.Ret);
  312. MethodBuilder mbSet = tb.DefineMethod("set_" + dp.Name,
  313. MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig,
  314. null, new Type[] { dp.Type });
  315. ILGenerator genSet = mbSet.GetILGenerator();
  316. genSet.Emit(OpCodes.Ldarg_0);
  317. genSet.Emit(OpCodes.Ldarg_1);
  318. genSet.Emit(OpCodes.Stfld, fb);
  319. genSet.Emit(OpCodes.Ret);
  320. pb.SetGetMethod(mbGet);
  321. pb.SetSetMethod(mbSet);
  322. fields[i] = fb;
  323. }
  324. return fields;
  325. }
  326. void GenerateEquals(TypeBuilder tb, FieldInfo[] fields)
  327. {
  328. MethodBuilder mb = tb.DefineMethod("Equals",
  329. MethodAttributes.Public | MethodAttributes.ReuseSlot |
  330. MethodAttributes.Virtual | MethodAttributes.HideBySig,
  331. typeof(bool), new Type[] { typeof(object) });
  332. ILGenerator gen = mb.GetILGenerator();
  333. LocalBuilder other = gen.DeclareLocal(tb);
  334. Label next = gen.DefineLabel();
  335. gen.Emit(OpCodes.Ldarg_1);
  336. gen.Emit(OpCodes.Isinst, tb);
  337. gen.Emit(OpCodes.Stloc, other);
  338. gen.Emit(OpCodes.Ldloc, other);
  339. gen.Emit(OpCodes.Brtrue_S, next);
  340. gen.Emit(OpCodes.Ldc_I4_0);
  341. gen.Emit(OpCodes.Ret);
  342. gen.MarkLabel(next);
  343. foreach (FieldInfo field in fields)
  344. {
  345. Type ft = field.FieldType;
  346. Type ct = typeof(EqualityComparer<>).MakeGenericType(ft);
  347. next = gen.DefineLabel();
  348. gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null);
  349. gen.Emit(OpCodes.Ldarg_0);
  350. gen.Emit(OpCodes.Ldfld, field);
  351. gen.Emit(OpCodes.Ldloc, other);
  352. gen.Emit(OpCodes.Ldfld, field);
  353. gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("Equals", new Type[] { ft, ft }), null);
  354. gen.Emit(OpCodes.Brtrue_S, next);
  355. gen.Emit(OpCodes.Ldc_I4_0);
  356. gen.Emit(OpCodes.Ret);
  357. gen.MarkLabel(next);
  358. }
  359. gen.Emit(OpCodes.Ldc_I4_1);
  360. gen.Emit(OpCodes.Ret);
  361. }
  362. void GenerateGetHashCode(TypeBuilder tb, FieldInfo[] fields)
  363. {
  364. MethodBuilder mb = tb.DefineMethod("GetHashCode",
  365. MethodAttributes.Public | MethodAttributes.ReuseSlot |
  366. MethodAttributes.Virtual | MethodAttributes.HideBySig,
  367. typeof(int), Type.EmptyTypes);
  368. ILGenerator gen = mb.GetILGenerator();
  369. gen.Emit(OpCodes.Ldc_I4_0);
  370. foreach (FieldInfo field in fields)
  371. {
  372. Type ft = field.FieldType;
  373. Type ct = typeof(EqualityComparer<>).MakeGenericType(ft);
  374. gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null);
  375. gen.Emit(OpCodes.Ldarg_0);
  376. gen.Emit(OpCodes.Ldfld, field);
  377. gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("GetHashCode", new Type[] { ft }), null);
  378. gen.Emit(OpCodes.Xor);
  379. }
  380. gen.Emit(OpCodes.Ret);
  381. }
  382. }
  383. public sealed class ParseException : Exception
  384. {
  385. int position;
  386. public ParseException(string message, int position)
  387. : base(message)
  388. {
  389. this.position = position;
  390. }
  391. public int Position
  392. {
  393. get { return position; }
  394. }
  395. public override string ToString()
  396. {
  397. return string.Format(Res.ParseExceptionFormat, Message, position);
  398. }
  399. }
  400. internal class ExpressionParser
  401. {
  402. struct Token
  403. {
  404. public TokenId id;
  405. public string text;
  406. public int pos;
  407. }
  408. enum TokenId
  409. {
  410. Unknown,
  411. End,
  412. Identifier,
  413. StringLiteral,
  414. IntegerLiteral,
  415. RealLiteral,
  416. Exclamation,
  417. Percent,
  418. Amphersand,
  419. OpenParen,
  420. CloseParen,
  421. Asterisk,
  422. Plus,
  423. Comma,
  424. Minus,
  425. Dot,
  426. Slash,
  427. Colon,
  428. LessThan,
  429. Equal,
  430. GreaterThan,
  431. Question,
  432. OpenBracket,
  433. CloseBracket,
  434. Bar,
  435. ExclamationEqual,
  436. DoubleAmphersand,
  437. LessThanEqual,
  438. LessGreater,
  439. DoubleEqual,
  440. GreaterThanEqual,
  441. DoubleBar
  442. }
  443. interface ILogicalSignatures
  444. {
  445. void F(bool x, bool y);
  446. void F(bool? x, bool? y);
  447. }
  448. interface IArithmeticSignatures
  449. {
  450. void F(int x, int y);
  451. void F(uint x, uint y);
  452. void F(long x, long y);
  453. void F(ulong x, ulong y);
  454. void F(float x, float y);
  455. void F(double x, double y);
  456. void F(decimal x, decimal y);
  457. void F(int? x, int? y);
  458. void F(uint? x, uint? y);
  459. void F(long? x, long? y);
  460. void F(ulong? x, ulong? y);
  461. void F(float? x, float? y);
  462. void F(double? x, double? y);
  463. void F(decimal? x, decimal? y);
  464. }
  465. interface IRelationalSignatures : IArithmeticSignatures
  466. {
  467. void F(string x, string y);
  468. void F(char x, char y);
  469. void F(DateTime x, DateTime y);
  470. void F(TimeSpan x, TimeSpan y);
  471. void F(char? x, char? y);
  472. void F(DateTime? x, DateTime? y);
  473. void F(TimeSpan? x, TimeSpan? y);
  474. }
  475. interface IEqualitySignatures : IRelationalSignatures
  476. {
  477. void F(bool x, bool y);
  478. void F(bool? x, bool? y);
  479. }
  480. interface IAddSignatures : IArithmeticSignatures
  481. {
  482. void F(DateTime x, TimeSpan y);
  483. void F(TimeSpan x, TimeSpan y);
  484. void F(DateTime? x, TimeSpan? y);
  485. void F(TimeSpan? x, TimeSpan? y);
  486. }
  487. interface ISubtractSignatures : IAddSignatures
  488. {
  489. void F(DateTime x, DateTime y);
  490. void F(DateTime? x, DateTime? y);
  491. }
  492. interface INegationSignatures
  493. {
  494. void F(int x);
  495. void F(long x);
  496. void F(float x);
  497. void F(double x);
  498. void F(decimal x);
  499. void F(int? x);
  500. void F(long? x);
  501. void F(float? x);
  502. void F(double? x);
  503. void F(decimal? x);
  504. }
  505. interface INotSignatures
  506. {
  507. void F(bool x);
  508. void F(bool? x);
  509. }
  510. interface IEnumerableSignatures
  511. {
  512. void Where(bool predicate);
  513. void Any();
  514. void Any(bool predicate);
  515. void All(bool predicate);
  516. void Count();
  517. void Count(bool predicate);
  518. void Min(object selector);
  519. void Max(object selector);
  520. void Sum(int selector);
  521. void Sum(int? selector);
  522. void Sum(long selector);
  523. void Sum(long? selector);
  524. void Sum(float selector);
  525. void Sum(float? selector);
  526. void Sum(double selector);
  527. void Sum(double? selector);
  528. void Sum(decimal selector);
  529. void Sum(decimal? selector);
  530. void Average(int selector);
  531. void Average(int? selector);
  532. void Average(long selector);
  533. void Average(long? selector);
  534. void Average(float selector);
  535. void Average(float? selector);
  536. void Average(double selector);
  537. void Average(double? selector);
  538. void Average(decimal selector);
  539. void Average(decimal? selector);
  540. }
  541. static readonly Type[] predefinedTypes = {
  542. typeof(Object),
  543. typeof(Boolean),
  544. typeof(Char),
  545. typeof(String),
  546. typeof(SByte),
  547. typeof(Byte),
  548. typeof(Int16),
  549. typeof(UInt16),
  550. typeof(Int32),
  551. typeof(UInt32),
  552. typeof(Int64),
  553. typeof(UInt64),
  554. typeof(Single),
  555. typeof(Double),
  556. typeof(Decimal),
  557. typeof(DateTime),
  558. typeof(TimeSpan),
  559. typeof(Guid),
  560. typeof(Math),
  561. typeof(Convert)
  562. };
  563. static readonly Expression trueLiteral = Expression.Constant(true);
  564. static readonly Expression falseLiteral = Expression.Constant(false);
  565. static readonly Expression nullLiteral = Expression.Constant(null);
  566. static readonly string keywordIt = "it";
  567. static readonly string keywordIif = "iif";
  568. static readonly string keywordNew = "new";
  569. static Dictionary<string, object> keywords;
  570. Dictionary<string, object> symbols;
  571. IDictionary<string, object> externals;
  572. Dictionary<Expression, string> literals;
  573. ParameterExpression it;
  574. string text;
  575. int textPos;
  576. int textLen;
  577. char ch;
  578. Token token;
  579. public ExpressionParser(ParameterExpression[] parameters, string expression, object[] values)
  580. {
  581. if (expression == null) throw new ArgumentNullException("expression");
  582. if (keywords == null) keywords = CreateKeywords();
  583. symbols = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  584. literals = new Dictionary<Expression, string>();
  585. if (parameters != null) ProcessParameters(parameters);
  586. if (values != null) ProcessValues(values);
  587. text = expression;
  588. textLen = text.Length;
  589. SetTextPos(0);
  590. NextToken();
  591. }
  592. void ProcessParameters(ParameterExpression[] parameters)
  593. {
  594. foreach (ParameterExpression pe in parameters)
  595. if (!String.IsNullOrEmpty(pe.Name))
  596. AddSymbol(pe.Name, pe);
  597. if (parameters.Length == 1 && String.IsNullOrEmpty(parameters[0].Name))
  598. it = parameters[0];
  599. }
  600. void ProcessValues(object[] values)
  601. {
  602. for (int i = 0; i < values.Length; i++)
  603. {
  604. object value = values[i];
  605. if (i == values.Length - 1 && value is IDictionary<string, object>)
  606. {
  607. externals = (IDictionary<string, object>)value;
  608. }
  609. else
  610. {
  611. AddSymbol("@" + i.ToString(System.Globalization.CultureInfo.InvariantCulture), value);
  612. }
  613. }
  614. }
  615. void AddSymbol(string name, object value)
  616. {
  617. if (symbols.ContainsKey(name))
  618. throw ParseError(Res.DuplicateIdentifier, name);
  619. symbols.Add(name, value);
  620. }
  621. public Expression Parse(Type resultType)
  622. {
  623. int exprPos = token.pos;
  624. Expression expr = ParseExpression();
  625. if (resultType != null)
  626. if ((expr = PromoteExpression(expr, resultType, true)) == null)
  627. throw ParseError(exprPos, Res.ExpressionTypeMismatch, GetTypeName(resultType));
  628. ValidateToken(TokenId.End, Res.SyntaxError);
  629. return expr;
  630. }
  631. #pragma warning disable 0219
  632. public IEnumerable<DynamicOrdering> ParseOrdering()
  633. {
  634. List<DynamicOrdering> orderings = new List<DynamicOrdering>();
  635. while (true)
  636. {
  637. Expression expr = ParseExpression();
  638. bool ascending = true;
  639. if (TokenIdentifierIs("asc") || TokenIdentifierIs("ascending"))
  640. {
  641. NextToken();
  642. }
  643. else if (TokenIdentifierIs("desc") || TokenIdentifierIs("descending"))
  644. {
  645. NextToken();
  646. ascending = false;
  647. }
  648. orderings.Add(new DynamicOrdering { Selector = expr, Ascending = ascending });
  649. if (token.id != TokenId.Comma) break;
  650. NextToken();
  651. }
  652. ValidateToken(TokenId.End, Res.SyntaxError);
  653. return orderings;
  654. }
  655. #pragma warning restore 0219
  656. // ?: operator
  657. Expression ParseExpression()
  658. {
  659. int errorPos = token.pos;
  660. Expression expr = ParseLogicalOr();
  661. if (token.id == TokenId.Question)
  662. {
  663. NextToken();
  664. Expression expr1 = ParseExpression();
  665. ValidateToken(TokenId.Colon, Res.ColonExpected);
  666. NextToken();
  667. Expression expr2 = ParseExpression();
  668. expr = GenerateConditional(expr, expr1, expr2, errorPos);
  669. }
  670. return expr;
  671. }
  672. // ||, or operator
  673. Expression ParseLogicalOr()
  674. {
  675. Expression left = ParseLogicalAnd();
  676. while (token.id == TokenId.DoubleBar || TokenIdentifierIs("or"))
  677. {
  678. Token op = token;
  679. NextToken();
  680. Expression right = ParseLogicalAnd();
  681. CheckAndPromoteOperands(typeof(ILogicalSignatures), op.text, ref left, ref right, op.pos);
  682. left = Expression.OrElse(left, right);
  683. }
  684. return left;
  685. }
  686. // &&, and operator
  687. Expression ParseLogicalAnd()
  688. {
  689. Expression left = ParseComparison();
  690. while (token.id == TokenId.DoubleAmphersand || TokenIdentifierIs("and"))
  691. {
  692. Token op = token;
  693. NextToken();
  694. Expression right = ParseComparison();
  695. CheckAndPromoteOperands(typeof(ILogicalSignatures), op.text, ref left, ref right, op.pos);
  696. left = Expression.AndAlso(left, right);
  697. }
  698. return left;
  699. }
  700. // =, ==, !=, <>, >, >=, <, <= operators
  701. Expression ParseComparison()
  702. {
  703. Expression left = ParseAdditive();
  704. while (token.id == TokenId.Equal || token.id == TokenId.DoubleEqual ||
  705. token.id == TokenId.ExclamationEqual || token.id == TokenId.LessGreater ||
  706. token.id == TokenId.GreaterThan || token.id == TokenId.GreaterThanEqual ||
  707. token.id == TokenId.LessThan || token.id == TokenId.LessThanEqual)
  708. {
  709. Token op = token;
  710. NextToken();
  711. Expression right = ParseAdditive();
  712. bool isEquality = op.id == TokenId.Equal || op.id == TokenId.DoubleEqual ||
  713. op.id == TokenId.ExclamationEqual || op.id == TokenId.LessGreater;
  714. //if (isEquality && !left.Type.IsValueType && !right.Type.IsValueType)
  715. //{
  716. // liudong 2011-02-08 for GUID
  717. if (isEquality && ((!left.Type.IsValueType && !right.Type.IsValueType)
  718. || (left.Type == typeof(Guid) && right.Type == typeof(Guid))))
  719. {
  720. if (left.Type != right.Type)
  721. {
  722. if (left.Type.IsAssignableFrom(right.Type))
  723. {
  724. right = Expression.Convert(right, left.Type);
  725. }
  726. else if (right.Type.IsAssignableFrom(left.Type))
  727. {
  728. left = Expression.Convert(left, right.Type);
  729. }
  730. else
  731. {
  732. throw IncompatibleOperandsError(op.text, left, right, op.pos);
  733. }
  734. }
  735. }
  736. else if (IsEnumType(left.Type) || IsEnumType(right.Type))
  737. {
  738. if (left.Type != right.Type)
  739. {
  740. Expression e;
  741. if ((e = PromoteExpression(right, left.Type, true)) != null)
  742. {
  743. right = e;
  744. }
  745. else if ((e = PromoteExpression(left, right.Type, true)) != null)
  746. {
  747. left = e;
  748. }
  749. else
  750. {
  751. throw IncompatibleOperandsError(op.text, left, right, op.pos);
  752. }
  753. }
  754. }
  755. else
  756. {
  757. CheckAndPromoteOperands(isEquality ? typeof(IEqualitySignatures) : typeof(IRelationalSignatures),
  758. op.text, ref left, ref right, op.pos);
  759. }
  760. switch (op.id)
  761. {
  762. case TokenId.Equal:
  763. case TokenId.DoubleEqual:
  764. left = GenerateEqual(left, right);
  765. break;
  766. case TokenId.ExclamationEqual:
  767. case TokenId.LessGreater:
  768. left = GenerateNotEqual(left, right);
  769. break;
  770. case TokenId.GreaterThan:
  771. left = GenerateGreaterThan(left, right);
  772. break;
  773. case TokenId.GreaterThanEqual:
  774. left = GenerateGreaterThanEqual(left, right);
  775. break;
  776. case TokenId.LessThan:
  777. left = GenerateLessThan(left, right);
  778. break;
  779. case TokenId.LessThanEqual:
  780. left = GenerateLessThanEqual(left, right);
  781. break;
  782. }
  783. }
  784. return left;
  785. }
  786. // +, -, & operators
  787. Expression ParseAdditive()
  788. {
  789. Expression left = ParseMultiplicative();
  790. while (token.id == TokenId.Plus || token.id == TokenId.Minus ||
  791. token.id == TokenId.Amphersand)
  792. {
  793. Token op = token;
  794. NextToken();
  795. Expression right = ParseMultiplicative();
  796. switch (op.id)
  797. {
  798. case TokenId.Plus:
  799. if (left.Type == typeof(string) || right.Type == typeof(string))
  800. goto case TokenId.Amphersand;
  801. CheckAndPromoteOperands(typeof(IAddSignatures), op.text, ref left, ref right, op.pos);
  802. left = GenerateAdd(left, right);
  803. break;
  804. case TokenId.Minus:
  805. CheckAndPromoteOperands(typeof(ISubtractSignatures), op.text, ref left, ref right, op.pos);
  806. left = GenerateSubtract(left, right);
  807. break;
  808. case TokenId.Amphersand:
  809. left = GenerateStringConcat(left, right);
  810. break;
  811. }
  812. }
  813. return left;
  814. }
  815. // *, /, %, mod operators
  816. Expression ParseMultiplicative()
  817. {
  818. Expression left = ParseUnary();
  819. while (token.id == TokenId.Asterisk || token.id == TokenId.Slash ||
  820. token.id == TokenId.Percent || TokenIdentifierIs("mod"))
  821. {
  822. Token op = token;
  823. NextToken();
  824. Expression right = ParseUnary();
  825. CheckAndPromoteOperands(typeof(IArithmeticSignatures), op.text, ref left, ref right, op.pos);
  826. switch (op.id)
  827. {
  828. case TokenId.Asterisk:
  829. left = Expression.Multiply(left, right);
  830. break;
  831. case TokenId.Slash:
  832. left = Expression.Divide(left, right);
  833. break;
  834. case TokenId.Percent:
  835. case TokenId.Identifier:
  836. left = Expression.Modulo(left, right);
  837. break;
  838. }
  839. }
  840. return left;
  841. }
  842. // -, !, not unary operators
  843. Expression ParseUnary()
  844. {
  845. if (token.id == TokenId.Minus || token.id == TokenId.Exclamation ||
  846. TokenIdentifierIs("not"))
  847. {
  848. Token op = token;
  849. NextToken();
  850. if (op.id == TokenId.Minus && (token.id == TokenId.IntegerLiteral ||
  851. token.id == TokenId.RealLiteral))
  852. {
  853. token.text = "-" + token.text;
  854. token.pos = op.pos;
  855. return ParsePrimary();
  856. }
  857. Expression expr = ParseUnary();
  858. if (op.id == TokenId.Minus)
  859. {
  860. CheckAndPromoteOperand(typeof(INegationSignatures), op.text, ref expr, op.pos);
  861. expr = Expression.Negate(expr);
  862. }
  863. else
  864. {
  865. CheckAndPromoteOperand(typeof(INotSignatures), op.text, ref expr, op.pos);
  866. expr = Expression.Not(expr);
  867. }
  868. return expr;
  869. }
  870. return ParsePrimary();
  871. }
  872. Expression ParsePrimary()
  873. {
  874. Expression expr = ParsePrimaryStart();
  875. while (true)
  876. {
  877. if (token.id == TokenId.Dot)
  878. {
  879. NextToken();
  880. expr = ParseMemberAccess(null, expr);
  881. }
  882. else if (token.id == TokenId.OpenBracket)
  883. {
  884. expr = ParseElementAccess(expr);
  885. }
  886. else
  887. {
  888. break;
  889. }
  890. }
  891. return expr;
  892. }
  893. Expression ParsePrimaryStart()
  894. {
  895. switch (token.id)
  896. {
  897. case TokenId.Identifier:
  898. return ParseIdentifier();
  899. case TokenId.StringLiteral:
  900. return ParseStringLiteral();
  901. case TokenId.IntegerLiteral:
  902. return ParseIntegerLiteral();
  903. case TokenId.RealLiteral:
  904. return ParseRealLiteral();
  905. case TokenId.OpenParen:
  906. return ParseParenExpression();
  907. default:
  908. throw ParseError(Res.ExpressionExpected);
  909. }
  910. }
  911. Expression ParseStringLiteral()
  912. {
  913. ValidateToken(TokenId.StringLiteral);
  914. char quote = token.text[0];
  915. string s = token.text.Substring(1, token.text.Length - 2);
  916. int start = 0;
  917. while (true)
  918. {
  919. int i = s.IndexOf(quote, start);
  920. if (i < 0) break;
  921. s = s.Remove(i, 1);
  922. start = i + 1;
  923. }
  924. if (quote == '\'')
  925. {
  926. if (s.Length != 1)
  927. throw ParseError(Res.InvalidCharacterLiteral);
  928. NextToken();
  929. return CreateLiteral(s[0], s);
  930. }
  931. NextToken();
  932. return CreateLiteral(s, s);
  933. }
  934. Expression ParseIntegerLiteral()
  935. {
  936. ValidateToken(TokenId.IntegerLiteral);
  937. string text = token.text;
  938. if (text[0] != '-')
  939. {
  940. ulong value;
  941. if (!UInt64.TryParse(text, out value))
  942. throw ParseError(Res.InvalidIntegerLiteral, text);
  943. NextToken();
  944. if (value <= (ulong)Int32.MaxValue) return CreateLiteral((int)value, text);
  945. if (value <= (ulong)UInt32.MaxValue) return CreateLiteral((uint)value, text);
  946. if (value <= (ulong)Int64.MaxValue) return CreateLiteral((long)value, text);
  947. return CreateLiteral(value, text);
  948. }
  949. else
  950. {
  951. long value;
  952. if (!Int64.TryParse(text, out value))
  953. throw ParseError(Res.InvalidIntegerLiteral, text);
  954. NextToken();
  955. if (value >= Int32.MinValue && value <= Int32.MaxValue)
  956. return CreateLiteral((int)value, text);
  957. return CreateLiteral(value, text);
  958. }
  959. }
  960. Expression ParseRealLiteral()
  961. {
  962. ValidateToken(TokenId.RealLiteral);
  963. string text = token.text;
  964. object value = null;
  965. char last = text[text.Length - 1];
  966. if (last == 'F' || last == 'f')
  967. {
  968. float f;
  969. if (Single.TryParse(text.Substring(0, text.Length - 1), out f)) value = f;
  970. }
  971. else
  972. {
  973. double d;
  974. if (Double.TryParse(text, out d)) value = d;
  975. }
  976. if (value == null) throw ParseError(Res.InvalidRealLiteral, text);
  977. NextToken();
  978. return CreateLiteral(value, text);
  979. }
  980. Expression CreateLiteral(object value, string text)
  981. {
  982. ConstantExpression expr = Expression.Constant(value);
  983. literals.Add(expr, text);
  984. return expr;
  985. }
  986. Expression ParseParenExpression()
  987. {
  988. ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
  989. NextToken();
  990. Expression e = ParseExpression();
  991. ValidateToken(TokenId.CloseParen, Res.CloseParenOrOperatorExpected);
  992. NextToken();
  993. return e;
  994. }
  995. Expression ParseIdentifier()
  996. {
  997. ValidateToken(TokenId.Identifier);
  998. object value;
  999. if (keywords.TryGetValue(token.text, out value))
  1000. {
  1001. if (value is Type) return ParseTypeAccess((Type)value);
  1002. if (value == (object)keywordIt) return ParseIt();
  1003. if (value == (object)keywordIif) return ParseIif();
  1004. if (value == (object)keywordNew) return ParseNew();
  1005. NextToken();
  1006. return (Expression)value;
  1007. }
  1008. if (symbols.TryGetValue(token.text, out value) ||
  1009. externals != null && externals.TryGetValue(token.text, out value))
  1010. {
  1011. Expression expr = value as Expression;
  1012. if (expr == null)
  1013. {
  1014. expr = Expression.Constant(value);
  1015. }
  1016. else
  1017. {
  1018. LambdaExpression lambda = expr as LambdaExpression;
  1019. if (lambda != null) return ParseLambdaInvocation(lambda);
  1020. }
  1021. NextToken();
  1022. return expr;
  1023. }
  1024. if (it != null) return ParseMemberAccess(null, it);
  1025. throw ParseError(Res.UnknownIdentifier, token.text);
  1026. }
  1027. Expression ParseIt()
  1028. {
  1029. if (it == null)
  1030. throw ParseError(Res.NoItInScope);
  1031. NextToken();
  1032. return it;
  1033. }
  1034. Expression ParseIif()
  1035. {
  1036. int errorPos = token.pos;
  1037. NextToken();
  1038. Expression[] args = ParseArgumentList();
  1039. if (args.Length != 3)
  1040. throw ParseError(errorPos, Res.IifRequiresThreeArgs);
  1041. return GenerateConditional(args[0], args[1], args[2], errorPos);
  1042. }
  1043. Expression GenerateConditional(Expression test, Expression expr1, Expression expr2, int errorPos)
  1044. {
  1045. if (test.Type != typeof(bool))
  1046. throw ParseError(errorPos, Res.FirstExprMustBeBool);
  1047. if (expr1.Type != expr2.Type)
  1048. {
  1049. Expression expr1as2 = expr2 != nullLiteral ? PromoteExpression(expr1, expr2.Type, true) : null;
  1050. Expression expr2as1 = expr1 != nullLiteral ? PromoteExpression(expr2, expr1.Type, true) : null;
  1051. if (expr1as2 != null && expr2as1 == null)
  1052. {
  1053. expr1 = expr1as2;
  1054. }
  1055. else if (expr2as1 != null && expr1as2 == null)
  1056. {
  1057. expr2 = expr2as1;
  1058. }
  1059. else
  1060. {
  1061. string type1 = expr1 != nullLiteral ? expr1.Type.Name : "null";
  1062. string type2 = expr2 != nullLiteral ? expr2.Type.Name : "null";
  1063. if (expr1as2 != null && expr2as1 != null)
  1064. throw ParseError(errorPos, Res.BothTypesConvertToOther, type1, type2);
  1065. throw ParseError(errorPos, Res.NeitherTypeConvertsToOther, type1, type2);
  1066. }
  1067. }
  1068. return Expression.Condition(test, expr1, expr2);
  1069. }
  1070. Expression ParseNew()
  1071. {
  1072. NextToken();
  1073. ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
  1074. NextToken();
  1075. List<DynamicProperty> properties = new List<DynamicProperty>();
  1076. List<Expression> expressions = new List<Expression>();
  1077. while (true)
  1078. {
  1079. int exprPos = token.pos;
  1080. Expression expr = ParseExpression();
  1081. string propName;
  1082. if (TokenIdentifierIs("as"))
  1083. {
  1084. NextToken();
  1085. propName = GetIdentifier();
  1086. NextToken();
  1087. }
  1088. else
  1089. {
  1090. MemberExpression me = expr as MemberExpression;
  1091. if (me == null) throw ParseError(exprPos, Res.MissingAsClause);
  1092. propName = me.Member.Name;
  1093. }
  1094. expressions.Add(expr);
  1095. properties.Add(new DynamicProperty(propName, expr.Type));
  1096. if (token.id != TokenId.Comma) break;
  1097. NextToken();
  1098. }
  1099. ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected);
  1100. NextToken();
  1101. Type type = DynamicExpression.CreateClass(properties);
  1102. MemberBinding[] bindings = new MemberBinding[properties.Count];
  1103. for (int i = 0; i < bindings.Length; i++)
  1104. bindings[i] = Expression.Bind(type.GetProperty(properties[i].Name), expressions[i]);
  1105. return Expression.MemberInit(Expression.New(type), bindings);
  1106. }
  1107. Expression ParseLambdaInvocation(LambdaExpression lambda)
  1108. {
  1109. int errorPos = token.pos;
  1110. NextToken();
  1111. Expression[] args = ParseArgumentList();
  1112. MethodBase method;
  1113. if (FindMethod(lambda.Type, "Invoke", false, args, out method) != 1)
  1114. throw ParseError(errorPos, Res.ArgsIncompatibleWithLambda);
  1115. return Expression.Invoke(lambda, args);
  1116. }
  1117. Expression ParseTypeAccess(Type type)
  1118. {
  1119. int errorPos = token.pos;
  1120. NextToken();
  1121. if (token.id == TokenId.Question)
  1122. {
  1123. if (!type.IsValueType || IsNullableType(type))
  1124. throw ParseError(errorPos, Res.TypeHasNoNullableForm, GetTypeName(type));
  1125. type = typeof(Nullable<>).MakeGenericType(type);
  1126. NextToken();
  1127. }
  1128. if (token.id == TokenId.OpenParen)
  1129. {
  1130. Expression[] args = ParseArgumentList();
  1131. MethodBase method;
  1132. switch (FindBestMethod(type.GetConstructors(), args, out method))
  1133. {
  1134. case 0:
  1135. if (args.Length == 1)
  1136. return GenerateConversion(args[0], type, errorPos);
  1137. throw ParseError(errorPos, Res.NoMatchingConstructor, GetTypeName(type));
  1138. case 1:
  1139. return Expression.New((ConstructorInfo)method, args);
  1140. default:
  1141. throw ParseError(errorPos, Res.AmbiguousConstructorInvocation, GetTypeName(type));
  1142. }
  1143. }
  1144. ValidateToken(TokenId.Dot, Res.DotOrOpenParenExpected);
  1145. NextToken();
  1146. return ParseMemberAccess(type, null);
  1147. }
  1148. Expression GenerateConversion(Expression expr, Type type, int errorPos)
  1149. {
  1150. Type exprType = expr.Type;
  1151. if (exprType == type) return expr;
  1152. if (exprType.IsValueType && type.IsValueType)
  1153. {
  1154. if ((IsNullableType(exprType) || IsNullableType(type)) &&
  1155. GetNonNullableType(exprType) == GetNonNullableType(type))
  1156. return Expression.Convert(expr, type);
  1157. if ((IsNumericType(exprType) || IsEnumType(exprType)) &&
  1158. (IsNumericType(type)) || IsEnumType(type))
  1159. return Expression.ConvertChecked(expr, type);
  1160. }
  1161. if (exprType.IsAssignableFrom(type) || type.IsAssignableFrom(exprType) ||
  1162. exprType.IsInterface || type.IsInterface)
  1163. return Expression.Convert(expr, type);
  1164. throw ParseError(errorPos, Res.CannotConvertValue,
  1165. GetTypeName(exprType), GetTypeName(type));
  1166. }
  1167. Expression ParseMemberAccess(Type type, Expression instance)
  1168. {
  1169. if (instance != null) type = instance.Type;
  1170. int errorPos = token.pos;
  1171. string id = GetIdentifier();
  1172. NextToken();
  1173. if (token.id == TokenId.OpenParen)
  1174. {
  1175. if (instance != null && type != typeof(string))
  1176. {
  1177. Type enumerableType = FindGenericType(typeof(IEnumerable<>), type);
  1178. if (enumerableType != null)
  1179. {
  1180. Type elementType = enumerableType.GetGenericArguments()[0];
  1181. return ParseAggregate(instance, elementType, id, errorPos);
  1182. }
  1183. }
  1184. Expression[] args = ParseArgumentList();
  1185. MethodBase mb;
  1186. switch (FindMethod(type, id, instance == null, args, out mb))
  1187. {
  1188. case 0:
  1189. throw ParseError(errorPos, Res.NoApplicableMethod,
  1190. id, GetTypeName(type));
  1191. case 1:
  1192. MethodInfo method = (MethodInfo)mb;
  1193. if (!IsPredefinedType(method.DeclaringType))
  1194. throw ParseError(errorPos, Res.MethodsAreInaccessible, GetTypeName(method.DeclaringType));
  1195. if (method.ReturnType == typeof(void))
  1196. throw ParseError(errorPos, Res.MethodIsVoid,
  1197. id, GetTypeName(method.DeclaringType));
  1198. return Expression.Call(instance, (MethodInfo)method, args);
  1199. default:
  1200. throw ParseError(errorPos, Res.AmbiguousMethodInvocation,
  1201. id, GetTypeName(type));
  1202. }
  1203. }
  1204. else
  1205. {
  1206. MemberInfo member = FindPropertyOrField(type, id, instance == null);
  1207. if (member == null)
  1208. throw ParseError(errorPos, Res.UnknownPropertyOrField,
  1209. id, GetTypeName(type));
  1210. return member is PropertyInfo ?
  1211. Expression.Property(instance, (PropertyInfo)member) :
  1212. Expression.Field(instance, (FieldInfo)member);
  1213. }
  1214. }
  1215. static Type FindGenericType(Type generic, Type type)
  1216. {
  1217. while (type != null && type != typeof(object))
  1218. {
  1219. if (type.IsGenericType && type.GetGenericTypeDefinition() == generic) return type;
  1220. if (generic.IsInterface)
  1221. {
  1222. foreach (Type intfType in type.GetInterfaces())
  1223. {
  1224. Type found = FindGenericType(generic, intfType);
  1225. if (found != null) return found;
  1226. }
  1227. }
  1228. type = type.BaseType;
  1229. }
  1230. return null;
  1231. }
  1232. Expression ParseAggregate(Expression instance, Type elementType, string methodName, int errorPos)
  1233. {
  1234. ParameterExpression outerIt = it;
  1235. ParameterExpression innerIt = Expression.Parameter(elementType, "");
  1236. it = innerIt;
  1237. Expression[] args = ParseArgumentList();
  1238. it = outerIt;
  1239. MethodBase signature;
  1240. if (FindMethod(typeof(IEnumerableSignatures), methodName, false, args, out signature) != 1)
  1241. throw ParseError(errorPos, Res.NoApplicableAggregate, methodName);
  1242. Type[] typeArgs;
  1243. if (signature.Name == "Min" || signature.Name == "Max")
  1244. {
  1245. typeArgs = new Type[] { elementType, args[0].Type };
  1246. }
  1247. else
  1248. {
  1249. typeArgs = new Type[] { elementType };
  1250. }
  1251. if (args.Length == 0)
  1252. {
  1253. args = new Expression[] { instance };
  1254. }
  1255. else
  1256. {
  1257. args = new Expression[] { instance, Expression.Lambda(args[0], innerIt) };
  1258. }
  1259. return Expression.Call(typeof(Enumerable), signature.Name, typeArgs, args);
  1260. }
  1261. Expression[] ParseArgumentList()
  1262. {
  1263. ValidateToken(TokenId.OpenParen, Res.OpenParenExpected);
  1264. NextToken();
  1265. Expression[] args = token.id != TokenId.CloseParen ? ParseArguments() : new Expression[0];
  1266. ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected);
  1267. NextToken();
  1268. return args;
  1269. }
  1270. Expression[] ParseArguments()
  1271. {
  1272. List<Expression> argList = new List<Expression>();
  1273. while (true)
  1274. {
  1275. argList.Add(ParseExpression());
  1276. if (token.id != TokenId.Comma) break;
  1277. NextToken();
  1278. }
  1279. return argList.ToArray();
  1280. }
  1281. Expression ParseElementAccess(Expression expr)
  1282. {
  1283. int errorPos = token.pos;
  1284. ValidateToken(TokenId.OpenBracket, Res.OpenParenExpected);
  1285. NextToken();
  1286. Expression[] args = ParseArguments();
  1287. ValidateToken(TokenId.CloseBracket, Res.CloseBracketOrCommaExpected);
  1288. NextToken();
  1289. if (expr.Type.IsArray)
  1290. {
  1291. if (expr.Type.GetArrayRank() != 1 || args.Length != 1)
  1292. throw ParseError(errorPos, Res.CannotIndexMultiDimArray);
  1293. Expression index = PromoteExpression(args[0], typeof(int), true);
  1294. if (index == null)
  1295. throw ParseError(errorPos, Res.InvalidIndex);
  1296. return Expression.ArrayIndex(expr, index);
  1297. }
  1298. else
  1299. {
  1300. MethodBase mb;
  1301. switch (FindIndexer(expr.Type, args, out mb))
  1302. {
  1303. case 0:
  1304. throw ParseError(errorPos, Res.NoApplicableIndexer,
  1305. GetTypeName(expr.Type));
  1306. case 1:
  1307. return Expression.Call(expr, (MethodInfo)mb, args);
  1308. default:
  1309. throw ParseError(errorPos, Res.AmbiguousIndexerInvocation,
  1310. GetTypeName(expr.Type));
  1311. }
  1312. }
  1313. }
  1314. static bool IsPredefinedType(Type type)
  1315. {
  1316. foreach (Type t in predefinedTypes) if (t == type) return true;
  1317. return false;
  1318. }
  1319. static bool IsNullableType(Type type)
  1320. {
  1321. return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
  1322. }
  1323. static Type GetNonNullableType(Type type)
  1324. {
  1325. return IsNullableType(type) ? type.GetGenericArguments()[0] : type;
  1326. }
  1327. static string GetTypeName(Type type)
  1328. {
  1329. Type baseType = GetNonNullableType(type);
  1330. string s = baseType.Name;
  1331. if (type != baseType) s += '?';
  1332. return s;
  1333. }
  1334. static bool IsNumericType(Type type)
  1335. {
  1336. return GetNumericTypeKind(type) != 0;
  1337. }
  1338. static bool IsSignedIntegralType(Type type)
  1339. {
  1340. return GetNumericTypeKind(type) == 2;
  1341. }
  1342. static bool IsUnsignedIntegralType(Type type)
  1343. {
  1344. return GetNumericTypeKind(type) == 3;
  1345. }
  1346. static int GetNumericTypeKind(Type type)
  1347. {
  1348. type = GetNonNullableType(type);
  1349. if (type.IsEnum) return 0;
  1350. switch (Type.GetTypeCode(type))
  1351. {
  1352. case TypeCode.Char:
  1353. case TypeCode.Single:
  1354. case TypeCode.Double:
  1355. case TypeCode.Decimal:
  1356. return 1;
  1357. case TypeCode.SByte:
  1358. case TypeCode.Int16:
  1359. case TypeCode.Int32:
  1360. case TypeCode.Int64:
  1361. return 2;
  1362. case TypeCode.Byte:
  1363. case TypeCode.UInt16:
  1364. case TypeCode.UInt32:
  1365. case TypeCode.UInt64:
  1366. return 3;
  1367. default:
  1368. return 0;
  1369. }
  1370. }
  1371. static bool IsEnumType(Type type)
  1372. {
  1373. return GetNonNullableType(type).IsEnum;
  1374. }
  1375. void CheckAndPromoteOperand(Type signatures, string opName, ref Expression expr, int errorPos)
  1376. {
  1377. Expression[] args = new Expression[] { expr };
  1378. MethodBase method;
  1379. if (FindMethod(signatures, "F", false, args, out method) != 1)
  1380. throw ParseError(errorPos, Res.IncompatibleOperand,
  1381. opName, GetTypeName(args[0].Type));
  1382. expr = args[0];
  1383. }
  1384. void CheckAndPromoteOperands(Type signatures, string opName, ref Expression left, ref Expression right, int errorPos)
  1385. {
  1386. Expression[] args = new Expression[] { left, right };
  1387. MethodBase method;
  1388. if (FindMethod(signatures, "F", false, args, out method) != 1)
  1389. throw IncompatibleOperandsError(opName, left, right, errorPos);
  1390. left = args[0];
  1391. right = args[1];
  1392. }
  1393. Exception IncompatibleOperandsError(string opName, Expression left, Expression right, int pos)
  1394. {
  1395. return ParseError(pos, Res.IncompatibleOperands,
  1396. opName, GetTypeName(left.Type), GetTypeName(right.Type));
  1397. }
  1398. MemberInfo FindPropertyOrField(Type type, string memberName, bool staticAccess)
  1399. {
  1400. BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly |
  1401. (staticAccess ? BindingFlags.Static : BindingFlags.Instance);
  1402. foreach (Type t in SelfAndBaseTypes(type))
  1403. {
  1404. MemberInfo[] members = t.FindMembers(MemberTypes.Property | MemberTypes.Field,
  1405. flags, Type.FilterNameIgnoreCase, memberName);
  1406. if (members.Length != 0) return members[0];
  1407. }
  1408. return null;
  1409. }
  1410. int FindMethod(Type type, string methodName, bool staticAccess, Expression[] args, out MethodBase method)
  1411. {
  1412. BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly |
  1413. (staticAccess ? BindingFlags.Static : BindingFlags.Instance);
  1414. foreach (Type t in SelfAndBaseTypes(type))
  1415. {
  1416. MemberInfo[] members = t.FindMembers(MemberTypes.Method,
  1417. flags, Type.FilterNameIgnoreCase, methodName);
  1418. int count = FindBestMethod(members.Cast<MethodBase>(), args, out method);
  1419. if (count != 0) return count;
  1420. }
  1421. method = null;
  1422. return 0;
  1423. }
  1424. int FindIndexer(Type type, Expression[] args, out MethodBase method)
  1425. {
  1426. foreach (Type t in SelfAndBaseTypes(type))
  1427. {
  1428. MemberInfo[] members = t.GetDefaultMembers();
  1429. if (members.Length != 0)
  1430. {
  1431. IEnumerable<MethodBase> methods = members.
  1432. OfType<PropertyInfo>().
  1433. Select(p => (MethodBase)p.GetGetMethod()).
  1434. Where(m => m != null);
  1435. int count = FindBestMethod(methods, args, out method);
  1436. if (count != 0) return count;
  1437. }
  1438. }
  1439. method = null;
  1440. return 0;
  1441. }
  1442. static IEnumerable<Type> SelfAndBaseTypes(Type type)
  1443. {
  1444. if (type.IsInterface)
  1445. {
  1446. List<Type> types = new List<Type>();
  1447. AddInterface(types, type);
  1448. return types;
  1449. }
  1450. return SelfAndBaseClasses(type);
  1451. }
  1452. static IEnumerable<Type> SelfAndBaseClasses(Type type)
  1453. {
  1454. while (type != null)
  1455. {
  1456. yield return type;
  1457. type = type.BaseType;
  1458. }
  1459. }
  1460. static void AddInterface(List<Type> types, Type type)
  1461. {
  1462. if (!types.Contains(type))
  1463. {
  1464. types.Add(type);
  1465. foreach (Type t in type.GetInterfaces()) AddInterface(types, t);
  1466. }
  1467. }
  1468. class MethodData
  1469. {
  1470. public MethodBase MethodBase;
  1471. public ParameterInfo[] Parameters;
  1472. public Expression[] Args;
  1473. }
  1474. int FindBestMethod(IEnumerable<MethodBase> methods, Expression[] args, out MethodBase method)
  1475. {
  1476. MethodData[] applicable = methods.
  1477. Select(m => new MethodData { MethodBase = m, Parameters = m.GetParameters() }).
  1478. Where(m => IsApplicable(m, args)).
  1479. ToArray();
  1480. if (applicable.Length > 1)
  1481. {
  1482. applicable = applicable.
  1483. Where(m => applicable.All(n => m == n || IsBetterThan(args, m, n))).
  1484. ToArray();
  1485. }
  1486. if (applicable.Length == 1)
  1487. {
  1488. MethodData md = applicable[0];
  1489. for (int i = 0; i < args.Length; i++) args[i] = md.Args[i];
  1490. method = md.MethodBase;
  1491. }
  1492. else
  1493. {
  1494. method = null;
  1495. }
  1496. return applicable.Length;
  1497. }
  1498. bool IsApplicable(MethodData method, Expression[] args)
  1499. {
  1500. if (method.Parameters.Length != args.Length) return false;
  1501. Expression[] promotedArgs = new Expression[args.Length];
  1502. for (int i = 0; i < args.Length; i++)
  1503. {
  1504. ParameterInfo pi = method.Parameters[i];
  1505. if (pi.IsOut) return false;
  1506. Expression promoted = PromoteExpression(args[i], pi.ParameterType, false);
  1507. if (promoted == null) return false;
  1508. promotedArgs[i] = promoted;
  1509. }
  1510. method.Args = promotedArgs;
  1511. return true;
  1512. }
  1513. Expression PromoteExpression(Expression expr, Type type, bool exact)
  1514. {
  1515. if (expr.Type == type) return expr;
  1516. if (expr is ConstantExpression)
  1517. {
  1518. ConstantExpression ce = (ConstantExpression)expr;
  1519. if (ce == nullLiteral)
  1520. {
  1521. if (!type.IsValueType || IsNullableType(type))
  1522. return Expression.Constant(null, type);
  1523. }
  1524. else
  1525. {
  1526. string text;
  1527. if (literals.TryGetValue(ce, out text))
  1528. {
  1529. Type target = GetNonNullableType(type);
  1530. Object value = null;
  1531. switch (Type.GetTypeCode(ce.Type))
  1532. {
  1533. case TypeCode.Int32:
  1534. case TypeCode.UInt32:
  1535. case TypeCode.Int64:
  1536. case TypeCode.UInt64:
  1537. value = ParseNumber(text, target);
  1538. break;
  1539. case TypeCode.Double:
  1540. if (target == typeof(decimal)) value = ParseNumber(text, target);
  1541. break;
  1542. case TypeCode.String:
  1543. value = ParseEnum(text, target);
  1544. break;
  1545. }
  1546. if (value != null)
  1547. return Expression.Constant(value, type);
  1548. }
  1549. }
  1550. }
  1551. if (IsCompatibleWith(expr.Type, type))
  1552. {
  1553. if (type.IsValueType || exact) return Expression.Convert(expr, type);
  1554. return expr;
  1555. }
  1556. return null;
  1557. }
  1558. static object ParseNumber(string text, Type type)
  1559. {
  1560. switch (Type.GetTypeCode(GetNonNullableType(type)))
  1561. {
  1562. case TypeCode.SByte:
  1563. sbyte sb;
  1564. if (sbyte.TryParse(text, out sb)) return sb;
  1565. break;
  1566. case TypeCode.Byte:
  1567. byte b;
  1568. if (byte.TryParse(text, out b)) return b;
  1569. break;
  1570. case TypeCode.Int16:
  1571. short s;
  1572. if (short.TryParse(text, out s)) return s;
  1573. break;
  1574. case TypeCode.UInt16:
  1575. ushort us;
  1576. if (ushort.TryParse(text, out us)) return us;
  1577. break;
  1578. case TypeCode.Int32:
  1579. int i;
  1580. if (int.TryParse(text, out i)) return i;
  1581. break;
  1582. case TypeCode.UInt32:
  1583. uint ui;
  1584. if (uint.TryParse(text, out ui)) return ui;
  1585. break;
  1586. case TypeCode.Int64:
  1587. long l;
  1588. if (long.TryParse(text, out l)) return l;
  1589. break;
  1590. case TypeCode.UInt64:
  1591. ulong ul;
  1592. if (ulong.TryParse(text, out ul)) return ul;
  1593. break;
  1594. case TypeCode.Single:
  1595. float f;
  1596. if (float.TryParse(text, out f)) return f;
  1597. break;
  1598. case TypeCode.Double:
  1599. double d;
  1600. if (double.TryParse(text, out d)) return d;
  1601. break;
  1602. case TypeCode.Decimal:
  1603. decimal e;
  1604. if (decimal.TryParse(text, out e)) return e;
  1605. break;
  1606. }
  1607. return null;
  1608. }
  1609. static object ParseEnum(string name, Type type)
  1610. {
  1611. if (type.IsEnum)
  1612. {
  1613. MemberInfo[] memberInfos = type.FindMembers(MemberTypes.Field,
  1614. BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static,
  1615. Type.FilterNameIgnoreCase, name);
  1616. if (memberInfos.Length != 0) return ((FieldInfo)memberInfos[0]).GetValue(null);
  1617. }
  1618. return null;
  1619. }
  1620. static bool IsCompatibleWith(Type source, Type target)
  1621. {
  1622. if (source == target) return true;
  1623. if (!target.IsValueType) return target.IsAssignableFrom(source);
  1624. Type st = GetNonNullableType(source);
  1625. Type tt = GetNonNullableType(target);
  1626. if (st != source && tt == target) return false;
  1627. TypeCode sc = st.IsEnum ? TypeCode.Object : Type.GetTypeCode(st);
  1628. TypeCode tc = tt.IsEnum ? TypeCode.Object : Type.GetTypeCode(tt);
  1629. switch (sc)
  1630. {
  1631. case TypeCode.SByte:
  1632. switch (tc)
  1633. {
  1634. case TypeCode.SByte:
  1635. case TypeCode.Int16:
  1636. case TypeCode.Int32:
  1637. case TypeCode.Int64:
  1638. case TypeCode.Single:
  1639. case TypeCode.Double:
  1640. case TypeCode.Decimal:
  1641. return true;
  1642. }
  1643. break;
  1644. case TypeCode.Byte:
  1645. switch (tc)
  1646. {
  1647. case TypeCode.Byte:
  1648. case TypeCode.Int16:
  1649. case TypeCode.UInt16:
  1650. case TypeCode.Int32:
  1651. case TypeCode.UInt32:
  1652. case TypeCode.Int64:
  1653. case TypeCode.UInt64:
  1654. case TypeCode.Single:
  1655. case TypeCode.Double:
  1656. case TypeCode.Decimal:
  1657. return true;
  1658. }
  1659. break;
  1660. case TypeCode.Int16:
  1661. switch (tc)
  1662. {
  1663. case TypeCode.Int16:
  1664. case TypeCode.Int32:
  1665. case TypeCode.Int64:
  1666. case TypeCode.Single:
  1667. case TypeCode.Double:
  1668. case TypeCode.Decimal:
  1669. return true;
  1670. }
  1671. break;
  1672. case TypeCode.UInt16:
  1673. switch (tc)
  1674. {
  1675. case TypeCode.UInt16:
  1676. case TypeCode.Int32:
  1677. case TypeCode.UInt32:
  1678. case TypeCode.Int64:
  1679. case TypeCode.UInt64:
  1680. case TypeCode.Single:
  1681. case TypeCode.Double:
  1682. case TypeCode.Decimal:
  1683. return true;
  1684. }
  1685. break;
  1686. case TypeCode.Int32:
  1687. switch (tc)
  1688. {
  1689. case TypeCode.Int32:
  1690. case TypeCode.Int64:
  1691. case TypeCode.Single:
  1692. case TypeCode.Double:
  1693. case TypeCode.Decimal:
  1694. return true;
  1695. }
  1696. break;
  1697. case TypeCode.UInt32:
  1698. switch (tc)
  1699. {
  1700. case TypeCode.UInt32:
  1701. case TypeCode.Int64:
  1702. case TypeCode.UInt64:
  1703. case TypeCode.Single:
  1704. case TypeCode.Double:
  1705. case TypeCode.Decimal:
  1706. return true;
  1707. }
  1708. break;
  1709. case TypeCode.Int64:
  1710. switch (tc)
  1711. {
  1712. case TypeCode.Int64:
  1713. case TypeCode.Single:
  1714. case TypeCode.Double:
  1715. case TypeCode.Decimal:
  1716. return true;
  1717. }
  1718. break;
  1719. case TypeCode.UInt64:
  1720. switch (tc)
  1721. {
  1722. case TypeCode.UInt64:
  1723. case TypeCode.Single:
  1724. case TypeCode.Double:
  1725. case TypeCode.Decimal:
  1726. return true;
  1727. }
  1728. break;
  1729. case TypeCode.Single:
  1730. switch (tc)
  1731. {
  1732. case TypeCode.Single:
  1733. case TypeCode.Double:
  1734. return true;
  1735. }
  1736. break;
  1737. default:
  1738. if (st == tt) return true;
  1739. break;
  1740. }
  1741. return false;
  1742. }
  1743. static bool IsBetterThan(Expression[] args, MethodData m1, MethodData m2)
  1744. {
  1745. bool better = false;
  1746. for (int i = 0; i < args.Length; i++)
  1747. {
  1748. int c = CompareConversions(args[i].Type,
  1749. m1.Parameters[i].ParameterType,
  1750. m2.Parameters[i].ParameterType);
  1751. if (c < 0) return false;
  1752. if (c > 0) better = true;
  1753. }
  1754. return better;
  1755. }
  1756. // Return 1 if s -> t1 is a better conversion than s -> t2
  1757. // Return -1 if s -> t2 is a better conversion than s -> t1
  1758. // Return 0 if neither conversion is better
  1759. static int CompareConversions(Type s, Type t1, Type t2)
  1760. {
  1761. if (t1 == t2) return 0;
  1762. if (s == t1) return 1;
  1763. if (s == t2) return -1;
  1764. bool t1t2 = IsCompatibleWith(t1, t2);
  1765. bool t2t1 = IsCompatibleWith(t2, t1);
  1766. if (t1t2 && !t2t1) return 1;
  1767. if (t2t1 && !t1t2) return -1;
  1768. if (IsSignedIntegralType(t1) && IsUnsignedIntegralType(t2)) return 1;
  1769. if (IsSignedIntegralType(t2) && IsUnsignedIntegralType(t1)) return -1;
  1770. return 0;
  1771. }
  1772. Expression GenerateEqual(Expression left, Expression right)
  1773. {
  1774. return Expression.Equal(left, right);
  1775. }
  1776. Expression GenerateNotEqual(Expression left, Expression right)
  1777. {
  1778. return Expression.NotEqual(left, right);
  1779. }
  1780. Expression GenerateGreaterThan(Expression left, Expression right)
  1781. {
  1782. if (left.Type == typeof(string))
  1783. {
  1784. return Expression.GreaterThan(
  1785. GenerateStaticMethodCall("Compare", left, right),
  1786. Expression.Constant(0)
  1787. );
  1788. }
  1789. return Expression.GreaterThan(left, right);
  1790. }
  1791. Expression GenerateGreaterThanEqual(Expression left, Expression right)
  1792. {
  1793. if (left.Type == typeof(string))
  1794. {
  1795. return Expression.GreaterThanOrEqual(
  1796. GenerateStaticMethodCall("Compare", left, right),
  1797. Expression.Constant(0)
  1798. );
  1799. }
  1800. return Expression.GreaterThanOrEqual(left, right);
  1801. }
  1802. Expression GenerateLessThan(Expression left, Expression right)
  1803. {
  1804. if (left.Type == typeof(string))
  1805. {
  1806. return Expression.LessThan(
  1807. GenerateStaticMethodCall("Compare", left, right),
  1808. Expression.Constant(0)
  1809. );
  1810. }
  1811. return Expression.LessThan(left, right);
  1812. }
  1813. Expression GenerateLessThanEqual(Expression left, Expression right)
  1814. {
  1815. if (left.Type == typeof(string))
  1816. {
  1817. return Expression.LessThanOrEqual(
  1818. GenerateStaticMethodCall("Compare", left, right),
  1819. Expression.Constant(0)
  1820. );
  1821. }
  1822. return Expression.LessThanOrEqual(left, right);
  1823. }
  1824. Expression GenerateAdd(Expression left, Expression right)
  1825. {
  1826. if (left.Type == typeof(string) && right.Type == typeof(string))
  1827. {
  1828. return GenerateStaticMethodCall("Concat", left, right);
  1829. }
  1830. return Expression.Add(left, right);
  1831. }
  1832. Expression GenerateSubtract(Expression left, Expression right)
  1833. {
  1834. return Expression.Subtract(left, right);
  1835. }
  1836. Expression GenerateStringConcat(Expression left, Expression right)
  1837. {
  1838. return Expression.Call(
  1839. null,
  1840. typeof(string).GetMethod("Concat", new[] { typeof(object), typeof(object) }),
  1841. new[] { left, right });
  1842. }
  1843. MethodInfo GetStaticMethod(string methodName, Expression left, Expression right)
  1844. {
  1845. return left.Type.GetMethod(methodName, new[] { left.Type, right.Type });
  1846. }
  1847. Expression GenerateStaticMethodCall(string methodName, Expression left, Expression right)
  1848. {
  1849. return Expression.Call(null, GetStaticMethod(methodName, left, right), new[] { left, right });
  1850. }
  1851. void SetTextPos(int pos)
  1852. {
  1853. textPos = pos;
  1854. ch = textPos < textLen ? text[textPos] : '\0';
  1855. }
  1856. void NextChar()
  1857. {
  1858. if (textPos < textLen) textPos++;
  1859. ch = textPos < textLen ? text[textPos] : '\0';
  1860. }
  1861. void NextToken()
  1862. {
  1863. while (Char.IsWhiteSpace(ch)) NextChar();
  1864. TokenId t;
  1865. int tokenPos = textPos;
  1866. switch (ch)
  1867. {
  1868. case '!':
  1869. NextChar();
  1870. if (ch == '=')
  1871. {
  1872. NextChar();
  1873. t = TokenId.ExclamationEqual;
  1874. }
  1875. else
  1876. {
  1877. t = TokenId.Exclamation;
  1878. }
  1879. break;
  1880. case '%':
  1881. NextChar();
  1882. t = TokenId.Percent;
  1883. break;
  1884. case '&':
  1885. NextChar();
  1886. if (ch == '&')
  1887. {
  1888. NextChar();
  1889. t = TokenId.DoubleAmphersand;
  1890. }
  1891. else
  1892. {
  1893. t = TokenId.Amphersand;
  1894. }
  1895. break;
  1896. case '(':
  1897. NextChar();
  1898. t = TokenId.OpenParen;
  1899. break;
  1900. case ')':
  1901. NextChar();
  1902. t = TokenId.CloseParen;
  1903. break;
  1904. case '*':
  1905. NextChar();
  1906. t = TokenId.Asterisk;
  1907. break;
  1908. case '+':
  1909. NextChar();
  1910. t = TokenId.Plus;
  1911. break;
  1912. case ',':
  1913. NextChar();
  1914. t = TokenId.Comma;
  1915. break;
  1916. case '-':
  1917. NextChar();
  1918. t = TokenId.Minus;
  1919. break;
  1920. case '.':
  1921. NextChar();
  1922. t = TokenId.Dot;
  1923. break;
  1924. case '/':
  1925. NextChar();
  1926. t = TokenId.Slash;
  1927. break;
  1928. case ':':
  1929. NextChar();
  1930. t = TokenId.Colon;
  1931. break;
  1932. case '<':
  1933. NextChar();
  1934. if (ch == '=')
  1935. {
  1936. NextChar();
  1937. t = TokenId.LessThanEqual;
  1938. }
  1939. else if (ch == '>')
  1940. {
  1941. NextChar();
  1942. t = TokenId.LessGreater;
  1943. }
  1944. else
  1945. {
  1946. t = TokenId.LessThan;
  1947. }
  1948. break;
  1949. case '=':
  1950. NextChar();
  1951. if (ch == '=')
  1952. {
  1953. NextChar();
  1954. t = TokenId.DoubleEqual;
  1955. }
  1956. else
  1957. {
  1958. t = TokenId.Equal;
  1959. }
  1960. break;
  1961. case '>':
  1962. NextChar();
  1963. if (ch == '=')
  1964. {
  1965. NextChar();
  1966. t = TokenId.GreaterThanEqual;
  1967. }
  1968. else
  1969. {
  1970. t = TokenId.GreaterThan;
  1971. }
  1972. break;
  1973. case '?':
  1974. NextChar();
  1975. t = TokenId.Question;
  1976. break;
  1977. case '[':
  1978. NextChar();
  1979. t = TokenId.OpenBracket;
  1980. break;
  1981. case ']':
  1982. NextChar();
  1983. t = TokenId.CloseBracket;
  1984. break;
  1985. case '|':
  1986. NextChar();
  1987. if (ch == '|')
  1988. {
  1989. NextChar();
  1990. t = TokenId.DoubleBar;
  1991. }
  1992. else
  1993. {
  1994. t = TokenId.Bar;
  1995. }
  1996. break;
  1997. case '"':
  1998. case '\'':
  1999. char quote = ch;
  2000. do
  2001. {
  2002. NextChar();
  2003. while (textPos < textLen && ch != quote) NextChar();
  2004. if (textPos == textLen)
  2005. throw ParseError(textPos, Res.UnterminatedStringLiteral);
  2006. NextChar();
  2007. } while (ch == quote);
  2008. t = TokenId.StringLiteral;
  2009. break;
  2010. default:
  2011. if (Char.IsLetter(ch) || ch == '@' || ch == '_')
  2012. {
  2013. do
  2014. {
  2015. NextChar();
  2016. } while (Char.IsLetterOrDigit(ch) || ch == '_');
  2017. t = TokenId.Identifier;
  2018. break;
  2019. }
  2020. if (Char.IsDigit(ch))
  2021. {
  2022. t = TokenId.IntegerLiteral;
  2023. do
  2024. {
  2025. NextChar();
  2026. } while (Char.IsDigit(ch));
  2027. if (ch == '.')
  2028. {
  2029. t = TokenId.RealLiteral;
  2030. NextChar();
  2031. ValidateDigit();
  2032. do
  2033. {
  2034. NextChar();
  2035. } while (Char.IsDigit(ch));
  2036. }
  2037. if (ch == 'E' || ch == 'e')
  2038. {
  2039. t = TokenId.RealLiteral;
  2040. NextChar();
  2041. if (ch == '+' || ch == '-') NextChar();
  2042. ValidateDigit();
  2043. do
  2044. {
  2045. NextChar();
  2046. } while (Char.IsDigit(ch));
  2047. }
  2048. if (ch == 'F' || ch == 'f') NextChar();
  2049. break;
  2050. }
  2051. if (textPos == textLen)
  2052. {
  2053. t = TokenId.End;
  2054. break;
  2055. }
  2056. throw ParseError(textPos, Res.InvalidCharacter, ch);
  2057. }
  2058. token.id = t;
  2059. token.text = text.Substring(tokenPos, textPos - tokenPos);
  2060. token.pos = tokenPos;
  2061. }
  2062. bool TokenIdentifierIs(string id)
  2063. {
  2064. return token.id == TokenId.Identifier && String.Equals(id, token.text, StringComparison.OrdinalIgnoreCase);
  2065. }
  2066. string GetIdentifier()
  2067. {
  2068. ValidateToken(TokenId.Identifier, Res.IdentifierExpected);
  2069. string id = token.text;
  2070. if (id.Length > 1 && id[0] == '@') id = id.Substring(1);
  2071. return id;
  2072. }
  2073. void ValidateDigit()
  2074. {
  2075. if (!Char.IsDigit(ch)) throw ParseError(textPos, Res.DigitExpected);
  2076. }
  2077. void ValidateToken(TokenId t, string errorMessage)
  2078. {
  2079. if (token.id != t) throw ParseError(errorMessage);
  2080. }
  2081. void ValidateToken(TokenId t)
  2082. {
  2083. if (token.id != t) throw ParseError(Res.SyntaxError);
  2084. }
  2085. Exception ParseError(string format, params object[] args)
  2086. {
  2087. return ParseError(token.pos, format, args);
  2088. }
  2089. Exception ParseError(int pos, string format, params object[] args)
  2090. {
  2091. return new ParseException(string.Format(System.Globalization.CultureInfo.CurrentCulture, format, args), pos);
  2092. }
  2093. static Dictionary<string, object> CreateKeywords()
  2094. {
  2095. Dictionary<string, object> d = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
  2096. d.Add("true", trueLiteral);
  2097. d.Add("false", falseLiteral);
  2098. d.Add("null", nullLiteral);
  2099. d.Add(keywordIt, keywordIt);
  2100. d.Add(keywordIif, keywordIif);
  2101. d.Add(keywordNew, keywordNew);
  2102. foreach (Type type in predefinedTypes) d.Add(type.Name, type);
  2103. return d;
  2104. }
  2105. }
  2106. static class Res
  2107. {
  2108. public const string DuplicateIdentifier = "The identifier '{0}' was defined more than once";
  2109. public const string ExpressionTypeMismatch = "Expression of type '{0}' expected";
  2110. public const string ExpressionExpected = "Expression expected";
  2111. public const string InvalidCharacterLiteral = "Character literal must contain exactly one character";
  2112. public const string InvalidIntegerLiteral = "Invalid integer literal '{0}'";
  2113. public const string InvalidRealLiteral = "Invalid real literal '{0}'";
  2114. public const string UnknownIdentifier = "Unknown identifier '{0}'";
  2115. public const string NoItInScope = "No 'it' is in scope";
  2116. public const string IifRequiresThreeArgs = "The 'iif' function requires three arguments";
  2117. public const string FirstExprMustBeBool = "The first expression must be of type 'Boolean'";
  2118. public const string BothTypesConvertToOther = "Both of the types '{0}' and '{1}' convert to the other";
  2119. public const string NeitherTypeConvertsToOther = "Neither of the types '{0}' and '{1}' converts to the other";
  2120. public const string MissingAsClause = "Expression is missing an 'as' clause";
  2121. public const string ArgsIncompatibleWithLambda = "Argument list incompatible with lambda expression";
  2122. public const string TypeHasNoNullableForm = "Type '{0}' has no nullable form";
  2123. public const string NoMatchingConstructor = "No matching constructor in type '{0}'";
  2124. public const string AmbiguousConstructorInvocation = "Ambiguous invocation of '{0}' constructor";
  2125. public const string CannotConvertValue = "A value of type '{0}' cannot be converted to type '{1}'";
  2126. public const string NoApplicableMethod = "No applicable method '{0}' exists in type '{1}'";
  2127. public const string MethodsAreInaccessible = "Methods on type '{0}' are not accessible";
  2128. public const string MethodIsVoid = "Method '{0}' in type '{1}' does not return a value";
  2129. public const string AmbiguousMethodInvocation = "Ambiguous invocation of method '{0}' in type '{1}'";
  2130. public const string UnknownPropertyOrField = "No property or field '{0}' exists in type '{1}'";
  2131. public const string NoApplicableAggregate = "No applicable aggregate method '{0}' exists";
  2132. public const string CannotIndexMultiDimArray = "Indexing of multi-dimensional arrays is not supported";
  2133. public const string InvalidIndex = "Array index must be an integer expression";
  2134. public const string NoApplicableIndexer = "No applicable indexer exists in type '{0}'";
  2135. public const string AmbiguousIndexerInvocation = "Ambiguous invocation of indexer in type '{0}'";
  2136. public const string IncompatibleOperand = "Operator '{0}' incompatible with operand type '{1}'";
  2137. public const string IncompatibleOperands = "Operator '{0}' incompatible with operand types '{1}' and '{2}'";
  2138. public const string UnterminatedStringLiteral = "Unterminated string literal";
  2139. public const string InvalidCharacter = "Syntax error '{0}'";
  2140. public const string DigitExpected = "Digit expected";
  2141. public const string SyntaxError = "Syntax error";
  2142. public const string TokenExpected = "{0} expected";
  2143. public const string ParseExceptionFormat = "{0} (at index {1})";
  2144. public const string ColonExpected = "':' expected";
  2145. public const string OpenParenExpected = "'(' expected";
  2146. public const string CloseParenOrOperatorExpected = "')' or operator expected";
  2147. public const string CloseParenOrCommaExpected = "')' or ',' expected";
  2148. public const string DotOrOpenParenExpected = "'.' or '(' expected";
  2149. public const string OpenBracketExpected = "'[' expected";
  2150. public const string CloseBracketOrCommaExpected = "']' or ',' expected";
  2151. public const string IdentifierExpected = "Identifier expected";
  2152. }
  2153. }