Example #1
0
        static Exp IfThenElse(Stack <If> ifparts, Block elseblock = null)
        {
            If  node = ifparts.Pop();
            Exp r;

            if (elseblock is null)
            {
                r = node;
            }
            else
            {
                r = new IfElse {
                    test = node.test, ifTrue = node.body, ifFalse = elseblock
                }
            };

            while (ifparts.Count > 0)
            {
                node = ifparts.Pop();
                r    = new IfElse {
                    test = node.test, ifTrue = node.body, ifFalse = r
                };
            }

            return(r);
        }
    }
Example #2
0
        public static void Main()
        {
            GetMethod_Name.TestName();
            GetMethod_Name.TestNamePrivate();
            GetMethod_Name_Types.TestNameAndType();
            GetMethod_Name_BindingAttr.TestExplicitBindingFlags();
            GetMethod_Name_BindingAttr.TestUnknownBindingFlags(BindingFlags.Public);
            GetMethod_Name_BindingAttr.TestUnknownBindingFlagsAndName(BindingFlags.Public, "DoesntMatter");
            GetMethod_Name_BindingAttr.TestUnknownNullBindingFlags(BindingFlags.Public);
            GetMethod_Name_BindingAttr_Binder_Types_Modifiers.TestNameBindingFlagsAndParameterModifier();
            GetMethod_Name_BindingAttr_Binder_CallConvention_Types_Modifiers.TestNameBindingFlagsCallingConventionParameterModifier();
#if NETCOREAPP
            GetMethod_Name_BindingAttr_Types.TestNameBindingFlagsAndTypes();
            GetMethod_Name_GenericParameterCount_Types.TestNameWithIntAndType();
            GetMethod_Name_GenericParameterCount_Types_Modifiers.TestNameWithIntAndTypeAndModifiers();
            GetMethod_Name_GenericParameterCount_BindingAttr_Binder_Types_Modifiers.TestNameWithIntAndBindingFlags();
            GetMethod_Name_GenericParameterCount_BindingAttr_Binder_Types_Modifiers_PrivateBinding.TestNameWithIntAndPrivateBindingFlags();
            GetMethod_Name_GenericParameterCount_BindingAttr_Binder_CallConvention_Types_Modifiers.TestNameWithIntBindingFlagsCallingConventionParameter();
#endif
            TestNullName();
            TestEmptyName();
            TestNonExistingName();
            TestNullType();
            TestDataFlowType();
            IfElse.TestIfElse(1);
            DerivedAndBase.TestMethodInBaseType();
            IgnoreCaseBindingFlags.TestIgnoreCaseBindingFlags();
            FailIgnoreCaseBindingFlags.TestFailIgnoreCaseBindingFlags();
            IgnorableBindingFlags.TestIgnorableBindingFlags();
            UnsupportedBindingFlags.TestUnsupportedBindingFlags();
        }
Example #3
0
    void GenerateInstructions()
    {
        Timer timer = GetComponentInParent <Timer>();

        if (!timer)
        {
            Debug.LogError("No timer component in parent game object found. Stop generating instructions.");
            return;
        }

        int       from = UnityEngine.Random.Range(0, 9);
        int       to   = from + UnityEngine.Random.Range(1, 9 - from);
        Condition a    = new DigitInRange((Ordering)UnityEngine.Random.Range(0, 1), UnityEngine.Random.Range(1, 3), from, to);
        Condition b    = new DigitEvenOrOdd((Ordering)UnityEngine.Random.Range(0, 1), UnityEngine.Random.Range(0, 1) != 0);
        Condition c    = new And(a, b);

        Instruction cutThird = new CutWire(UnityEngine.Random.Range(0, WireColors.Length));
        Instruction cutFifth = new CutWire(UnityEngine.Random.Range(0, WireColors.Length));
        Instruction first    = new IfElse(timer, c, cutThird, cutFifth);

        Debug.Log(first.generateOutput());
        for (int i = 0; i < WireColors.Length; i++)
        {
            Debug.LogFormat("{0} = isValid({1})", first.isValid(i), i);
        }

        _instructions.Add(first);

        if (GeneratedInstructions != null)
        {
            GeneratedInstructions(_instructions);
        }
    }
Example #4
0
 public void visit(IfElse ifElse)
 {
     ifElse.expression.accept(this);
     ifElse.block1.accept(this);
     if (ifElse.block2 != null)
     {
         ifElse.block2.accept(this);
     }
 }
Example #5
0
        public void TestIfElse()
        {
            var ifElse = new IfElse(new Rel(new Token('>'), new Constant(42), new Constant(99)), new Stmt(), new Stmt());

            ifElse.Gen(10, 100);
            //output:
            //      iffalse 42 > 99 goto L2
            //L1:	goto L100
            //L2:
        }
Example #6
0
 protected override EP_VP1 Visit(IfElse node)
 {
     node.Condition.Visit(this);
     node.Then.Visit(this);
     if (node.Else != null)
     {
         node.Else.Visit(this);
     }
     return(this);
 }
Example #7
0
 public void SolveQuadraticEquatioNegative(double a, double b, double c)
 {
     try
     {
         IfElse.SolveQuadraticEquation(a, b, c);
     }
     catch
     {
         Assert.Pass();
     }
     Assert.Fail();
 }
        public static void Main()
        {
            GetConstructor_Types.Test();
            GetConstructor_BindingAttr_Binder_Types_Modifiers.TestWithBindingFlags();
            GetConstructor_BindingAttr_Binder_Types_Modifiers.TestWithUnknownBindingFlags(BindingFlags.Public);
            GetConstructor_BindingAttr_Binder_CallConvention_Types_Modifiers.TestWithCallingConvention();
#if NETCOREAPP
            GetConstructor_BindingAttr_Types.Test();
#endif
            TestNullType();
            TestDataFlowType();
            IfElse.TestIfElse(true);
        }
Example #9
0
        public override AstNode VisitIfElse(IfElse ast)
        {
            Visit(ast.Condition);

            if (ast.Condition.ExpressionType != PrimaryType.Boolean)
            {
                AddError(c_SE_IfStmtTypeInvalid, ast.IfSpan);
            }

            Visit(ast.TruePart);
            Visit(ast.FalsePart);

            return(ast);
        }
