CommandReader.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using EXTS;
  2. using System.Collections.Generic;
  3. namespace Island.StandardLib.CommandHelper
  4. {
  5. public class CommandReader
  6. {
  7. int compilingPos;
  8. string compilingCode;
  9. const char EOF = (char)0;
  10. public readonly string[] Result;
  11. public CommandReader(string input)
  12. {
  13. compilingCode = input;
  14. compilingPos = 0;
  15. List<string> parts = new List<string>();
  16. char ch;
  17. while ((ch = Peek()) != EOF)
  18. {
  19. if (ch == '\"') parts.Add(PeekString(true));
  20. else if (ch == ' ') continue;
  21. else parts.Add(ch + PeekString(false));
  22. }
  23. Result = parts.ToArray();
  24. }
  25. char Peek()
  26. {
  27. if (compilingPos < compilingCode.Length)
  28. return compilingCode[compilingPos++];
  29. else
  30. {
  31. compilingPos++;
  32. return EOF;
  33. }
  34. }
  35. string PeekString(bool useEndQuote)
  36. {
  37. string str = "";
  38. char ch;
  39. while (true)
  40. {
  41. ch = Peek();
  42. if (ch == '\\')
  43. {
  44. char ct = Peek();
  45. switch (ct)
  46. {
  47. case 'n': str += '\n'; break;
  48. case 't': str += '\t'; break;
  49. case '\"': str += '\"'; break;
  50. case '\\': str += '\\'; break;
  51. default: throw new SyntaxException("未识别的转义符。", compilingPos);
  52. }
  53. }
  54. if (ch == ' ' && !useEndQuote) return str;
  55. if (ch == EOF)
  56. {
  57. if (useEndQuote)
  58. throw new SyntaxException("字符串直到文件结尾都未结束,请检查引号是否完整。", compilingPos);
  59. else return str;
  60. }
  61. if (ch == '\"') break;
  62. str += ch;
  63. }
  64. return str;
  65. }
  66. public static implicit operator string[](CommandReader engine) => engine.Result;
  67. }
  68. }