Esempio n. 1
0
        public ExecutableNodeFactory(Executable executable,Executables collection)
        {
            _collection = collection;
            _executable = (DtsContainer)executable;
            _host = _executable as TaskHost;
            _seq = _executable as Sequence;
            _foreachloop = _executable as ForEachLoop;
            _forloop = _executable as ForLoop;
            _psExecutable = PSObject.AsPSObject(_executable);

            if (null != _host)
            {
                _psExecutable.Properties.Add( new PSNoteProperty( "IsTaskHost", true ));
                _mainPipe = _host.InnerObject as MainPipe;
            }
            if (null != _mainPipe)
            {
                _psExecutable.Properties.Add(new PSNoteProperty("IsDataFlow", true));
            }
            if (null != _seq)
            {
                _psExecutable.Properties.Add(new PSNoteProperty("IsSequence", true));
            }
            if (null != _foreachloop)
            {
                _psExecutable.Properties.Add(new PSNoteProperty("IsForEachLoop", true));
            }
            if (null != _forloop)
            {
                _psExecutable.Properties.Add(new PSNoteProperty("IsForLoop", true));
            }
        }
Esempio n. 2
0
        /// <summary>
        ///     Generates the code for a ForLoop node.
        /// </summary>
        /// <param name="fl">The ForLoop node.</param>
        /// <returns>String containing C# code for ForLoop fl.</returns>
        private string GenerateForLoop(ForLoop fl)
        {
            StringBuilder retVal = new StringBuilder();
            StringBuilder tmpVal = new StringBuilder();

            bool marc = FuncCallsMarc();

            tmpVal.Append(GenerateIndented("for (", fl));

            // It's possible that we don't have an assignment, in which case
            // the child will be null and we only print the semicolon.
            // for (x = 0; x < 10; x++)
            //      ^^^^^
            ForLoopStatement s = (ForLoopStatement) fl.kids.Pop();
            if (null != s)
            {
                tmpVal.Append(GenerateForLoopStatement(s));
            }
            tmpVal.Append(Generate("; "));
            // for (x = 0; x < 10; x++)
            //             ^^^^^^
            tmpVal.Append(GenerateNode((SYMBOL) fl.kids.Pop()));
            tmpVal.Append(Generate("; "));
            // for (x = 0; x < 10; x++)
            //                     ^^^
            tmpVal.Append(GenerateForLoopStatement((ForLoopStatement) fl.kids.Pop()));
            tmpVal.Append(GenerateLine(")"));

            retVal.Append(DumpFunc(marc));
            retVal.Append(tmpVal.ToString());

            if (IsParentEnumerable)
            {
                retVal.Append(GenerateLine("{")); // SLAM! No 'for(i = 0; i < 1; i = 0) doSomething();' statements for you
                retVal.Append(GenerateLine("if (CheckSlice()) yield return null;"));
            }

            // CompoundStatement handles indentation itself but we need to do it
            // otherwise.
            bool indentHere = fl.kids.Top is Statement;
            if (indentHere) m_braceCount++;
            retVal.Append(GenerateNode((SYMBOL) fl.kids.Pop()));
            if (indentHere) m_braceCount--;

            if (IsParentEnumerable)
                retVal.Append(GenerateLine("}"));
            
            retVal.Append(DumpAfterFunc(marc));
            return retVal.ToString();
        }
Esempio n. 3
0
    private Stmt ParseForLoop()
    {
        _index++;
        var forLoop = new ForLoop();

        if (_index >= _tokens.Count || !(_tokens[_index] is string))
            throw new Exception("expected identifier after 'for'");

        forLoop.Ident = ((string)_tokens[_index]).Replace("#", "");

        _index++;

        if (_index == _tokens.Count ||
            (Scanner.ArithToken)_tokens[_index] != Scanner.ArithToken.Equal)
            throw new Exception("for missing '='");

        _index++;

        forLoop.From = ParseExpr();

        if (_index == _tokens.Count ||
            !_tokens[_index].Equals("to"))
            throw new Exception("expected 'to' after for");

        _index++;

        forLoop.To = ParseExpr();   //TODO: Change compiler - loop ends one step early

        if (_index == _tokens.Count || !_tokens[_index].Equals("up") && !_tokens[_index].Equals("down"))
            throw new Exception("expected increment or decrement operator after from expression in for");

        forLoop.Type = _loopType;

        _index++;

        forLoop.Body = ParseNextStmt();

        if (_index == _tokens.Count ||
            !_tokens[_index].Equals("end"))
            throw new Exception("unterminated for body");

        _index++;

        return forLoop;
    }
