MathExpress.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. using Microsoft.CodeAnalysis;
  2. using Microsoft.CodeAnalysis.CSharp;
  3. using Microsoft.CodeAnalysis.Emit;
  4. using System;
  5. using System.CodeDom.Compiler;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Runtime.Loader;
  11. using System.Text;
  12. namespace MathConsoleApp
  13. {
  14. /// <summary>
  15. /// 本类用来将字符串转为可执行文本并执行
  16. /// </summary>
  17. public class MyEvaluator
  18. {
  19. #region 构造函数
  20. /// <summary>
  21. /// 可执行串的构造函数
  22. /// </summary>
  23. /// <param name="items">
  24. /// 可执行字符串数组
  25. /// </param>
  26. public MyEvaluator(EvaluatorItem[] items)
  27. {
  28. ConstructEvaluator(items); //调用解析字符串构造函数进行解析
  29. }
  30. /// <summary>
  31. /// 可执行串的构造函数
  32. /// </summary>
  33. /// <param name="returnType">返回值类型</param>
  34. /// <param name="expression">执行表达式</param>
  35. /// <param name="name">执行字符串名称</param>
  36. public MyEvaluator(Type returnType, string expression, string name)
  37. {
  38. //创建可执行字符串数组
  39. EvaluatorItem[] items = { new EvaluatorItem(returnType, expression, name) };
  40. ConstructEvaluator(items); //调用解析字符串构造函数进行解析
  41. }
  42. /// <summary>
  43. /// 可执行串的构造函数
  44. /// </summary>
  45. /// <param name="item">可执行字符串项</param>
  46. public MyEvaluator(EvaluatorItem item)
  47. {
  48. EvaluatorItem[] items = { item };//将可执行字符串项转为可执行字符串项数组
  49. ConstructEvaluator(items); //调用解析字符串构造函数进行解析
  50. }
  51. /// <summary>
  52. /// 解析字符串构造函数
  53. /// </summary>
  54. /// <param name="items">待解析字符串数组</param>
  55. private void ConstructEvaluator_net46(EvaluatorItem[] items)
  56. {
  57. string sysFile = typeof(Enumerable).Assembly.Location;
  58. string sysDir = Directory.GetParent(sysFile).FullName;
  59. //创建C#编译器实例
  60. CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
  61. //CodeDomProvider provider = new CSharpCodeProvider();
  62. //过时了
  63. //ICodeCompiler comp = provider.CreateCompiler();
  64. //编译器的传入参数
  65. CompilerParameters cp = new CompilerParameters();
  66. cp.ReferencedAssemblies.Add(Path.Combine(sysDir, "System.dll")); //添加程序集 system.dll 的引用
  67. cp.ReferencedAssemblies.Add(Path.Combine(sysDir, "System.Data.dll")); //添加程序集 system.data.dll 的引用
  68. cp.ReferencedAssemblies.Add(Path.Combine(sysDir, "System.Xml.dll")); //添加程序集 system.xml.dll 的引用
  69. cp.GenerateExecutable = false; //不生成可执行文件
  70. cp.GenerateInMemory = true; //在内存中运行
  71. StringBuilder code = new StringBuilder(); //创建代码串
  72. /*
  73. * 添加常见且必须的引用字符串
  74. */
  75. code.Append("using System; \n");
  76. code.Append("using System.Data; \n");
  77. code.Append("using System.Data.SqlClient; \n");
  78. code.Append("using System.Data.OleDb; \n");
  79. code.Append("using System.Xml; \n");
  80. code.Append("namespace SSEC.Math { \n"); //生成代码的命名空间为EvalGuy,和本代码一样
  81. code.Append(" public class _Evaluator { \n"); //产生 _Evaluator 类,所有可执行代码均在此类中运行
  82. foreach (EvaluatorItem item in items) //遍历每一个可执行字符串项
  83. {
  84. code.AppendFormat(" public {0} {1}() ", //添加定义公共函数代码
  85. item.ReturnType.Name, //函数返回值为可执行字符串项中定义的返回值类型
  86. item.Name); //函数名称为可执行字符串项中定义的执行字符串名称
  87. code.Append("{ "); //添加函数开始括号
  88. code.AppendFormat("return ({0});", item.Expression);//添加函数体,返回可执行字符串项中定义的表达式的值
  89. code.Append("} \n"); //添加函数结束括号
  90. }
  91. code.Append("} }"); //添加类结束和命名空间结束括号
  92. //得到编译器实例的返回结果
  93. CompilerResults cr = provider.CompileAssemblyFromSource(cp, code.ToString());//comp
  94. if (cr.Errors.HasErrors) //如果有错误
  95. {
  96. StringBuilder error = new StringBuilder(); //创建错误信息字符串
  97. error.Append("编译有错误的表达式: "); //添加错误文本
  98. foreach (CompilerError err in cr.Errors) //遍历每一个出现的编译错误
  99. {
  100. error.AppendFormat("{0}\n", err.ErrorText); //添加进错误文本,每个错误后换行
  101. }
  102. throw new Exception("编译错误: " + error.ToString());//抛出异常
  103. }
  104. Assembly a = cr.CompiledAssembly; //获取编译器实例的程序集
  105. _Compiled = a.CreateInstance("SSEC.Math._Evaluator"); //通过程序集查找并声明 SSEC.Math._Evaluator 的实例
  106. }
  107. /// <summary>
  108. /// 解析字符串构造函数
  109. /// </summary>
  110. /// <param name="items">待解析字符串数组</param>
  111. private void ConstructEvaluator(EvaluatorItem[] items)
  112. {
  113. string sysFile = typeof(Enumerable).Assembly.Location;
  114. string sysDir = Directory.GetParent(sysFile).FullName;
  115. List<MetadataReference> references = new List<MetadataReference>();
  116. references.Add(MetadataReference.CreateFromFile(Path.Combine(sysDir, "System.dll")));
  117. references.Add(MetadataReference.CreateFromFile(Path.Combine(sysDir, "System.Data.dll")));
  118. references.Add(MetadataReference.CreateFromFile(Path.Combine(sysDir, "System.Xml.dll")));
  119. StringBuilder code = new StringBuilder(); //创建代码串
  120. /*
  121. * 添加常见且必须的引用字符串
  122. */
  123. code.Append("using System; \n");
  124. code.Append("using System.Data; \n");
  125. code.Append("using System.Data.SqlClient; \n");
  126. code.Append("using System.Data.OleDb; \n");
  127. code.Append("using System.Xml; \n");
  128. code.Append("namespace SSEC.Math { \n"); //生成代码的命名空间为EvalGuy,和本代码一样
  129. code.Append(" public class _Evaluator { \n"); //产生 _Evaluator 类,所有可执行代码均在此类中运行
  130. foreach (EvaluatorItem item in items) //遍历每一个可执行字符串项
  131. {
  132. code.AppendFormat(" public {0} {1}() ", //添加定义公共函数代码
  133. item.ReturnType.Name, //函数返回值为可执行字符串项中定义的返回值类型
  134. item.Name); //函数名称为可执行字符串项中定义的执行字符串名称
  135. code.Append("{ "); //添加函数开始括号
  136. code.AppendFormat("return ({0});", item.Expression);//添加函数体,返回可执行字符串项中定义的表达式的值
  137. code.Append("} \n"); //添加函数结束括号
  138. }
  139. code.Append("}}"); //添加类结束和命名空间结束括号
  140. string assemblyName = "SSEC.Math";
  141. SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(code.ToString());
  142. CSharpCompilation compilation = CSharpCompilation.Create(assemblyName);
  143. compilation.WithOptions(
  144. new CSharpCompilationOptions(
  145. OutputKind.DynamicallyLinkedLibrary
  146. , usings: null
  147. , optimizationLevel: OptimizationLevel.Debug
  148. , checkOverflow: false
  149. , allowUnsafe: true
  150. , platform: Platform.AnyCpu
  151. , warningLevel: 4
  152. , xmlReferenceResolver: null)
  153. );
  154. compilation.AddReferences(references);
  155. compilation.AddSyntaxTrees(tree);
  156. using (var ms = new MemoryStream())
  157. {
  158. EmitResult result = compilation.Emit(ms);
  159. if (!result.Success)
  160. {
  161. IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
  162. diagnostic.IsWarningAsError ||
  163. diagnostic.Severity == DiagnosticSeverity.Error);
  164. foreach (Diagnostic diagnostic in failures)
  165. {
  166. Console.Error.WriteLine("\t{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
  167. }
  168. }
  169. else
  170. {
  171. ms.Seek(0, SeekOrigin.Begin);
  172. Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms);
  173. //var type = assembly.GetTypes().Where(x => x.IsImplementlInterface(typeof(IProtocolExecutor))).FirstOrDefault();
  174. //_Compiled=(IProtocolExecutor)Activator.CreateInstance(type, newProtocol.ProtocolID, newProtocol.Version); //实例化解析类
  175. _Compiled = assembly.CreateInstance("SSEC.Math._Evaluator");
  176. }
  177. }
  178. }
  179. #endregion 构造函数
  180. #region 公有成员
  181. /// <summary>
  182. /// 执行字符串并返回整型值
  183. /// </summary>
  184. /// <param name="name">执行字符串名称</param>
  185. /// <returns>执行结果</returns>
  186. public int EvaluateInt(string name)
  187. {
  188. return (int)Evaluate(name);
  189. }
  190. /// <summary>
  191. /// 执行字符串并返回双精度值
  192. /// </summary>
  193. /// <param name="name">执行字符串名称</param>
  194. /// <returns>执行结果</returns>
  195. public double EvaluateDouble(string name)
  196. {
  197. return (double)Evaluate(name);
  198. }
  199. /// <summary>
  200. /// 执行字符串并返回长整型数值
  201. /// </summary>
  202. /// <param name="name">执行字符串名称</param>
  203. /// <returns>执行结果</returns>
  204. public long EvaluateLong(string name)
  205. {
  206. return (long)Evaluate(name);
  207. }
  208. /// <summary>
  209. /// 执行字符串并返回十进制数值
  210. /// </summary>
  211. /// <param name="name">执行字符串名称</param>
  212. /// <returns>执行结果</returns>
  213. public decimal EvaluateDecimal(string name)
  214. {
  215. return (decimal)Evaluate(name);
  216. }
  217. /// <summary>
  218. /// 执行字符串并返回字符串型值
  219. /// </summary>
  220. /// <param name="name">执行字符串名称</param>
  221. /// <returns>执行结果</returns>
  222. public string EvaluateString(string name)
  223. {
  224. return (string)Evaluate(name);
  225. }
  226. /// <summary>
  227. /// 执行字符串并返回布尔型值
  228. /// </summary>
  229. /// <param name="name">执行字符串名称</param>
  230. /// <returns>执行结果</returns>
  231. public bool EvaluateBool(string name)
  232. {
  233. return (bool)Evaluate(name);
  234. }
  235. /// <summary>
  236. /// 执行字符串并返 object 型值
  237. /// </summary>
  238. /// <param name="name">执行字符串名称</param>
  239. /// <returns>执行结果</returns>
  240. public object Evaluate(string name)
  241. {
  242. MethodInfo mi = _Compiled.GetType().GetMethod(name);//获取 _Compiled 所属类型中名称为 name 的方法的引用
  243. return mi.Invoke(_Compiled, null); //执行 mi 所引用的方法
  244. }
  245. #endregion 公有成员
  246. #region 静态成员
  247. /// <summary>
  248. /// 执行表达式并返回整型值
  249. /// </summary>
  250. /// <param name="code">要执行的表达式</param>
  251. /// <returns>运算结果</returns>
  252. static public int EvaluateToInteger(string code)
  253. {
  254. MyEvaluator eval = new MyEvaluator(typeof(int), code, staticMethodName);//生成 Evaluator 类的对像
  255. return (int)eval.Evaluate(staticMethodName); //执行并返回整型数据
  256. }
  257. /// <summary>
  258. /// 执行表达式并返回双精度值
  259. /// </summary>
  260. /// <param name="name">执行字符串名称</param>
  261. /// <returns>执行结果</returns>
  262. static public double EvaluateToDouble(string code)
  263. {
  264. MyEvaluator eval = new MyEvaluator(typeof(double), code, staticMethodName);//生成 Evaluator 类的对像
  265. return (double)eval.Evaluate(staticMethodName);
  266. }
  267. /// <summary>
  268. /// 执行表达式并返回长整型数值
  269. /// </summary>
  270. /// <param name="name">执行字符串名称</param>
  271. /// <returns>执行结果</returns>
  272. static public long EvaluateToLong(string code)
  273. {
  274. MyEvaluator eval = new MyEvaluator(typeof(long), code, staticMethodName);//生成 Evaluator 类的对像
  275. return (long)eval.Evaluate(staticMethodName);
  276. }
  277. /// <summary>
  278. /// 执行表达式并返回十进制数值
  279. /// </summary>
  280. /// <param name="name">执行字符串名称</param>
  281. /// <returns>执行结果</returns>
  282. static public decimal EvaluateToDecimal(string code)
  283. {
  284. MyEvaluator eval = new MyEvaluator(typeof(decimal), code, staticMethodName);//生成 Evaluator 类的对像
  285. return (decimal)eval.Evaluate(staticMethodName);
  286. }
  287. /// <summary>
  288. /// 执行表达式并返回字符串型值
  289. /// </summary>
  290. /// <param name="code">要执行的表达式</param>
  291. /// <returns>运算结果</returns>
  292. static public string EvaluateToString(string code)
  293. {
  294. MyEvaluator eval = new MyEvaluator(typeof(string), code, staticMethodName);//生成 Evaluator 类的对像
  295. return (string)eval.Evaluate(staticMethodName); //执行并返回字符串型数据
  296. }
  297. /// <summary>
  298. /// 执行表达式并返回布尔型值
  299. /// </summary>
  300. /// <param name="code">要执行的表达式</param>
  301. /// <returns>运算结果</returns>
  302. static public bool EvaluateToBool(string code)
  303. {
  304. MyEvaluator eval = new MyEvaluator(typeof(bool), code, staticMethodName);//生成 Evaluator 类的对像
  305. return (bool)eval.Evaluate(staticMethodName); //执行并返回布尔型数据
  306. }
  307. /// <summary>
  308. /// 执行表达式并返回 object 型值
  309. /// </summary>
  310. /// <param name="code">要执行的表达式</param>
  311. /// <returns>运算结果</returns>
  312. static public object EvaluateToObject(string code)
  313. {
  314. MyEvaluator eval = new MyEvaluator(typeof(object), code, staticMethodName);//生成 Evaluator 类的对像
  315. return eval.Evaluate(staticMethodName); //执行并返回 object 型数据
  316. }
  317. #endregion 静态成员
  318. #region 私有成员
  319. /// <summary>
  320. /// 静态方法的执行字符串名称
  321. /// </summary>
  322. private const string staticMethodName = "__foo";
  323. /// <summary>
  324. /// 用于动态引用生成的类,执行其内部包含的可执行字符串
  325. /// </summary>
  326. private object _Compiled = null;
  327. #endregion 私有成员
  328. }
  329. /// <summary>
  330. /// 可执行字符串项(即一条可执行字符串)
  331. /// </summary>
  332. public class EvaluatorItem
  333. {
  334. /// <summary>
  335. /// 返回值类型
  336. /// </summary>
  337. public Type ReturnType;
  338. /// <summary>
  339. /// 执行表达式
  340. /// </summary>
  341. public string Expression;
  342. /// <summary>
  343. /// 执行字符串名称
  344. /// </summary>
  345. public string Name;
  346. /// <summary>
  347. /// 可执行字符串项构造函数
  348. /// </summary>
  349. /// <param name="returnType">返回值类型</param>
  350. /// <param name="expression">执行表达式</param>
  351. /// <param name="name">执行字符串名称</param>
  352. public EvaluatorItem(Type returnType, string expression, string name)
  353. {
  354. ReturnType = returnType;
  355. Expression = expression;
  356. Name = name;
  357. }
  358. }
  359. }