Example #10
0
        public void WriteIfElse(IfElse s, bool chain = false)
        {
            if (!chain)
            {
                Skip();
                BeginLine();
            }

            Write("if" + Space + "(");
            WriteExpression(s.Condition);
            EndLine(")");
            WriteShortScope(s.OptionalIfBody, true);

            if (s.OptionalElseBody != null)
            {
                DisableSkip();
                BeginLine("else");
                var elseIf = s.OptionalElseBody as IfElse;

                if (elseIf != null)
                {
                    Write(" ");
                    WriteIfElse(elseIf, true);
                }
                else
                {
                    // Avoid missing space in a minified shader, e.g.: `... elsereturn ...`
                    if (EnableMinify && s.OptionalElseBody.StatementType != StatementType.Scope)
                    {
                        Write(" ");
                    }
                    else
                    {
                        EndLine();
                    }

                    WriteShortScope(s.OptionalElseBody, true);
                }
            }
            else
            {
                Skip();
            }
        }
Example #11
0
        private void Emit(IfElse value)
        {
            code.Append("if(");
            Emit(ThrowIfNull(value.Cond));
            code.Append("){");

            if (value.IfBody != null)
            {
                Emit(value.IfBody);
            }

            code.Append("}else{");

            if (value.ElseBody != null)
            {
                Emit(value.ElseBody);
            }

            code.Append("}");
        }
Example #12
0
        void AppendIfElse(IfElse s, string indent, bool parentWasElse = false)
        {
            Append(parentWasElse ? " " : indent);
            AppendLine("if (" + s.Condition + ")");
            AppendScope(s.OptionalIfBody, indent);

            if (s.OptionalElseBody != null)
            {
                Append(indent + "else");

                if (s.OptionalElseBody is IfElse)
                {
                    AppendIfElse(s.OptionalElseBody as IfElse, indent, true);
                }
                else
                {
                    AppendLine();
                    AppendScope(s.OptionalElseBody, indent);
                }
            }
        }
Example #13
0
    public static void Main(string[] args)
    {
        //non static method we need to create object to call methods
        IfElse ifelse = new IfElse();

        ifelse.StaticEvenOrOdd();
        Console.WriteLine("Enter N:");
        int n = int.Parse(Console.ReadLine());

        //static method no need to create object directly call with class name
        IfElse.DynamicEvenOrOdd(n);
        int result = ifelse.ValueReturnEvenOrOdd(n);

        Console.WriteLine(result);
        string resultdata = ifelse.ConditionalEvenOrOdd(n);

        Console.WriteLine(resultdata);
        bool resultbool = ifelse.BolEvenOrOdd(n);

        Console.WriteLine(resultbool);
    }
Example #14
0
        public override AstNode VisitIfElse(IfElse ast)
        {
            var ifBlock   = m_ilgen.DefineLabel();
            var elseBlock = m_ilgen.DefineLabel();
            var endif     = m_ilgen.DefineLabel();

            Visit(ast.Condition);
            //the e-stack should have a bool value
            m_ilgen.Emit(OpCodes.Brfalse, elseBlock);

            //if block
            m_ilgen.MarkLabel(ifBlock);
            Visit(ast.TruePart);
            m_ilgen.Emit(OpCodes.Br, endif);

            //elseblock
            m_ilgen.MarkLabel(elseBlock);
            Visit(ast.FalsePart);

            //after if
            m_ilgen.MarkLabel(endif);

            return(ast);
        }
Example #15
0
 public void initInventory()
 {
     inventorySkills = new baseSkill[14];
     inventorySkills [0] = new Arrays ();
     inventorySkills [1] = new BreakAndContinue ();
     inventorySkills [2] = new DDOS ();
     inventorySkills [3] = new DefaultFunctions ();
     inventorySkills [4] = new FireWall ();
     inventorySkills [5] = new FunctionsWithInputOutput ();
     inventorySkills [6] = new FunctionsWithOutput ();
     inventorySkills [7] = new Hash ();
     inventorySkills [8] = new IfElse ();
     inventorySkills [9] = new InfiniteLoop ();
     inventorySkills [10] = new Loop ();
     inventorySkills [11] = new PacketSniffing ();
     inventorySkills [12] = new Recursion ();
     inventorySkills [13] = new Stack ();
     Debug.Log ("Finished Loading Inventory");
 }
Example #16
0
        /// <summary>
        /// 递归将所有语句以树形结构组织
        /// </summary>
        /// <param name="sens">传入一个Sentence数组</param>
        /// <returns></returns>
        public List <Sentence> CalcSentences(List <Sentence> sens)
        {
            List <Sentence> result = new List <Sentence>();
            IfElse          ifElse = null;

            for (int i = 0; i < sens.Count; i++)
            {
                switch (sens[i].toks[0].value)
                {
                case "while": {
                    int   whiledep = sens[i].deepth;
                    While @while   = new While(null, whiledep);
                    @while.judgesentence = new Sentence(sens[i].toks.GetRange(1, sens[i].toks.Count - 1), whiledep);
                    int j = i + 1;
                    for (; j < sens.Count && sens[j].deepth > whiledep; j++)
                    {
                    }
                    @while.sentences = CalcSentences(sens.GetRange(i + 1, j - i - 1));
                    result.Add(@while);
                    i = j - 1;
                    break;
                }

                case "if": {
                    int ifdeepth = sens[i].deepth;
                    int j        = i + 1;
                    for (; sens[j].deepth > ifdeepth; j++)
                    {
                    }
                    ifElse = new IfElse(null, sens[i].deepth);
                    ifElse.branchs.Add(new Branch(new Sentence(sens[i].toks.GetRange(1, sens[i].toks.Count - 1), ifdeepth), CalcSentences(sens.GetRange(i + 1, j - i - 1))));
                    i = j - 1;
                    break;
                }

                case "elseif": {
                    int elifdep = sens[i].deepth;
                    int j       = i + 1;
                    for (; sens[j].deepth > elifdep; j++)
                    {
                    }
                    if (ifElse == null)
                    {
                        throw new SyntaxErrorException("syntax error:expected 'if'");
                    }
                    else
                    {
                        ifElse.branchs.Add(new Branch(new Sentence(sens[i].toks.GetRange(1, sens[i].toks.Count - 1), elifdep), CalcSentences(sens.GetRange(i + 1, j - i - 1))));
                    }
                    i = j - 1;
                    break;
                }

                case "else": {
                    int elifdep = sens[i].deepth;
                    int j       = i + 1;
                    for (; sens[j].deepth > elifdep; j++)
                    {
                    }
                    if (ifElse == null)
                    {
                        throw new SyntaxErrorException("syntax error:expected 'if'");
                    }
                    else
                    {
                        ifElse.branchs.Add(new Branch(null, CalcSentences(sens.GetRange(i + 1, j - i - 1))));
                    }
                    result.Add(ifElse);
                    i = j - 1;
                    break;
                }

                default: {
                    result.Add(sens[i]);
                    break;
                }
                }
            }
            return(result);
        }
Example #17
0
 public void SolveQuadraticEquation(double a, double b, double c, double[] expected)
 {
     double[] actual = IfElse.SolveQuadraticEquation(a, b, c);
     Assert.AreEqual(expected, actual);
 }