Esempio n. 4
0
    private Stmt ParseStmt()
    {
        Stmt resultado;

        if (this.indice == this.tokens.Count)
        {
            throw new System.Exception("se esperaban sentencias, se llego al final del archivo");
        }

        // <stmt> := print <expr>

        // <expr> := <string>
        // | <int>
        // | <arith_expr>
        // | <ident>
        if (this.tokens[this.indice].Equals("print"))
        {
            this.indice++;
            Print print = new Print();
            print.Expr = this.ParseExpr();
            resultado = print;
        }
        else if (this.tokens[this.indice].Equals("var"))
        {
            this.indice++;
            DeclareVar declareVar = new DeclareVar();

            if (this.indice < this.tokens.Count &&
                this.tokens[this.indice] is string)
            {
                declareVar.Ident = (string)this.tokens[this.indice];
            }
            else
            {
                throw new System.Exception("Se esperaba nombre de variable despues de 'var'");
            }

            this.indice++;

            if (this.indice == this.tokens.Count ||
                this.tokens[this.indice] != Scanner.Igual)
            {
                throw new System.Exception("se esperaba = despues de 'var ident'");
            }

            this.indice++;

            declareVar.Expr = this.ParseExpr();
            resultado = declareVar;
        }
        else if (this.tokens[this.indice].Equals("read_int"))
        {
            this.indice++;
            ReadInt readInt = new ReadInt();

            if (this.indice < this.tokens.Count &&
                this.tokens[this.indice] is string)
            {
                readInt.Ident = (string)this.tokens[this.indice++];
                resultado = readInt;
            }
            else
            {
                throw new System.Exception("Se esperaba el nombre de la variable 'read_int'");
            }
        }
        //*******************
        else if (this.tokens[this.indice].Equals("if"))
        {
            this.indice++;
            mcIf mcif = new mcIf();
            Expr temp = ParseExpr();
            if (this.tokens[this.indice] == Scanner.Eq || this.tokens[this.indice] == Scanner.Neq ||
                this.tokens[this.indice] == Scanner.Gt || this.tokens[this.indice] == Scanner.Gte ||
                this.tokens[this.indice] == Scanner.Lt || this.tokens[this.indice] == Scanner.Lte)
            {
                CompExpr compExpr = new CompExpr();
                compExpr.Left = temp;
                object op = this.tokens[this.indice++];
                if (op == Scanner.Eq)
                    compExpr.Op = CompOp.Eq;
                else if (op == Scanner.Neq)
                    compExpr.Op = CompOp.Neq;
                else if (op == Scanner.Gt)
                    compExpr.Op = CompOp.Gt;
                else if (op == Scanner.Gte)
                    compExpr.Op = CompOp.Gte;
                else if (op == Scanner.Lt)
                    compExpr.Op = CompOp.Lt;
                else if (op == Scanner.Lte)
                    compExpr.Op = CompOp.Lte;
                compExpr.Rigth = ParseExpr();
                temp = compExpr;
            }
            mcif.compExpr = temp;
            if (this.indice == this.tokens.Count || !this.tokens[this.indice].Equals("then"))
            {
                throw new System.Exception("Se esperaba el identificador 'then' despues de 'if'");
            }
            this.indice++;
            mcif.Then = ParseStmt();
            if (this.tokens[this.indice].Equals("else"))
            {
                this.indice++;
                mcif.Else = ParseStmt();
            }

            resultado = mcif;
            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("end"))
            {
                throw new System.Exception("Sentencia if inconclusa");
            }

            this.indice++;

        }
        else if (this.tokens[this.indice].Equals("while"))
        {
            this.indice++;
            WhileLoop whileLoop = new WhileLoop();
            Expr temp = ParseExpr();
            if (this.tokens[this.indice] == Scanner.Eq || this.tokens[this.indice] == Scanner.Neq ||
                this.tokens[this.indice] == Scanner.Gt || this.tokens[this.indice] == Scanner.Gte ||
                this.tokens[this.indice] == Scanner.Lt || this.tokens[this.indice] == Scanner.Lte)
            {
                CompExpr compExpr = new CompExpr();
                compExpr.Left = temp;
                object op = this.tokens[this.indice++];
                if (op == Scanner.Eq)
                    compExpr.Op = CompOp.Eq;
                else if (op == Scanner.Neq)
                    compExpr.Op = CompOp.Neq;
                else if (op == Scanner.Gt)
                    compExpr.Op = CompOp.Gt;
                else if (op == Scanner.Gte)
                    compExpr.Op = CompOp.Gte;
                else if (op == Scanner.Lt)
                    compExpr.Op = CompOp.Lt;
                else if (op == Scanner.Lte)
                    compExpr.Op = CompOp.Lte;
                compExpr.Rigth = ParseExpr();
                temp = compExpr;
            }
            whileLoop.Cond = temp;
            if (this.indice == this.tokens.Count || !this.tokens[this.indice].Equals("do"))
            {
                throw new System.Exception("Se esperaba el identificador 'do' despues de 'while'");
            }
            this.indice++;
            whileLoop.Body = ParseStmt();
            resultado = whileLoop;
            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("end"))
            {
                throw new System.Exception("sentencia while inconclusa");
            }
            this.indice++;
        }
        //*******************
        else if (this.tokens[this.indice].Equals("for"))
        {
            this.indice++;
            ForLoop forLoop = new ForLoop();

            if (this.indice < this.tokens.Count &&
                this.tokens[this.indice] is string)
            {
                forLoop.Ident = (string)this.tokens[this.indice];
            }
            else
            {
                throw new System.Exception("se esperaba un indentificador despues de 'for'");
            }

            this.indice++;

            if (this.indice == this.tokens.Count ||
                this.tokens[this.indice] != Scanner.Igual)
            {
                throw new System.Exception("no se encontro en la sentencia for '='");
            }

            this.indice++;

            forLoop.From = this.ParseExpr();

            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("to"))
            {
                throw new System.Exception("se epsaraba 'to' despues de for");
            }

            this.indice++;

            forLoop.To = this.ParseExpr();

            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("do"))
            {
                throw new System.Exception("se esperaba 'do' despues de la expresion en el ciclo for");
            }

            this.indice++;

            forLoop.Body = this.ParseStmt();
            resultado = forLoop;

            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("end"))
            {
                throw new System.Exception("setencia for inconclusa");
            }

            this.indice++;
        }
        else if (this.tokens[this.indice] is string)
        {
            // assignment

            Assign assign = new Assign();
            assign.Ident = (string)this.tokens[this.indice++];

            if (this.indice == this.tokens.Count ||
                this.tokens[this.indice] != Scanner.Igual)
            {
                throw new System.Exception("se esperaba '='");
            }

            this.indice++;

            assign.Expr = this.ParseExpr();
            resultado = assign;
        }
        else
        {
            throw new System.Exception("Error en el token " + this.indice + ": " + this.tokens[this.indice]);
        }

        if (this.indice < this.tokens.Count && this.tokens[this.indice] == Scanner.PyC)
        {
            this.indice++;

            if (this.indice < this.tokens.Count &&
                !this.tokens[this.indice].Equals("end") && !this.tokens[this.indice].Equals("else"))
            {
                Sequence sequence = new Sequence();
                sequence.First = resultado;
                sequence.Second = this.ParseStmt();
                resultado = sequence;
            }
        }

        return resultado;
    }
