Lexer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. namespace NTERA.Interpreter.Compiler
  9. {
  10. public class Lexer : IEnumerable<Token>
  11. {
  12. private readonly string source;
  13. private Marker sourceMarker;
  14. private char currentChar;
  15. private readonly IEnumerator<Token> currentEnumerator;
  16. private LexerType _type;
  17. public LexerType Type
  18. {
  19. get => _type;
  20. internal set
  21. {
  22. _type = value;
  23. InitTokenDictionaries();
  24. }
  25. }
  26. public Marker TokenMarker { get; set; }
  27. public string Identifer { get; set; }
  28. public Value Value { get; set; }
  29. public Lexer(string input, LexerType type = LexerType.Both)
  30. {
  31. Type = type;
  32. source = input;
  33. sourceMarker = new Marker(-1, 1, 0);
  34. currentEnumerator = GetTokens();
  35. currentEnumerator.MoveNext();
  36. }
  37. public void GoTo(Marker marker)
  38. {
  39. sourceMarker = marker;
  40. }
  41. char GetNextChar(bool peek = false)
  42. {
  43. if (sourceMarker.Pointer + 1 >= source.Length)
  44. {
  45. sourceMarker.Pointer = source.Length;
  46. return currentChar = (char)0;
  47. }
  48. if (peek)
  49. return currentChar = source[sourceMarker.Pointer + 1];
  50. sourceMarker.Column++;
  51. sourceMarker.Pointer++;
  52. if ((currentChar = source[sourceMarker.Pointer]) == '\n')
  53. {
  54. sourceMarker.Column = 0;
  55. sourceMarker.Line++;
  56. }
  57. return currentChar;
  58. }
  59. private static Dictionary<string, Token> TokenDictionary;
  60. private static Dictionary<string, Token> TokenLineDictionary;
  61. private Dictionary<char, Token> TokenCharDictionary;
  62. private static Dictionary<char, Token> BothModeTokens;
  63. private static Dictionary<char, Token> StringModeTokens;
  64. private void InitTokenDictionaries()
  65. {
  66. if (TokenDictionary == null || TokenLineDictionary == null)
  67. {
  68. TokenDictionary = new Dictionary<string, Token>(StringComparer.InvariantCultureIgnoreCase);
  69. TokenLineDictionary = new Dictionary<string, Token>(StringComparer.InvariantCultureIgnoreCase);
  70. foreach (Token token in Enum.GetValues(typeof(Token)))
  71. {
  72. foreach (var attribute in Utility.GetEnumAttributes<Token, LexerKeywordAttribute>(token))
  73. {
  74. if (attribute.IsLineKeyword)
  75. TokenLineDictionary[attribute.Keyword] = token;
  76. else
  77. TokenDictionary[attribute.Keyword] = token;
  78. }
  79. }
  80. }
  81. if (BothModeTokens == null || StringModeTokens == null)
  82. {
  83. BothModeTokens = new Dictionary<char, Token>();
  84. StringModeTokens = new Dictionary<char, Token>();
  85. foreach (Token token in Enum.GetValues(typeof(Token)))
  86. {
  87. foreach (var attribute in Utility.GetEnumAttributes<Token, LexerCharacterAttribute>(token))
  88. {
  89. if ((attribute.LexerContext & LexerType.String) > 0)
  90. StringModeTokens[attribute.Character] = token;
  91. BothModeTokens[attribute.Character] = token;
  92. }
  93. }
  94. }
  95. TokenCharDictionary = Type == LexerType.String ? StringModeTokens : BothModeTokens;
  96. }
  97. private static Regex PowRegex = new Regex(@"(\d+)p(\d+)");
  98. private static bool IsWhitespace(char c)
  99. {
  100. return char.IsWhiteSpace(c) && c != '\n';
  101. }
  102. private static bool IsEndOfLine(char c)
  103. {
  104. return c == '\n' || c == '\r' || c == '\0';
  105. }
  106. private Token DetermineToken(char c)
  107. {
  108. if (TokenCharDictionary.TryGetValue(c, out Token charToken))
  109. return charToken;
  110. switch (c)
  111. {
  112. case ';': //semicolon is comment
  113. while (currentChar != '\n')
  114. {
  115. if (currentChar == '\0')
  116. return Token.EOF;
  117. GetNextChar();
  118. }
  119. return Token.NewLine;
  120. case '[':
  121. const string SkipStart = "[SKIPSTART]";
  122. const string SkipEnd = "[SKIPEND]";
  123. if (sourceMarker.Column > 1
  124. || source.Substring(sourceMarker.Pointer, SkipStart.Length) != SkipStart)
  125. return Token.Unknown;
  126. while (GetNextChar() != '\0')
  127. {
  128. if (currentChar == '[' && source.Substring(sourceMarker.Pointer, SkipEnd.Length) == SkipEnd)
  129. {
  130. while (true)
  131. {
  132. switch (GetNextChar())
  133. {
  134. case '\n':
  135. return Token.NewLine;
  136. case '\0':
  137. return Token.EOF;
  138. }
  139. }
  140. }
  141. }
  142. return Token.EOF;
  143. case '%':
  144. return Type == LexerType.String ? Token.Format : Token.Modulo;
  145. case '<':
  146. if (!Type.HasFlag(LexerType.Real))
  147. break;
  148. if (GetNextChar(true) == '>')
  149. {
  150. GetNextChar();
  151. return Token.NotEqual;
  152. }
  153. else if (GetNextChar(true) == '=')
  154. {
  155. GetNextChar();
  156. return Token.LessEqual;
  157. }
  158. else
  159. return Token.Less;
  160. case '>':
  161. if (!Type.HasFlag(LexerType.Real))
  162. break;
  163. if (GetNextChar(true) == '=')
  164. {
  165. GetNextChar();
  166. return Token.MoreEqual;
  167. }
  168. else
  169. return Token.More;
  170. case '+':
  171. if (Type == LexerType.String)
  172. return Token.Unknown;
  173. if ((source[sourceMarker.Pointer] == '+' && source[sourceMarker.Pointer + 1] == '+') || source[sourceMarker.Pointer + 2] == '+')
  174. {
  175. GetNextChar();
  176. return Token.Increment;
  177. }
  178. else
  179. return Token.Plus;
  180. case '-':
  181. if (Type == LexerType.String)
  182. return Token.Unknown;
  183. if ((source[sourceMarker.Pointer] == '-' && source[sourceMarker.Pointer + 1] == '-') || source[sourceMarker.Pointer + 2] == '-')
  184. {
  185. GetNextChar();
  186. return Token.Decrement;
  187. }
  188. else
  189. return Token.Minus;
  190. case '=':
  191. if (Type == LexerType.String)
  192. return Token.Unknown;
  193. if ((source[sourceMarker.Pointer] == '=' && source[sourceMarker.Pointer + 1] == '=') || source[sourceMarker.Pointer + 2] == '=')
  194. GetNextChar();
  195. return Token.Equal;
  196. case '&':
  197. if ((source[sourceMarker.Pointer] == '&' && source[sourceMarker.Pointer + 1] == '&') || source[sourceMarker.Pointer + 2] == '&')
  198. GetNextChar();
  199. return Token.And;
  200. case '|':
  201. if ((source[sourceMarker.Pointer] == '|' && source[sourceMarker.Pointer + 1] == '|') || source[sourceMarker.Pointer + 2] == '|')
  202. GetNextChar();
  203. return Token.Or;
  204. case '"':
  205. string str = "";
  206. while (GetNextChar() != '"')
  207. {
  208. if (currentChar == '\\')
  209. {
  210. switch (char.ToLower(GetNextChar()))
  211. {
  212. case 'n':
  213. str += '\n';
  214. break;
  215. case 't':
  216. str += '\t';
  217. break;
  218. case '\\':
  219. str += '\\';
  220. break;
  221. case '"':
  222. str += '"';
  223. break;
  224. }
  225. }
  226. else if (currentChar == '\0')
  227. throw new Exception("Unexpected end of file");
  228. else
  229. {
  230. str += currentChar;
  231. }
  232. }
  233. Value = new Value(str);
  234. return Token.Value;
  235. case (char)0:
  236. return Token.EOF;
  237. }
  238. return Token.Unknown;
  239. }
  240. private IEnumerator<Token> GetTokens()
  241. {
  242. sourceMarker = new Marker(-1, 1, 0);
  243. while (true)
  244. {
  245. while (IsWhitespace(GetNextChar()) && Type != LexerType.String || currentChar == '\r')
  246. {
  247. }
  248. TokenMarker = sourceMarker;
  249. Token token = DetermineToken(currentChar);
  250. if (token == Token.EOF)
  251. {
  252. yield return Token.EOF;
  253. yield break;
  254. }
  255. if (token != Token.Unknown)
  256. {
  257. yield return token;
  258. continue;
  259. }
  260. StringBuilder bodyBuilder = new StringBuilder(currentChar.ToString());
  261. while (DetermineToken(GetNextChar(true)) == Token.Unknown
  262. && (!IsWhitespace(GetNextChar(true)) || Type == LexerType.String)
  263. && GetNextChar(true) != '\r')
  264. {
  265. bodyBuilder.Append(GetNextChar());
  266. }
  267. string result = bodyBuilder.ToString();
  268. if (double.TryParse(result, NumberStyles.Float, CultureInfo.InvariantCulture, out var real))
  269. {
  270. Value = real;
  271. yield return Token.Value;
  272. continue;
  273. }
  274. if (result.StartsWith("0x") && int.TryParse(result.Replace("0x", ""), NumberStyles.HexNumber, CultureInfo.CurrentCulture, out int hexResult))
  275. {
  276. Value = hexResult;
  277. yield return Token.Value;
  278. continue;
  279. }
  280. Match powMatch = PowRegex.Match(result);
  281. if (powMatch.Success)
  282. {
  283. int a = int.Parse(powMatch.Groups[1].Value);
  284. int b = int.Parse(powMatch.Groups[2].Value);
  285. Value = a << b;
  286. yield return Token.Value;
  287. continue;
  288. }
  289. Identifer = bodyBuilder.ToString();
  290. if (TokenDictionary.TryGetValue(Identifer, out token))
  291. {
  292. yield return token;
  293. continue;
  294. }
  295. if (Type == LexerType.String)
  296. {
  297. Value = char.IsWhiteSpace(Identifer[0])
  298. ? Identifer.Substring(1)
  299. : Identifer;
  300. yield return Token.Value;
  301. continue;
  302. }
  303. if (TokenLineDictionary.TryGetValue(Identifer, out token))
  304. {
  305. bodyBuilder = new StringBuilder();
  306. while (!IsEndOfLine(GetNextChar(true)))
  307. bodyBuilder.Append(GetNextChar());
  308. yield return token;
  309. string strValue = bodyBuilder.ToString();
  310. if (strValue.Length > 0 && char.IsWhiteSpace(strValue[0]))
  311. strValue = strValue.Substring(1);
  312. Value = new Value(strValue);
  313. yield return Token.Value;
  314. yield return currentChar == '\0' ? Token.EOF : Token.NewLine;
  315. continue;
  316. }
  317. yield return Token.Identifer;
  318. if (currentChar == '\n')
  319. yield return Token.NewLine;
  320. }
  321. }
  322. public IEnumerator<Token> GetEnumerator()
  323. {
  324. return currentEnumerator;
  325. }
  326. IEnumerator IEnumerable.GetEnumerator()
  327. {
  328. return GetEnumerator();
  329. }
  330. private static readonly Dictionary<Token, int> OrderOfOps = new Dictionary<Token, int>
  331. {
  332. { Token.Or, 0 }, { Token.And, 0 },
  333. { Token.Equal, 1 }, { Token.NotEqual, 1 },
  334. { Token.Less, 1 }, { Token.More, 1 }, { Token.LessEqual, 1 }, { Token.MoreEqual, 1 },
  335. { Token.Plus, 2 }, { Token.Minus, 2 },
  336. { Token.Asterisk, 3 }, { Token.Slash, 3 },
  337. { Token.Caret, 4 }
  338. };
  339. public Value Expression()
  340. {
  341. Stack<Value> stack = new Stack<Value>();
  342. Stack<Token> operators = new Stack<Token>();
  343. void Operation(Token token)
  344. {
  345. Value b = stack.Pop();
  346. Value a = stack.Pop();
  347. Value result = a.Operate(b, token);
  348. stack.Push(result);
  349. }
  350. int i = 0;
  351. while (true)
  352. {
  353. if (currentEnumerator.Current == Token.Value)
  354. {
  355. stack.Push(Value);
  356. }
  357. else if (currentEnumerator.Current == Token.Identifer)
  358. {
  359. if (Type == LexerType.String)
  360. stack.Push(Identifer);
  361. else
  362. throw new ParserException("Undeclared variable " + Identifer, TokenMarker);
  363. }
  364. else if (currentEnumerator.Current == Token.LParen)
  365. {
  366. currentEnumerator.MoveNext();
  367. stack.Push(Expression());
  368. if (currentEnumerator.Current != Token.RParen)
  369. throw new ParserException($"Was expecting [LParen] got [{currentEnumerator.Current}]", TokenMarker);
  370. }
  371. else if (Type.HasFlag(LexerType.Real) && currentEnumerator.Current.IsArithmetic()
  372. && currentEnumerator.Current.IsUnary() && (i == 0)) // || previousToken == Token.LParen))
  373. {
  374. stack.Push(0);
  375. operators.Push(currentEnumerator.Current);
  376. }
  377. else if (Type == LexerType.String && currentEnumerator.Current.IsStringOp()
  378. || Type.HasFlag(LexerType.Real) && currentEnumerator.Current.IsArithmetic())
  379. {
  380. while (operators.Count > 0 && OrderOfOps[currentEnumerator.Current] <= OrderOfOps[operators.Peek()])
  381. Operation(operators.Pop());
  382. operators.Push(currentEnumerator.Current);
  383. }
  384. else
  385. {
  386. if (i == 0)
  387. {
  388. if (Type == LexerType.String)
  389. stack.Push("");
  390. else
  391. throw new ParserException("Empty expression", TokenMarker);
  392. }
  393. break;
  394. }
  395. i++;
  396. currentEnumerator.MoveNext();
  397. }
  398. while (operators.Count > 0)
  399. Operation(operators.Pop());
  400. return Type == LexerType.String
  401. ? stack.Aggregate((a, b) => b.String + a.String)
  402. : stack.Pop();
  403. }
  404. }
  405. }