Example #1
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            // What all functions do.
            Node firstEvaluationResult = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);

            logger.LogVerbose("EvalFun: After first eval: " + NodeOps.Serialize(firstEvaluationResult));
            logger.LogVerbose("EvalFun: After first eval: Type:" + firstEvaluationResult.NodeType);

            int listLength = ListOps.CalculateListLength(node);

            logger.LogVerbose("EvalFun: Eval number of parameters: " + listLength);

            // Create copy so we don't change the original data.
            firstEvaluationResult = NodeOps.CloneTree(firstEvaluationResult);

            for (int i = 2; i < listLength; i++)
            {
                Node additional = Evaluator.Evaluate(NodeOps.GetChild(node, i), env);
                logger.LogVerbose("EvalFun: Additional value: " + NodeOps.Serialize(additional));
                ListOps.AppendToList(additional, firstEvaluationResult);
            }

            // What eval does.
            Node evalResult = Evaluator.Evaluate(firstEvaluationResult, env);

            logger.LogVerbose("EvalFun: After second eval: " + NodeOps.Serialize(evalResult));

            return(evalResult);
        }
Example #2
0
        private static Node EvaluateEnvFunction(Node functionNode, Node node, Env env, Logger logger)
        {
            logger.LogVerbose("Trying to evaluate: " + NodeOps.Serialize(node));

            Node parameterNames = functionNode.Head;
            Node errorNode      = CreateParameterizedEnv(parameterNames, node, env, logger, out Env localEnv);

            if (errorNode != Node.NIL)
            {
                return(errorNode);
            }

            Node functionBody = functionNode.Tail;

            logger.LogVerbose("Starting functionBody evaluation: " + NodeOps.Serialize(functionBody));

            // Evaluate function.
            Node result = Evaluator.Evaluate(functionBody, localEnv);

            logger.LogVerbose("Evaluation result: " + result);

            // Discard child env.
            localEnv.CloseEnv();

            // Return function result.
            return(result);
        }
Example #3
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            int numberOfParameters = ListOps.CalculateListLength(node);

            if (numberOfParameters < 3 || numberOfParameters > 4)
            {
                string errorMsg = "Wrong number of parameters for if: " + ListOps.CalculateListLength(node);
                return(new Node(StdNodeTypes.Error, errorMsg));
            }

            Node condition = NodeOps.GetChild(node, 1);

            logger.LogVerbose("if: comparsion: " + NodeOps.Serialize(condition));

            Node   compareResult = Evaluator.Evaluate(condition, env);
            string compare       = compareResult.Content.ToString();

            logger.LogVerbose("if: compare result: " + NodeOps.Serialize(compareResult));

            if ("True".Equals(compare))
            {
                return(Evaluator.Evaluate(NodeOps.GetChild(node, 2), env));
            }

            // If we have an else part...
            if (numberOfParameters == 4)
            {
                return(Evaluator.Evaluate(NodeOps.GetChild(node, 3), env));
            }

            return(Node.NIL);
        }
Example #4
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("read-dict", node, 2);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node dictNode = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);
            Node key      = Evaluator.Evaluate(NodeOps.GetChild(node, 2), env);

            if (StdNodeTypes.Dict.Equals(dictNode.NodeType))
            {
                if (dictNode.Content is Dictionary <string, Node> dict)
                {
                    if (dict.TryGetValue(key.Content.ToString(), out Node value))
                    {
                        return(value);
                    }
                }
            }

            return(new Node(StdNodeTypes.Error, "Malformed call to read-dict: " + dictNode + ", " + key));
        }
Example #5
0
        private static void StoreMacro(Node node, Env env)
        {
            Node parameters = NodeOps.GetChild(node, 2);
            Node macroBody  = NodeOps.GetChild(node, 3);

            Node macroNode = new Node(StdNodeTypes.Macro, parameters, macroBody, node.Content);

            env.AddGlobal(NodeOps.GetChild(node, 1).Content.ToString(), macroNode);
        }
Example #6
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node parameters   = NodeOps.GetChild(node, 1);
            Node functionBody = NodeOps.GetChild(node, 2);

            Node resultNode = new Node(StdNodeTypes.Function, parameters, functionBody);

            return(resultNode);
        }