Esempio n. 5
0
        public ForLoopNode() : base(NodeType.FlowControl)
        {
            var boundsGroup = new EndpointGroup("Bounds");

            var controlFlowGroup = new EndpointGroup("Control Flow");

            var controlFlowInputsGroup = new EndpointGroup(controlFlowGroup);

            this.Name = "For Loop";
            
            LoopBodyFlow = new CodeGenListInputViewModel<IStatement>(PortType.Execution)
            {
                Name = "Loop Body",
                Group = controlFlowInputsGroup
            };
            this.Inputs.Add(LoopBodyFlow);

            LoopEndFlow = new CodeGenListInputViewModel<IStatement>(PortType.Execution)
            {
                Name = "Loop End",
                Group = controlFlowInputsGroup
            };
            this.Inputs.Add(LoopEndFlow);


            FirstIndex = new CodeGenInputViewModel<ITypedExpression<int>>(PortType.Integer)
            {
                Name = "First Index",
                Group = boundsGroup
            };
            this.Inputs.Add(FirstIndex);

            LastIndex = new CodeGenInputViewModel<ITypedExpression<int>>(PortType.Integer)
            {
                Name = "Last Index",
                Group = boundsGroup

            };
            this.Inputs.Add(LastIndex);

            ForLoop value = new ForLoop();

            var loopBodyChanged = LoopBodyFlow.Values.Connect().Select(_ => Unit.Default).StartWith(Unit.Default);
            var loopEndChanged = LoopEndFlow.Values.Connect().Select(_ => Unit.Default).StartWith(Unit.Default);
            FlowIn = new CodeGenOutputViewModel<IStatement>(PortType.Execution)
            {
                Name = "",
                Value = Observable.CombineLatest(loopBodyChanged, loopEndChanged, FirstIndex.ValueChanged, LastIndex.ValueChanged,
                        (bodyChange, endChange, firstI, lastI) => (BodyChange: bodyChange, EndChange: endChange, FirstI: firstI, LastI: lastI))
                    .Select(v => {
                        value.LoopBody = new StatementSequence(LoopBodyFlow.Values.Items);
                        value.LoopEnd = new StatementSequence(LoopEndFlow.Values.Items);
                        value.LowerBound = v.FirstI ?? new IntLiteral {Value = 0};
                        value.UpperBound = v.LastI ?? new IntLiteral {Value = 1};
                        return value; 
                    }),
                Group = controlFlowGroup
            };
            this.Outputs.Add(FlowIn);

            CurrentIndex = new CodeGenOutputViewModel<ITypedExpression<int>>(PortType.Integer)
            {
                Name = "Current Index",
                Value = Observable.Return(new VariableReference<int>{ LocalVariable = value.CurrentIndex })
            };
            this.Outputs.Add(CurrentIndex);
        }
    }