Example #18
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();

            //Если есть текстовое описание
            if (this.index < this.tokens.Count &&
                this.tokens[this.index] is Text.StringBuilder)
            {
                print.Expression = this.ParseExpr();
            }

            if (this.index < this.tokens.Count &&
                this.tokens[this.index] is string)
            {
                print.VarExpression = 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.Expression = this.ParseExpr();
            result = declareVar;
        }
        else if (this.tokens[this.index].Equals("input"))
        {
            this.index++;
            ReadValue readValue = new ReadValue();

            //Если есть текстовое описание
            if (this.index < this.tokens.Count &&
                this.tokens[this.index] is Text.StringBuilder)
            {
                readValue.Exp = this.ParseExpr();
            }

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

        /*else if (this.tokens[this.index].Equals("read_int"))
         *      {
         *              this.index++;
         *              ReadValue readValue = new ReadValue();
         *
         *              if (this.index < this.tokens.Count &&
         *                      this.tokens[this.index] is string)
         *              {
         *                      readValue.Ident = (string)this.tokens[this.index++];
         *                      result = readValue;
         *              }
         *              else
         *              {
         *                      throw new System.Exception("expected variable name after 'read_int'");
         *              }
         *      }*/
        else if (this.tokens[this.index].Equals("for"))
        {
            this.index++;
            ForNext forNext = new ForNext();

            if (this.index < this.tokens.Count &&
                this.tokens[this.index] is string)
            {
                forNext.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++;

            forNext.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++;

            forNext.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 next");
             * }*/

            this.index++;

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

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

            this.index++;
        }
        else if (this.tokens[this.index].Equals("if"))
        {
            this.index++;
            IfElse ifthen = new IfElse();
            ifthen.Condition = new ConExpression();

            //Запишем первый операнд в условии
            if (this.index < this.tokens.Count &&
                this.tokens[this.index] is string)
            {
                ifthen.Condition.Left = this.ParseExpr();
            }
            else
            {
                throw new System.Exception("expected identifier after 'if'");
            }

            // Запишем условный оператор
            if (this.tokens[this.index] == Scanner.More) //Больше
            {
                ifthen.Condition.Operation = ConOperation.More;
            }
            else if (this.tokens[this.index] == Scanner.MoreEqual) //Больше-равно
            {
                ifthen.Condition.Operation = ConOperation.MoreEqual;
            }
            else if (this.tokens[this.index] == Scanner.Less) //Меньше
            {
                ifthen.Condition.Operation = ConOperation.Less;
            }
            else if (this.tokens[this.index] == Scanner.LessEqual) //Меньше-равно
            {
                ifthen.Condition.Operation = ConOperation.LessEqual;
            }
            else if (this.tokens[this.index] == Scanner.Equal) //Равенство
            {
                ifthen.Condition.Operation = ConOperation.Equal;
            }
            else
            {
                throw new System.Exception("missing condition operator");
            }

            //Запишем второй операнд в условии
            this.index++;
            ifthen.Condition.Right = this.ParseExpr();

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

            this.index++;
            ifthen.BodyThen = this.ParseStmt();

            if (this.index < this.tokens.Count && this.tokens[this.index].Equals("else"))
            {
                this.index++;
                ifthen.BodyElse = this.ParseStmt();
            }

            result = ifthen;

            if (this.index == this.tokens.Count ||
                !this.tokens[this.index].Equals("endif"))
            {
                throw new System.Exception("unterminated 'if' 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.Expression = this.ParseExpr();

            //Проверим наличие операции

            if (this.tokens[this.index] != Scanner.Semi)
            {
                assign.Expression = this.ParseBinExpr(assign.Expression);
            }

            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("next") && !this.tokens[this.index].Equals("endif") && !this.tokens[this.index].Equals("else"))
            {
                Sequence sequence = new Sequence();
                sequence.First  = result;
                sequence.Second = this.ParseStmt();
                result          = sequence;
            }
        }

        return(result);
    }
Example #19
0
        static bool TrySplitVirtualAppliesInDrawBlockRecursive(Compiler compiler, DrawBlock drawBlock, ref int drawBlockIndex, HashSet <Scope> drawScopes)
        {
            for (int i = 0, l = drawBlock.Members.Count; i < l; i++)
            {
                var apply = drawBlock.Members[i] as Apply;

                if (apply != null &&
                    apply.Modifier == ApplyModifier.Virtual &&
                    apply.Object != null)
                {
                    var dt        = apply.Object.ReturnType;
                    int baseIndex = drawBlockIndex;

                    Statement root   = null;
                    IfElse    lastIf = null;

                    HashSet <DataType> subSet;
                    if (compiler.BlockBuilder.FlattenedTypes.TryGetValue(dt, out subSet))
                    {
                        var subArray = subSet.ToArray();

                        // Make sure array is sorted correctly.
                        // Reverse order since this is most similar to the original order making sorting ~O(n)

                        Array.Sort(subArray,
                                   (a, b) =>
                        {
                            int al = 0, bl = 0;

                            for (var bt = a.Base; bt != null && bt != dt; bt = bt.Base)
                            {
                                al++;
                            }
                            for (var bt = b.Base; bt != null && bt != dt; bt = bt.Base)
                            {
                                bl++;
                            }

                            return(al - bl);
                        });

                        foreach (var st in subArray.Reverse())
                        {
                            if (st.IsAbstract || st.Block == null || !st.IsAccessibleFrom(apply.Source))
                            {
                                continue;
                            }

                            var obj      = new AsOp(apply.Object.Source, apply.Object, st);
                            var subBlock = CreateFlattenedVirtualApplyInDrawBlock(apply.Source, drawBlock, i, obj, st.Block);
                            var cond     = new IsOp(apply.Object.Source, apply.Object, st, compiler.Essentials.Bool);
                            var subIf    = new IfElse(subBlock.Source, cond, subBlock.DrawScope);

                            if (lastIf == null)
                            {
                                root   = subIf;
                                lastIf = subIf;
                            }
                            else
                            {
                                lastIf.OptionalElseBody = subIf;
                                lastIf = subIf;
                            }

                            drawBlock.Method.DrawBlocks.Insert(++baseIndex, subBlock);
                            TrySplitVirtualAppliesInDrawBlockRecursive(compiler, subBlock, ref baseIndex, drawScopes);
                        }
                    }

                    if (!dt.IsAbstract)
                    {
                        var baseBlock = CreateFlattenedVirtualApplyInDrawBlock(apply.Source, drawBlock, i, apply.Object, apply.Block);

                        if (lastIf == null)
                        {
                            root = baseBlock.DrawScope;
                        }
                        else
                        {
                            lastIf.OptionalElseBody = baseBlock.DrawScope;
                        }

                        drawBlock.Method.DrawBlocks.Insert(++baseIndex, baseBlock);
                        TrySplitVirtualAppliesInDrawBlockRecursive(compiler, baseBlock, ref baseIndex, drawScopes);
                    }

                    if (root != null)
                    {
                        drawBlock.DrawScope.Statements.Add(root);
                    }

                    drawScopes.Add(drawBlock.Method.DrawBlocks[drawBlockIndex].DrawScope);
                    drawBlock.Method.DrawBlocks.RemoveAt(drawBlockIndex);
                    drawBlockIndex += baseIndex - drawBlockIndex - 1;
                    return(true);
                }
            }

            return(false);
        }
Example #20
0
        public override AstNode VisitIfElse(IfElse ast)
        {
            Visit(ast.Condition);

            if (ast.Condition.ExpressionType != PrimaryType.Boolean)
            {
                m_errorManager.AddError(c_SE_IfStmtTypeInvalid, ast.IfSpan);
            }

            Visit(ast.TruePart);
            Visit(ast.FalsePart);

            return ast;
        }
Example #21
0
 public void TestInitialize( )
 {
     this.ifelse = new IfElse();
 }
 void OP_IFELSE(out pBaseLangObject outObj, pBaseLangObject parent)
 {
     var obj = new IfElse(parent); outObj = obj; pBaseLangObject blo;
     Expect(64);
     Expect(10);
     EXPRESSION(out blo, obj);
     obj.expression = blo;
     Expect(11);
     if (la.kind == 14) {
         Get();
         while (StartOf(14)) {
             CODEINSTRUCTION(out blo, obj);
             obj.addChild(blo);
         }
         Expect(15);
     } else if (StartOf(14)) {
         CODEINSTRUCTION(out blo, obj);
         obj.addChild(blo);
     } else SynErr(109);
     obj.markIfEnd();
     if (la.kind == 65) {
         Get();
         if (la.kind == 14) {
             Get();
             while (StartOf(14)) {
                 CODEINSTRUCTION(out blo, obj);
                 obj.addChild(blo);
             }
             Expect(15);
         } else if (StartOf(14)) {
             CODEINSTRUCTION(out blo, obj);
             obj.addChild(blo);
         } else SynErr(110);
     }
 }
Example #23
0
        public Statement CompileStatement(AstStatement e)
        {
            switch (e.StatementType)
            {
            default:
                if (e is AstExpression)
                {
                    return(CompileExpression(e as AstExpression));
                }
                break;

            case AstStatementType.VariableDeclaration:
                return(CompileVariableDeclaration(e as AstVariableDeclaration));

            case AstStatementType.FixedArrayDeclaration:
                return(CompileFixedArrayDeclaration(e as AstFixedArrayDeclaration));

            case AstStatementType.Scope:
                return(CompileScope(e as AstScope));

            case AstStatementType.Draw:
                return(Compiler.BlockBuilder.CompileDraw(Function, VariableScopeStack, e as AstDraw));

            case AstStatementType.DrawDispose:
                return(new DrawDispose(e.Source));

            case AstStatementType.Break:
                return(new Break(e.Source));

            case AstStatementType.Continue:
                return(new Continue(e.Source));

            case AstStatementType.Unchecked:
            {
                CheckCastStack.Add(false);

                try
                {
                    return(CompileStatement(((AstModifiedStatement)e).Statement));
                }
                finally
                {
                    CheckCastStack.RemoveLast();
                }
            }

            case AstStatementType.IfElse:
            {
                var s = e as AstIfElse;

                if (s.Condition is AstDefined)
                {
                    var def = s.Condition as AstDefined;

                    return(Environment.Test(def.Source, def.Condition)
                            ? s.OptionalIfBody != null
                                ? CompileStatement(s.OptionalIfBody)
                                : new NoOp(s.Source)
                            : s.OptionalElseBody != null
                                ? CompileStatement(s.OptionalElseBody)
                                : new NoOp(s.Source));
                }

                var r = new IfElse(s.Source, CompileCondition(s.Condition));

                if (s.OptionalIfBody != null)
                {
                    r.OptionalIfBody = CompileStatement(s.OptionalIfBody);
                }
                if (s.OptionalElseBody != null)
                {
                    r.OptionalElseBody = CompileStatement(s.OptionalElseBody);
                }

                return(r);
            }

            case AstStatementType.ExternScope:
            {
                var s = (AstExternScope)e;
                return(new ExternScope(s.Source,
                                       Compiler.CompileAttributes(Namescope, s.Attributes),
                                       s.Body.String,
                                       ExtensionTransform.CreateObject(s.Source, Function, TypeBuilder.Parameterize(Function.DeclaringType)),
                                       s.OptionalArguments != null
                            ? CompileArgumentList(s.OptionalArguments)
                            : ExtensionTransform.CreateArgumentList(s.Source, Function),
                                       GetUsings(s.Source)));
            }

            case AstStatementType.While:
            {
                var s = e as AstLoop;
                var r = new While(s.Source, false, CompileCondition(s.Condition));

                var vscope = new VariableScope();
                VariableScopeStack.Add(vscope);

                if (s.OptionalBody != null)
                {
                    r.OptionalBody = CompileStatement(s.OptionalBody);
                }

                if (s.OptionalBody == null || (!s.OptionalBody.IsInvalid && ((s.OptionalBody is AstScope && (s.OptionalBody as AstScope).IsClosed) || !(s.OptionalBody is AstScope))))
                {
                    VariableScopeStack.Remove(vscope);
                    CurrentVariableScope.Scopes.Add(vscope);
                }

                return(r);
            }

            case AstStatementType.DoWhile:
            {
                var s      = e as AstLoop;
                var r      = new While(s.Source, true, CompileCondition(s.Condition));
                var vscope = new VariableScope();
                VariableScopeStack.Add(vscope);

                if (s.OptionalBody != null)
                {
                    r.OptionalBody = CompileStatement(s.OptionalBody);
                }

                if (s.OptionalBody == null || (!s.OptionalBody.IsInvalid && ((s.OptionalBody is AstScope && (s.OptionalBody as AstScope).IsClosed) || !(s.OptionalBody is AstScope))))
                {
                    VariableScopeStack.Remove(vscope);
                    CurrentVariableScope.Scopes.Add(vscope);
                }

                return(r);
            }

            case AstStatementType.For:
            {
                var s      = e as AstFor;
                var r      = new For(s.Source);
                var vscope = new VariableScope();
                VariableScopeStack.Add(vscope);

                if (s.OptionalInitializer != null)
                {
                    r.OptionalInitializer = CompileStatement(s.OptionalInitializer);
                }
                if (s.OptionalCondition != null)
                {
                    r.OptionalCondition = CompileCondition(s.OptionalCondition);
                }
                if (s.OptionalBody != null)
                {
                    r.OptionalBody = CompileStatement(s.OptionalBody);
                }
                if (s.OptionalIncrement != null)
                {
                    r.OptionalIncrement = CompileExpression(s.OptionalIncrement);
                }

                if (s.OptionalBody == null ||
                    (!s.OptionalBody.IsInvalid && ((s.OptionalBody is AstScope && (s.OptionalBody as AstScope).IsClosed) ||
                                                   !(s.OptionalBody is AstScope))))
                {
                    VariableScopeStack.Remove(vscope);
                    CurrentVariableScope.Scopes.Add(vscope);
                }

                return(r);
            }

            case AstStatementType.Foreach:
            {
                var       s          = e as AstForeach;
                var       scope      = new Scope(s.Source);
                var       collection = CompileExpression(s.Collection);
                Statement result;

                var vscope = new VariableScope();
                VariableScopeStack.Add(vscope);
                VerifyVariableName(s.ElementName.Source, s.ElementName.Symbol);

                if (collection.ReturnType.IsArray ||
                    collection.ReturnType == Essentials.String)
                {
                    var loop = new For(s.Source)
                    {
                        OptionalBody = scope
                    };
                    var collectionVar = new Variable(s.Collection.Source, Function, Namescope.GetUniqueIdentifier("array"), collection.ReturnType);

                    if (collection is LoadLocal)
                    {
                        collectionVar = (collection as LoadLocal).Variable;
                    }
                    else
                    {
                        vscope.Variables.Add(collectionVar.Name, collectionVar);
                    }

                    var indexInitializer  = new Constant(s.Collection.Source, Essentials.Int, 0);
                    var lengthInitializer = CompileImplicitCast(s.Collection.Source, Essentials.Int,
                                                                CompileExpression(
                                                                    new AstMember(
                                                                        new AstIdentifier(s.Collection.Source, collectionVar.Name),
                                                                        new AstIdentifier(s.Collection.Source, "Length"))));

                    var indexVar  = new Variable(s.Collection.Source, Function, Namescope.GetUniqueIdentifier("index"), Essentials.Int);
                    var lengthVar = new Variable(s.Collection.Source, Function, Namescope.GetUniqueIdentifier("length"), Essentials.Int);

                    if (collection is LoadLocal)
                    {
                        indexVar.OptionalValue   = indexInitializer;
                        lengthVar.OptionalValue  = lengthInitializer;
                        loop.OptionalInitializer = new VariableDeclaration(indexVar, lengthVar);
                    }
                    else
                    {
                        loop.OptionalInitializer = new SequenceOp(
                            new StoreLocal(s.Collection.Source, collectionVar, collection),
                            new StoreLocal(s.Collection.Source, indexVar, indexInitializer),
                            new StoreLocal(s.Collection.Source, lengthVar, lengthInitializer));
                    }

                    vscope.Variables.Add(indexVar.Name, indexVar);
                    vscope.Variables.Add(lengthVar.Name, lengthVar);

                    loop.OptionalCondition = CompileCondition(
                        new AstBinary(AstBinaryType.LessThan,
                                      new AstIdentifier(s.Collection.Source, indexVar.Name),
                                      s.Collection.Source,
                                      new AstIdentifier(s.Collection.Source, lengthVar.Name)));

                    loop.OptionalIncrement = new FixOp(s.Collection.Source, FixOpType.IncreaseBefore,
                                                       new LoadLocal(s.Collection.Source, indexVar));

                    var elementType = s.ElementType.ExpressionType == AstExpressionType.Var
                            ? collection.ReturnType.IsArray
                                    ? collection.ReturnType.ElementType
                                    : Essentials.Char
                            : NameResolver.GetType(Namescope, s.ElementType);

                    var elementVar = new Variable(s.ElementName.Source, Function, s.ElementName.Symbol, elementType, VariableType.Iterator,
                                                  CompileImplicitCast(s.ElementName.Source, elementType,
                                                                      CompileExpression(
                                                                          new AstCall(AstCallType.LookUp,
                                                                                      new AstIdentifier(s.ElementName.Source, collectionVar.Name),
                                                                                      new AstIdentifier(s.ElementName.Source, indexVar.Name)))));

                    scope.Statements.Add(new VariableDeclaration(elementVar));
                    vscope.Variables.Add(elementVar.Name, elementVar);
                    result = loop;
                }
                else
                {
                    // TODO: Verify that collection implements IEnumerable<T>

                    var loop = new While(s.Source)
                    {
                        OptionalBody = scope
                    };
                    var enumeratorInitializer = ILFactory.CallMethod(s.Collection.Source, collection.Address, "GetEnumerator");
                    var enumeratorVar         = new Variable(s.Collection.Source, Function, Namescope.GetUniqueIdentifier("enum"), enumeratorInitializer.ReturnType, VariableType.Default, enumeratorInitializer);

                    vscope.Variables.Add(enumeratorVar.Name, enumeratorVar);

                    loop.Condition = CompileImplicitCast(s.Collection.Source, Essentials.Bool,
                                                         ILFactory.CallMethod(s.Collection.Source,
                                                                              new LoadLocal(s.Collection.Source, enumeratorVar).Address,
                                                                              "MoveNext"));

                    var elementInitializer = CompileExpression(new AstMember(
                                                                   new AstIdentifier(s.ElementName.Source, enumeratorVar.Name),
                                                                   new AstIdentifier(s.ElementName.Source, "Current")));

                    var elementType = s.ElementType.ExpressionType == AstExpressionType.Var
                                ? elementInitializer.ReturnType
                                : NameResolver.GetType(Namescope, s.ElementType);
                    var elementVar = new Variable(s.Source, Function, s.ElementName.Symbol, elementType, VariableType.Iterator,
                                                  CompileImplicitCast(s.ElementName.Source, elementType, elementInitializer));

                    var hasDispose = false;
                    foreach (var m in enumeratorVar.ValueType.Methods)
                    {
                        if (m.Name == "Dispose" && m.Parameters.Length == 0)
                        {
                            hasDispose = true;
                            break;
                        }
                    }

                    // Optimization: avoid casting to IDisposable when Dispose() method is found
                    var dispose = hasDispose
                            ? ILFactory.CallMethod(s.Collection.Source,
                                                   new LoadLocal(s.Collection.Source, enumeratorVar).Address,
                                                   "Dispose")
                            : ILFactory.CallMethod(s.Collection.Source,
                                                   new CastOp(s.Collection.Source, Essentials.IDisposable,
                                                              new LoadLocal(s.Collection.Source, enumeratorVar)).Address,
                                                   "Dispose");

                    scope.Statements.Add(new VariableDeclaration(elementVar));
                    vscope.Variables.Add(elementVar.Name, elementVar);
                    result = new Scope(s.Source,
                                       new VariableDeclaration(enumeratorVar),
                                       new TryCatchFinally(s.Source,
                                                           new Scope(s.Source, loop),
                                                           new Scope(s.Source, dispose)));
                }

                if (s.OptionalBody != null)
                {
                    var body = CompileStatement(s.OptionalBody);

                    if (body is Scope)
                    {
                        scope.Statements.AddRange((body as Scope).Statements);
                    }
                    else
                    {
                        scope.Statements.Add(body);
                    }
                }

                if (s.OptionalBody == null ||
                    !s.OptionalBody.IsInvalid && ((s.OptionalBody is AstScope && (s.OptionalBody as AstScope).IsClosed) ||
                                                  !(s.OptionalBody is AstScope)))
                {
                    VariableScopeStack.Remove(vscope);
                    CurrentVariableScope.Scopes.Add(vscope);
                }

                return(result);
            }

            case AstStatementType.Return:
                return(new Return(e.Source));

            case AstStatementType.ReturnValue:
            {
                var s = e as AstValueStatement;

                var returnValue = CompileExpression(s.Value);

                var returnType = Lambdas.Count == 0
                        ? Function.ReturnType
                        : Lambdas.Peek().DelegateType.ReturnType;

                return(new Return(s.Source, CompileImplicitCast(s.Source, returnType, returnValue)));
            }

            case AstStatementType.TryCatchFinally:
            {
                var   s            = e as AstTryCatchFinally;
                var   tryScope     = CompileScope(s.TryScope);
                var   catchBlocks  = new List <CatchBlock>();
                Scope finallyScope = null;

                foreach (var c in s.CatchBlocks)
                {
                    var exceptionType =
                        c.OptionalType != null?
                        NameResolver.GetType(Namescope, c.OptionalType) :
                            Essentials.Exception;

                    var vscope = new VariableScope();
                    VariableScopeStack.Add(vscope);

                    VerifyVariableName(c.Name.Source, c.Name.Symbol);
                    var exceptionVar = new Variable(c.Name.Source, Function, c.Name.Symbol, exceptionType, VariableType.Exception);
                    vscope.Variables.Add(exceptionVar.Name, exceptionVar);

                    var catchBody = CompileScope(c.Body);

                    if (c.Body == null || !c.Body.IsInvalid && c.Body.IsClosed)
                    {
                        VariableScopeStack.Remove(vscope);
                        CurrentVariableScope.Scopes.Add(vscope);
                    }

                    catchBlocks.Add(new CatchBlock(c.Name.Source, exceptionVar, catchBody));
                }

                if (s.OptionalFinallyScope != null)
                {
                    finallyScope = CompileScope(s.OptionalFinallyScope);
                }

                return(new TryCatchFinally(s.Source, tryScope, finallyScope, catchBlocks.ToArray()));
            }

            case AstStatementType.Lock:
            {
                var s            = e as AstLock;
                var scope        = new Scope(s.Source);
                var tryScope     = new Scope(s.Source);
                var finallyScope = new Scope(s.Source);
                var obj          = CompileExpression(s.Object);

                switch (obj.ExpressionType)
                {
                case ExpressionType.LoadLocal:
                case ExpressionType.LoadArgument:
                case ExpressionType.LoadField:
                case ExpressionType.This:
                case ExpressionType.Base:
                    if (!obj.ReturnType.IsReferenceType)
                    {
                        Log.Error(obj.Source, ErrorCode.E0000, "Only reference types can be used in 'lock'");
                    }
                    break;

                default:
                    Log.Error(obj.Source, ErrorCode.E0000, "Only variables can occur inside 'lock' initializer");
                    break;
                }

                if (s.OptionalBody != null)
                {
                    tryScope.Statements.Add(CompileStatement(s.OptionalBody));
                }

                scope.Statements.Add(ILFactory.CallMethod(obj.Source, Essentials.Monitor, "Enter", obj));
                finallyScope.Statements.Add(ILFactory.CallMethod(obj.Source, Essentials.Monitor, "Exit", obj));
                scope.Statements.Add(new TryCatchFinally(s.Source, tryScope, finallyScope));
                return(scope);
            }

            case AstStatementType.Using:
            {
                var s       = e as AstUsing;
                var scope   = new Scope(s.Source);
                var objects = new List <Expression>();
                var vscope  = new VariableScope();
                VariableScopeStack.Add(vscope);
                var init = CompileStatement(s.Initializer);

                for (int i = 0; i < 1; i++)
                {
                    switch (init.StatementType)
                    {
                    case StatementType.VariableDeclaration:
                    {
                        scope.Statements.Add(init);
                        for (var var = ((VariableDeclaration)init).Variable;
                             var != null;
                             var = var.Next)
                        {
                            objects.Add(new LoadLocal(var.Source, var));
                        }
                        continue;
                    }

                    case StatementType.Expression:
                    {
                        if (AddObjects(objects, (Expression)init))
                        {
                            continue;
                        }
                        break;
                    }
                    }

                    // TODO: Actually some expressions are valid as well in C#. Read spec and implement later
                    Log.Error(init.Source, ErrorCode.E0000, "Only variable declarations, fields and/or local variables can occur inside 'using' initializer");
                }

                var tryScope     = new Scope(s.Source);
                var finallyScope = new Scope(s.Source);

                if (s.OptionalBody != null)
                {
                    tryScope.Statements.Add(CompileStatement(s.OptionalBody));
                }

                foreach (var dispose in Enumerable.Reverse(objects))
                {
                    var idisposable = CompileImplicitCast(dispose.Source, Essentials.IDisposable, dispose);
                    finallyScope.Statements.Add(ILFactory.CallMethod(dispose.Source, idisposable, "Dispose"));
                }

                scope.Statements.Add(new TryCatchFinally(s.Source, tryScope, finallyScope));

                if (s.OptionalBody == null ||
                    (!s.OptionalBody.IsInvalid && ((s.OptionalBody is AstScope && (s.OptionalBody as AstScope).IsClosed) ||
                                                   !(s.OptionalBody is AstScope))))
                {
                    VariableScopeStack.Remove(vscope);
                    CurrentVariableScope.Scopes.Add(vscope);
                }

                return(scope);
            }

            case AstStatementType.ThrowValue:
            {
                var s = e as AstValueStatement;
                return(new Throw(s.Source, CompileExpression(s.Value)));
            }

            case AstStatementType.Throw:
            {
                for (int i = VariableScopeStack.Count - 1; i >= 0; i--)
                {
                    foreach (var v in VariableScopeStack[i].Variables.Values)
                    {
                        if (v.IsException)
                        {
                            return(new Throw(e.Source, new LoadLocal(e.Source, v), true));
                        }
                    }
                }

                return(Error(e.Source, ErrorCode.E0000, "Cannot rethrow outside of catch block"));
            }

            case AstStatementType.Switch:
            {
                var s = e as AstSwitch;
                var c = CompileExpression(s.Condition);

                if (!c.ReturnType.IsIntegralType)
                {
                    c = TryCompileImplicitCast(s.Source, Essentials.Int, c) ??
                        Error(s.Condition.Source, ErrorCode.E3415, "A switch expression must be of enum or integral type");
                }

                var cases = new List <SwitchCase>();

                foreach (var a in s.Cases)
                {
                    var handler         = CompileScope(a.Scope);
                    var values          = new List <Constant>();
                    var includesDefault = false;

                    foreach (var v in a.Values)
                    {
                        if (v == null)
                        {
                            includesDefault = true;
                            continue;
                        }

                        var sym      = CompileImplicitCast(v.Source, c.ReturnType, CompileExpression(v));
                        var constSym = Compiler.ConstantFolder.TryMakeConstant(sym);

                        if (constSym != null)
                        {
                            values.Add(constSym);
                        }
                        else if (sym.IsInvalid)
                        {
                            values.Add(new Constant(sym.Source, DataType.Invalid, -1));
                        }
                        else
                        {
                            Log.Error(v.Source, ErrorCode.E3410, "Case-expression must be constant");
                        }
                    }

                    cases.Add(new SwitchCase(values.ToArray(), includesDefault, handler));
                }

                return(new Switch(s.Source, c, cases.ToArray()));
            }

            case AstStatementType.Assert:
            {
                if (!Environment.Debug)
                {
                    return(new NoOp(e.Source, "Stripped assert"));
                }

                var s     = e as AstValueStatement;
                var value = CompileExpression(s.Value);
                var args  = new List <Expression>
                {
                    value,
                    new Constant(s.Source, Essentials.String, value.ToString()),
                    new Constant(s.Source, Essentials.String, s.Source.File.ToString().Replace('\\', '/')),
                    new Constant(s.Source, Essentials.Int, s.Source.Line),
                };
                var locals = new List <StoreLocal>();

                switch (value.ExpressionType)
                {
                case ExpressionType.CallUnOp:
                {
                    var o = value as CallUnOp;
                    args.Add(CreateAssertIndirection(ref o.Operand, locals, Namescope));
                    break;
                }

                case ExpressionType.CallBinOp:
                {
                    var o = value as CallBinOp;
                    args.Add(CreateAssertIndirection(ref o.Left, locals, Namescope));
                    args.Add(CreateAssertIndirection(ref o.Right, locals, Namescope));
                    break;
                }

                case ExpressionType.BranchOp:
                {
                    var o = value as BranchOp;
                    args.Add(CreateAssertIndirection(ref o.Left, locals, Namescope));
                    args.Add(CreateAssertIndirection(ref o.Right, locals, Namescope));
                    break;
                }

                case ExpressionType.CallMethod:
                {
                    var o = value as CallMethod;
                    for (int i = 0; i < o.Arguments.Length; i++)
                    {
                        args.Add(CreateAssertIndirection(ref o.Arguments[i], locals, Namescope));
                    }
                    break;
                }
                }

                var result = ILFactory.CallMethod(s.Source, "Uno.Diagnostics.Debug", "Assert", args.ToArray());

                while (locals.Count > 0)
                {
                    result = new SequenceOp(locals.RemoveLast(), result);
                }

                return(result);
            }

            case AstStatementType.DebugLog:
            {
                if (!Environment.Debug)
                {
                    return(new NoOp(e.Source, "Stripped debug_log"));
                }
                var s       = (AstValueStatement)e;
                var message = CompileExpression(s.Value);
                return(ILFactory.CallMethod(s.Source, "Uno.Diagnostics.Log", "Debug", message));
            }

            case AstStatementType.BuildError:
                return(CreateBuildError(e.Source, true));

            case AstStatementType.BuildWarning:
                return(CreateBuildError(e.Source, false));

            case AstStatementType.BuildErrorMessage:
            {
                var s = (AstValueStatement)e;
                return(CreateBuildError(e.Source, true, s.Value));
            }

            case AstStatementType.BuildWarningMessage:
            {
                var s = (AstValueStatement)e;
                return(CreateBuildError(e.Source, false, s.Value));
            }
            }

            Log.Error(e.Source, ErrorCode.I3411, "Unknown statement type <" + e.StatementType + ">");
            return(Expression.Invalid);
        }
Example #24
0
        public void ConvertTwoDigitNumberToString(int a, string expected)
        {
            string actual = IfElse.ConvertTwoDigitNumberToString(a);

            Assert.AreEqual(expected, actual);
        }
Example #25
0
        public void FindQuarter(int x, int y, string expected)
        {
            string actual = IfElse.FindQuarter(x, y);

            Assert.AreEqual(expected, actual);
        }
Example #26
0
        public override AstNode VisitIfElse(IfElse ast)
        {
            var ifBlock = m_ilgen.DefineLabel();
            var elseBlock = m_ilgen.DefineLabel();
            var endif = m_ilgen.DefineLabel();

            Visit(ast.Condition);
            //the e-stack should have a bool value
            m_ilgen.Emit(OpCodes.Brfalse, elseBlock);

            //if block
            m_ilgen.MarkLabel(ifBlock);
            Visit(ast.TruePart);
            m_ilgen.Emit(OpCodes.Br, endif);

            //elseblock
            m_ilgen.MarkLabel(elseBlock);
            Visit(ast.FalsePart);

            //after if
            m_ilgen.MarkLabel(endif);

            return ast;
        }
Example #27
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)
        {
            // Добавим переменную в список переменных
            DeclareVar declare = (DeclareVar)stmt;
            this.varTable[declare.Ident] = this.TypeOfExpr(declare.Expression);

            //Приведем элемент типа "Объевление" к типу "Присвоение"
            Assign assign = new Assign();
            assign.Ident      = declare.Ident;
            assign.Expression = declare.Expression;

            //Запишем тип переменной
            accum.Append(string.Format("\n{0} ", this.TypeOfExpr(declare.Expression).Name));
            //Запустим на обработку
            this.GenStmt(assign);
        }

        //Обработка элемента дерева - "Присвоение"
        else if (stmt is Assign)
        {
            Assign assign = (Assign)stmt;
            accum.Append(string.Format("{0}=", assign.Ident));

            //Обработка правой части элемента
            this.GenAssign(assign.Expression);
            accum.Append(";");
        }

        //Обработка элемента дерева - "Вывод данных"
        else if (stmt is Print)
        {
            Print print = (Print)stmt;
            accum.Append(print.VarExpression != null
                             ? string.Format("\nConsole.WriteLine(\"{0}\", {1});", this.GetExprValue(print.Expression),
                                             this.GetExprValue(print.VarExpression))
                             : string.Format("\nConsole.WriteLine(\"{0}\");", this.GetExprValue(print.Expression)));
        }

        //Обработка элемента дерева - "Ввод данных"
        else if (stmt is ReadValue)
        {
            ReadValue readValue = (ReadValue)stmt;
            accum.Append(readValue.Exp != null
                             ? string.Format("\n{0} = Console.ReadLine(\"{1}\");", readValue.Ident, this.GetExprValue(readValue.Exp))
                             : string.Format("\n{0} = Console.ReadLine();", readValue.Ident));

            //Проверка, что переменная объявлена ранее
            //CheckVariable
        }
        else if (stmt is IfElse)
        {
            IfElse ifElse    = (IfElse)stmt;
            string operation = string.Empty;

            switch (ifElse.Condition.Operation)
            {
            case ConOperation.Equal: operation = "="; break;

            case ConOperation.Less: operation = "<"; break;

            case ConOperation.LessEqual: operation = "<="; break;

            case ConOperation.More: operation = ">"; break;

            case ConOperation.MoreEqual: operation = ">="; break;
            }
            accum.Append(string.Format("\nif ({0}{1}{2})", this.GetExprValue(ifElse.Condition.Left), operation, this.GetExprValue(ifElse.Condition.Right)));


            if (ifElse.BodyThen != null)
            {
                accum.Append("\n{\n");
                this.GenStmt(ifElse.BodyThen);
                accum.Append("\n}");
            }

            if (ifElse.BodyElse != null)
            {
                if (ifElse.BodyThen == null)
                {
                    throw new System.Exception("error if - else");
                }
                accum.Append("\nelse\n{\n");
                this.GenStmt(ifElse.BodyElse);
                accum.Append("\n}");
            }
        }
        else if (stmt is ForNext)
        {
            ForNext forNext = (ForNext)stmt;

            accum.Append(string.Format("\nfor("));
            Assign assign = new Assign();
            assign.Ident      = forNext.Ident;
            assign.Expression = forNext.From;
            this.GenStmt(assign);
            accum.Append(string.Format("{0}<{1};{2}++)", forNext.Ident, this.GetExprValue(forNext.To), forNext.Ident));

            this.varTable[forNext.Ident] = typeof(int);

            if (forNext.Body != null)
            {
                accum.Append("\n{");
                this.GenStmt(forNext.Body);
                accum.Append("\n}");
            }
        }
        else
        {
            throw new System.Exception("Отсутствует инструкция для генерирования операции: " + stmt.GetType().Name);
        }
    }
