Interpreter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. [TargetKeyword(Token.PrintImg)]
  204. void PrintImg()
  205. {
  206. console.PrintImg(Expr().ToString().Trim().Trim('"'));
  207. }
  208. [TargetKeyword(Token.PrintButton)]
  209. void PrintButton()
  210. {
  211. console.PrintButton(Expr().ToString(), 0);
  212. }
  213. private static readonly Regex FormRegex = new Regex("{(.*?)}");
  214. [TargetKeyword(Token.PrintFormL)]
  215. void PrintFormL()
  216. {
  217. string rawString = Expr().ToString();
  218. var evaluator = new MatchEvaluator(match => vars[match.Groups[1].Value].ToString());
  219. console.PrintSingleLine(FormRegex.Replace(rawString, evaluator));
  220. }
  221. [TargetKeyword(Token.DrawLine)]
  222. void DrawLine()
  223. {
  224. console.PrintBar();
  225. }
  226. [TargetKeyword(Token.DrawLineForm)]
  227. void DrawLineForm()
  228. {
  229. console.printCustomBar(Expr().ToString().Trim());
  230. }
  231. [TargetKeyword(Token.If)]
  232. private void If()
  233. {
  234. bool result = Expr().BinOp(new Value(0), Token.Equal).Real == 1;
  235. Match(Token.Then);
  236. GetNextToken();
  237. if (result)
  238. {
  239. int i = ifcounter;
  240. while (true)
  241. {
  242. if (lastToken == Token.If)
  243. {
  244. i++;
  245. }
  246. else if (lastToken == Token.Else)
  247. {
  248. if (i == ifcounter)
  249. {
  250. GetNextToken();
  251. return;
  252. }
  253. }
  254. else if (lastToken == Token.EndIf)
  255. {
  256. if (i == ifcounter)
  257. {
  258. GetNextToken();
  259. return;
  260. }
  261. i--;
  262. }
  263. GetNextToken();
  264. }
  265. }
  266. }
  267. [TargetKeyword(Token.Else)]
  268. private void Else()
  269. {
  270. int i = ifcounter;
  271. while (true)
  272. {
  273. if (lastToken == Token.If)
  274. {
  275. i++;
  276. }
  277. else if (lastToken == Token.EndIf)
  278. {
  279. if (i == ifcounter)
  280. {
  281. GetNextToken();
  282. return;
  283. }
  284. i--;
  285. }
  286. GetNextToken();
  287. }
  288. }
  289. [TargetKeyword(Token.EndIf)]
  290. private void EndIf()
  291. {
  292. }
  293. [TargetKeyword(Token.End)]
  294. private void End()
  295. {
  296. exit = true;
  297. }
  298. [TargetKeyword(Token.Let)]
  299. private void Let()
  300. {
  301. if (lastToken != Token.Equal)
  302. {
  303. Match(Token.Identifer);
  304. GetNextToken();
  305. Match(Token.Equal);
  306. }
  307. string id = lex.Identifer;
  308. GetNextToken();
  309. SetVar(id, Expr());
  310. }
  311. [TargetKeyword(Token.For)]
  312. private void For()
  313. {
  314. Match(Token.Identifer);
  315. string var = lex.Identifer;
  316. GetNextToken();
  317. Match(Token.Equal);
  318. GetNextToken();
  319. Value v = Expr();
  320. if (loops.ContainsKey(var))
  321. {
  322. loops[var] = lineMarker;
  323. }
  324. else
  325. {
  326. SetVar(var, v);
  327. loops.Add(var, lineMarker);
  328. }
  329. Match(Token.To);
  330. GetNextToken();
  331. v = Expr();
  332. if (vars[var].BinOp(v, Token.More).Real == 1)
  333. {
  334. while (true)
  335. {
  336. while (!(GetNextToken() == Token.Identifer && prevToken == Token.Next)) ;
  337. if (lex.Identifer == var)
  338. {
  339. loops.Remove(var);
  340. GetNextToken();
  341. Match(Token.NewLine);
  342. break;
  343. }
  344. }
  345. }
  346. }
  347. [TargetKeyword(Token.Next)]
  348. private void Next()
  349. {
  350. Match(Token.Identifer);
  351. string var = lex.Identifer;
  352. vars[var] = vars[var].BinOp(new Value(1), Token.Plus);
  353. lex.GoTo(new Marker(loops[var].Pointer - 1, loops[var].Line, loops[var].Column - 1));
  354. lastToken = Token.NewLine;
  355. }
  356. [TargetKeyword(Token.Times)]
  357. private void Times()
  358. {
  359. Match(Token.Identifer);
  360. string var = lex.Identifer;
  361. GetNextToken();
  362. Match(Token.Comma);
  363. GetNextToken();
  364. var arg2 = Expr();
  365. vars[var] = vars[var].BinOp(arg2, Token.Asterisk);
  366. Match(Token.NewLine);
  367. }
  368. #endregion
  369. void Input()
  370. {
  371. while (true)
  372. {
  373. Match(Token.Identifer);
  374. if (!vars.ContainsKey(lex.Identifer)) vars.Add(lex.Identifer, new Value());
  375. console.WaitInput(new Core.Interop.InputRequest() { InputType = Core.Interop.InputType.StrValue });
  376. string input = console.LastInput;
  377. double d;
  378. if (double.TryParse(input, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out d))
  379. vars[lex.Identifer] = new Value(d);
  380. else
  381. vars[lex.Identifer] = new Value(input);
  382. GetNextToken();
  383. if (lastToken != Token.Comma) break;
  384. GetNextToken();
  385. }
  386. }
  387. Value Expr()
  388. {
  389. Dictionary<Token, int> prec = new Dictionary<Token, int>()
  390. {
  391. { Token.Or, 0 }, { Token.And, 0 },
  392. { Token.Equal, 1 }, { Token.NotEqual, 1 },
  393. { Token.Less, 1 }, { Token.More, 1 }, { Token.LessEqual, 1 }, { Token.MoreEqual, 1 },
  394. { Token.Plus, 2 }, { Token.Minus, 2 },
  395. { Token.Asterisk, 3 }, {Token.Slash, 3 },
  396. { Token.Caret, 4 }
  397. };
  398. Stack<Value> stack = new Stack<Value>();
  399. Stack<Token> operators = new Stack<Token>();
  400. int i = 0;
  401. while (true)
  402. {
  403. if (lastToken == Token.Value)
  404. {
  405. stack.Push(lex.Value);
  406. }
  407. else if (lastToken == Token.Identifer)
  408. {
  409. if (vars.ContainsKey(lex.Identifer))
  410. {
  411. stack.Push(vars[lex.Identifer]);
  412. }
  413. else if (FunctionDictionary.ContainsKey(lex.Identifer))
  414. {
  415. string name = lex.Identifer;
  416. List<Value> args = new List<Value>();
  417. GetNextToken();
  418. Match(Token.LParen);
  419. start:
  420. if (GetNextToken() != Token.RParen)
  421. {
  422. args.Add(Expr());
  423. if (lastToken == Token.Comma)
  424. goto start;
  425. }
  426. stack.Push(FunctionDictionary[name](args));
  427. }
  428. else
  429. {
  430. Error("Undeclared variable " + lex.Identifer);
  431. }
  432. }
  433. else if (lastToken == Token.LParen)
  434. {
  435. GetNextToken();
  436. stack.Push(Expr());
  437. Match(Token.RParen);
  438. }
  439. else if (lastToken >= Token.Plus && lastToken <= Token.Not)
  440. {
  441. if ((lastToken == Token.Minus || lastToken == Token.Minus) && (i == 0 || prevToken == Token.LParen))
  442. {
  443. stack.Push(new Value(0));
  444. operators.Push(lastToken);
  445. }
  446. else
  447. {
  448. while (operators.Count > 0 && prec[lastToken] <= prec[operators.Peek()])
  449. Operation(ref stack, operators.Pop());
  450. operators.Push(lastToken);
  451. }
  452. }
  453. else
  454. {
  455. if (i == 0)
  456. Error("Empty expression");
  457. break;
  458. }
  459. i++;
  460. GetNextToken();
  461. }
  462. while (operators.Count > 0)
  463. Operation(ref stack, operators.Pop());
  464. return stack.Pop();
  465. }
  466. void Operation(ref Stack<Value> stack, Token token)
  467. {
  468. Value b = stack.Pop();
  469. Value a = stack.Pop();
  470. Value result = a.BinOp(b, token);
  471. stack.Push(result);
  472. }
  473. }
  474. }