Esempio n. 6
0
        private Expression ParseExpression()
        {
            Expression curExpression;

            if (GetCurToken().Equals("print"))
            {
                Print print = new Print();

                NextToken();
                print._Expr = GetCurTokenAsLiteral();

                curExpression = print;
            }
            else if (GetCurToken().Equals("var"))
            {
                DeclareVar declareVar = new DeclareVar();

                NextToken();
                declareVar.Identifier = GetCurTokenAsString();

                NextToken();
                if (!Arithmetic.Colon.Equals(GetCurToken()))
                    throw new System.Exception("expected : after 'var ident'");

                NextToken();
                if (!(GetCurToken() is String))
                    throw new System.Exception("expected var type (integer, float)");
                else
                {
                    String curToken = GetCurTokenAsString();
                    if (curToken.Equals("array", StringComparison.InvariantCultureIgnoreCase))
                    {
                        NextToken();
                        if (!Arithmetic.OpenSquareBracket.Equals(GetCurToken()) )
                            throw new System.Exception("Invalid Array Declaration");

                        NextToken();
                        if (!(GetCurToken() is Int32))
                            throw new System.Exception("Invalid Array Declaration");

                        NextToken();
                        if (!Arithmetic.DoubleDots.Equals(GetCurToken()))
                            throw new System.Exception("Invalid Array Declaration");

                        NextToken();
                        if (!(GetCurToken() is Int32))
                            throw new System.Exception("Invalid Array Declaration");

                        NextToken();
                        if (!Arithmetic.CloseSquareBracket.Equals(GetCurToken()))
                            throw new System.Exception("Invalid Array Declaration");

                        NextToken();
                        if (!GetCurToken().Equals("of"))
                            throw new System.Exception("Invalid Array Declaration");
                        /*
                            Added Token array, Type String
                            Added Token OpenSquareBracket, Type Arithmetic
                            Added Token 1, Type Int32
                            Added Token DoubleDots, Type Arithmetic
                            Added Token 5, Type Int32
                            Added Token CloseSquareBracket, Type Arithmetic
                            Added Token of, Type String
                            Added Token integer, Type String
                        */
                        NextToken();
                        declareVar.IdentifierType = GetCurTokenAsString();
                        declareVar.IsArray = true;
                    }
                    else
                    {
                        declareVar.IdentifierType = curToken;
                    }
                }

                curExpression = declareVar;
            }
            else if (GetCurToken().Equals("read_int"))
            {
                ReadInt readInt = new ReadInt();

                NextToken();
                if (!(GetCurToken() is String))
                    throw new System.Exception("expected var name after read_int");
                else
                    readInt._Identifier = GetCurTokenAsString();

                curExpression = readInt;
            }
            else if (GetCurToken().Equals("for"))
            {
                ForLoop forLoop = new ForLoop();

                //Get For Identifier followed by :-
                NextToken();
                if (!(GetCurToken() is String))
                    throw new System.Exception("expected identifier after 'for'");
                else
                    forLoop._Identifier = (String)GetCurToken();

                NextToken();
                if (!Arithmetic.Colon.Equals(GetCurToken()))
                    throw new System.Exception("for missing ': after for'");

                NextToken();
                if (!Arithmetic.Equal.Equals(GetCurToken()))
                    throw new System.Exception("for missing '=' after for");

                //Get x to y
                NextToken();
                forLoop._From = GetCurTokenAsLiteral();

                NextToken();
                if (!GetCurToken().Equals("to"))
                    throw new System.Exception("expected 'to' after for");

                NextToken();
                forLoop._To = GetCurTokenAsLiteral();

                //Begin do, begin
                NextToken();
                if (!GetCurToken().Equals("do"))
                    throw new System.Exception("expected 'do' after from expression in for loop");

                NextToken();
                if (!GetCurToken().Equals("begin"))
                    throw new System.Exception("expected 'begin' in for loop");

                //Get For Loop Body
                NextToken();
                forLoop._Body = ParseExpression();

                //Todo: Parse STatement probly increements Token
                //Get For Loop end
                if (_index == _tokens.Count || !GetCurToken().Equals("end"))
                    throw new System.Exception("unterminated 'for' loop body");

                curExpression = forLoop;
            }
            else if (GetCurToken() is String)
            {
                Assign assign = new Assign();
                assign._Identifier = GetCurTokenAsString();

                NextToken();
                if (!Arithmetic.Equal.Equals(GetCurToken()))
                    throw new System.Exception("Invalid Array Assignment");

                assign._Expression = GetCurTokenAsLiteral();

                curExpression = assign;
            }
            else
            {
                throw new System.Exception("parse error at token " + _index + ": " + GetCurToken());
            }

            NextToken();
            //Check for Graceful end of Line
            if (!Arithmetic.Semi.Equals(GetCurToken()))
                throw new Exception("Unterminated Statement ");

            //Check for End of Program, If program has not ended yet, Recurse....
            NextToken();
            if (_index == _tokens.Count || GetCurToken().Equals("end"))
                return curExpression;
            else
                return new LinkedList(curExpression, ParseExpression());
        }
