Interpreter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text.RegularExpressions;
  6. using NTERA.Core;
  7. namespace NTERA.Interpreter
  8. {
  9. public partial class Interpreter
  10. {
  11. private Lexer lex;
  12. private Token prevToken;
  13. private Token lastToken;
  14. public readonly Dictionary<string, Value> Variables;
  15. private Dictionary<string, Marker> loops;
  16. public delegate Value BasicFunction(List<Value> args);
  17. private readonly IConsole console;
  18. private int ifcounter;
  19. private Marker lineMarker;
  20. private bool exit;
  21. public Interpreter(IConsole console, string input)
  22. {
  23. this.console = console;
  24. lex = new Lexer(input);
  25. Variables = new Dictionary<string, Value>();
  26. loops = new Dictionary<string, Marker>();
  27. ifcounter = 0;
  28. GenerateKeywordDictionary();
  29. GenerateFunctionDictionary();
  30. }
  31. public Value GetVar(string name)
  32. {
  33. if (!Variables.ContainsKey(name))
  34. throw new Exception("Variable with name " + name + " does not exist.");
  35. return Variables[name];
  36. }
  37. public void SetVar(string name, Value val)
  38. {
  39. if (!Variables.ContainsKey(name)) Variables.Add(name, val);
  40. else Variables[name] = val;
  41. }
  42. void Error(string text)
  43. {
  44. throw new Exception(text + " at line: " + lineMarker.Line);
  45. }
  46. void Match(Token tok)
  47. {
  48. if (lastToken != tok)
  49. Error("Expect " + tok + " got " + lastToken);
  50. }
  51. private IEnumerator<Token> tokens;
  52. public void Exec()
  53. {
  54. exit = false;
  55. tokens = lex.GetTokens().GetEnumerator();
  56. GetNextToken();
  57. while (!exit) Line();
  58. }
  59. Token GetNextToken()
  60. {
  61. prevToken = lastToken;
  62. tokens.MoveNext();
  63. lastToken = tokens.Current;
  64. if (lastToken == Token.EOF && prevToken == Token.EOF)
  65. Error("Unexpected end of file");
  66. return lastToken;
  67. }
  68. void Line()
  69. {
  70. while (lastToken == Token.NewLine) GetNextToken();
  71. if (lastToken == Token.EOF)
  72. {
  73. exit = true;
  74. return;
  75. }
  76. lineMarker = lex.TokenMarker;
  77. Statment();
  78. if (lastToken != Token.NewLine && lastToken != Token.EOF)
  79. Error("Expect new line got " + lastToken);
  80. }
  81. void Statment()
  82. {
  83. Token keyword = lastToken;
  84. GetNextToken();
  85. if (KeywordMethods.ContainsKey(keyword))
  86. KeywordMethods[keyword]();
  87. else
  88. {
  89. switch (keyword)
  90. {
  91. case Token.Input: Input(); break;
  92. case Token.Function:
  93. case Token.Global:
  94. case Token.Dim:
  95. case Token.Const:
  96. while (GetNextToken() != Token.NewLine) { }
  97. break;
  98. case Token.Identifer:
  99. if (lastToken == Token.Equal) Let();
  100. else goto default;
  101. break;
  102. case Token.EOF:
  103. exit = true;
  104. break;
  105. default:
  106. Error("Expect keyword got " + keyword);
  107. break;
  108. }
  109. }
  110. if (lastToken == Token.Colon)
  111. {
  112. GetNextToken();
  113. Statment();
  114. }
  115. }
  116. #region Functions
  117. private Dictionary<string, BasicFunction> FunctionDictionary { get; set; }
  118. private void GenerateFunctionDictionary()
  119. {
  120. FunctionDictionary = new Dictionary<string, BasicFunction>(StringComparer.InvariantCultureIgnoreCase);
  121. foreach (var method in typeof(Interpreter).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
  122. {
  123. var attribute = method.GetCustomAttributes(typeof(BuiltInFunctionAttribute), true).FirstOrDefault() as BuiltInFunctionAttribute;
  124. if (attribute == null)
  125. continue;
  126. FunctionDictionary[attribute.Name] = args => (Value)method.Invoke(this, new object[] { args });
  127. }
  128. }
  129. [BuiltInFunction("abs")]
  130. private Value Abs(List<Value> args)
  131. {
  132. if (args.Count < 1)
  133. throw new ArgumentException();
  134. return new Value(Math.Abs(args[0].Real));
  135. }
  136. [BuiltInFunction("min")]
  137. private Value Min(List<Value> args)
  138. {
  139. if (args.Count < 2)
  140. throw new ArgumentException();
  141. return new Value(Math.Min(args[0].Real, args[1].Real));
  142. }
  143. [BuiltInFunction("max")]
  144. private Value Max(List<Value> args)
  145. {
  146. if (args.Count < 2)
  147. throw new ArgumentException();
  148. return new Value(Math.Max(args[0].Real, args[1].Real));
  149. }
  150. [BuiltInFunction("not")]
  151. private Value Not(List<Value> args)
  152. {
  153. if (args.Count < 1)
  154. throw new ArgumentException();
  155. return new Value(args[0].Real == 0 ? 1 : 0);
  156. }
  157. private readonly Random random = new Random();
  158. [BuiltInFunction("rand")]
  159. private Value Rand(List<Value> args)
  160. {
  161. if (args.Count < 2)
  162. throw new ArgumentException();
  163. return new Value(random.Next((int)args[0].Real, (int)args[1].Real - 1));
  164. }
  165. #endregion
  166. #region Keywords
  167. private Dictionary<Token, Action> KeywordMethods { get; set; }
  168. private void GenerateKeywordDictionary()
  169. {
  170. KeywordMethods = new Dictionary<Token, Action>();
  171. foreach (var method in typeof(Interpreter).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
  172. {
  173. var attribute = method.GetCustomAttributes(typeof(KeywordMethodAttribute), true).FirstOrDefault() as KeywordMethodAttribute;
  174. if (attribute == null)
  175. continue;
  176. KeywordMethods[attribute.Token] = () => method.Invoke(this, null);
  177. }
  178. }
  179. [KeywordMethod(Token.Print)]
  180. void Print()
  181. {
  182. console.Write(Expr().ToString());
  183. }
  184. [KeywordMethod(Token.PrintL)]
  185. void PrintL()
  186. {
  187. console.PrintSingleLine(Expr().ToString());
  188. }
  189. [KeywordMethod(Token.PrintImg)]
  190. void PrintImg()
  191. {
  192. console.PrintImg(Expr().ToString().Trim().Trim('"'));
  193. }
  194. [KeywordMethod(Token.PrintButton)]
  195. void PrintButton()
  196. {
  197. console.PrintButton(Expr().ToString(), 0);
  198. }
  199. private static readonly Regex FormRegex = new Regex("{(.*?)}");
  200. [KeywordMethod(Token.PrintFormL)]
  201. void PrintFormL()
  202. {
  203. string rawString = Expr().ToString();
  204. var evaluator = new MatchEvaluator(match => Variables[match.Groups[1].Value].ToString());
  205. console.PrintSingleLine(FormRegex.Replace(rawString, evaluator));
  206. }
  207. [KeywordMethod(Token.DrawLine)]
  208. void DrawLine()
  209. {
  210. console.PrintBar();
  211. }
  212. [KeywordMethod(Token.DrawLineForm)]
  213. void DrawLineForm()
  214. {
  215. console.printCustomBar(Expr().ToString().Trim());
  216. }
  217. [KeywordMethod(Token.If)]
  218. private void If()
  219. {
  220. bool result = Expr().Real == 1;
  221. Match(Token.Then);
  222. GetNextToken();
  223. if (result)
  224. {
  225. int i = ifcounter;
  226. while (true)
  227. {
  228. if (lastToken == Token.If)
  229. {
  230. i++;
  231. }
  232. else if (lastToken == Token.Else)
  233. {
  234. if (i == ifcounter)
  235. {
  236. GetNextToken();
  237. return;
  238. }
  239. }
  240. else if (lastToken == Token.EndIf)
  241. {
  242. if (i == ifcounter)
  243. {
  244. GetNextToken();
  245. return;
  246. }
  247. i--;
  248. }
  249. GetNextToken();
  250. }
  251. }
  252. }
  253. [KeywordMethod(Token.Else)]
  254. private void Else()
  255. {
  256. int i = ifcounter;
  257. while (true)
  258. {
  259. if (lastToken == Token.If)
  260. {
  261. i++;
  262. }
  263. else if (lastToken == Token.EndIf)
  264. {
  265. if (i == ifcounter)
  266. {
  267. GetNextToken();
  268. return;
  269. }
  270. i--;
  271. }
  272. GetNextToken();
  273. }
  274. }
  275. [KeywordMethod(Token.EndIf)]
  276. private void EndIf()
  277. {
  278. }
  279. [KeywordMethod(Token.End)]
  280. private void End()
  281. {
  282. exit = true;
  283. }
  284. [KeywordMethod(Token.Let)]
  285. private void Let()
  286. {
  287. if (lastToken != Token.Equal)
  288. {
  289. Match(Token.Identifer);
  290. GetNextToken();
  291. Match(Token.Equal);
  292. }
  293. string id = lex.Identifer;
  294. GetNextToken();
  295. SetVar(id, Expr());
  296. }
  297. [KeywordMethod(Token.For)]
  298. private void For()
  299. {
  300. Match(Token.Identifer);
  301. string var = lex.Identifer;
  302. GetNextToken();
  303. Match(Token.Equal);
  304. GetNextToken();
  305. Value v = Expr();
  306. if (loops.ContainsKey(var))
  307. {
  308. loops[var] = lineMarker;
  309. }
  310. else
  311. {
  312. SetVar(var, v);
  313. loops.Add(var, lineMarker);
  314. }
  315. Match(Token.To);
  316. GetNextToken();
  317. v = Expr();
  318. if (Variables[var].Operate(v, Token.More).Real == 1)
  319. {
  320. while (true)
  321. {
  322. while (!(GetNextToken() == Token.Identifer && prevToken == Token.Next)) ;
  323. if (lex.Identifer == var)
  324. {
  325. loops.Remove(var);
  326. GetNextToken();
  327. Match(Token.NewLine);
  328. break;
  329. }
  330. }
  331. }
  332. }
  333. [KeywordMethod(Token.Next)]
  334. private void Next()
  335. {
  336. Match(Token.Identifer);
  337. string var = lex.Identifer;
  338. Variables[var] = Variables[var].Operate(new Value(1), Token.Plus);
  339. lex.GoTo(new Marker(loops[var].Pointer - 1, loops[var].Line, loops[var].Column - 1));
  340. lastToken = Token.NewLine;
  341. }
  342. [KeywordMethod(Token.Times)]
  343. private void Times()
  344. {
  345. Match(Token.Identifer);
  346. string var = lex.Identifer;
  347. GetNextToken();
  348. Match(Token.Comma);
  349. GetNextToken();
  350. var arg2 = Expr();
  351. Variables[var] = Variables[var].Operate(arg2, Token.Asterisk);
  352. Match(Token.NewLine);
  353. }
  354. #endregion
  355. void Input()
  356. {
  357. while (true)
  358. {
  359. Match(Token.Identifer);
  360. if (!Variables.ContainsKey(lex.Identifer)) Variables.Add(lex.Identifer, new Value());
  361. console.WaitInput(new Core.Interop.InputRequest() { InputType = Core.Interop.InputType.StrValue });
  362. string input = console.LastInput;
  363. double d;
  364. if (double.TryParse(input, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out d))
  365. Variables[lex.Identifer] = new Value(d);
  366. else
  367. Variables[lex.Identifer] = new Value(input);
  368. GetNextToken();
  369. if (lastToken != Token.Comma) break;
  370. GetNextToken();
  371. }
  372. }
  373. private static readonly Dictionary<Token, int> OrderOfOps = new Dictionary<Token, int>()
  374. {
  375. { Token.Or, 0 }, { Token.And, 0 },
  376. { Token.Equal, 1 }, { Token.NotEqual, 1 },
  377. { Token.Less, 1 }, { Token.More, 1 }, { Token.LessEqual, 1 }, { Token.MoreEqual, 1 },
  378. { Token.Plus, 2 }, { Token.Minus, 2 },
  379. { Token.Asterisk, 3 }, {Token.Slash, 3 },
  380. { Token.Caret, 4 }
  381. };
  382. Value Expr()
  383. {
  384. Stack<Value> stack = new Stack<Value>();
  385. Stack<Token> operators = new Stack<Token>();
  386. int i = 0;
  387. while (true)
  388. {
  389. if (lastToken == Token.Value)
  390. {
  391. stack.Push(lex.Value);
  392. }
  393. else if (lastToken == Token.Identifer)
  394. {
  395. if (Variables.ContainsKey(lex.Identifer))
  396. {
  397. stack.Push(Variables[lex.Identifer]);
  398. }
  399. else if (FunctionDictionary.ContainsKey(lex.Identifer))
  400. {
  401. string name = lex.Identifer;
  402. List<Value> args = new List<Value>();
  403. GetNextToken();
  404. Match(Token.LParen);
  405. while (GetNextToken() != Token.RParen)
  406. {
  407. args.Add(Expr());
  408. if (lastToken != Token.Comma)
  409. break;
  410. }
  411. stack.Push(FunctionDictionary[name](args));
  412. }
  413. else
  414. {
  415. Error("Undeclared variable " + lex.Identifer);
  416. }
  417. }
  418. else if (lastToken == Token.LParen)
  419. {
  420. GetNextToken();
  421. stack.Push(Expr());
  422. Match(Token.RParen);
  423. }
  424. else if (lastToken.IsArithmetic())
  425. {
  426. if (lastToken.IsUnary() && (i == 0 || prevToken == Token.LParen))
  427. {
  428. stack.Push(0);
  429. operators.Push(lastToken);
  430. }
  431. else
  432. {
  433. while (operators.Count > 0 && OrderOfOps[lastToken] <= OrderOfOps[operators.Peek()])
  434. Operation(stack, operators.Pop());
  435. operators.Push(lastToken);
  436. }
  437. }
  438. else
  439. {
  440. if (i == 0)
  441. Error("Empty expression");
  442. break;
  443. }
  444. i++;
  445. GetNextToken();
  446. }
  447. while (operators.Count > 0)
  448. Operation(stack, operators.Pop());
  449. return stack.Pop();
  450. }
  451. void Operation(Stack<Value> stack, Token token)
  452. {
  453. Value b = stack.Pop();
  454. Value a = stack.Pop();
  455. Value result = a.Operate(b, token);
  456. stack.Push(result);
  457. }
  458. }
  459. }