public override Token compile(Token currentToken, Token lastToken, NodeLinkedList nodeLinkedList, Node before)
        {
            //string supportedTokenString;
            //int level = currentToken.level;

            var first  = currentToken;
            var second = currentToken.nextToken;
            var third  = second.nextToken;

            string leftVarName  = first.value;
            string rightVarName = third.value;

            Node current = before;

            // numbers omzetten naar identifiers
            if (first.tokenType != TokenType.Identifier)
            {
                current     = current.insertPrevious(new NodeDirectFunction("ConstantToReturn", first.value));
                leftVarName = Guid.NewGuid().ToString("N");
                current     = current.insertPrevious(new NodeDirectFunction("ReturnToVariable", leftVarName));
            }
            if (third.tokenType != TokenType.Identifier)
            {
                current      = current.insertPrevious(new NodeDirectFunction("ConstantToReturn", third.value));
                rightVarName = Guid.NewGuid().ToString("N");
                current      = current.insertPrevious(new NodeDirectFunction("ReturnToVariable", rightVarName));
            }

            //Zet een berekening klaar
            //TODO "AreEqual is hardcoded" '!=' elke middelste token zal als 'AreEqual beschouwt worden'
            current = current.insertPrevious(new NodeFunction("AreEqual", leftVarName, rightVarName));

            return(third.nextToken);
        }
Esempio n. 2
0
        public override NodeLinkedList compile(ref LinkedListNode <Token> currentToken)
        {
            Token  leftToken  = currentToken.Value;
            string leftName   = leftToken.value;
            Token  rightToken = currentToken.Next.Next.Value;
            string rightName  = rightToken.value;

            //Compile left of +
            //var leftCompiled = CompilerFactory.Instance.CreateCompiledStatement(currentToken);

            //simple assignment
            if (currentToken.Next.Next.Next.Value.type == TokenType.Endstatement)
            {
                //Temp variable for right
                if (rightToken.type == TokenType.Number)
                {
                    Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.CONSTANTTORETURN, rightToken));
                }
                else if (rightToken.type == TokenType.Variable)
                {
                    Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.VARIABLETORETURN, rightName));
                }
                currentToken = currentToken.Next.Next.Next.Next;
            }
            else
            {
                currentToken = currentToken.Next.Next;
                CompiledStatement cs  = CompilerFactory.Instance.CreateCompiledStatement(currentToken);
                NodeLinkedList    nll = cs.compile(ref currentToken);
                Compiled.Add(nll);
                currentToken = currentToken.Next;
            }
            Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.RETURNTOVARIABLE, leftName));
            return(Compiled);
        }
        public void run(NodeLinkedList list)
        {
            Console.WriteLine("<------ Virtual Machine ------>");
            Console.WriteLine("");
            _commands = new Dictionary<string, BaseCommand>();
            Variables = new Dictionary<string, Variable>();
            ReturnVariable = new Variable();

            initialiseCommands();

            Node currentNode = list.getFirst();
            NextNodeVisitor visitor = new NextNodeVisitor(this);

            while (currentNode != null)
            {
                AbstractFunctionCall actionNode = currentNode as AbstractFunctionCall;

                if (actionNode != null)
                {
                    string name = actionNode.parameters[0];
                    _commands[name].execute(this, actionNode.parameters);
                }

                // Bepaal de volgende node:
                currentNode.accept(visitor);
                currentNode = visitor.nextNode;
            }
            Console.WriteLine("");
            Console.WriteLine("<------ Einde programma ------>");
            Console.WriteLine("");
        }
Esempio n. 4
0
        public override NodeLinkedList compile(ref LinkedListNode <Token> currentToken)
        {
            Token  valueToken = currentToken.Next.Next.Value;
            string valueName  = valueToken.value;

            //Compile left of +
            //var leftCompiled = CompilerFactory.Instance.CreateCompiledStatement(currentToken);

            currentToken = currentToken.Next.Next;
            try
            {
                CompiledStatement cs  = CompilerFactory.Instance.CreateCompiledStatement(currentToken);
                NodeLinkedList    nll = cs.compile(ref currentToken);
                Compiled.Add(nll);
            }
            catch
            {
                if (valueToken.type == TokenType.Number)
                {
                    Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.CONSTANTTORETURN, valueToken));
                }
                else if (valueToken.type == TokenType.Variable)
                {
                    Compiled.Add(new DirectFunctionCallNode(DirectFunctionCallNode.VARIABLETORETURN, valueName));
                }
                currentToken = currentToken.Next;
            }

            Compiled.Add(new FunctionCallNode("Print"));

            currentToken = currentToken.Next.Next;
            return(Compiled);
        }