Esempio n. 7
0
 public virtual T visitFor(ForLoop forLoop) => visit(forLoop);
Esempio n. 8
0
 public virtual T visitForLoop(ForLoop forLoop, A arg) => visit(forLoop, arg);
Esempio n. 9
0
 public abstract void Visit(ForLoop visitable);
Esempio n. 10
0
    private Stmt ParseStmt()
    {
        Stmt resultado;

        if (this.indice == this.tokens.Count)
        {
            throw new System.Exception("se esperaban sentencias, se llego al final del archivo");
        }

        // <stmt> := print <expr>

        // <expr> := <string>
        // | <int>
        // | <arith_expr>
        // | <ident>
        if (this.tokens[this.indice].Equals("print"))
        {
            this.indice++;
            Print print = new Print();
            print.Expr = this.ParseExpr();
            resultado  = print;
        }
        else if (this.tokens[this.indice].Equals("var"))
        {
            this.indice++;
            DeclareVar declareVar = new DeclareVar();

            if (this.indice < this.tokens.Count &&
                this.tokens[this.indice] is string)
            {
                declareVar.Ident = (string)this.tokens[this.indice];
            }
            else
            {
                throw new System.Exception("Se esperaba nombre de variable despues de 'var'");
            }

            this.indice++;

            if (this.indice == this.tokens.Count ||
                this.tokens[this.indice] != Scanner.Igual)
            {
                throw new System.Exception("se esperaba = despues de 'var ident'");
            }

            this.indice++;

            declareVar.Expr = this.ParseExpr();
            resultado       = declareVar;
        }
        else if (this.tokens[this.indice].Equals("read_int"))
        {
            this.indice++;
            ReadInt readInt = new ReadInt();

            if (this.indice < this.tokens.Count &&
                this.tokens[this.indice] is string)
            {
                readInt.Ident = (string)this.tokens[this.indice++];
                resultado     = readInt;
            }
            else
            {
                throw new System.Exception("Se esperaba el nombre de la variable 'read_int'");
            }
        }
        //*******************
        else if (this.tokens[this.indice].Equals("if"))
        {
            this.indice++;
            mcIf mcif = new mcIf();
            Expr temp = ParseExpr();
            if (this.tokens[this.indice] == Scanner.Eq || this.tokens[this.indice] == Scanner.Neq ||
                this.tokens[this.indice] == Scanner.Gt || this.tokens[this.indice] == Scanner.Gte ||
                this.tokens[this.indice] == Scanner.Lt || this.tokens[this.indice] == Scanner.Lte)
            {
                CompExpr compExpr = new CompExpr();
                compExpr.Left = temp;
                object op = this.tokens[this.indice++];
                if (op == Scanner.Eq)
                {
                    compExpr.Op = CompOp.Eq;
                }
                else if (op == Scanner.Neq)
                {
                    compExpr.Op = CompOp.Neq;
                }
                else if (op == Scanner.Gt)
                {
                    compExpr.Op = CompOp.Gt;
                }
                else if (op == Scanner.Gte)
                {
                    compExpr.Op = CompOp.Gte;
                }
                else if (op == Scanner.Lt)
                {
                    compExpr.Op = CompOp.Lt;
                }
                else if (op == Scanner.Lte)
                {
                    compExpr.Op = CompOp.Lte;
                }
                compExpr.Rigth = ParseExpr();
                temp           = compExpr;
            }
            mcif.compExpr = temp;
            if (this.indice == this.tokens.Count || !this.tokens[this.indice].Equals("then"))
            {
                throw new System.Exception("Se esperaba el identificador 'then' despues de 'if'");
            }
            this.indice++;
            mcif.Then = ParseStmt();
            if (this.tokens[this.indice].Equals("else"))
            {
                this.indice++;
                mcif.Else = ParseStmt();
            }

            resultado = mcif;
            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("end"))
            {
                throw new System.Exception("Sentencia if inconclusa");
            }

            this.indice++;
        }
        else if (this.tokens[this.indice].Equals("while"))
        {
            this.indice++;
            WhileLoop whileLoop = new WhileLoop();
            Expr      temp      = ParseExpr();
            if (this.tokens[this.indice] == Scanner.Eq || this.tokens[this.indice] == Scanner.Neq ||
                this.tokens[this.indice] == Scanner.Gt || this.tokens[this.indice] == Scanner.Gte ||
                this.tokens[this.indice] == Scanner.Lt || this.tokens[this.indice] == Scanner.Lte)
            {
                CompExpr compExpr = new CompExpr();
                compExpr.Left = temp;
                object op = this.tokens[this.indice++];
                if (op == Scanner.Eq)
                {
                    compExpr.Op = CompOp.Eq;
                }
                else if (op == Scanner.Neq)
                {
                    compExpr.Op = CompOp.Neq;
                }
                else if (op == Scanner.Gt)
                {
                    compExpr.Op = CompOp.Gt;
                }
                else if (op == Scanner.Gte)
                {
                    compExpr.Op = CompOp.Gte;
                }
                else if (op == Scanner.Lt)
                {
                    compExpr.Op = CompOp.Lt;
                }
                else if (op == Scanner.Lte)
                {
                    compExpr.Op = CompOp.Lte;
                }
                compExpr.Rigth = ParseExpr();
                temp           = compExpr;
            }
            whileLoop.Cond = temp;
            if (this.indice == this.tokens.Count || !this.tokens[this.indice].Equals("do"))
            {
                throw new System.Exception("Se esperaba el identificador 'do' despues de 'while'");
            }
            this.indice++;
            whileLoop.Body = ParseStmt();
            resultado      = whileLoop;
            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("end"))
            {
                throw new System.Exception("sentencia while inconclusa");
            }
            this.indice++;
        }
        //*******************
        else if (this.tokens[this.indice].Equals("for"))
        {
            this.indice++;
            ForLoop forLoop = new ForLoop();

            if (this.indice < this.tokens.Count &&
                this.tokens[this.indice] is string)
            {
                forLoop.Ident = (string)this.tokens[this.indice];
            }
            else
            {
                throw new System.Exception("se esperaba un indentificador despues de 'for'");
            }

            this.indice++;

            if (this.indice == this.tokens.Count ||
                this.tokens[this.indice] != Scanner.Igual)
            {
                throw new System.Exception("no se encontro en la sentencia for '='");
            }

            this.indice++;

            forLoop.From = this.ParseExpr();

            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("to"))
            {
                throw new System.Exception("se epsaraba 'to' despues de for");
            }

            this.indice++;

            forLoop.To = this.ParseExpr();

            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("do"))
            {
                throw new System.Exception("se esperaba 'do' despues de la expresion en el ciclo for");
            }

            this.indice++;

            forLoop.Body = this.ParseStmt();
            resultado    = forLoop;

            if (this.indice == this.tokens.Count ||
                !this.tokens[this.indice].Equals("end"))
            {
                throw new System.Exception("setencia for inconclusa");
            }

            this.indice++;
        }
        else if (this.tokens[this.indice] is string)
        {
            // assignment

            Assign assign = new Assign();
            assign.Ident = (string)this.tokens[this.indice++];

            if (this.indice == this.tokens.Count ||
                this.tokens[this.indice] != Scanner.Igual)
            {
                throw new System.Exception("se esperaba '='");
            }

            this.indice++;

            assign.Expr = this.ParseExpr();
            resultado   = assign;
        }
        else
        {
            throw new System.Exception("Error en el token " + this.indice + ": " + this.tokens[this.indice]);
        }

        if (this.indice < this.tokens.Count && this.tokens[this.indice] == Scanner.PyC)
        {
            this.indice++;

            if (this.indice < this.tokens.Count &&
                !this.tokens[this.indice].Equals("end") && !this.tokens[this.indice].Equals("else"))
            {
                Sequence sequence = new Sequence();
                sequence.First  = resultado;
                sequence.Second = this.ParseStmt();
                resultado       = sequence;
            }
        }

        return(resultado);
    }