Example #28
0
        public void DoSomeMath(int a, int b, int expected)
        {
            int actual = IfElse.DoSomeMath(a, b);

            Assert.AreEqual(expected, actual);
        }
Example #29
0
        static void Main(string[] args)
        {
            RunConfig runConfig;

            if (!TryParseArguments(args, out runConfig))
            {
                Usage();
                return;
            }

            var code = File.ReadAllText(args[0]);

            var pageState = new GraphicsState();

            var stack     = new LinearList <IOperation>();
            var execStack = new LinearList <IOperation>();
            var dictStack = new LinearList <IDictionary <string, IOperation> >();

            var system = new Dictionary <string, IOperation>();

            system["add"]    = new Add();
            system["sub"]    = new Substract();
            system["mul"]    = new Multiplicate();
            system["div"]    = new Divide();
            system["mod"]    = new Mod();
            system["def"]    = new Define();
            system["for"]    = new For();
            system["dup"]    = new Duplicate();
            system["index"]  = new Index();
            system["pop"]    = new Pop();
            system["exch"]   = new Exchange();
            system["repeat"] = new Repeat();
            system["array"]  = new EmptyArray();
            system["astore"] = new LoadArray();
            system["rand"]   = new Rand();
            system["cvi"]    = new ConvertToInteger();
            system["copy"]   = new Copy();
            system["roll"]   = new Roll();
            system["get"]    = new ArrayGet();
            system["put"]    = new ArrayPut();
            system["ne"]     = new NotEqual();
            system["eq"]     = new Equal();
            system["or"]     = new Or();
            system["ifelse"] = new IfElse();
            system["if"]     = new If();
            system["neg"]    = new Neg();
            system["not"]    = new Not();
            system["sqrt"]   = new Sqrt();
            system["lt"]     = new LessThan();
            system["ge"]     = new GreaterOrEqualThan();

            dictStack.Push(system);


            var graphics = new Dictionary <string, IOperation>();

            graphics["newpath"]      = new NewPath(pageState);
            graphics["closepath"]    = new ClosePath(pageState);
            graphics["fillpath"]     = new FillPath(pageState);
            graphics["setgray"]      = new SetGray(pageState);
            graphics["setrgbcolor"]  = new SetRGB(pageState);
            graphics["setlinewidth"] = new SetLineWidth(pageState);
            graphics["fill"]         = new FillPath(pageState);
            graphics["showpage"]     = new ShowPage(pageState);
            graphics["moveto"]       = new MoveTo(pageState);
            graphics["lineto"]       = new LineTo(pageState);
            graphics["rlineto"]      = new RelativeLineTo(pageState);
            graphics["gsave"]        = new SaveGraphicsState(pageState);
            graphics["grestore"]     = new RestoreGraphicsState(pageState);
            graphics["stroke"]       = new StrokePath(pageState);
            graphics["curveto"]      = new CurveTo(pageState);
            graphics["arc"]          = new Arc(pageState);

            dictStack.Push(graphics);

            dictStack.Push(new Dictionary <string, IOperation>());

            //execStack.Push(start);


            CodeParser.LoadCode(execStack,
                                @"
/findfont { pop (somefont) } def
/scalefont { exch pop } def
/setfont { pop } def
/setlinecap { pop } def
/srand { pop } def
");

            CodeParser.LoadCode(execStack, code);

            var state = new PreScriptState(stack, execStack, dictStack);

            while (execStack.Count > 0)
            {
                var operation = execStack.Pop();
                operation.Process(state);
            }
        }
Example #30
0
 internal protected virtual T Visit(IfElse node)
 {
     return(Visit(node as CodeNode));
 }
Example #31
0
 public virtual AstNode VisitIfElse(IfElse ast)
 {
     return(ast);
 }
Example #32
0
 public void Sort3ToBig(int a, int b, int c, int[] expected)
 {
     int[] actual = IfElse.Sort3ToBig(a, b, c);
     Assert.AreEqual(expected, actual);
 }