Esempio n. 5
0
 //sub compile method OLD
 public virtual Token compile(Token currentToken, Token endToken, NodeLinkedList nodeList, Node before)
 {
     while (currentToken != null)
     {
         currentToken = CompilerFactory.getInstance().getCompiler(currentToken).compile(currentToken, endToken, nodeList, before);
     }
     return(null);
 }
 public CompiledIfGeneral()
     : base()
 {
     _compiledStatement = new NodeLinkedList();
     _condition = new NodeLinkedList();
     _body = new NodeLinkedList();
     _conditionalJump = new ConditionalJump();
 }
Esempio n. 7
0
        static void Main(string[] args)
        {
            Parser p = new Parser();

            string[]           codeLines = p.readFile("code.ivaron"); //Read code
            LinkedList <Token> list      = new LinkedList <Token>();

            try {
                list = Tokenizer.tokenize(codeLines); //Tokenize code
            } catch (CompilerException e) {
                foreach (string error in e.Errors)
                {
                    Console.WriteLine(error);
                }
            }

            if (list.Count > 0)
            {
                LinkedListNode <Token> token = list.First;
                while (token != null)
                {
                    Console.Write(token.Value.value + " ");
                    if (token.Value.value == "{" || token.Value.value == ";")
                    {
                        Console.Write("\n");
                    }
                    token = token.Next;
                }
            }

            if (list.Count > 0)
            {
                LinkedListNode <Token> token = list.First;
                while (token != null)
                {
                    Console.Write(token.Value.type + " ");
                    if (token.Value.value == "{" || token.Value.value == ";")
                    {
                        Console.Write("\n");
                    }
                    token = token.Next;
                }
            }


            NodeLinkedList nll = TheCompiler.compile(list.First);

            VirtualMachine vm = new VirtualMachine();

            vm.Run(nll);

            // Keep the console window open in debug mode.
            Console.WriteLine("Press return key to exit.");
            System.Console.ReadKey();
        }
Esempio n. 8
0
        public CompiledWhile()
        {
            compiledStatement = new NodeLinkedList();
            condition         = new NodeLinkedList();
            body = new NodeLinkedList();

            var conditionalJumpNode = new ConditionalJumpNode(compiledStatement.Last, body.First);
            var jumpBackNode        = new JumpNode(compiledStatement.First);

            compiledStatement.Add(condition);
            compiledStatement.Add(conditionalJumpNode); // De body komt dus rechtstreeks na de conditionalJumpNode (dus op de .Next property)
            compiledStatement.Add(body);
            compiledStatement.Add(jumpBackNode);
        }
Esempio n. 9
0
        public CompiledWhile()
        {
            compiledStatement = new NodeLinkedList();
            condition = new NodeLinkedList();
            body = new NodeLinkedList();

            var conditionalJumpNode = new ConditionalJumpNode(compiledStatement.Last, body.First);
            var jumpBackNode = new JumpNode(compiledStatement.First);

            compiledStatement.Add(condition);
            compiledStatement.Add(conditionalJumpNode); // De body komt dus rechtstreeks na de conditionalJumpNode (dus op de .Next property)
            compiledStatement.Add(body);
            compiledStatement.Add(jumpBackNode);
        }
        public override Token compile(Token currentToken, Token endToken, NodeLinkedList nodeList, Node before)
        {
            Node   current = before;
            Token  first   = currentToken;
            Token  second  = currentToken.nextToken.nextToken;
            string value   = second.value;
            string varName;

            current = current.insertPrevious(new NodeDirectFunction("ConstantToReturn", value));
            varName = Guid.NewGuid().ToString("N");
            current = current.insertPrevious(new NodeDirectFunction("ReturnToVariable", varName));

            current = current.insertPrevious(new NodeFunction("write", varName));

            return(second.nextToken.nextToken.nextToken);
        }
