Interpreter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. private Dictionary<string, Value> vars;
  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. vars = 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 (!vars.ContainsKey(name))
  34. throw new Exception("Variable with name " + name + " does not exist.");
  35. return vars[name];
  36. }
  37. public void SetVar(string name, Value val)
  38. {
  39. if (!vars.ContainsKey(name)) vars.Add(name, val);
  40. else vars[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("str")]
  130. private Value Str(List<Value> args)
  131. {
  132. if (args.Count < 1)
  133. throw new ArgumentException();
  134. return args[0].Convert(ValueType.String);
  135. }
  136. [BuiltInFunction("num")]
  137. private Value Num(List<Value> args)
  138. {
  139. if (args.Count < 1)
  140. throw new ArgumentException();
  141. return args[0].Convert(ValueType.Real);
  142. }
  143. [BuiltInFunction("abs")]
  144. private Value Abs(List<Value> args)
  145. {
  146. if (args.Count < 1)
  147. throw new ArgumentException();
  148. return new Value(Math.Abs(args[0].Real));
  149. }
  150. [BuiltInFunction("min")]
  151. private Value Min(List<Value> args)
  152. {
  153. if (args.Count < 2)
  154. throw new ArgumentException();
  155. return new Value(Math.Min(args[0].Real, args[1].Real));
  156. }
  157. [BuiltInFunction("max")]
  158. private Value Max(List<Value> args)
  159. {
  160. if (args.Count < 2)
  161. throw new ArgumentException();
  162. return new Value(Math.Max(args[0].Real, args[1].Real));
  163. }
  164. [BuiltInFunction("not")]
  165. private Value Not(List<Value> args)
  166. {
  167. if (args.Count < 1)
  168. throw new ArgumentException();
  169. return new Value(args[0].Real == 0 ? 1 : 0);
  170. }
  171. private readonly Random random = new Random();
  172. [BuiltInFunction("rand")]
  173. private Value Rand(List<Value> args)
  174. {
  175. if (args.Count < 2)
  176. throw new ArgumentException();
  177. return new Value(random.Next((int)args[0].Real, (int)args[1].Real - 1));
  178. }
  179. #endregion
  180. #region Keywords
  181. private Dictionary<Token, Action> KeywordMethods { get; set; }
  182. private void GenerateKeywordDictionary()
  183. {
  184. KeywordMethods = new Dictionary<Token, Action>();
  185. foreach (var method in typeof(Interpreter).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
  186. {
  187. var attribute = method.GetCustomAttributes(typeof(TargetKeywordAttribute), true).FirstOrDefault() as TargetKeywordAttribute;
  188. if (attribute == null)
  189. continue;
  190. KeywordMethods[attribute.Token] = () => method.Invoke(this, null);
  191. }
  192. }
  193. [TargetKeyword(Token.Print)]
  194. void Print()
  195. {
  196. console.Write(Expr().ToString());
  197. }
  198. [TargetKeyword(Token.PrintL)]
  199. void PrintL()
  200. {
  201. console.PrintSingleLine(Expr().ToString());
  202. }
  203. private static Regex formRegex = new Regex("{(.*?)}");
  204. [TargetKeyword(Token.PrintFormL)]
  205. void PrintFormL()
  206. {
  207. string rawString = Expr().ToString();
  208. var evaluator = new MatchEvaluator((match) => { return vars[match.Groups[1].Value].ToString(); });
  209. console.PrintSingleLine(formRegex.Replace(rawString, evaluator));
  210. }
  211. [TargetKeyword(Token.DrawLine)]
  212. void DrawLine()
  213. {
  214. console.PrintBar();
  215. }
  216. [TargetKeyword(Token.DrawLineForm)]
  217. void DrawLineForm()
  218. {
  219. console.printCustomBar(Expr().ToString().Trim());
  220. }
  221. [TargetKeyword(Token.If)]
  222. private void If()
  223. {
  224. bool result = Expr().BinOp(new Value(0), Token.Equal).Real == 1;
  225. Match(Token.Then);
  226. GetNextToken();
  227. if (result)
  228. {
  229. int i = ifcounter;
  230. while (true)
  231. {
  232. if (lastToken == Token.If)
  233. {
  234. i++;
  235. }
  236. else if (lastToken == Token.Else)
  237. {
  238. if (i == ifcounter)
  239. {
  240. GetNextToken();
  241. return;
  242. }
  243. }
  244. else if (lastToken == Token.EndIf)
  245. {
  246. if (i == ifcounter)
  247. {
  248. GetNextToken();
  249. return;
  250. }
  251. i--;
  252. }
  253. GetNextToken();
  254. }
  255. }
  256. }
  257. [TargetKeyword(Token.Else)]
  258. private void Else()
  259. {
  260. int i = ifcounter;
  261. while (true)
  262. {
  263. if (lastToken == Token.If)
  264. {
  265. i++;
  266. }
  267. else if (lastToken == Token.EndIf)
  268. {
  269. if (i == ifcounter)
  270. {
  271. GetNextToken();
  272. return;
  273. }
  274. i--;
  275. }
  276. GetNextToken();
  277. }
  278. }
  279. [TargetKeyword(Token.EndIf)]
  280. private void EndIf()
  281. {
  282. }
  283. [TargetKeyword(Token.End)]
  284. private void End()
  285. {
  286. exit = true;
  287. }
  288. [TargetKeyword(Token.Let)]
  289. private void Let()
  290. {
  291. if (lastToken != Token.Equal)
  292. {
  293. Match(Token.Identifer);
  294. GetNextToken();
  295. Match(Token.Equal);
  296. }
  297. string id = lex.Identifer;
  298. GetNextToken();
  299. SetVar(id, Expr());
  300. }
  301. [TargetKeyword(Token.For)]
  302. private void For()
  303. {
  304. Match(Token.Identifer);
  305. string var = lex.Identifer;
  306. GetNextToken();
  307. Match(Token.Equal);
  308. GetNextToken();
  309. Value v = Expr();
  310. if (loops.ContainsKey(var))
  311. {
  312. loops[var] = lineMarker;
  313. }
  314. else
  315. {
  316. SetVar(var, v);
  317. loops.Add(var, lineMarker);
  318. }
  319. Match(Token.To);
  320. GetNextToken();
  321. v = Expr();
  322. if (vars[var].BinOp(v, Token.More).Real == 1)
  323. {
  324. while (true)
  325. {
  326. while (!(GetNextToken() == Token.Identifer && prevToken == Token.Next)) ;
  327. if (lex.Identifer == var)
  328. {
  329. loops.Remove(var);
  330. GetNextToken();
  331. Match(Token.NewLine);
  332. break;
  333. }
  334. }
  335. }
  336. }
  337. [TargetKeyword(Token.Next)]
  338. private void Next()
  339. {
  340. Match(Token.Identifer);
  341. string var = lex.Identifer;
  342. vars[var] = vars[var].BinOp(new Value(1), Token.Plus);
  343. lex.GoTo(new Marker(loops[var].Pointer - 1, loops[var].Line, loops[var].Column - 1));
  344. lastToken = Token.NewLine;
  345. }
  346. [TargetKeyword(Token.Times)]
  347. private void Times()
  348. {
  349. Match(Token.Identifer);
  350. string var = lex.Identifer;
  351. GetNextToken();
  352. Match(Token.Comma);
  353. GetNextToken();
  354. var arg2 = Expr();
  355. vars[var] = vars[var].BinOp(arg2, Token.Asterisk);
  356. Match(Token.NewLine);
  357. }
  358. #endregion
  359. void Input()
  360. {
  361. while (true)
  362. {
  363. Match(Token.Identifer);
  364. if (!vars.ContainsKey(lex.Identifer)) vars.Add(lex.Identifer, new Value());
  365. console.WaitInput(new Core.Interop.InputRequest() { InputType = Core.Interop.InputType.StrValue });
  366. string input = console.LastInput;
  367. double d;
  368. if (double.TryParse(input, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out d))
  369. vars[lex.Identifer] = new Value(d);
  370. else
  371. vars[lex.Identifer] = new Value(input);
  372. GetNextToken();
  373. if (lastToken != Token.Comma) break;
  374. GetNextToken();
  375. }
  376. }
  377. Value Expr()
  378. {
  379. Dictionary<Token, int> prec = new Dictionary<Token, int>()
  380. {
  381. { Token.Or, 0 }, { Token.And, 0 },
  382. { Token.Equal, 1 }, { Token.NotEqual, 1 },
  383. { Token.Less, 1 }, { Token.More, 1 }, { Token.LessEqual, 1 }, { Token.MoreEqual, 1 },
  384. { Token.Plus, 2 }, { Token.Minus, 2 },
  385. { Token.Asterisk, 3 }, {Token.Slash, 3 },
  386. { Token.Caret, 4 }
  387. };
  388. Stack<Value> stack = new Stack<Value>();
  389. Stack<Token> operators = new Stack<Token>();
  390. int i = 0;
  391. while (true)
  392. {
  393. if (lastToken == Token.Value)
  394. {
  395. stack.Push(lex.Value);
  396. }
  397. else if (lastToken == Token.Identifer)
  398. {
  399. if (vars.ContainsKey(lex.Identifer))
  400. {
  401. stack.Push(vars[lex.Identifer]);
  402. }
  403. else if (FunctionDictionary.ContainsKey(lex.Identifer))
  404. {
  405. string name = lex.Identifer;
  406. List<Value> args = new List<Value>();
  407. GetNextToken();
  408. Match(Token.LParen);
  409. start:
  410. if (GetNextToken() != Token.RParen)
  411. {
  412. args.Add(Expr());
  413. if (lastToken == Token.Comma)
  414. goto start;
  415. }
  416. stack.Push(FunctionDictionary[name](args));
  417. }
  418. else
  419. {
  420. Error("Undeclared variable " + lex.Identifer);
  421. }
  422. }
  423. else if (lastToken == Token.LParen)
  424. {
  425. GetNextToken();
  426. stack.Push(Expr());
  427. Match(Token.RParen);
  428. }
  429. else if (lastToken >= Token.Plus && lastToken <= Token.Not)
  430. {
  431. if ((lastToken == Token.Minus || lastToken == Token.Minus) && (i == 0 || prevToken == Token.LParen))
  432. {
  433. stack.Push(new Value(0));
  434. operators.Push(lastToken);
  435. }
  436. else
  437. {
  438. while (operators.Count > 0 && prec[lastToken] <= prec[operators.Peek()])
  439. Operation(ref stack, operators.Pop());
  440. operators.Push(lastToken);
  441. }
  442. }
  443. else
  444. {
  445. if (i == 0)
  446. Error("Empty expression");
  447. break;
  448. }
  449. i++;
  450. GetNextToken();
  451. }
  452. while (operators.Count > 0)
  453. Operation(ref stack, operators.Pop());
  454. return stack.Pop();
  455. }
  456. void Operation(ref Stack<Value> stack, Token token)
  457. {
  458. Value b = stack.Pop();
  459. Value a = stack.Pop();
  460. Value result = a.BinOp(b, token);
  461. stack.Push(result);
  462. }
  463. }
  464. }