Example #7
0
        public void TestStringEvaluation()
        {
            string expr = "Test";
            Node   node = new Node(StdNodeTypes.String, expr);

            Node   nodeResult = Evaluator.Evaluate(node, env);
            string result     = NodeOps.Serialize(nodeResult);

            Assert.AreEqual("\"Test\"", result);
        }
Example #8
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            string str = NodeOps.GetChild(node, 1).Content.ToString();

            List <string> tokens = Tokenizer.Tokenize(str);

            Queue <string> q          = new Queue <string>(tokens);
            Node           parsedNode = Parser.Parse(q);

            return(parsedNode);
        }
Example #9
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("quote", node, 1);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            return(NodeOps.GetChild(node, 1));
        }
Example #10
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("type?", node, 1);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node param = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);

            return(new Node(StdNodeTypes.Identifier, param.NodeType));
        }
Example #11
0
        public static string Evaluate(string line, TraceLevel traceLevel = TraceLevel.Error, Env env = null, bool traceStdLib = false)
        {
            Node node = Parse(line);

            if (node == null)
            {
                return(null);
            }

            if (traceLevel == TraceLevel.Verbose)
            {
                Console.WriteLine("Parsed input:");
                Console.WriteLine(NodeOps.Serialize(node));
            }

            if (traceStdLib)
            {
                Evaluator.Logger.TraceLevel = traceLevel;
            }
            else
            {
                Evaluator.Logger.TraceLevel = TraceLevel.Error;
            }

            if (env == null)
            {
                env = EnvOps.CreateStdLibEnv();
            }

            Evaluator.Logger.TraceLevel = traceLevel;

            node = ExpandMacros(node, env);

            if (traceLevel == TraceLevel.Verbose)
            {
                Console.WriteLine("Expanded input:");
                Console.WriteLine(NodeOps.Serialize(node));
            }

            Node resultNode = Evaluator.Evaluate(node, env);

            if (traceLevel == TraceLevel.Verbose)
            {
                Console.WriteLine("Evaluated input:");
                Console.WriteLine(NodeOps.Serialize(resultNode));
            }

            string result = NodeOps.Serialize(resultNode);

            return(result);
        }
Example #12
0
        private static Node ApplyMacro(Node node, Node macroNode)
        {
            Node parameters = macroNode.Head;
            Node macroBody  = macroNode.Tail;

            Node clone = NodeOps.CloneTree(macroBody);

            Dictionary <string, Node> replaceMap = CreateReplacements(parameters, node);

            // Perform replace.
            clone = Replace(clone, replaceMap);

            return(clone);
        }
Example #13
0
        public void TestLambdaApplicationEvaluation()
        {
            string expr      = "(eval (list (lambda (x) (+ 1 x)) 3))";
            Node   parseTree = HighLevel.Parse(expr);

            Node nodeResult = Evaluator.Evaluate(parseTree, env);

            Assert.IsNotNull(nodeResult);
            Assert.AreEqual(StdNodeTypes.Identifier, nodeResult.NodeType);

            string result = NodeOps.Serialize(nodeResult);

            Assert.AreEqual("4", result);
        }
Example #14
0
        public void TestSimpleParse()
        {
            string line = "(seq (defmacro inc (x) (+ x 1)) (inc 2))";

            Node node = HighLevel.Parse(line);

            Assert.IsNotNull(node);

            Env env = new Env(null);

            node = MacroExpander.ExpandMacros(node, env);
            string serialization = NodeOps.Serialize(node);

            Assert.AreEqual("(seq (+ 2 1))", serialization);
        }
Example #15
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("cons", node, 2);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node head = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);
            Node tail = Evaluator.Evaluate(NodeOps.GetChild(node, 2), env);

            Node cons = new Node(StdNodeTypes.Cons, head, tail, null);

            return(cons);
        }
Example #16
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node keyNode = NodeOps.GetChild(node, 1);

            if (!StdNodeTypes.Identifier.Equals(keyNode.NodeType))
            {
                keyNode = Evaluator.Evaluate(keyNode, env);
            }

            string key   = keyNode.Content.ToString();
            Node   value = Evaluator.Evaluate(NodeOps.GetChild(node, 2), env);

            env.Add(key, value);

            return(Node.NIL);
        }
