Ejemplo n.º 1
0
 public override void VisitIfNode(IfNode ifn)
 {
     if (ifn.Else == null && ifn.If == null)
     {
         ReplaceStat(ifn, new NullNode());
     }
 }
 public override void VisitIfNode(IfNode c)
 {
     c.Parent = st.Peek();
     st.Push(c);
     base.VisitIfNode(c);
     st.Pop();
 }
Ejemplo n.º 3
0
            public bool VisitIfNode(IfNode node, CompilationState state)
            {
                bool first = true;

                foreach (var stmt in node.Ifs)
                {
                    state.Write(first ? "if " : "elseif ");
                    stmt.Key.AcceptVisitor(this, state);
                    state.Write(" then");
                    state.NewLine();
                    state.Ident();
                    stmt.Value.AcceptVisitor(this, state);
                    state.NewLine();
                    state.FinishIdent();
                    first = false;
                }

                if (!(node.IfElse is null))
                {
                    state.Write("else");
                    state.NewLine();
                    state.Ident();
                    node.IfElse.AcceptVisitor(this, state);
                    state.NewLine();
                    state.FinishIdent();
                }

                state.Write("end");
                return(true);
            }
Ejemplo n.º 4
0
 public override void VisitIfNode(IfNode inode)
 {
     if (inode.Expr is BoolNode bln && bln.Value == true)
     {
         inode.Stat1.Visit(this);
         ReplaceStatement(inode, inode.Stat1);
     }
Ejemplo n.º 5
0
 public override void VisitIfNode(IfNode ifn)
 {
     ifn.Parent = st.Peek();
     st.Push(ifn);
     base.VisitIfNode(ifn);
     st.Pop();
 }
Ejemplo n.º 6
0
        public override void VisitIfNode(IfNode ifn)
        {
            Text += IndentStr() + "if (";
            ifn.Cond.Visit(this);
            Text += ")" + Environment.NewLine;

            if (!(ifn.If is BlockNode))
            {
                IndentPlus();
            }
            ifn.If.Visit(this);
            if (!(ifn.If is BlockNode))
            {
                IndentMinus();
            }

            if (ifn.Else != null)
            {
                Text += Environment.NewLine + IndentStr() + "else" + Environment.NewLine;

                if (!(ifn.Else is BlockNode))
                {
                    IndentPlus();
                }
                ifn.Else.Visit(this);
                if (!(ifn.Else is BlockNode))
                {
                    IndentMinus();
                }
            }
        }
Ejemplo n.º 7
0
    public override bool Parse()
    {
        Parser parser = Parser.instance;

        // If the parser hasn't visited this join yet
        if (!_isSaturated)
        {
            // Add jump command with if count as label
            parser.AddCommand(Parser.CMD_JUMP, parser.ifCount, this);
            // Add if count as argument
            parser.AddCommand(parser.ifCount, this);
            // Get the if node related to this join
            IfNode prevIf = (IfNode)parser.FindIfWithLabel(parser.ifCount).node;
            // Set the parsers node to parse back to the false stream of
            // the if node
            parser.currentNode = prevIf.altNextNode;
            // Mark this node as visited
            _isSaturated = true;
            return(false);
        }
        else
        {
            // Add end if command with if count as label
            parser.AddCommand(Parser.CMD_ENDIF, parser.ifCount, this);
            // Decrease if count
            --parser.ifCount;
            return(true);
        }
    }
Ejemplo n.º 8
0
        private void Visit(IfNode node, MethodBuilder builder, CodegenContext context)
        {
            Visit(node.Condition, builder, context);

            int label1 = builder.PrepareJump(true);

            Visit(node.IfTrue, builder, context);

            if (node.IfFalse != null)
            {
                int label2    = builder.PrepareJump(false);
                int elseLabel = builder.Nop();

                builder.MakeJump(label1, elseLabel, Jump.IfFalse);

                Visit(node.IfFalse, builder, context);

                int label3 = builder.Nop();

                builder.MakeJump(label2, label3, Jump.Always);
            }
            else
            {
                int label2 = builder.Nop();
                builder.MakeJump(label1, label2, Jump.IfFalse);
            }
        }
Ejemplo n.º 9
0
 public IfNodeTests()
 {
     condition = new IdentNode(SourcePosition.NIL, "foo");
     @true     = new BlockNode(SourcePosition.NIL);
     @false    = new BlockNode(SourcePosition.NIL);
     subject   = new IfNode(SourcePosition.NIL, condition, @true, @false);
 }
Ejemplo n.º 10
0
 public override void VisitIfNode(IfNode ifn)
 {
     if (ifn.Stat1 == null && ifn.Stat2 == null)
     {
         ReplaceStatment(ifn, null);
     }
 }
Ejemplo n.º 11
0
 public void Visit(IfNode node)
 {
     foreach (var subnode in node)
     {
         Visit((dynamic)subnode);
     }
 }
        public override void VisitIfNode(IfNode iif)
        {
            var ifGoto = new TACNodes.IfGoto();

            // Результат вычисления логического выражения
            var cond1 = RecAssign(iif.Conditon);

            ifGoto.Condition = cond1;

            code.AddNode(ifGoto);

            // Разбор тела else (если есть)
            iif.ElseClause?.Visit(this);

            // Пропускаем тело if
            var elseGoTo = new TACNodes.Goto();

            code.AddNode(elseGoTo);

            // Добавление новой метки непосредственно перед телом if
            var newLabelIf = GetEmptyLabeledNode();

            ifGoto.TargetLabel = newLabelIf.Label;

            // Обход выражений тела условного оператора
            iif.IfClause.Visit(this);

            // Метка после тела if, на нее передается управление из else
            var newLabelElse = GetEmptyLabeledNode();

            elseGoTo.TargetLabel = newLabelElse.Label;
        }
Ejemplo n.º 13
0
            public bool VisitIfNode(IfNode node, CompilationState state)
            {
                state.Write("if ");
                node.Condition.AcceptVisitor(this, state);
                state.Write(" then");
                state.NewLine();
                state.Ident();
                node.IfTrue.AcceptVisitor(this, state);
                state.NewLine();
                state.FinishIdent();

                //TODO: Optimize to elseif if needed
                if (node.IfFalse == null)
                {
                    state.Write("end");
                }
                else
                {
                    state.Write("else");
                    state.NewLine();
                    state.Ident();
                    node.IfFalse.AcceptVisitor(this, state);
                    state.NewLine();
                    state.FinishIdent();
                    state.Write("end");
                }

                return(true);
            }
Ejemplo n.º 14
0
        public override void VisitIfNode(IfNode cond)
        {
            var f = genc.DeclareLocal(typeof(int));

            cond.expr.Visit(this);
            genc.Emit(OpCodes.Stloc, f);

            //Label trueLoop = genc.DefineLabel();
            Label falseLoop = genc.DefineLabel();
            Label endLoop   = genc.DefineLabel();

            genc.Emit(OpCodes.Ldloc, f);
            genc.Emit(OpCodes.Ldc_I4_0);
            genc.Emit(OpCodes.Ble, falseLoop); // if i<=0 then goto endLoop

            cond.ifTrue.Visit(this);
            genc.Emit(OpCodes.Br, endLoop);

            genc.MarkLabel(falseLoop);

            if (cond.ifFalse != null)
            {
                cond.ifFalse.Visit(this);
            }

            genc.MarkLabel(endLoop);
        }
Ejemplo n.º 15
0
        public static void CompileIf(IfNode node, ref List <Instruction> instructions)
        {
            var moveAddresses = new List <PrecompiledAdress>();

            var ifInstructions = CompileBranch(node);
            var ifMoveAdress   = (PrecompiledAdress)ifInstructions.Last().Value;

            instructions = instructions.Concat(ifInstructions).ToList();

            ifMoveAdress.Address = instructions.Count;
            moveAddresses.Add(ifMoveAdress);

            foreach (var elseifNode in node.ElseIfNodes)
            {
                var elseifInstructions = CompileBranch(elseifNode);
                var elseifMoveAdress   = (PrecompiledAdress)elseifInstructions.Last().Value;

                instructions = instructions.Concat(elseifInstructions).ToList();

                elseifMoveAdress.Address = instructions.Count;
                moveAddresses.Add(elseifMoveAdress);
            }

            if (node.ElseNode != null)
            {
                CompileGeneral(node.ElseNode, ref instructions);
            }

            foreach (var adress in moveAddresses)
            {
                adress.Delta = instructions.Count - adress.Address;
            }
        }
Ejemplo n.º 16
0
        private IfNode ParseIfBlock()
        {
            Token <TokenType> ifToken = GetNextToken();
            IfNode            ifNode  = new IfNode(ifToken);

            ifNode.TrueNode = ParseParagraph();
            Token <TokenType> t = PeekNextToken();

            switch (t.TokenType)
            {
            case TokenType.Else:
                GetNextToken();
                ifNode.FalseNode = ParseParagraph();
                if (GetNextToken().TokenType != TokenType.End)
                {
                    ExceptionHelper.ThrowIfBlockNotEnd();
                    return(null);
                }
                break;

            case TokenType.End:
                if (GetNextToken().TokenType != TokenType.End)
                {
                    ExceptionHelper.ThrowIfBlockNotEnd();
                    return(null);
                }
                break;

            default:
                Assertion.Fail("Unexpected token in if block.");
                break;
            }
            return(ifNode);
        }
Ejemplo n.º 17
0
 public override void VisitIfNode(IfNode ifn)
 {
     if (ifn.Cond is BooleanNode boolVal && !boolVal.Val)
     {
         ReplaceStat(ifn, ifn.Else);
     }
 }
        /// <summary>
        /// Посещение узла условного оператора
        /// </summary>
        /// <param name="iif">Узел IfNode</param>
        public virtual void VisitIfNode(IfNode iif)
        {
            Text += IndentStr() + "if (";
            iif.Conditon.Visit(this);
            Text += ")" + Environment.NewLine;

            if (!(iif.IfClause is BlockNode))
            {
                IndentPlus();
                iif.IfClause.Visit(this);
                Text += ";" + Environment.NewLine;
                IndentMinus();
            }
            else
            {
                iif.IfClause.Visit(this);
            }
            if (iif.ElseClause != null)
            {
                Text += IndentStr() + "else" + Environment.NewLine;
                if (!(iif.ElseClause is BlockNode))
                {
                    IndentPlus();
                    iif.ElseClause.Visit(this);
                    Text += ";" + Environment.NewLine;
                    IndentMinus();
                }
                else
                {
                    iif.ElseClause.Visit(this);
                }
            }
        }
Ejemplo n.º 19
0
 public override void VisitIfNode(IfNode ifn)
 {
     if (ifn.Else is NullNode)
     {
         ReplaceStat(ifn, new NullNode());
     }
 }
Ejemplo n.º 20
0
        public override void VisitIfNode(IfNode ifn)
        {
            Text += IndentStr() + "if (";
            ifn.Cond.Visit(this);
            Text += ")\n";

            if (!(ifn.If is BlockNode))
            {
                IndentPlus();
            }
            ifn.If.Visit(this);
            if (!(ifn.If is BlockNode))
            {
                IndentMinus();
            }

            if (ifn.Else != null)
            {
                Text += "\n" + IndentStr() + "else\n";

                if (!(ifn.Else is BlockNode))
                {
                    IndentPlus();
                }
                ifn.Else.Visit(this);
                if (!(ifn.Else is BlockNode))
                {
                    IndentMinus();
                }
            }
        }
Ejemplo n.º 21
0
        public Word Visit(IfNode ifNode)
        {
            var result = ifNode.Condition.Accept(this);

            if (IsError(result))
            {
                return(result);
            }
            PyObj pyObj;

            if (IsMemoryBlock(result))//comentar ese if else si se hace la desereferencia en atomic expr.
            {
                pyObj = ((MemoryBlock)result).Value;
            }
            else
            {
                pyObj = (PyObj)result;
            }
            //pyObj = (PyObj)result;//Descomentar esta linea si se hace la desereferencia en atomic expr.
            if (pyObj.GetMyType() != TypeConstants.BOOLEAN)
            {
                return(ErrorFactory.IfError(ifNode.Condition, pyObj));
            }
            var myBool = (MyBoolean)pyObj;

            if (myBool.Bool)
            {
                return(ifNode.Block.Accept(this));
            }
            else if (ifNode.Else != null)
            {
                return(ifNode.Else.Accept(this));
            }
            return(null);
        }
Ejemplo n.º 22
0
        public void Visit(IfNode node)
        {
            List <Instruction> jumps = new List <Instruction>();

            foreach (var branch in node.Branches)
            {
                AddInstruction(OpCode.EVAL, 1);
                var jf = AddInstruction(OpCode.JF, 1);

                foreach (var child in branch.Nodes)
                {
                    child.Accept(this);
                }

                jf.Argument = NextLoc;

                var jump = AddInstruction(OpCode.JUMP, 1);
                jumps.Add(jump);
            }

            foreach (var jump in jumps)
            {
                jump.Argument = NextLoc;
            }
        }
Ejemplo n.º 23
0
        public override void VisitIfNode(IfNode c)
        {
            var fl = genc.DeclareLocal(typeof(int)); // переменная цикла cycle

            c.expr.Visit(this);                      // сгенерировать команды, связанные с вычислением количества итераций цикла
            genc.Emit(OpCodes.Stloc, fl);

            Label ifTrue  = genc.DefineLabel();
            Label ifFalse = genc.DefineLabel();
            Label ifEnd   = genc.DefineLabel();

            genc.Emit(OpCodes.Ldloc, fl);
            genc.Emit(OpCodes.Ldc_I4_0);
            genc.Emit(OpCodes.Beq, ifFalse); // if fl == 0 then goto ifFalse


            genc.MarkLabel(ifTrue);
            c.ifTrue.Visit(this); // выполнить тело цикла
            genc.Emit(OpCodes.Br, ifEnd);

            genc.MarkLabel(ifFalse);
            if (c.ifFalse != null)
            {
                c.ifFalse.Visit(this);
            }

            genc.MarkLabel(ifEnd);
        }
Ejemplo n.º 24
0
        public override void VisitIfNode(IfNode node)
        {
            bool prevInner = IsInner;

            if (prevInner)
            {
                IndentPlus();
            }
            IsInner         = true;
            Text           += IndentStr() + "if (";
            IsDisableIndent = true;
            node.Expr.Visit(this);
            IsDisableIndent = false;
            Text           += ")";
            Text           += Environment.NewLine;
            node.Stat1.Visit(this);
            if (node.Stat2 != null)
            {
                Text += Environment.NewLine;
                Text += IndentStr() + "else ";
                Text += Environment.NewLine;
                node.Stat2.Visit(this);
            }
            if (prevInner)
            {
                IndentMinus();
            }
            IsInner = prevInner;
        }
Ejemplo n.º 25
0
        public override void VisitIfNode(IfNode bl)
        {
            Console.WriteLine(Tag + " VisitIfNode");

            bl.Cond.Visit(this);
            var ifThenLine = new ThreeAddrLine();

            ifThenLine.Label  = GenNewLabel();
            ifThenLine.LeftOp = GetLastLine().Accum;
            ifThenLine.OpType = ThreeAddrOpType.IfGoto;
            Data.Add(ifThenLine);
            if (bl.ElseB != null)
            {
                bl.ElseB.Visit(this);
            }
            var outsideIfLine = new ThreeAddrLine();

            outsideIfLine.Label  = GenNewLabel();
            outsideIfLine.OpType = ThreeAddrOpType.Goto;
            Data.Add(outsideIfLine);
            ifThenLine.RightOp = GenNewLabel();
            bl.ThenB.Visit(this);
            InsertNop();
            outsideIfLine.RightOp = GetLastLine().Label;
        }
Ejemplo n.º 26
0
 public override void Visit(IfNode node)
 {
     if (node.Condition is BoolValNode bv && bv.Val)
     {
         Visit(node.Stat);
         ReplaceStatement(node, node.Stat);
     }
Ejemplo n.º 27
0
 public override void VisitIfNode(IfNode inode)
 {
     base.VisitIfNode(inode);
     if (inode.Expr is BoolNode expr && expr.Value == false)
     {
         ReplaceStatement(inode, inode.Stat2 ?? new EmptyNode());
     }
Ejemplo n.º 28
0
        private string GetExpression(IfNode ifNode, IDictionary <IFixing, string> fixingRefs)
        {
            var testExpression    = GetExpressionBase(ifNode.Test, fixingRefs);
            var ifTrueExpression  = GetExpressionBase(ifNode.IfTrue, fixingRefs);
            var ifFalseExpression = GetExpressionBase(ifNode.IfFalse, fixingRefs);

            return(string.Format("({0}) ? ({1}) : ({2})", testExpression, ifTrueExpression, ifFalseExpression));
        }
Ejemplo n.º 29
0
 public override void VisitIfNode(IfNode ifn)
 {
     if (WithinCycle)
     {
         HasIfNestedToCycle = true;
     }
     base.VisitIfNode(ifn);
 }
Ejemplo n.º 30
0
 public override void Visit(IfNode node)
 {
     PreVisit(node);
     node.Condition.Visit(this);
     node.Stat.Visit(this);
     node.ElseStat?.Visit(this);
     PostVisit(node);
 }
Ejemplo n.º 31
0
 /// <summary>
 /// clone
 /// </summary>
 /// <returns></returns>
 public IBehaviourNode Clone()
 {
     var condition = this.children[0].Clone() as ConditionNode;
     var node = this.children[1].Clone();
     var behaviourNode = new IfNode(condition, node,this.name);
     //base.CopyToCompositeNode(behaviourNode);
     return behaviourNode;
 }
Ejemplo n.º 32
0
        public virtual void Visit(IfNode node)
        {
            if (node != null)
            {
                if (node.Condition != null)
                {
                    node.Condition.Accept(this);
                }

                if (node.TrueBlock != null)
                {
                    node.TrueBlock.Accept(this);
                }

                if (node.FalseBlock != null)
                {
                    node.FalseBlock.Accept(this);
                }
            }
        }
Ejemplo n.º 33
0
 public virtual void PostWalk(IfNode node) { }
Ejemplo n.º 34
0
 public virtual bool Walk(IfNode node) { return true; }
Ejemplo n.º 35
0
	private IfNode ifExp()
	{
		EnterRule_ifExp();
		EnterRule("ifExp", 9);
		TraceIn("ifExp", 9);
		IfNode node = default(IfNode);


		Node con = default(Node);
		Node true_body = default(Node);
		Node false_body = default(Node);

		try { DebugEnterRule(GrammarFileName, "ifExp");
		DebugLocation(78, 1);
		try
		{
			// KnightyCode.g:79:2: ( If con= exp '{' true_body= exp '}' ( Else '{' false_body= exp '}' )? )
			DebugEnterAlt(1);
			// KnightyCode.g:79:4: If con= exp '{' true_body= exp '}' ( Else '{' false_body= exp '}' )?
			{
			DebugLocation(79, 4);
			Match(input,If,Follow._If_in_ifExp371); if (state.failed) return node;
			DebugLocation(79, 10);
			PushFollow(Follow._exp_in_ifExp375);
			con=exp();
			PopFollow();
			if (state.failed) return node;
			DebugLocation(79, 15);
			if (state.backtracking == 0)
			{
				 node = new IfNode( con ); 
			}
			DebugLocation(80, 2);
			Match(input,19,Follow._19_in_ifExp380); if (state.failed) return node;
			DebugLocation(80, 15);
			PushFollow(Follow._exp_in_ifExp384);
			true_body=exp();
			PopFollow();
			if (state.failed) return node;
			DebugLocation(80, 20);
			Match(input,20,Follow._20_in_ifExp386); if (state.failed) return node;
			DebugLocation(80, 24);
			if (state.backtracking == 0)
			{
				 node.True = true_body; 
			}
			DebugLocation(81, 2);
			// KnightyCode.g:81:2: ( Else '{' false_body= exp '}' )?
			int alt8=2;
			try { DebugEnterSubRule(8);
			try { DebugEnterDecision(8, false);
			int LA8_1 = input.LA(1);

			if ((LA8_1==Else))
			{
				alt8 = 1;
			}
			} finally { DebugExitDecision(8); }
			switch (alt8)
			{
			case 1:
				DebugEnterAlt(1);
				// KnightyCode.g:81:4: Else '{' false_body= exp '}'
				{
				DebugLocation(81, 4);
				Match(input,Else,Follow._Else_in_ifExp393); if (state.failed) return node;
				DebugLocation(81, 9);
				Match(input,19,Follow._19_in_ifExp395); if (state.failed) return node;
				DebugLocation(81, 23);
				PushFollow(Follow._exp_in_ifExp399);
				false_body=exp();
				PopFollow();
				if (state.failed) return node;
				DebugLocation(81, 28);
				Match(input,20,Follow._20_in_ifExp401); if (state.failed) return node;
				DebugLocation(81, 32);
				if (state.backtracking == 0)
				{
					 node.False = false_body; 
				}

				}
				break;

			}
			} finally { DebugExitSubRule(8); }


			}

		}
		catch (RecognitionException re)
		{
			ReportError(re);
			Recover(input,re);
		}
		finally
		{
			TraceOut("ifExp", 9);
			LeaveRule("ifExp", 9);
			LeaveRule_ifExp();
		}
		DebugLocation(82, 1);
		} finally { DebugExitRule(GrammarFileName, "ifExp"); }
		return node;

	}
Ejemplo n.º 36
0
            void ParseInternal()
            {
                this.mainBlock = new BlockNode(null);
                this.stack = new Stack<BlockNode>();
                this.errors = new List<TemplateError>(); 
                PushBlock(mainBlock);

                var matches = TemplateUtils.KeywordsRegex.Matches(text);

                if (matches.Count == 0)
                {
                    stack.Peek().Nodes.Add(new LiteralNode { Text = text });
                    stack.Pop();
                    return;
                }

                int index = 0;
                foreach (Match match in matches)
                {
                    if (index < match.Index)
                    {
                        stack.Peek().Nodes.Add(new LiteralNode { Text = text.Substring(index, match.Index - index) });
                    }
                    var type = match.Groups["type"].Value;
                    var token = match.Groups["token"].Value;
                    var keyword = match.Groups["keyword"].Value;
                    var dec = match.Groups["dec"].Value;
                    switch (keyword)
                    {
                        case "":
                        case "raw":
                            var tok = TemplateUtils.TokenFormatRegex.Match(token);
                            if (!tok.Success)
                                AddError(true, "{0} has invalid format".FormatWith(token));
                            else
                            {
                                var t = TryParseValueProvider(type, tok.Groups["token"].Value, dec);

                                stack.Peek().Nodes.Add(new ValueNode(t, tok.Groups["format"].Value.DefaultText(null), isRaw: keyword.Contains("raw")));

                                DeclareVariable(t);
                            }
                            break;
                        case "declare":
                            {
                                var t = TryParseValueProvider(type, token, dec);

                                stack.Peek().Nodes.Add(new DeclareNode(t, this.AddError));

                                DeclareVariable(t);
                            }
                            break;
                        case "any":
                            {
                                AnyNode any;
                                ValueProviderBase vp;
                                var filter = TemplateUtils.TokenOperationValueRegex.Match(token);
                                if (!filter.Success)
                                {
                                    vp = TryParseValueProvider(type, token, dec);

                                    any = new AnyNode(vp);
                                }
                                else
                                {
                                    vp = TryParseValueProvider(type, filter.Groups["token"].Value, dec);
                                    var comparer = filter.Groups["comparer"].Value;
                                    var value = filter.Groups["value"].Value;
                                    any = new AnyNode(vp, comparer, value, this.AddError);

                                }
                                stack.Peek().Nodes.Add(any);
                                PushBlock(any.AnyBlock);

                                DeclareVariable(vp);
                                break;
                            }
                        case "notany":
                            {
                                var an = (AnyNode)PopBlock(typeof(AnyNode)).owner;
                                if (an != null)
                                    PushBlock(an.CreateNotAny());
                                break;
                            }
                        case "endany":
                            {
                                PopBlock(typeof(AnyNode));
                                break;
                            }
                        case "foreach":
                            {
                                ValueProviderBase vp = TryParseValueProvider(type, token, dec);
                                var fn = new ForeachNode(vp);
                                stack.Peek().Nodes.Add(fn);
                                PushBlock(fn.Block);
                                vp.IsForeach = true;
                                DeclareVariable(vp);
                                break;
                            }
                        case "endforeach":
                            {
                                PopBlock(typeof(ForeachNode));
                            }
                            break;
                        case "if":
                            {
                                IfNode ifn;
                                ValueProviderBase vp;
                                var filter = TemplateUtils.TokenOperationValueRegex.Match(token);
                                if (!filter.Success)
                                {
                                    vp = TryParseValueProvider(type, token, dec);
                                    ifn = new IfNode(vp, this);
                                }
                                else
                                {
                                    vp = TryParseValueProvider(type, filter.Groups["token"].Value, dec);
                                    var comparer = filter.Groups["comparer"].Value;
                                    var value = filter.Groups["value"].Value;
                                    ifn = new IfNode(vp, comparer, value, this.AddError);
                                }
                                stack.Peek().Nodes.Add(ifn);
                                PushBlock(ifn.IfBlock);
                                DeclareVariable(vp);
                                break;
                            }
                        case "else":
                            {
                                var ifn = (IfNode)PopBlock(typeof(IfNode)).owner;
                                if (ifn != null)
                                    PushBlock(ifn.CreateElse());
                                break;
                            }
                        case "endif":
                            {
                                PopBlock(typeof(IfNode));
                                break;
                            }
                        default :
                            AddError(true, "'{0}' is deprecated".FormatWith(keyword));
                            break;
                    }
                    index = match.Index + match.Length;
                }

                if (stack.Count != 1)
                    AddError(true, "Last block is not closed: {0}".FormatWith(stack.Peek()));

                var lastM = matches.Cast<Match>().LastOrDefault();
                if (lastM != null && lastM.Index + lastM.Length < text.Length)
                    stack.Peek().Nodes.Add(new LiteralNode { Text = text.Substring(lastM.Index + lastM.Length) });

                stack.Pop();
            }
Ejemplo n.º 37
0
 public virtual void Visit(IfNode node)
 {
     if (node != null)
     {
          AcceptChildren(node);
     }
 }
Ejemplo n.º 38
0
        public ITreeNode Program()
        {
            ITreeNode programNode = new ErrorNode();

            switch (curTokenType)
            {
                case TokenType.BEGINBL:
                    Match(ref matchToken, TokenType.BEGINBL);
                    ITreeNode someStatement = Program();
                    BlockNode block = new BlockNode();
                    block.addStatement(someStatement);
                    while (curTokenType != TokenType.ENDBL)
                    {
                        someStatement = Program();
                        block.addStatement(someStatement);
                    }
                    Match(ref matchToken, TokenType.ENDBL);
                    programNode = block;
                    break;
                case TokenType.LABEL:
                    Match(ref matchToken, TokenType.LABEL);
                    LabelNode labeledBlock = new LabelNode(matchToken.getValue());
                    ITreeNode labeledStatement;
                    do
                    {
                        labeledStatement = Program();
                        labeledBlock.addStatement(labeledStatement);
                    }
                    while (curTokenType != TokenType.EOF);
                    programNode = labeledBlock;
                    break;
                case TokenType.INTDEC:
                    Match(ref matchToken, TokenType.INTDEC);
                    Match(ref matchToken, TokenType.ID);
                    programNode = new IdentifierDeclarationNode(IdentifierType.INT, matchToken.getValue());
                    Match(ref matchToken, TokenType.EOS);
                    break;
                case TokenType.BOOLDEC:
                    Match(ref matchToken, TokenType.BOOLDEC);
                    Match(ref matchToken, TokenType.ID);
                    programNode = new IdentifierDeclarationNode(IdentifierType.BOOL, matchToken.getValue());
                    Match(ref matchToken, TokenType.EOS);
                    break;
                case TokenType.FOR:
                    Match(ref matchToken, TokenType.FOR);
                    Match(ref matchToken, TokenType.LPAREN);
                    AssignmentNode init = (AssignmentNode)Program();
                    AssignmentNode step = (AssignmentNode)Program();
                    BooleanExpressionNode condition = (BooleanExpressionNode)BooleanExpression();
                    Match(ref matchToken, TokenType.RPAREN);
                    BlockNode forBody = (BlockNode)Program();
                    programNode = new ForNode(init, step, condition, forBody);
                    break;
                /*case TokenType.FUN:
                    Match(ref matchToken, TokenType.FUN);
                    IdentifierNode id = (IdentifierNode)Factor();
                    programNode = new FunctionNode(id);
                    Match(ref matchToken, TokenType.EOS);
                    break;*/
                case TokenType.GOTO:
                    Match(ref matchToken, TokenType.GOTO);
                    Match(ref matchToken, TokenType.ID);
                    IdentifierNode gotoLabel = new IdentifierNode(matchToken.getValue(), IdentifierType.LABEL);
                    programNode = new GotoNode(gotoLabel);
                    Match(ref matchToken, TokenType.EOS);
                    break;
                case TokenType.ID:
                    Match(ref matchToken, TokenType.ID);
                    IdentifierNode assignId = new IdentifierNode(matchToken.getValue(), IdentifierType.UNKNOWN);
                    Match(ref matchToken, TokenType.ASSIGN);
                    BooleanExpressionNode assignValue = (BooleanExpressionNode)BooleanExpression();
                    programNode = new AssignmentNode(assignId, assignValue);
                    Match(ref matchToken, TokenType.EOS);
                    break;
                case TokenType.IF:
                    Match(ref matchToken, TokenType.IF);
                    ITreeNode thenBranch;
                    ITreeNode elseBranch;

                    Match(ref matchToken, TokenType.LPAREN);
                    BooleanExpressionNode ifCondition = (BooleanExpressionNode)BooleanExpression();
                    Match(ref matchToken, TokenType.RPAREN);
                    Match(ref matchToken, TokenType.THEN);
                    thenBranch = (BlockNode)Program();
                    if (curTokenType == TokenType.ELSE)
                    {
                        Match(ref matchToken, TokenType.ELSE);
                        elseBranch = (BlockNode)Program();
                    }
                    else
                    {
                        elseBranch = new BlankNode();
                    }
                    programNode = new IfNode(ifCondition, thenBranch, elseBranch);
                    break;
                /*case TokenType.LET:
                    Match(ref matchToken, TokenType.LET);
                    IdentifierNode shortId = (IdentifierNode)Factor();
                    Match(ref matchToken, TokenType.ASSIGN);
                    BooleanExpressionNode subst = (BooleanExpressionNode)BooleanExpression();
                    Match(ref matchToken, TokenType.IN);
                    BooleanExpressionNode target = (BooleanExpressionNode)BooleanExpression();
                    programNode = new LetNode(shortId, subst, target);
                    Match(ref matchToken, TokenType.EOS);
                    break;*/
                case TokenType.PRINT:
                    Match(ref matchToken, TokenType.PRINT);
                    Match(ref matchToken, TokenType.LPAREN);
                    BooleanExpressionNode printArgument = (BooleanExpressionNode)BooleanExpression();
                    Match(ref matchToken, TokenType.RPAREN);
                    programNode = new PrintNode(printArgument);
                    Match(ref matchToken, TokenType.EOS);
                    break;
                case TokenType.WHILE:
                    Match(ref matchToken, TokenType.WHILE);
                    Match(ref matchToken, TokenType.LPAREN);
                    BooleanExpressionNode whileCondition = (BooleanExpressionNode)BooleanExpression();
                    Match(ref matchToken, TokenType.RPAREN);
                    BlockNode whileBody = (BlockNode)Program();
                    programNode = new WhileNode(whileCondition, whileBody);
                    break;
                case TokenType.EOF:
                    programNode = new BlankNode();
                    break;
                default:
                    Expect(TokenType.UNKNOWN, lookAheadToken);
                    break;
            }
            return programNode;
        }
Ejemplo n.º 39
0
        private static void GenerateIf(IfNode node, DataContext data)
        {
            StartLine(data, "if (");

            GenerateExpression(node.EvaluateExpression, data);

            EndLine(data, ") {{");

            data.CodeBlock.Padding++;
            GenerateStatementBlock(node.BodyStatementBlock, data);

            if (node.ElseStatementBlock != null)
            {
                data.CodeBlock.Padding--;
                WriteLine(data, "}} else {{");

                data.CodeBlock.Padding++;
                GenerateStatementBlock(node.ElseStatementBlock, data);
            }

            data.CodeBlock.Padding--;
            WriteLine(data, "}}");
        }