Esempio n. 11
0
        public void NLL()
        {
            var nll = new NodeLinkedList <int>();
            var n0  = nll.Add(0);
            var n1  = nll.Add(1);
            var n2  = nll.Add(2);

            nll.Remove(n1, false);
            Assert.AreSame(n0.next, n2);
            Assert.AreSame(n2.prev, n0);
            Assert.AreSame(nll.At(1), n2);
            Assert.AreEqual(nll.At(2), null);
            Assert.AreEqual(nll.IndexOf(n1), -1);
            nll.InsertAfter(n0, n1);
            Assert.AreEqual(nll.IndexOf(n1), 1);
            nll.Reset();
            Assert.AreEqual(nll.count, 0);
        }
        public void Run(NodeLinkedList list)
        {
            ActionNode currentNode = list.First;

            variables = new Dictionary <string, Variable>();
            NodeVisitor visitor = new NodeVisitor(this);

            while (currentNode != null)
            {
                currentNode.accept(visitor);
                currentNode = currentNode.Next;
                // Doe iets met de huidige node:
                //          Command pattern

                // Bepaal de volgende node:
                //          Visitor pattern
            }
        }
        public override Token compile(Token currentToken, Token lastToken, NodeLinkedList nodeLinkedList, Node before)
        {
            int level = currentToken.level;

            List <TokenExpected> excepted = new List <TokenExpected>();

            excepted.Add(new TokenExpected(level, TokenType.Identifier)); //left hand value
            excepted.Add(new TokenExpected(level, TokenType.ANY));        // Operators
            excepted.Add(new TokenExpected(level, TokenType.ANY));        // right hand value


            foreach (TokenExpected expt in excepted)
            {
                //TODO
            }

            return(currentToken);
        }