Example #17
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("print", node, 1);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node   parameter = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);
            string result    = NodeOps.Serialize(parameter);

            Console.WriteLine(result);

            return(Node.NIL);
        }
Example #18
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("save-file", node, 2);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node   fileNode = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);
            string file     = fileNode.Content.ToString();

            Node   contentNode = Evaluator.Evaluate(NodeOps.GetChild(node, 2), env);
            string content     = contentNode.Content.ToString();

            File.WriteAllText(file, content);

            return(Node.NIL);
        }
Example #19
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("=", node, 2);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            string val1 = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env).Content.ToString();
            string val2 = Evaluator.Evaluate(NodeOps.GetChild(node, 2), env).Content.ToString();

            if (val1.Equals(val2))
            {
                return(Node.TRUE);
            }

            return(Node.FALSE);
        }
Example #20
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("keys-dict", node, 1);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node dictNode = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);

            if (StdNodeTypes.Dict.Equals(dictNode.NodeType))
            {
                if (dictNode.Content is Dictionary <string, Node> dict)
                {
                    Node list      = null;
                    Node listStart = null;

                    foreach (string key in dict.Keys)
                    {
                        Node keyNode = new Node(StdNodeTypes.String, key);

                        Node newCons = new Node(StdNodeTypes.Cons, null);
                        newCons.Head = keyNode;
                        if (listStart == null)
                        {
                            listStart = newCons;
                        }
                        else
                        {
                            list.Tail = newCons;
                        }
                        list = newCons;
                    }

                    return(listStart);
                }
            }

            return(new Node(StdNodeTypes.Error, "Malformed call to keys-dict: " + dictNode));
        }
Example #21
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("int-to-char", node, 1);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node intNode = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);

            if (int.TryParse(intNode.Content.ToString(), out int result))
            {
                string c = char.ConvertFromUtf32(result);
                return(new Node(StdNodeTypes.String, c));
            }

            string errorMsg = "Invalid parameter to IntToCharFun";

            return(new Node(StdNodeTypes.Error, errorMsg));
        }
Example #22
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("char-to-int", node, 1);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node charNode = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);

            if (charNode.Content.ToString().Length != 1)
            {
                string errorMsg = "Invalid parameter to CharToIntFun";
                return(new Node(StdNodeTypes.Error, errorMsg));
            }

            int c = char.ConvertToUtf32(charNode.Content.ToString(), 0);

            return(new Node(StdNodeTypes.String, c.ToString(CultureInfo.InvariantCulture)));
        }
Example #23
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node strNode = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);

            if (!strNode.NodeType.Equals(StdNodeTypes.String))
            {
                return(Node.NIL);
            }

            string str = strNode.Content.ToString();

            Node startNode  = Evaluator.Evaluate(NodeOps.GetChild(node, 2), env);
            Node lengthNode = Evaluator.Evaluate(NodeOps.GetChild(node, 3), env);

            int start  = int.Parse(startNode.Content.ToString(), CultureInfo.InvariantCulture);
            int length = int.Parse(lengthNode.Content.ToString(), CultureInfo.InvariantCulture);

            string result = str.Substring(start, length);

            return(new Node(StdNodeTypes.String, result));
        }
Example #24
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("string-length", node, 1);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node strNode = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);

            if (!StdNodeTypes.String.Equals(strNode.NodeType))
            {
                return(Node.NIL);
            }

            string str    = strNode.Content.ToString();
            string result = str.Length.ToString(CultureInfo.InvariantCulture);

            return(new Node(StdNodeTypes.Identifier, result));
        }
Example #25
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("load-file", node, 1);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node fileNode = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);

            string file = fileNode.Content.ToString();

            if (File.Exists(file))
            {
                string input = File.ReadAllText(file);
                return(new Node(StdNodeTypes.String, input));
            }

            return(new Node(StdNodeTypes.String, "File not found"));
        }
Example #26
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            double result = 0.0;

            int nodeChildrenCount = ListOps.CalculateListLength(node);

            if (nodeChildrenCount > 1)
            {
                Node parameter0 = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);
                result = double.Parse(parameter0.Content.ToString(), CultureInfo.InvariantCulture);
                for (int i = 2; i < nodeChildrenCount; i++)
                {
                    Node parameter = Evaluator.Evaluate(NodeOps.GetChild(node, i), env);
                    result -= double.Parse(parameter.Content.ToString(), CultureInfo.InvariantCulture);
                }
            }

            string resultStr = result.ToString(CultureInfo.InvariantCulture);

            return(new Node(StdNodeTypes.Identifier, resultStr));
        }
