123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Text.RegularExpressions;
- using NTERA.Core;
- namespace NTERA.Interpreter
- {
- public partial class Interpreter
- {
- private Lexer lex;
- private Token prevToken;
- private Token lastToken;
- private Dictionary<string, Value> vars;
- private Dictionary<string, Marker> loops;
- public delegate Value BasicFunction(List<Value> args);
- private readonly IConsole console;
- private int ifcounter;
- private Marker lineMarker;
- private bool exit;
- public Interpreter(IConsole console, string input)
- {
- this.console = console;
- lex = new Lexer(input);
- vars = new Dictionary<string, Value>();
- loops = new Dictionary<string, Marker>();
- ifcounter = 0;
- GenerateKeywordDictionary();
- GenerateFunctionDictionary();
- }
- public Value GetVar(string name)
- {
- if (!vars.ContainsKey(name))
- throw new Exception("Variable with name " + name + " does not exist.");
- return vars[name];
- }
- public void SetVar(string name, Value val)
- {
- if (!vars.ContainsKey(name)) vars.Add(name, val);
- else vars[name] = val;
- }
- void Error(string text)
- {
- throw new Exception(text + " at line: " + lineMarker.Line);
- }
- void Match(Token tok)
- {
- if (lastToken != tok)
- Error("Expect " + tok + " got " + lastToken);
- }
- private IEnumerator<Token> tokens;
- public void Exec()
- {
- exit = false;
- tokens = lex.GetTokens().GetEnumerator();
- GetNextToken();
- while (!exit) Line();
- }
- Token GetNextToken()
- {
- prevToken = lastToken;
- tokens.MoveNext();
- lastToken = tokens.Current;
- if (lastToken == Token.EOF && prevToken == Token.EOF)
- Error("Unexpected end of file");
-
- return lastToken;
- }
- void Line()
- {
- while (lastToken == Token.NewLine) GetNextToken();
- if (lastToken == Token.EOF)
- {
- exit = true;
- return;
- }
- lineMarker = lex.TokenMarker;
- Statment();
- if (lastToken != Token.NewLine && lastToken != Token.EOF)
- Error("Expect new line got " + lastToken);
- }
- void Statment()
- {
- Token keyword = lastToken;
- GetNextToken();
- if (KeywordMethods.ContainsKey(keyword))
- KeywordMethods[keyword]();
- else
- {
- switch (keyword)
- {
- case Token.Input: Input(); break;
- case Token.Function:
- case Token.Global:
- case Token.Dim:
- case Token.Const:
- while (GetNextToken() != Token.NewLine) { }
- break;
- case Token.Identifer:
- if (lastToken == Token.Equal) Let();
- else goto default;
- break;
- case Token.EOF:
- exit = true;
- break;
- default:
- Error("Expect keyword got " + keyword);
- break;
- }
- }
- if (lastToken == Token.Colon)
- {
- GetNextToken();
- Statment();
- }
- }
- #region Functions
-
- private Dictionary<string, BasicFunction> FunctionDictionary { get; set; }
- private void GenerateFunctionDictionary()
- {
- FunctionDictionary = new Dictionary<string, BasicFunction>(StringComparer.InvariantCultureIgnoreCase);
- foreach (var method in typeof(Interpreter).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
- {
- var attribute = method.GetCustomAttributes(typeof(BuiltInFunctionAttribute), true).FirstOrDefault() as BuiltInFunctionAttribute;
- if (attribute == null)
- continue;
- FunctionDictionary[attribute.Name] = args => (Value)method.Invoke(this, new object[] { args });
- }
- }
- [BuiltInFunction("str")]
- private Value Str(List<Value> args)
- {
- if (args.Count < 1)
- throw new ArgumentException();
- return args[0].Convert(ValueType.String);
- }
- [BuiltInFunction("num")]
- private Value Num(List<Value> args)
- {
- if (args.Count < 1)
- throw new ArgumentException();
- return args[0].Convert(ValueType.Real);
- }
- [BuiltInFunction("abs")]
- private Value Abs(List<Value> args)
- {
- if (args.Count < 1)
- throw new ArgumentException();
- return new Value(Math.Abs(args[0].Real));
- }
- [BuiltInFunction("min")]
- private Value Min(List<Value> args)
- {
- if (args.Count < 2)
- throw new ArgumentException();
- return new Value(Math.Min(args[0].Real, args[1].Real));
- }
- [BuiltInFunction("max")]
- private Value Max(List<Value> args)
- {
- if (args.Count < 2)
- throw new ArgumentException();
- return new Value(Math.Max(args[0].Real, args[1].Real));
- }
- [BuiltInFunction("not")]
- private Value Not(List<Value> args)
- {
- if (args.Count < 1)
- throw new ArgumentException();
- return new Value(args[0].Real == 0 ? 1 : 0);
- }
- private readonly Random random = new Random();
- [BuiltInFunction("rand")]
- private Value Rand(List<Value> args)
- {
- if (args.Count < 2)
- throw new ArgumentException();
- return new Value(random.Next((int)args[0].Real, (int)args[1].Real - 1));
- }
- #endregion
- #region Keywords
- private Dictionary<Token, Action> KeywordMethods { get; set; }
- private void GenerateKeywordDictionary()
- {
- KeywordMethods = new Dictionary<Token, Action>();
- foreach (var method in typeof(Interpreter).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
- {
- var attribute = method.GetCustomAttributes(typeof(TargetKeywordAttribute), true).FirstOrDefault() as TargetKeywordAttribute;
- if (attribute == null)
- continue;
- KeywordMethods[attribute.Token] = () => method.Invoke(this, null);
- }
- }
- [TargetKeyword(Token.Print)]
- void Print()
- {
- console.Write(Expr().ToString());
- }
- [TargetKeyword(Token.PrintL)]
- void PrintL()
- {
- console.PrintSingleLine(Expr().ToString());
- }
- [TargetKeyword(Token.PrintImg)]
- void PrintImg()
- {
- console.PrintImg(Expr().ToString().Trim().Trim('"'));
- }
- [TargetKeyword(Token.PrintButton)]
- void PrintButton()
- {
- console.PrintButton(Expr().ToString(), 0);
- }
- private static readonly Regex FormRegex = new Regex("{(.*?)}");
- [TargetKeyword(Token.PrintFormL)]
- void PrintFormL()
- {
- string rawString = Expr().ToString();
- var evaluator = new MatchEvaluator(match => vars[match.Groups[1].Value].ToString());
- console.PrintSingleLine(FormRegex.Replace(rawString, evaluator));
- }
- [TargetKeyword(Token.DrawLine)]
- void DrawLine()
- {
- console.PrintBar();
- }
- [TargetKeyword(Token.DrawLineForm)]
- void DrawLineForm()
- {
- console.printCustomBar(Expr().ToString().Trim());
- }
- [TargetKeyword(Token.If)]
- private void If()
- {
- bool result = Expr().BinOp(new Value(0), Token.Equal).Real == 1;
- Match(Token.Then);
- GetNextToken();
- if (result)
- {
- int i = ifcounter;
- while (true)
- {
- if (lastToken == Token.If)
- {
- i++;
- }
- else if (lastToken == Token.Else)
- {
- if (i == ifcounter)
- {
- GetNextToken();
- return;
- }
- }
- else if (lastToken == Token.EndIf)
- {
- if (i == ifcounter)
- {
- GetNextToken();
- return;
- }
- i--;
- }
- GetNextToken();
- }
- }
- }
- [TargetKeyword(Token.Else)]
- private void Else()
- {
- int i = ifcounter;
- while (true)
- {
- if (lastToken == Token.If)
- {
- i++;
- }
- else if (lastToken == Token.EndIf)
- {
- if (i == ifcounter)
- {
- GetNextToken();
- return;
- }
- i--;
- }
- GetNextToken();
- }
- }
- [TargetKeyword(Token.EndIf)]
- private void EndIf()
- {
- }
- [TargetKeyword(Token.End)]
- private void End()
- {
- exit = true;
- }
- [TargetKeyword(Token.Let)]
- private void Let()
- {
- if (lastToken != Token.Equal)
- {
- Match(Token.Identifer);
- GetNextToken();
- Match(Token.Equal);
- }
- string id = lex.Identifer;
- GetNextToken();
- SetVar(id, Expr());
- }
- [TargetKeyword(Token.For)]
- private void For()
- {
- Match(Token.Identifer);
- string var = lex.Identifer;
- GetNextToken();
- Match(Token.Equal);
- GetNextToken();
- Value v = Expr();
- if (loops.ContainsKey(var))
- {
- loops[var] = lineMarker;
- }
- else
- {
- SetVar(var, v);
- loops.Add(var, lineMarker);
- }
- Match(Token.To);
- GetNextToken();
- v = Expr();
- if (vars[var].BinOp(v, Token.More).Real == 1)
- {
- while (true)
- {
- while (!(GetNextToken() == Token.Identifer && prevToken == Token.Next)) ;
- if (lex.Identifer == var)
- {
- loops.Remove(var);
- GetNextToken();
- Match(Token.NewLine);
- break;
- }
- }
- }
- }
- [TargetKeyword(Token.Next)]
- private void Next()
- {
- Match(Token.Identifer);
- string var = lex.Identifer;
- vars[var] = vars[var].BinOp(new Value(1), Token.Plus);
- lex.GoTo(new Marker(loops[var].Pointer - 1, loops[var].Line, loops[var].Column - 1));
- lastToken = Token.NewLine;
- }
- [TargetKeyword(Token.Times)]
- private void Times()
- {
- Match(Token.Identifer);
- string var = lex.Identifer;
- GetNextToken();
- Match(Token.Comma);
- GetNextToken();
- var arg2 = Expr();
- vars[var] = vars[var].BinOp(arg2, Token.Asterisk);
-
- Match(Token.NewLine);
- }
- #endregion
- void Input()
- {
- while (true)
- {
- Match(Token.Identifer);
-
- if (!vars.ContainsKey(lex.Identifer)) vars.Add(lex.Identifer, new Value());
- console.WaitInput(new Core.Interop.InputRequest() { InputType = Core.Interop.InputType.StrValue });
- string input = console.LastInput;
- double d;
- if (double.TryParse(input, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out d))
- vars[lex.Identifer] = new Value(d);
- else
- vars[lex.Identifer] = new Value(input);
-
- GetNextToken();
- if (lastToken != Token.Comma) break;
- GetNextToken();
- }
- }
- Value Expr()
- {
- Dictionary<Token, int> prec = new Dictionary<Token, int>()
- {
- { Token.Or, 0 }, { Token.And, 0 },
- { Token.Equal, 1 }, { Token.NotEqual, 1 },
- { Token.Less, 1 }, { Token.More, 1 }, { Token.LessEqual, 1 }, { Token.MoreEqual, 1 },
- { Token.Plus, 2 }, { Token.Minus, 2 },
- { Token.Asterisk, 3 }, {Token.Slash, 3 },
- { Token.Caret, 4 }
- };
- Stack<Value> stack = new Stack<Value>();
- Stack<Token> operators = new Stack<Token>();
- int i = 0;
- while (true)
- {
- if (lastToken == Token.Value)
- {
- stack.Push(lex.Value);
- }
- else if (lastToken == Token.Identifer)
- {
- if (vars.ContainsKey(lex.Identifer))
- {
- stack.Push(vars[lex.Identifer]);
- }
- else if (FunctionDictionary.ContainsKey(lex.Identifer))
- {
- string name = lex.Identifer;
- List<Value> args = new List<Value>();
- GetNextToken();
- Match(Token.LParen);
- start:
- if (GetNextToken() != Token.RParen)
- {
- args.Add(Expr());
- if (lastToken == Token.Comma)
- goto start;
- }
- stack.Push(FunctionDictionary[name](args));
- }
- else
- {
- Error("Undeclared variable " + lex.Identifer);
- }
- }
- else if (lastToken == Token.LParen)
- {
- GetNextToken();
- stack.Push(Expr());
- Match(Token.RParen);
- }
- else if (lastToken >= Token.Plus && lastToken <= Token.Not)
- {
- if ((lastToken == Token.Minus || lastToken == Token.Minus) && (i == 0 || prevToken == Token.LParen))
- {
- stack.Push(new Value(0));
- operators.Push(lastToken);
- }
- else
- {
- while (operators.Count > 0 && prec[lastToken] <= prec[operators.Peek()])
- Operation(ref stack, operators.Pop());
- operators.Push(lastToken);
- }
- }
- else
- {
- if (i == 0)
- Error("Empty expression");
- break;
- }
- i++;
- GetNextToken();
- }
- while (operators.Count > 0)
- Operation(ref stack, operators.Pop());
- return stack.Pop();
- }
- void Operation(ref Stack<Value> stack, Token token)
- {
- Value b = stack.Pop();
- Value a = stack.Pop();
- Value result = a.BinOp(b, token);
- stack.Push(result);
- }
- }
- }
|