Esempio n. 14
0
        // From powerpoint:
        public void Run(NodeLinkedList list)
        {
            Node            currentNode = list.getFirst();
            NextNodeVisitor visitor     = new NextNodeVisitor();

            while (currentNode != null)
            {
                // Do something with the current node
                NodeAbstractFunction aNode = currentNode as NodeAbstractFunction;
                if (aNode != null)
                {
                    // TODO: Powerpoint niet duidelijk HIER!
                }

                // Get next Node
                currentNode.accept(visitor);
                currentNode = visitor.nextNode;
            }
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting tokenizer...");
            Tokenizer.Tokenizer tokenizer = new Tokenizer.Tokenizer("C:\\testScript.txt");
            Console.WriteLine("Finished tokenizer...\n");

            Console.WriteLine("Starting compiler...");
            Compiler.Compiler compiler       = new Compiler.Compiler();
            NodeLinkedList    nodeLinkedList = compiler.compile(tokenizer.tokens);

            Console.WriteLine("Finished compiler...\n");

            Console.WriteLine("Starting virtual machine...");
            Virtualmachine.VirtualMachine.getInstance().Run(nodeLinkedList);
            Console.WriteLine("Finished virtual machine...\n");

            Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
        public override Token compile(Token currentToken, Token lastToken, NodeLinkedList nodeLinkedList, Node before)
        {
            string variableName = currentToken.value; //left hand value

            currentToken = currentToken.nextToken.nextToken;

            Node current = before;

            Compiler rightCompiled = CompilerFactory.getInstance().getCompiler(currentToken); //right hand value

            currentToken = rightCompiled.compile(currentToken, lastToken, nodeLinkedList, before);

            if (before == null)
            {
                nodeLinkedList.addLast(new NodeDirectFunction("ReturnToVariable", variableName));
            }
            else
            {
                current = current.insertPrevious(new NodeDirectFunction("ReturnToVariable", variableName));
            }

            return(currentToken.nextToken);
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            // 1. Двусвязный список
            #region case1
            NodeLinkedList list = new NodeLinkedList();

            Console.WriteLine("Добавить элементы в список");
            list.AddNode(6);
            list.AddNode(3);
            list.AddNode(2);
            list.PrintValueList();
            Console.WriteLine($"Количество элеметов в списке = {list.GetCount()}\n");

            Console.WriteLine("Добавить элемент с Value=10 в список после элемента с Value=3");
            list.AddNodeAfter(list.FindNode(3), 10);
            list.PrintValueList();
            Console.WriteLine($"Количество элеметов в списке = {list.GetCount()}\n");

            Console.WriteLine("Удалить элемент с индексом 0");
            list.RemoveNode(0);
            list.PrintValueList();
            Console.WriteLine($"Количество элеметов в списке = {list.GetCount()}\n");

            Console.WriteLine("Удалить элемент с Value=10");
            list.RemoveNode(list.FindNode(10));
            list.PrintValueList();
            Console.WriteLine($"Количество элеметов в списке = {list.GetCount()}\n");

            Console.WriteLine("Удалить пустой элемент");
            try
            {
                list.RemoveNode(null);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Произошло исключение: {e.Message}\n");
            }

            Console.WriteLine("Удалить несуществующий элемент");
            try
            {
                list.RemoveNode(new Node {
                    Value = 0
                });
            }
            catch (Exception e)
            {
                Console.WriteLine($"Произошло исключение: {e.Message}\n");
            }

            Console.ReadLine();
            #endregion

            // 2. Двоичный поиск
            // О(log2 n)
            #region case2

            int   n       = 100;
            int[] segment = new int[100];

            for (int i = 0; i < n; i++)
            {
                segment[i] = i + 5;
            }

            Console.WriteLine($"Границы отсортированного массива: Min={segment[0]}, Max={segment[segment.Length-1]}");
            int searchValue = 25;
            Console.WriteLine($"Найти индекс числа {searchValue} в массиве: {BinarySearch(segment, searchValue)}");
            searchValue = 50;
            Console.WriteLine($"Найти индекс числа {searchValue} в массиве: {BinarySearch(segment, searchValue)}");
            searchValue = 100;
            Console.WriteLine($"Найти индекс числа {searchValue} в массиве: {BinarySearch(segment, searchValue)}");

            searchValue = 1;
            Console.WriteLine($"Найти индекс числа {searchValue} в массиве: {BinarySearch(segment, searchValue)}");
            searchValue = 107;
            Console.WriteLine($"Найти индекс числа {searchValue} в массиве: {BinarySearch(segment, searchValue)}");
            Console.ReadLine();
            #endregion
        }
Esempio n. 18
0
        public override Token compile(Token currentToken, Token lastToken, NodeLinkedList nodeLinkedList, Node before)
        {
            int level = currentToken.level;

            if (before != null)
            {
                before.insertPrevious(firstNodeDoNothing);
            }
            else
            {
                nodeLinkedList.insertBefore(before, firstNodeDoNothing);
            }

            List <TokenExpected> expected = new List <TokenExpected>();

            expected.Add(new TokenExpected(level, TokenType.IfStatement));
            expected.Add(new TokenExpected(level, TokenType.EllipsisOpen));
            expected.Add(new TokenExpected(level + 1, TokenType.ANY));
            expected.Add(new TokenExpected(level, TokenType.EllipsisClose));
            expected.Add(new TokenExpected(level, TokenType.BracketsOpen));
            expected.Add(new TokenExpected(level + 1, TokenType.ANY));
            expected.Add(new TokenExpected(level, TokenType.BracketsClose));

            foreach (TokenExpected expt in expected)
            {
                // If no currentToken anymore, return null to get out of the compiler loop
                if (currentToken == null)
                {
                    return(null);
                }

                if (expt.level == level)
                {
                    if (currentToken.tokenType != expt.tokenType)
                    {
                        if (expt.tokenType != currentToken.tokenType)
                        {
                            if (expt.tokenType == TokenType.BracketsOpen ||
                                (expt.tokenType == TokenType.BracketsClose && openedBracket))
                            {
                                openedBracket = false;
                            }
                            else
                            {
                                throw new Exception_UnexpectedEnd("#CP0001 :: Unexpected end of statement.");
                            }
                        }
                    }
                    else
                    {
                        currentToken = currentToken.nextToken;
                    }
                }
                else if (expt.level >= level)
                {
                    if (compileCondition == null)
                    {
                        compileCondition = new CompileCondition();
                        currentToken     = compileCondition.compile(currentToken, lastToken, nodeLinkedList, conditionalJump);
                    }
                    else
                    {
                        while (currentToken.tokenType != TokenType.BracketsClose && currentToken.tokenType != TokenType.EllipsisClose)
                        {
                            compileStatement = CompilerFactory.getInstance().getCompiler(currentToken);
                            currentToken     = compileStatement.compile(currentToken, lastToken, nodeLinkedList, falseNodeDoNothing);
                        }
                    }
                }
            }

            return(currentToken);
        }
        // TODO: Should be compileConstant....

        public override Token compile(Token currentToken, Token lastToken, NodeLinkedList nodeLinkedList, Node before)
        {
            int level = currentToken.level;

            string value   = "";
            string varName = "";
            Node   current = before;
            List <NodeDirectFunction> function = new List <NodeDirectFunction>();

            List <TokenExpected> excepted = new List <TokenExpected>();

            excepted.Add(new TokenExpected(level, TokenType.Identifier)); //left hand value
            excepted.Add(new TokenExpected(level, TokenType.Equals));     // Operators
            excepted.Add(new TokenExpected(level, TokenType.ANY));        // right hand value
            excepted.Add(new TokenExpected(level, TokenType.Semicolon));  // Close statement

            foreach (TokenExpected expt in excepted)
            {
                if (expt.level == level)
                {
                    if (currentToken.tokenType != expt.tokenType && expt.tokenType != TokenType.ANY)
                    {
                        throw new Exception_UnexpectedEnd("#CP0001 :: Unexpected end of statement.");
                    }
                    else
                    {
                        if (currentToken.tokenType == TokenType.Identifier)
                        {
                            varName = currentToken.value.ToString();
                        }
                        if (expt.tokenType == TokenType.ANY)
                        {
                            if (currentToken.nextToken.tokenType == TokenType.Plus)
                            {
                                String f1 = Guid.NewGuid().ToString("N");
                                String f2 = Guid.NewGuid().ToString("N");
                                String f3 = Guid.NewGuid().ToString("N");
                                if (before == null)
                                {
                                    nodeLinkedList.addLast(new NodeDirectFunction("ConstantToReturn", currentToken.value));
                                    nodeLinkedList.addLast(new NodeDirectFunction("ReturnToVariable", f1));
                                    nodeLinkedList.addLast(new NodeDirectFunction("ConstantToReturn", currentToken.nextToken.nextToken.value));
                                    nodeLinkedList.addLast(new NodeDirectFunction("ReturnToVariable", f2));
                                    nodeLinkedList.addLast(new NodeFunction("Plus", f1, f2));
                                }
                                else
                                {
                                    before.insertPrevious(new NodeDirectFunction("ConstantToReturn", currentToken.value));
                                    before.insertPrevious(new NodeDirectFunction("ReturnToVariable", f1));
                                    before.insertPrevious(new NodeDirectFunction("ConstantToReturn", currentToken.nextToken.nextToken.value));
                                    before.insertPrevious(new NodeDirectFunction("ReturnToVariable", f2));
                                    before.insertPrevious(new NodeFunction("Plus", f1, f2));
                                }

                                currentToken = currentToken.nextToken.nextToken;
                            }
                            value = currentToken.value;
                        }
                        currentToken = currentToken.nextToken;
                    }
                }
            }
            if (before == null)
            {
                nodeLinkedList.addLast(new NodeDirectFunction("ConstantToReturn", value));
                nodeLinkedList.addLast(new NodeDirectFunction("ReturnToVariable", Guid.NewGuid().ToString("N"))); // TODO: Klopt dit? Of geef "var" mee?
            }
            else
            {
                before = before.insertPrevious(new NodeDirectFunction("ConstantToReturn", value));
                before.insertPrevious(new NodeDirectFunction("ReturnToVariable", Guid.NewGuid().ToString("N"))); // TODO: klopt dit? Of geef "var" mee?
            }

            return(currentToken);
        }
 public CompiledStatement()
 {
     compiled = new NodeLinkedList();
 }
Esempio n. 21
0
 public Compiler()
 {
     compiledNodes = new NodeLinkedList();
 }