PageRenderTime 54ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/DLR_Main/Runtime/Samples/ExpressionTree/ETSample1_CS/Program.cs

https://bitbucket.org/mdavid/dlr
C# | 123 lines | 54 code | 22 blank | 47 comment | 0 complexity | c7b3fdad7012f63e10b4b1957cdcf192 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Reflection;
  5. using Microsoft.Scripting.Ast;
  6. namespace ETSample1_CS {
  7. class Program {
  8. static void Main(string[] args) {
  9. //In the main method we get an expression tree from one of the samples,
  10. //Use that expression as the body of a lambda,
  11. //Compile and execute the lambda.
  12. //You can select which sample to run by uncommenting it and commenting all others
  13. Expression LambdaBody;
  14. //Samples:
  15. //LambdaBody = SimpleHelloWorld();
  16. LambdaBody = NotSoSimpleHelloWorld();
  17. //Create the lambda
  18. LambdaExpression Lambda = Expression.Lambda(LambdaBody);
  19. //Compile and execute the lambda
  20. Lambda.Compile().DynamicInvoke();
  21. }
  22. /// <summary>
  23. /// This method demonstrates the typical "Hello world" sample using the DLR.
  24. /// </summary>
  25. /// <returns>An expression that if executed will print "Hello world!"</returns>
  26. static Expression SimpleHelloWorld() {
  27. //First step, we get the methodinfo for Console.WriteLine. This is standard reflection.
  28. MethodInfo WriteLine = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
  29. //Second step, we create an expression that invokes that method with "Hello world!"
  30. return Expression.Call(null, WriteLine, Expression.Constant("Hello world!"));
  31. }
  32. /// <summary>
  33. /// This method is a variation on the hello world sample to demonstrate how to build expression trees to:
  34. /// - Define and use variables
  35. /// - Use operators
  36. /// - Define conditions (in this case to define an if statement)
  37. /// - Invoke CLR methods
  38. /// </summary>
  39. static Expression NotSoSimpleHelloWorld() {
  40. //Not so simple Hello world
  41. //This list will hold the expressions that we want to execute.
  42. List<Expression> Instructions = new List<Expression>();
  43. //Variable that will hold the star name for the current star system.
  44. //The type ParameterExpression is used both to define parameters and variables.
  45. //Note that the string passed to the name argument of the Variable method is only used for debugging purposes
  46. //and isn't validated. you can have multiple variables with the same name, or no name.
  47. ParameterExpression StarName = Expression.Parameter(typeof(String), "StarName");
  48. //Variable that will hold the planet number (from the sun)
  49. ParameterExpression PlanetNumber = Expression.Parameter(typeof(String), "PlanetNumber");
  50. //Prompt the user for the star's name and assign the value to the StarName variable.
  51. Instructions.Add(
  52. Expression.Assign(
  53. StarName,
  54. Prompt("What is the name of the star you are currently orbiting?")
  55. )
  56. );
  57. //Prompt the user for the planets location and assign the value to the PlanetNumber variable.
  58. Instructions.Add(
  59. Expression.Assign(
  60. PlanetNumber,
  61. Prompt("What is the numer of the planet, counting from the sun, you are currently at?")
  62. )
  63. );
  64. //Are we in the general vicinity of the sun?
  65. Expression DoWeOrbitTheSun = Expression.Equal(StarName, Expression.Constant("sun"));
  66. //are there two other planets closer to the sun than we are?
  67. Expression AreWeTheThirdPlanet = Expression.Equal(PlanetNumber, Expression.Constant("3"));
  68. //Combining the two tests with an And
  69. Expression Test = Expression.And(DoWeOrbitTheSun, AreWeTheThirdPlanet);
  70. //create an if statement using the above defined test.
  71. //Note that a condition can actually have a value. This factory (Expression.Condition) can also be used
  72. //to create something equivalent to the ternary ?: operator.
  73. Expression If = Expression.Condition(
  74. Test,
  75. Print("Hello Earth!"),
  76. Print("Hello random planet!")
  77. );
  78. Instructions.Add(If);
  79. //And now it all comes together. we create a Block (an expression that holds a list of expressions)
  80. //and we wrap that in a Scope, which defines the scope of a set of variables.
  81. return Expression.Block(new ParameterExpression[] { StarName, PlanetNumber }, Expression.Block(Instructions));
  82. }
  83. static Expression Print(String arg) {
  84. //First step, we get the methodinfo for Console.WriteLine
  85. MethodInfo WriteLine = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
  86. //Second step, we create an expression that invokes that method with "Hello world!"
  87. return Expression.Call(null, WriteLine, Expression.Constant(arg));
  88. }
  89. /// <summary>
  90. /// Prompts the user, and returns an expression containing the user's reply (lower cased)
  91. /// </summary>
  92. /// <param name="PromptText">The text to prompt the user with</param>
  93. /// <returns>An Expression containing the value the user typed</returns>
  94. static Expression Prompt(String PromptText) {
  95. //Prompt the user.
  96. Console.WriteLine(PromptText);
  97. //Return the user's input as an expression
  98. return Expression.Constant(Console.ReadLine().ToLower());
  99. }
  100. }
  101. }