Example #1
0
        public Interpreter(string filename)
        {
            var gmem = KittenVisitor.globalMemory;

            gmem.Add("print", new DynObj {
                t = vType.Function, FuncVal = new function {
                    t = function.funcType.Builtin, BuiltinIMP = BI_print
                }
            });
            gmem.Add("println", new DynObj {
                t = vType.Function, FuncVal = new function {
                    t = function.funcType.Builtin, BuiltinIMP = BI_println
                }
            });
            gmem.Add("number", new DynObj {
                t = vType.Function, FuncVal = new function {
                    t = function.funcType.Builtin, BuiltinIMP = BI_numberCast
                }
            });
            gmem.Add("input", new DynObj {
                t = vType.Function, FuncVal = new function {
                    t = function.funcType.Builtin, BuiltinIMP = BI_input
                }
            });
            input   = File.ReadAllText(filename);
            lexer   = new KittenGrammarLexer(new AntlrInputStream(input));
            parser  = new KittenGrammarParser(new CommonTokenStream(lexer));
            tree    = parser.compileUnit();
            visitor = new KittenVisitor(new Dictionary <string, DynObj>());
        }
Example #2
0
        public override DynObj VisitFunctionCallExpr([NotNull] KittenGrammarParser.FunctionCallExprContext context)
        {
            var name = context.ID().Symbol.Text;

            if (!memory.ContainsKey(name))
            {
                ReportError("UnrecognizedIdentifierError", $"identifier name {name} not found in the context", context.start.Line);
            }
            var paraList  = memory[name].FuncVal.parameters;
            var valueList = new List <DynObj>();

            if (context.exprList() != null)
            {
                foreach (var item in context.exprList().expr())
                {
                    valueList.Add(Visit(item));
                }
            }
            if (memory[name].FuncVal.t == function.funcType.User)
            {
                if (paraList.Count != valueList.Count)
                {
                    ReportError("ArgumentNumberMismatchError", $"expected {paraList.Count}, but called with {valueList.Count}", context.start.Line);
                }
                Dictionary <string, DynObj> contextMem = new Dictionary <string, DynObj>();
                for (int i = 0; i < paraList.Count; i++)
                {
                    contextMem.Add(paraList[i], valueList[i]);
                }
                var funcVisitor = new KittenVisitor(contextMem);
                return(funcVisitor.Visit(memory[name].FuncVal.IMP));
            }
            if (memory[name].FuncVal.t == function.funcType.Builtin)
            {
                return(memory[name].FuncVal.BuiltinIMP(valueList));
            }
            return(base.VisitFunctionCallExpr(context));
        }