/Rhino.Etl.Dsl/Macros/AbstractChildMacro.cs

http://github.com/ayende/rhino-etl · C# · 89 lines · 52 code · 12 blank · 25 comment · 7 complexity · bf88712f9dd9d884a2476a49fa93bcd2 MD5 · raw file

  1. namespace Rhino.Etl.Dsl.Macros
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using Boo.Lang.Compiler;
  6. using Boo.Lang.Compiler.Ast;
  7. /// <summary>
  8. /// Base class for child macros, also handle validating the parents of a macro
  9. /// </summary>
  10. public abstract class AbstractChildMacro : AbstractAstMacro
  11. {
  12. private readonly string[] allowedParents;
  13. /// <summary>
  14. /// The parent macro statement
  15. /// </summary>
  16. protected MacroStatement parent;
  17. /// <summary>
  18. /// Initializes a new instance of the <see cref="AbstractChildMacro"/> class.
  19. /// </summary>
  20. /// <param name="allowedParents">The allowed parents.</param>
  21. public AbstractChildMacro(params string[] allowedParents)
  22. {
  23. this.allowedParents = allowedParents;
  24. }
  25. /// <summary>
  26. /// Expands the specified macro, validate that the parent is a valid parent,
  27. /// leave the actual processing to a base class
  28. /// </summary>
  29. /// <param name="macro">The macro.</param>
  30. /// <returns></returns>
  31. public override Statement Expand(MacroStatement macro)
  32. {
  33. if (ValidateParent(macro, out parent) == false)
  34. return null;
  35. return DoExpand(macro);
  36. }
  37. /// <summary>
  38. /// Perform the actual expansion of the macro
  39. /// </summary>
  40. /// <param name="macro">The macro.</param>
  41. /// <returns></returns>
  42. protected abstract Statement DoExpand(MacroStatement macro);
  43. private bool ValidateParent(MacroStatement macro, out MacroStatement parent)
  44. {
  45. parent = macro.ParentNode.ParentNode as MacroStatement;
  46. if (parent != null)
  47. {
  48. foreach (string validParent in allowedParents)
  49. {
  50. if (parent.Name.Equals(validParent, StringComparison.InvariantCultureIgnoreCase))
  51. {
  52. return true;
  53. }
  54. }
  55. }
  56. string msg = string.Format("A {0} statement can appear only under a {1}",
  57. macro.Name,
  58. string.Join(" | ", allowedParents));
  59. Errors.Add(CompilerErrorFactory.CustomError(macro.LexicalInfo, msg));
  60. return false;
  61. }
  62. /// <summary>
  63. /// Gets the parent methods collection
  64. /// </summary>
  65. /// <value>The parent methods.</value>
  66. protected IList<Method> ParentMethods
  67. {
  68. get
  69. {
  70. IList<Method> members = (IList<Method>)parent["members"];
  71. if (members == null)
  72. parent["members"] = members = new List<Method>();
  73. return members;
  74. }
  75. }
  76. }
  77. }