Esempio n. 11
0
        public void VisitorWithReturnIsImplemented()
        {
            var sut = new ForLoop();

            sut.Accept(23).VerifyWithReturn(v => v.Visit(sut, 23));
        }
Esempio n. 12
0
        private void GenStmt(Stmt stmt)
        {
            if (stmt is Sequence)
            {
                Sequence seq = (Sequence)stmt;
                this.GenStmt(seq.First);
                this.GenStmt(seq.Second);
            }

            else if (stmt is DeclareVar)
            {
                // declare a local
                DeclareVar declare = (DeclareVar)stmt;
                this.symbolTable[declare.Ident] = this.il.DeclareLocal(this.TypeOfExpr(declare.Expr));

                // set the initial value
                Assign assign = new Assign();
                assign.Ident = declare.Ident;
                assign.Expr  = declare.Expr;
                this.GenStmt(assign);
            }

            else if (stmt is Assign)
            {
                Assign assign = (Assign)stmt;

                if (this.typefieldList.ContainsKey(assign.Ident))
                {
                    if (!this.typefieldList[assign.Ident].IsStatic)
                    {
                        this.il.Emit(Emit.OpCodes.Ldarg_0);
                    }
                }


                // if(assign.Ident
                this.GenExpr(assign.Expr, this.TypeOfExpr(assign.Expr));
                this.Store(assign.Ident, this.TypeOfExpr(assign.Expr));
            }
            else if (stmt is Print)
            {
                // the "print" statement is an alias for System.Console.WriteLine.
                // it uses the string case
                this.GenExpr(((Print)stmt).Expr, typeof(string));
                this.il.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) }));
                // this.il.Emit(
            }
            else if (stmt is VoidMethodCall)
            {
                this.GenerteMethodCallCode((MethodCall)((VoidMethodCall)stmt).Expr);
            }

            else if (stmt is IfCondition)
            {
                IfCondition ifCon = (IfCondition)stmt;
                this.GenExpr(ifCon.BooleanExp, /*harcoded for string */ typeof(string));

                Emit.Label endOfIfBlock = this.il.DefineLabel();


                if (((BinExpr)ifCon.BooleanExp).Op == BinOp.EqualTo)
                {
                    this.il.Emit(Emit.OpCodes.Brfalse_S, endOfIfBlock);
                }
                else
                {
                    this.il.Emit(Emit.OpCodes.Brtrue_S, endOfIfBlock);
                }

                this.GenStmt(ifCon.Body);

                this.il.MarkLabel(endOfIfBlock);
                // this.GenerteMethodCallCode((MethodCall)((VoidMethodCall)stmt).Expr);
            }

            else if (stmt is WhileLoop)
            {
                WhileLoop whileLoop = (WhileLoop)stmt;

                Emit.Label whileBodyStart = this.il.DefineLabel();
                Emit.Label whileBodyEnd   = this.il.DefineLabel();
                Emit.Label whileCondition = this.il.DefineLabel();

                this.il.Emit(Emit.OpCodes.Br_S, whileBodyEnd);

                this.il.MarkLabel(whileBodyStart);
                this.GenStmt(whileLoop.Body);
                this.il.MarkLabel(whileBodyEnd);

                this.GenExpr(whileLoop.BooleanExp, /*harcoded for int */ typeof(int));

                if (((BinExpr)whileLoop.BooleanExp).Op == BinOp.EqualTo)
                {
                    this.il.Emit(Emit.OpCodes.Brtrue_S, whileBodyStart);
                }
                else
                {
                    this.il.Emit(Emit.OpCodes.Brfalse_S, whileBodyStart);
                }
            }


            // System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();

            else if (stmt is ReadInt)
            {
                this.il.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("ReadLine", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new System.Type[] { }, null));
                this.il.Emit(Emit.OpCodes.Call, typeof(int).GetMethod("Parse", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new System.Type[] { typeof(string) }, null));
                this.Store(((ReadInt)stmt).Ident, typeof(int));
            }
            else if (stmt is ForLoop)
            {
                // example:
                // for x = 0 to 100 do
                //   print "hello";
                // end;

                // x = 0
                ForLoop forLoop = (ForLoop)stmt;
                Assign  assign  = new Assign();
                assign.Ident = forLoop.Ident;
                assign.Expr  = forLoop.From;
                this.GenStmt(assign);
                // jump to the test
                Emit.Label test = this.il.DefineLabel();
                this.il.Emit(Emit.OpCodes.Br, test);

                // statements in the body of the for loop
                Emit.Label body = this.il.DefineLabel();
                this.il.MarkLabel(body);
                this.GenStmt(forLoop.Body);

                // to (increment the value of x)
                this.il.Emit(Emit.OpCodes.Ldloc, this.symbolTable[forLoop.Ident]);
                this.il.Emit(Emit.OpCodes.Ldc_I4, 1);
                this.il.Emit(Emit.OpCodes.Add);
                this.Store(forLoop.Ident, typeof(int));

                // **test** does x equal 100? (do the test)
                this.il.MarkLabel(test);
                this.il.Emit(Emit.OpCodes.Ldloc, this.symbolTable[forLoop.Ident]);
                this.GenExpr(forLoop.To, typeof(int));
                this.il.Emit(Emit.OpCodes.Blt, body);
            }
            else
            {
                throw new System.Exception("don't know how to gen a " + stmt.GetType().Name);
            }
        }