Example #27
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters(">", node, 2);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            string val1String = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env).Content.ToString();
            string val2String = Evaluator.Evaluate(NodeOps.GetChild(node, 2), env).Content.ToString();

            double val1 = double.Parse(val1String, CultureInfo.InvariantCulture);
            double val2 = double.Parse(val2String, CultureInfo.InvariantCulture);

            if (val1 > val2)
            {
                return(Node.TRUE);
            }

            return(Node.FALSE);
        }
Example #28
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("char-at", node, 2);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node strNode = Evaluator.Evaluate(NodeOps.GetChild(node, 1), env);

            if (!StdNodeTypes.String.Equals(strNode.NodeType))
            {
                return(Node.NIL);
            }

            Node indexNode = Evaluator.Evaluate(NodeOps.GetChild(node, 2), env);
            int  index     = int.Parse(indexNode.Content.ToString(), CultureInfo.InvariantCulture);

            string result = strNode.Content.ToString().Substring(index, 1);

            return(new Node(StdNodeTypes.String, result));
        }
Example #29
0
        public Node TryEval(Node node, Env env, Logger logger)
        {
            Node checkResult = BuiltinOps.CheckParameters("tail", node, 1);

            if (checkResult != Node.NIL)
            {
                return(checkResult);
            }

            Node list = Evaluator.Evaluate(node.Tail.Head, env);

            if (list == Node.NIL)
            {
                return(Node.NIL);
            }

            if (!StdNodeTypes.Cons.Equals(list.NodeType))
            {
                string errorMsg = "Invalid parameter type for tail: " + list.NodeType + " (should be Cons): " + NodeOps.Serialize(list);
                return(new Node(StdNodeTypes.Error, errorMsg));
            }

            return(list.Tail);
        }
Example #30
0
        private static Node CreateParameterizedEnv(Node parameterNames, Node node, Env env, Logger logger, out Env outEnv)
        {
            int numParameters = ListOps.CalculateListLength(parameterNames);

            logger.LogVerbose("envFunction has " + numParameters + " parameters.");

            // Create child env.
            Env localEnv = new Env(env);

            // At 0 is the function name.
            int parameterValueIndex = 1;

            // Add all parameters to local env.
            for (int i = 0; i < numParameters; i++)
            {
                string parameterName = NodeOps.GetChild(parameterNames, i).Content.ToString();

                if (parameterName.StartsWith("&"))
                {
                    // Handle special parameter.
                    if ("&rest".Equals(parameterName))
                    {
                        string restParameterName = NodeOps.GetChild(parameterNames, i + 1).Content.ToString();

                        int nodeChildrenCount = ListOps.CalculateListLength(node);

                        Node restParameterValues = null;

                        for (int j = parameterValueIndex; j < nodeChildrenCount; j++)
                        {
                            Node parameter = Evaluator.Evaluate(NodeOps.GetChild(node, j), env);
                            restParameterValues = ListOps.AppendToList(parameter, restParameterValues);
                        }

                        localEnv.Add(restParameterName, restParameterValues);
                        outEnv = localEnv;
                        return(Node.NIL);
                    }
                }
                else
                {
                    Node parameterValue = Evaluator.Evaluate(NodeOps.GetChild(node, parameterValueIndex), env);
                    logger.LogVerbose("Adding parameterValue " + i + "(" + parameterName + "): " + parameterValue);
                    localEnv.Add(parameterName, parameterValue);
                    parameterValueIndex++;
                }
            }

            int nodeChildrenCount2 = ListOps.CalculateListLength(node);

            if (nodeChildrenCount2 != parameterValueIndex)
            {
                int    remainingParameterCount = nodeChildrenCount2 - parameterValueIndex;
                string errorMsg = "EvaluateEnvFunction/CreateParameterizedEnv: " + remainingParameterCount + " additional parameters found.";
                outEnv = null;
                return(new Node(StdNodeTypes.Error, errorMsg));
            }

            outEnv = localEnv;
            return(Node.NIL);
        }