You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
2.4 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Text.RegularExpressions;
  6. namespace SuperBASIC
  7. {
  8. class Parser
  9. {
  10. [Serializable]
  11. public class ParseException : Exception
  12. {
  13. public ParseException() { }
  14. public ParseException(string message) : base(message) { }
  15. public ParseException(string message, Exception inner) : base(message, inner) { }
  16. protected ParseException(
  17. System.Runtime.Serialization.SerializationInfo info,
  18. System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
  19. }
  20. readonly Library library;
  21. readonly Runtime runtime;
  22. public Parser(Runtime rt)
  23. {
  24. runtime = rt;
  25. library = rt.lib;
  26. }
  27. public Bytecode ParseFile(string filepath)
  28. {
  29. Bytecode c = new Bytecode();
  30. string[] sourceLines = File.ReadAllLines(filepath);
  31. Regex lws = new Regex(@"\s+");
  32. Regex leadings = new Regex(@"^\s+");
  33. Regex trailings = new Regex(@"\s+$");
  34. List<string> codeLines = new List<string>();
  35. List<int> lineSpans = new List<int>();
  36. int a = 0;
  37. foreach (string line in sourceLines)
  38. {
  39. a++;
  40. string l = lws.Replace(line, " ");
  41. l = leadings.Replace(l, "");
  42. l = trailings.Replace(l, "");
  43. if(l != String.Empty)
  44. {
  45. lineSpans.Add(a);
  46. a = 0;
  47. codeLines.Add(l);
  48. }
  49. }
  50. for(int idx = 0; idx < codeLines.Count; idx++)
  51. {
  52. string line = codeLines[idx];
  53. var components = line.Split(' ');
  54. if(!library.nameResolution.ContainsKey(components[0]))
  55. {
  56. int lineIndex = 0;
  57. foreach (int cnt in lineSpans.GetRange(0, idx)) lineIndex += cnt;
  58. throw new ParseException($"Unknown operation \"{components[0]}\"\n\tat line {lineIndex}");
  59. }
  60. int opcode = library.nameResolution[components[0]];
  61. int arity = library.arities[opcode];
  62. if(arity != components.Length-1)
  63. {
  64. int lineIndex = 0;
  65. foreach (int cnt in lineSpans.GetRange(0, idx)) lineIndex += cnt;
  66. throw new ParseException($"Operation {components[0]} was provided with the wrong number of arguments\n\tExpected {arity} found {components.Length-1}\n\tat line {lineIndex}");
  67. }
  68. c.bytecode.Add(new BasicNumber(runtime, opcode));
  69. foreach (string elem in components.AsSpan(1))
  70. {
  71. if (elem != "$")
  72. {
  73. c.bytecode.Add(new BasicNumber(runtime, float.Parse(elem)));
  74. }
  75. else
  76. {
  77. c.bytecode.Add(new BasicNumber(runtime));
  78. }
  79. }
  80. }
  81. return c;
  82. }
  83. }
  84. }