Esempio n. 13
0
    private Stmt ParseStmt()
    {
        Stmt result;

        if (this.index == this.tokens.Count)
        {
            throw new System.Exception("expected statement, got EOF");
        }

        // <stmt> := print <expr>

        // <expr> := <string>
        // | <int>
        // | <arith_expr>
        // | <ident>
        if (this.tokens[this.index].Equals("print"))
        {
            this.index++;
            Print print = new Print();
            print.Expr = this.ParseExpr();
            result = print;
        }
        else if (this.tokens[this.index].Equals("var"))
        {
            this.index++;
            DeclareVar declareVar = new DeclareVar();

            if (this.index < this.tokens.Count &&
                this.tokens[this.index] is string)
            {
                declareVar.Ident = (string)this.tokens[this.index];
            }
            else
            {
                throw new System.Exception("expected variable name after 'var'");
            }

            this.index++;

            if (this.index == this.tokens.Count ||
                this.tokens[this.index] != Scanner.Equal)
            {
                throw new System.Exception("expected = after 'var ident'");
            }

            this.index++;

            declareVar.Expr = this.ParseExpr();
            result = declareVar;
        }
        else if (this.tokens[this.index].Equals("read_int"))
        {
            this.index++;
            ReadInt readInt = new ReadInt();

            if (this.index < this.tokens.Count &&
                this.tokens[this.index] is string)
            {
                readInt.Ident = (string)this.tokens[this.index++];
                result = readInt;
            }
            else
            {
                throw new System.Exception("expected variable name after 'read_int'");
            }
        }
        else if (this.tokens[this.index].Equals("for"))
        {
            this.index++;
            ForLoop forLoop = new ForLoop();

            if (this.index < this.tokens.Count &&
                this.tokens[this.index] is string)
            {
                forLoop.Ident = (string)this.tokens[this.index];
            }
            else
            {
                throw new System.Exception("expected identifier after 'for'");
            }

            this.index++;

            if (this.index == this.tokens.Count ||
                this.tokens[this.index] != Scanner.Equal)
            {
                throw new System.Exception("for missing '='");
            }

            this.index++;

            forLoop.From = this.ParseExpr();

            if (this.index == this.tokens.Count ||
                !this.tokens[this.index].Equals("to"))
            {
                throw new System.Exception("expected 'to' after for");
            }

            this.index++;

            forLoop.To = this.ParseExpr();

            if (this.index == this.tokens.Count ||
                !this.tokens[this.index].Equals("do"))
            {
                throw new System.Exception("expected 'do' after from expression in for loop");
            }

            this.index++;

            forLoop.Body = this.ParseStmt();
            result = forLoop;

            if (this.index == this.tokens.Count ||
                !this.tokens[this.index].Equals("end"))
            {
                throw new System.Exception("unterminated 'for' loop body");
            }

            this.index++;
        }
        else if (this.tokens[this.index] is string)
        {
            // assignment

            Assign assign = new Assign();
            assign.Ident = (string)this.tokens[this.index++];

            if (this.index == this.tokens.Count ||
                this.tokens[this.index] != Scanner.Equal)
            {
                throw new System.Exception("expected '='");
            }

            this.index++;

            assign.Expr = this.ParseExpr();
            result = assign;
        }
        else
        {
            throw new System.Exception("parse error at token " + this.index + ": " + this.tokens[this.index]);
        }

        if (this.index < this.tokens.Count && this.tokens[this.index] == Scanner.Semi)
        {
            this.index++;

            if (this.index < this.tokens.Count &&
                !this.tokens[this.index].Equals("end"))
            {
                Sequence sequence = new Sequence();
                sequence.First = result;
                sequence.Second = this.ParseStmt();
                result = sequence;
            }
        }

        return result;
    }