Expression.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Xml.Linq;
  5. namespace csharp_sccd_compiler
  6. {
  7. public class Expression : Visitable
  8. {
  9. private static Lexer lexer = new Lexer(false, true);
  10. public List<ExpressionPart> expression_parts { get; private set; }
  11. public Expression(string input_string)
  12. {
  13. if (input_string == "")
  14. throw new CompilerException("Empty Expression.");
  15. this.parse(input_string);
  16. }
  17. protected void parse(string input_string, string[] dont_parse = null)
  18. {
  19. this.expression_parts = new List<ExpressionPart>();
  20. Expression.lexer.setInput(input_string);
  21. string processed_bare_expression = "";
  22. if (dont_parse == null)
  23. dont_parse = new string[] { };
  24. foreach (Token token in Expression.lexer.iterateTokens())
  25. {
  26. ExpressionPart created_part = null;
  27. if (token.type == Token.Type.WORD)
  28. {
  29. if (dont_parse.Contains(token.val))
  30. throw new CompilerException(string.Format("Macro \"{0}\" not allowed here.",token.val));
  31. else if (token.val == Constants.SELF_REFERENCE_SEQ)
  32. created_part = new SelfReference();
  33. else if (token.val == Constants.INSTATE_SEQ)
  34. {
  35. created_part = this.parseInStateCall();
  36. if (created_part == null)
  37. throw new CompilerException(string.Format("Illegal use of \"{0}\" macro.", Constants.INSTATE_SEQ));
  38. }
  39. }
  40. if (created_part == null)
  41. processed_bare_expression += token.val;
  42. else
  43. {
  44. if (processed_bare_expression != "")
  45. {
  46. this.expression_parts.Add( new ExpressionPartString(processed_bare_expression));
  47. processed_bare_expression = "";
  48. }
  49. this.expression_parts.Add(created_part);
  50. }
  51. }
  52. //Process part of input after the last created macro object
  53. if (processed_bare_expression != "")
  54. this.expression_parts.Add( new ExpressionPartString(processed_bare_expression));
  55. }
  56. private InStateCall parseInStateCall()
  57. {
  58. Token token = Expression.lexer.nextToken();
  59. if (token == null || token.type != Token.Type.LBRACKET)
  60. return null;
  61. token = Expression.lexer.nextToken();
  62. if (token == null || token.type != Token.Type.QUOTED)
  63. return null;
  64. InStateCall result = new InStateCall(token.val.Substring(1, token.val.Length - 2));
  65. token = Expression.lexer.nextToken();
  66. if (token == null || token.type != Token.Type.RBRACKET)
  67. return null;
  68. return result;
  69. }
  70. public override void accept(Visitor visitor)
  71. {
  72. foreach (ExpressionPart expression_part in this.expression_parts)
  73. expression_part.accept(visitor);
  74. }
  75. }
  76. }